Merge vk-gl-cts/vulkan-cts-1.3.1 into vk-gl-cts/vulkan-cts-1.3.2
[platform/upstream/VK-GL-CTS.git] / external / vulkancts / modules / vulkan / image / vktImageLoadStoreTests.cpp
1 /*------------------------------------------------------------------------
2  * Vulkan Conformance Tests
3  * ------------------------
4  *
5  * Copyright (c) 2016 The Khronos Group Inc.
6  * Copyright (c) 2016 The Android Open Source Project
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 Image load/store Tests
23  *//*--------------------------------------------------------------------*/
24
25 #include "vktImageLoadStoreTests.hpp"
26 #include "vktTestCaseUtil.hpp"
27 #include "vktImageTestsUtil.hpp"
28 #include "vktImageLoadStoreUtil.hpp"
29 #include "vktImageTexture.hpp"
30
31 #include "vkDefs.hpp"
32 #include "vkRef.hpp"
33 #include "vkRefUtil.hpp"
34 #include "vkPlatform.hpp"
35 #include "vkPrograms.hpp"
36 #include "vkMemUtil.hpp"
37 #include "vkBarrierUtil.hpp"
38 #include "vkBuilderUtil.hpp"
39 #include "vkQueryUtil.hpp"
40 #include "vkImageUtil.hpp"
41 #include "vkCmdUtil.hpp"
42 #include "vkObjUtil.hpp"
43
44 #include "deMath.h"
45 #include "deUniquePtr.hpp"
46 #include "deSharedPtr.hpp"
47 #include "deStringUtil.hpp"
48
49 #include "tcuImageCompare.hpp"
50 #include "tcuTexture.hpp"
51 #include "tcuTextureUtil.hpp"
52 #include "tcuFloat.hpp"
53 #include "tcuFloatFormat.hpp"
54 #include "tcuStringTemplate.hpp"
55 #include "tcuVectorUtil.hpp"
56
57 #include <string>
58 #include <vector>
59 #include <map>
60
61 using namespace vk;
62
63 namespace vkt
64 {
65 namespace image
66 {
67 namespace
68 {
69
70 // Check for three-component (non-packed) format, i.e. pixel size is a multiple of 3.
71 bool formatHasThreeComponents(VkFormat format)
72 {
73         const tcu::TextureFormat texFormat = mapVkFormat(format);
74         return (getPixelSize(texFormat) % 3) == 0;
75 }
76
77 VkFormat getSingleComponentFormat(VkFormat format)
78 {
79         tcu::TextureFormat texFormat = mapVkFormat(format);
80         texFormat = tcu::TextureFormat(tcu::TextureFormat::R, texFormat.type);
81         return mapTextureFormat(texFormat);
82 }
83
84 inline VkBufferImageCopy makeBufferImageCopy (const Texture& texture)
85 {
86         return image::makeBufferImageCopy(makeExtent3D(texture.layerSize()), texture.numLayers());
87 }
88
89 tcu::ConstPixelBufferAccess getLayerOrSlice (const Texture& texture, const tcu::ConstPixelBufferAccess access, const int layer)
90 {
91         switch (texture.type())
92         {
93                 case IMAGE_TYPE_1D:
94                 case IMAGE_TYPE_2D:
95                 case IMAGE_TYPE_BUFFER:
96                         // Not layered
97                         DE_ASSERT(layer == 0);
98                         return access;
99
100                 case IMAGE_TYPE_1D_ARRAY:
101                         return tcu::getSubregion(access, 0, layer, access.getWidth(), 1);
102
103                 case IMAGE_TYPE_2D_ARRAY:
104                 case IMAGE_TYPE_CUBE:
105                 case IMAGE_TYPE_CUBE_ARRAY:
106                 case IMAGE_TYPE_3D:                     // 3d texture is treated as if depth was the layers
107                         return tcu::getSubregion(access, 0, 0, layer, access.getWidth(), access.getHeight(), 1);
108
109                 default:
110                         DE_FATAL("Internal test error");
111                         return tcu::ConstPixelBufferAccess();
112         }
113 }
114
115 //! \return the size in bytes of a given level of a mipmap image, including array layers.
116 vk::VkDeviceSize getMipmapLevelImageSizeBytes (const Texture& texture, const vk::VkFormat format, const deUint32 mipmapLevel)
117 {
118         tcu::IVec3 size = texture.size(mipmapLevel);
119         return tcu::getPixelSize(vk::mapVkFormat(format)) * size.x() * size.y() * size.z();
120 }
121
122 //! \return the size in bytes of the whole mipmap image, including all mipmap levels and array layers
123 vk::VkDeviceSize getMipmapImageTotalSizeBytes (const Texture& texture, const vk::VkFormat format)
124 {
125         vk::VkDeviceSize        size                    = 0u;
126         deInt32                         levelCount              = 0u;
127
128         do
129         {
130                 size += getMipmapLevelImageSizeBytes(texture, format, levelCount);
131                 levelCount++;
132         } while (levelCount < texture.numMipmapLevels());
133         return size;
134 }
135
136 //! \return true if all layers match in both pixel buffers
137 bool comparePixelBuffers (tcu::TestLog&                                         log,
138                                                   const Texture&                                        texture,
139                                                   const VkFormat                                        format,
140                                                   const tcu::ConstPixelBufferAccess     reference,
141                                                   const tcu::ConstPixelBufferAccess     result,
142                                                   const deUint32                                        mipmapLevel = 0u)
143 {
144         DE_ASSERT(reference.getFormat() == result.getFormat());
145         DE_ASSERT(reference.getSize() == result.getSize());
146
147         const bool is3d = (texture.type() == IMAGE_TYPE_3D);
148         const int numLayersOrSlices = (is3d ? texture.size(mipmapLevel).z() : texture.numLayers());
149         const int numCubeFaces = 6;
150
151         int passedLayers = 0;
152         for (int layerNdx = 0; layerNdx < numLayersOrSlices; ++layerNdx)
153         {
154                 const std::string comparisonName = "Comparison" + de::toString(layerNdx);
155                 const std::string comparisonDesc = "Image Comparison, " +
156                         (isCube(texture) ? "face " + de::toString(layerNdx % numCubeFaces) + ", cube " + de::toString(layerNdx / numCubeFaces) :
157                         is3d                     ? "slice " + de::toString(layerNdx) : "layer " + de::toString(layerNdx) + " , level " + de::toString(mipmapLevel));
158
159                 const tcu::ConstPixelBufferAccess refLayer = getLayerOrSlice(texture, reference, layerNdx);
160                 const tcu::ConstPixelBufferAccess resultLayer = getLayerOrSlice(texture, result, layerNdx);
161
162                 bool ok = false;
163
164                 switch (tcu::getTextureChannelClass(mapVkFormat(format).type))
165                 {
166                         case tcu::TEXTURECHANNELCLASS_UNSIGNED_INTEGER:
167                         case tcu::TEXTURECHANNELCLASS_SIGNED_INTEGER:
168                         {
169                                 ok = tcu::intThresholdCompare(log, comparisonName.c_str(), comparisonDesc.c_str(), refLayer, resultLayer, tcu::UVec4(0), tcu::COMPARE_LOG_RESULT);
170                                 break;
171                         }
172
173                         case tcu::TEXTURECHANNELCLASS_UNSIGNED_FIXED_POINT:
174                         {
175                                 // Allow error of minimum representable difference
176                                 tcu::Vec4 threshold(1.0f / ((tcu::UVec4(1u) << tcu::getTextureFormatMantissaBitDepth(mapVkFormat(format)).cast<deUint32>()) - 1u).cast<float>());
177
178                                 // Add 1 ULP of fp32 imprecision to account for image comparison fp32 math with unorm->float conversions.
179                                 threshold += tcu::Vec4(std::numeric_limits<float>::epsilon());
180
181                                 ok = tcu::floatThresholdCompare(log, comparisonName.c_str(), comparisonDesc.c_str(), refLayer, resultLayer, threshold, tcu::COMPARE_LOG_RESULT);
182                                 break;
183                         }
184
185                         case tcu::TEXTURECHANNELCLASS_SIGNED_FIXED_POINT:
186                         {
187                                 const tcu::UVec4 bitDepth = tcu::getTextureFormatMantissaBitDepth(mapVkFormat(format)).cast<deUint32>() - 1u;
188                                 // To avoid bit-shifting with negative value, which is undefined behaviour.
189                                 const tcu::UVec4 fixedBitDepth = tcu::select(bitDepth, tcu::UVec4(0u, 0u, 0u, 0u), tcu::greaterThanEqual(bitDepth.cast<deInt32>(), tcu::IVec4(0, 0, 0, 0)));
190
191                                 // Allow error of minimum representable difference
192                                 const tcu::Vec4 threshold (1.0f / ((tcu::UVec4(1u) << fixedBitDepth) - 1u).cast<float>());
193
194                                 ok = tcu::floatThresholdCompare(log, comparisonName.c_str(), comparisonDesc.c_str(), refLayer, resultLayer, threshold, tcu::COMPARE_LOG_RESULT);
195                                 break;
196                         }
197
198                         case tcu::TEXTURECHANNELCLASS_FLOATING_POINT:
199                         {
200                                 // Convert target format ulps to float ulps and allow 1 ulp difference
201                                 const tcu::UVec4 threshold (tcu::UVec4(1u) << (tcu::UVec4(23) - tcu::getTextureFormatMantissaBitDepth(mapVkFormat(format)).cast<deUint32>()));
202
203                                 ok = tcu::floatUlpThresholdCompare(log, comparisonName.c_str(), comparisonDesc.c_str(), refLayer, resultLayer, threshold, tcu::COMPARE_LOG_RESULT);
204                                 break;
205                         }
206
207                         default:
208                                 DE_FATAL("Unknown channel class");
209                 }
210
211                 if (ok)
212                         ++passedLayers;
213         }
214
215         return passedLayers == numLayersOrSlices;
216 }
217
218 //!< Zero out invalid pixels in the image (denormalized, infinite, NaN values)
219 void replaceBadFloatReinterpretValues (const tcu::PixelBufferAccess access)
220 {
221         DE_ASSERT(tcu::getTextureChannelClass(access.getFormat().type) == tcu::TEXTURECHANNELCLASS_FLOATING_POINT);
222
223         for (int z = 0; z < access.getDepth(); ++z)
224         for (int y = 0; y < access.getHeight(); ++y)
225         for (int x = 0; x < access.getWidth(); ++x)
226         {
227                 const tcu::Vec4 color(access.getPixel(x, y, z));
228                 tcu::Vec4 newColor = color;
229
230                 for (int i = 0; i < 4; ++i)
231                 {
232                         if (access.getFormat().type == tcu::TextureFormat::HALF_FLOAT)
233                         {
234                                 const tcu::Float16 f(color[i]);
235                                 if (f.isDenorm() || f.isInf() || f.isNaN())
236                                         newColor[i] = 0.0f;
237                         }
238                         else
239                         {
240                                 const tcu::Float32 f(color[i]);
241                                 if (f.isDenorm() || f.isInf() || f.isNaN())
242                                         newColor[i] = 0.0f;
243                         }
244                 }
245
246                 if (newColor != color)
247                         access.setPixel(newColor, x, y, z);
248         }
249 }
250
251 //!< replace invalid pixels in the image (-128)
252 void replaceSnormReinterpretValues (const tcu::PixelBufferAccess access)
253 {
254         DE_ASSERT(tcu::getTextureChannelClass(access.getFormat().type) == tcu::TEXTURECHANNELCLASS_SIGNED_FIXED_POINT);
255
256         for (int z = 0; z < access.getDepth(); ++z)
257         for (int y = 0; y < access.getHeight(); ++y)
258         for (int x = 0; x < access.getWidth(); ++x)
259         {
260                 const tcu::IVec4 color(access.getPixelInt(x, y, z));
261                 tcu::IVec4 newColor = color;
262
263                 for (int i = 0; i < 4; ++i)
264                 {
265                         const deInt32 oldColor(color[i]);
266                         if (oldColor == -128) newColor[i] = -127;
267                 }
268
269                 if (newColor != color)
270                 access.setPixel(newColor, x, y, z);
271         }
272 }
273
274 tcu::Vec4 getMiddleValue(VkFormat imageFormat)
275 {
276         tcu::TextureFormat              format  = mapVkFormat(imageFormat);
277         tcu::TextureFormatInfo  fmtInfo = tcu::getTextureFormatInfo(format);
278         tcu::Vec4                               val             = (fmtInfo.valueMax - fmtInfo.valueMin) * tcu::Vec4(0.5f);
279
280         if (isIntegerFormat(imageFormat))
281                 val = floor(val);
282
283         return val;
284 }
285
286 tcu::TextureLevel generateReferenceImage (const tcu::IVec3& imageSize, const VkFormat imageFormat, const VkFormat readFormat, bool constantValue = false)
287 {
288         // Generate a reference image data using the storage format
289
290         tcu::TextureLevel reference(mapVkFormat(imageFormat), imageSize.x(), imageSize.y(), imageSize.z());
291         const tcu::PixelBufferAccess access = reference.getAccess();
292
293         const float storeColorScale = computeStoreColorScale(imageFormat, imageSize);
294         const float storeColorBias = computeStoreColorBias(imageFormat);
295
296         const bool intFormat = isIntegerFormat(imageFormat);
297         const bool storeNegativeValues = isSignedFormat(imageFormat) && (storeColorBias == 0);
298         const int xMax = imageSize.x() - 1;
299         const int yMax = imageSize.y() - 1;
300
301         for (int z = 0; z < imageSize.z(); ++z)
302         for (int y = 0; y < imageSize.y(); ++y)
303         for (int x = 0; x < imageSize.x(); ++x)
304         {
305                 if (constantValue)
306                 {
307                         access.setPixel(getMiddleValue(imageFormat), x, y, z);
308                 }
309                 else
310                 {
311                         tcu::IVec4 color = tcu::IVec4(x ^ y ^ z, (xMax - x) ^ y ^ z, x ^ (yMax - y) ^ z, (xMax - x) ^ (yMax - y) ^ z);
312
313                         if (storeNegativeValues)
314                                 color -= tcu::IVec4(deRoundFloatToInt32((float)de::max(xMax, yMax) / 2.0f));
315
316                         if (intFormat)
317                                 access.setPixel(color, x, y, z);
318                         else
319                                 access.setPixel(color.asFloat()*storeColorScale + storeColorBias, x, y, z);
320                 }
321         }
322
323         // If the image is to be accessed as a float texture, get rid of invalid values
324
325         if (isFloatFormat(readFormat) && imageFormat != readFormat)
326                 replaceBadFloatReinterpretValues(tcu::PixelBufferAccess(mapVkFormat(readFormat), imageSize, access.getDataPtr()));
327         if (isSnormFormat(readFormat) && imageFormat != readFormat)
328                 replaceSnormReinterpretValues(tcu::PixelBufferAccess(mapVkFormat(readFormat), imageSize, access.getDataPtr()));
329
330         return reference;
331 }
332
333 inline tcu::TextureLevel generateReferenceImage (const tcu::IVec3& imageSize, const VkFormat imageFormat, bool constantValue = false)
334 {
335         return generateReferenceImage(imageSize, imageFormat, imageFormat, constantValue);
336 }
337
338 void flipHorizontally (const tcu::PixelBufferAccess access)
339 {
340         const int xMax = access.getWidth() - 1;
341         const int halfWidth = access.getWidth() / 2;
342
343         if (isIntegerFormat(mapTextureFormat(access.getFormat())))
344                 for (int z = 0; z < access.getDepth(); z++)
345                 for (int y = 0; y < access.getHeight(); y++)
346                 for (int x = 0; x < halfWidth; x++)
347                 {
348                         const tcu::UVec4 temp = access.getPixelUint(xMax - x, y, z);
349                         access.setPixel(access.getPixelUint(x, y, z), xMax - x, y, z);
350                         access.setPixel(temp, x, y, z);
351                 }
352         else
353                 for (int z = 0; z < access.getDepth(); z++)
354                 for (int y = 0; y < access.getHeight(); y++)
355                 for (int x = 0; x < halfWidth; x++)
356                 {
357                         const tcu::Vec4 temp = access.getPixel(xMax - x, y, z);
358                         access.setPixel(access.getPixel(x, y, z), xMax - x, y, z);
359                         access.setPixel(temp, x, y, z);
360                 }
361 }
362
363 inline bool formatsAreCompatible (const VkFormat format0, const VkFormat format1)
364 {
365         return format0 == format1 || mapVkFormat(format0).getPixelSize() == mapVkFormat(format1).getPixelSize();
366 }
367
368 void commandImageWriteBarrierBetweenShaderInvocations (Context& context, const VkCommandBuffer cmdBuffer, const VkImage image, const Texture& texture)
369 {
370         const DeviceInterface& vk = context.getDeviceInterface();
371
372         const VkImageSubresourceRange fullImageSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, texture.numMipmapLevels(), 0u, texture.numLayers());
373         const VkImageMemoryBarrier shaderWriteBarrier = makeImageMemoryBarrier(
374                 VK_ACCESS_SHADER_WRITE_BIT, 0u,
375                 VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL,
376                 image, fullImageSubresourceRange);
377
378         vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 0, (const VkBufferMemoryBarrier*)DE_NULL, 1, &shaderWriteBarrier);
379 }
380
381 void commandBufferWriteBarrierBeforeHostRead (Context& context, const VkCommandBuffer cmdBuffer, const VkBuffer buffer, const VkDeviceSize bufferSizeBytes)
382 {
383         const DeviceInterface& vk = context.getDeviceInterface();
384
385         const VkBufferMemoryBarrier shaderWriteBarrier = makeBufferMemoryBarrier(
386                 VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT,
387                 buffer, 0ull, bufferSizeBytes);
388
389         vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &shaderWriteBarrier, 0, (const VkImageMemoryBarrier*)DE_NULL);
390 }
391
392 //! Copy all layers of an image to a buffer.
393 void commandCopyImageToBuffer (Context&                                 context,
394                                                            const VkCommandBuffer        cmdBuffer,
395                                                            const VkImage                        image,
396                                                            const VkBuffer                       buffer,
397                                                            const VkDeviceSize           bufferSizeBytes,
398                                                            const Texture&                       texture)
399 {
400         const DeviceInterface& vk = context.getDeviceInterface();
401
402         const VkImageSubresourceRange fullImageSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, texture.numLayers());
403         const VkImageMemoryBarrier prepareForTransferBarrier = makeImageMemoryBarrier(
404                 VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT,
405                 VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
406                 image, fullImageSubresourceRange);
407
408         const VkBufferImageCopy copyRegion = makeBufferImageCopy(texture);
409
410         const VkBufferMemoryBarrier copyBarrier = makeBufferMemoryBarrier(
411                 VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT,
412                 buffer, 0ull, bufferSizeBytes);
413
414         vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 0, (const VkBufferMemoryBarrier*)DE_NULL, 1, &prepareForTransferBarrier);
415         vk.cmdCopyImageToBuffer(cmdBuffer, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, buffer, 1u, &copyRegion);
416         vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &copyBarrier, 0, (const VkImageMemoryBarrier*)DE_NULL);
417 }
418
419 //! Copy all layers of a mipmap image to a buffer.
420 void commandCopyMipmapImageToBuffer (Context&                           context,
421                                                                          const VkCommandBuffer  cmdBuffer,
422                                                                          const VkImage                  image,
423                                                                          const VkFormat                 imageFormat,
424                                                                          const VkBuffer                 buffer,
425                                                                          const VkDeviceSize             bufferSizeBytes,
426                                                                          const Texture&                 texture)
427 {
428         const DeviceInterface& vk = context.getDeviceInterface();
429
430         const VkImageSubresourceRange fullImageSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, texture.numMipmapLevels(), 0u, texture.numLayers());
431         const VkImageMemoryBarrier prepareForTransferBarrier = makeImageMemoryBarrier(
432                 VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT,
433                 VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
434                 image, fullImageSubresourceRange);
435
436         std::vector<VkBufferImageCopy> copyRegions;
437         VkDeviceSize bufferOffset = 0u;
438         for (deInt32 levelNdx = 0; levelNdx < texture.numMipmapLevels(); levelNdx++)
439         {
440                 const VkBufferImageCopy copyParams =
441                 {
442                         bufferOffset,                                                                                                                                                           //      VkDeviceSize                            bufferOffset;
443                         0u,                                                                                                                                                                                     //      deUint32                                        bufferRowLength;
444                         0u,                                                                                                                                                                                     //      deUint32                                        bufferImageHeight;
445                         makeImageSubresourceLayers(VK_IMAGE_ASPECT_COLOR_BIT, levelNdx, 0u, texture.numLayers()),       //      VkImageSubresourceLayers        imageSubresource;
446                         makeOffset3D(0, 0, 0),                                                                                                                                          //      VkOffset3D                                      imageOffset;
447                         makeExtent3D(texture.layerSize(levelNdx)),                                                                                                      //      VkExtent3D                                      imageExtent;
448                 };
449                 copyRegions.push_back(copyParams);
450                 bufferOffset += getMipmapLevelImageSizeBytes(texture, imageFormat, levelNdx);
451         }
452
453         const VkBufferMemoryBarrier copyBarrier = makeBufferMemoryBarrier(
454                 VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT,
455                 buffer, 0ull, bufferSizeBytes);
456
457         vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 0, (const VkBufferMemoryBarrier*)DE_NULL, 1, &prepareForTransferBarrier);
458         vk.cmdCopyImageToBuffer(cmdBuffer, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, buffer, (deUint32) copyRegions.size(), copyRegions.data());
459         vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &copyBarrier, 0, (const VkImageMemoryBarrier*)DE_NULL);
460 }
461
462 class StoreTest : public TestCase
463 {
464 public:
465         enum TestFlags
466         {
467                 FLAG_SINGLE_LAYER_BIND                          = 0x1,  //!< Run the shader multiple times, each time binding a different layer.
468                 FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER     = 0x2,  //!< Declare the format of the images in the shader code
469                 FLAG_MINALIGN                                           = 0x4,  //!< Use bufferview offset that matches the advertised minimum alignment
470                 FLAG_STORE_CONSTANT_VALUE                       = 0x8,  //!< Store constant value
471         };
472
473                                                         StoreTest                       (tcu::TestContext&      testCtx,
474                                                                                                  const std::string&     name,
475                                                                                                  const std::string&     description,
476                                                                                                  const Texture&         texture,
477                                                                                                  const VkFormat         format,
478                                                                                                  const deUint32         flags = FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER);
479
480         virtual void                    checkSupport            (Context&                       context) const;
481         void                                    initPrograms            (SourceCollections&     programCollection) const;
482         TestInstance*                   createInstance          (Context&                       context) const;
483
484 private:
485         const Texture                   m_texture;
486         const VkFormat                  m_format;
487         const bool                              m_declareImageFormatInShader;
488         const bool                              m_singleLayerBind;
489         const bool                              m_minalign;
490         const bool                              m_storeConstantValue;
491 };
492
493 StoreTest::StoreTest (tcu::TestContext&         testCtx,
494                                           const std::string&    name,
495                                           const std::string&    description,
496                                           const Texture&                texture,
497                                           const VkFormat                format,
498                                           const deUint32                flags)
499         : TestCase                                              (testCtx, name, description)
500         , m_texture                                             (texture)
501         , m_format                                              (format)
502         , m_declareImageFormatInShader  ((flags & FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER) != 0)
503         , m_singleLayerBind                             ((flags & FLAG_SINGLE_LAYER_BIND) != 0)
504         , m_minalign                                    ((flags & FLAG_MINALIGN) != 0)
505         , m_storeConstantValue                  ((flags & FLAG_STORE_CONSTANT_VALUE) != 0)
506 {
507         if (m_singleLayerBind)
508                 DE_ASSERT(m_texture.numLayers() > 1);
509 }
510
511 void StoreTest::checkSupport (Context& context) const
512 {
513         const VkFormatProperties3 formatProperties (context.getFormatProperties(m_format));
514
515         if (!m_declareImageFormatInShader && !(formatProperties.bufferFeatures & VK_FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT_KHR))
516                 TCU_THROW(NotSupportedError, "Format not supported for unformatted stores via storage buffer");
517
518         if (!m_declareImageFormatInShader && !(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT_KHR))
519                 TCU_THROW(NotSupportedError, "Format not supported for unformatted stores via storage images");
520
521         if (m_texture.type() == IMAGE_TYPE_CUBE_ARRAY)
522                 context.requireDeviceCoreFeature(DEVICE_CORE_FEATURE_IMAGE_CUBE_ARRAY);
523
524         if ((m_texture.type() != IMAGE_TYPE_BUFFER) && !(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT))
525                 TCU_THROW(NotSupportedError, "Format not supported for storage images");
526
527         if (m_texture.type() == IMAGE_TYPE_BUFFER && !(formatProperties.bufferFeatures & VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT))
528                 TCU_THROW(NotSupportedError, "Format not supported for storage texel buffers");
529 }
530
531 void StoreTest::initPrograms (SourceCollections& programCollection) const
532 {
533         const float storeColorScale = computeStoreColorScale(m_format, m_texture.size());
534         const float storeColorBias = computeStoreColorBias(m_format);
535         DE_ASSERT(colorScaleAndBiasAreValid(m_format, storeColorScale, storeColorBias));
536
537         const deUint32 xMax = m_texture.size().x() - 1;
538         const deUint32 yMax = m_texture.size().y() - 1;
539         const std::string signednessPrefix = isUintFormat(m_format) ? "u" : isIntFormat(m_format) ? "i" : "";
540         const bool storeNegativeValues = isSignedFormat(m_format) && (storeColorBias == 0);
541         bool useClamp = false;
542         std::string colorBaseExpr = signednessPrefix + "vec4(";
543
544         std::string colorExpr;
545
546         if (m_storeConstantValue)
547         {
548                 tcu::Vec4 val = getMiddleValue(m_format);
549
550                 if (isIntegerFormat(m_format))
551                 {
552                         colorExpr = colorBaseExpr
553                                                 + de::toString(static_cast<deInt64>(val.x())) + ", "
554                                                 + de::toString(static_cast<deInt64>(val.y())) + ", "
555                                                 + de::toString(static_cast<deInt64>(val.z())) + ", "
556                                                 + de::toString(static_cast<deInt64>(val.w())) + ")";
557                 }
558                 else
559                 {
560                         colorExpr = colorBaseExpr
561                                                 + de::toString(val.x()) + ", "
562                                                 + de::toString(val.y()) + ", "
563                                                 + de::toString(val.z()) + ", "
564                                                 + de::toString(val.w()) + ")";
565                 }
566         }
567         else
568         {
569                 colorBaseExpr = colorBaseExpr
570                                                 + "gx^gy^gz, "
571                                                 + "(" + de::toString(xMax) + "-gx)^gy^gz, "
572                                                 + "gx^(" + de::toString(yMax) + "-gy)^gz, "
573                                                 + "(" + de::toString(xMax) + "-gx)^(" + de::toString(yMax) + "-gy)^gz)";
574
575                 // Large integer values may not be represented with formats with low bit depths
576                 if (isIntegerFormat(m_format))
577                 {
578                         const deInt64 minStoreValue = storeNegativeValues ? 0 - deRoundFloatToInt64((float)de::max(xMax, yMax) / 2.0f) : 0;
579                         const deInt64 maxStoreValue = storeNegativeValues ? deRoundFloatToInt64((float)de::max(xMax, yMax) / 2.0f) : de::max(xMax, yMax);
580
581                         useClamp = !isRepresentableIntegerValue(tcu::Vector<deInt64, 4>(minStoreValue), mapVkFormat(m_format)) ||
582                                            !isRepresentableIntegerValue(tcu::Vector<deInt64, 4>(maxStoreValue), mapVkFormat(m_format));
583                 }
584
585                 // Clamp if integer value cannot be represented with the current format
586                 if (useClamp)
587                 {
588                         const tcu::IVec4 bitDepths = tcu::getTextureFormatBitDepth(mapVkFormat(m_format));
589                         tcu::IVec4 minRepresentableValue;
590                         tcu::IVec4 maxRepresentableValue;
591
592                         switch (tcu::getTextureChannelClass(mapVkFormat(m_format).type))
593                         {
594                                 case tcu::TEXTURECHANNELCLASS_UNSIGNED_INTEGER:
595                                 {
596                                         minRepresentableValue = tcu::IVec4(0);
597                                         maxRepresentableValue = (tcu::IVec4(1) << bitDepths) - tcu::IVec4(1);
598                                         break;
599                                 }
600
601                                 case tcu::TEXTURECHANNELCLASS_SIGNED_INTEGER:
602                                 {
603                                         minRepresentableValue = -(tcu::IVec4(1) << bitDepths - tcu::IVec4(1));
604                                         maxRepresentableValue = (tcu::IVec4(1) << (bitDepths - tcu::IVec4(1))) - tcu::IVec4(1);
605                                         break;
606                                 }
607
608                                 default:
609                                         DE_ASSERT(isIntegerFormat(m_format));
610                         }
611
612                         colorBaseExpr = "clamp(" + colorBaseExpr + ", "
613                                                         + signednessPrefix + "vec4" + de::toString(minRepresentableValue) + ", "
614                                                         + signednessPrefix + "vec4" + de::toString(maxRepresentableValue) + ")";
615                 }
616
617                 colorExpr = colorBaseExpr + (storeColorScale == 1.0f ? "" : "*" + de::toString(storeColorScale))
618                                         + (storeColorBias == 0.0f ? "" : " + float(" + de::toString(storeColorBias) + ")");
619
620                 if (storeNegativeValues)
621                         colorExpr += "-" + de::toString(deRoundFloatToInt32((float)deMax32(xMax, yMax) / 2.0f));
622         }
623
624         const int dimension = (m_singleLayerBind ? m_texture.layerDimension() : m_texture.dimension());
625         const std::string texelCoordStr = (dimension == 1 ? "gx" : dimension == 2 ? "ivec2(gx, gy)" : dimension == 3 ? "ivec3(gx, gy, gz)" : "");
626
627         const ImageType usedImageType = (m_singleLayerBind ? getImageTypeForSingleLayer(m_texture.type()) : m_texture.type());
628         const std::string imageTypeStr = getShaderImageType(mapVkFormat(m_format), usedImageType);
629
630         std::ostringstream src;
631         src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_440) << "\n"
632                 << "\n"
633                 << "layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;\n";
634         if (m_declareImageFormatInShader)
635         {
636                 const std::string formatQualifierStr = getShaderImageFormatQualifier(mapVkFormat(m_format));
637                 src << "layout (binding = 0, " << formatQualifierStr << ") writeonly uniform " << imageTypeStr << " u_image;\n";
638         }
639         else
640                 src << "layout (binding = 0) writeonly uniform " << imageTypeStr << " u_image;\n";
641
642         if (m_singleLayerBind)
643                 src << "layout (binding = 1) readonly uniform Constants {\n"
644                         << "    int u_layerNdx;\n"
645                         << "};\n";
646
647         src << "\n"
648                 << "void main (void)\n"
649                 << "{\n"
650                 << "    int gx = int(gl_GlobalInvocationID.x);\n"
651                 << "    int gy = int(gl_GlobalInvocationID.y);\n"
652                 << "    int gz = " << (m_singleLayerBind ? "u_layerNdx" : "int(gl_GlobalInvocationID.z)") << ";\n"
653                 << "    imageStore(u_image, " << texelCoordStr << ", " << colorExpr << ");\n"
654                 << "}\n";
655
656         programCollection.glslSources.add("comp") << glu::ComputeSource(src.str());
657 }
658
659 //! Generic test iteration algorithm for image tests
660 class BaseTestInstance : public TestInstance
661 {
662 public:
663                                                                         BaseTestInstance                                                (Context&               context,
664                                                                                                                                                          const Texture& texture,
665                                                                                                                                                          const VkFormat format,
666                                                                                                                                                          const bool             declareImageFormatInShader,
667                                                                                                                                                          const bool             singleLayerBind,
668                                                                                                                                                          const bool             minalign,
669                                                                                                                                                          const bool             bufferLoadUniform);
670
671         tcu::TestStatus                                 iterate                                                                 (void);
672
673         virtual                                                 ~BaseTestInstance                                               (void) {}
674
675 protected:
676         virtual VkDescriptorSetLayout   prepareDescriptors                                              (void) = 0;
677         virtual tcu::TestStatus                 verifyResult                                                    (void) = 0;
678
679         virtual void                                    commandBeforeCompute                                    (const VkCommandBuffer  cmdBuffer) = 0;
680         virtual void                                    commandBetweenShaderInvocations                 (const VkCommandBuffer  cmdBuffer) = 0;
681         virtual void                                    commandAfterCompute                                             (const VkCommandBuffer  cmdBuffer) = 0;
682
683         virtual void                                    commandBindDescriptorsForLayer                  (const VkCommandBuffer  cmdBuffer,
684                                                                                                                                                          const VkPipelineLayout pipelineLayout,
685                                                                                                                                                          const int                              layerNdx) = 0;
686         virtual deUint32                                getViewOffset                                                   (Context&               context,
687                                                                                                                                                          const VkFormat format,
688                                                                                                                                                          bool                   uniform);
689
690         const Texture                                   m_texture;
691         const VkFormat                                  m_format;
692         const bool                                              m_declareImageFormatInShader;
693         const bool                                              m_singleLayerBind;
694         const bool                                              m_minalign;
695         const bool                                              m_bufferLoadUniform;
696         const deUint32                                  m_srcViewOffset;
697         const deUint32                                  m_dstViewOffset;
698 };
699
700 BaseTestInstance::BaseTestInstance (Context& context, const Texture& texture, const VkFormat format, const bool declareImageFormatInShader, const bool singleLayerBind, const bool minalign, const bool bufferLoadUniform)
701         : TestInstance                                  (context)
702         , m_texture                                             (texture)
703         , m_format                                              (format)
704         , m_declareImageFormatInShader  (declareImageFormatInShader)
705         , m_singleLayerBind                             (singleLayerBind)
706         , m_minalign                                    (minalign)
707         , m_bufferLoadUniform                   (bufferLoadUniform)
708         , m_srcViewOffset                               (getViewOffset(context, format, m_bufferLoadUniform))
709         , m_dstViewOffset                               (getViewOffset(context, formatHasThreeComponents(format) ? getSingleComponentFormat(format) : format, false))
710 {
711 }
712
713 tcu::TestStatus BaseTestInstance::iterate (void)
714 {
715         const DeviceInterface&                  vk                                      = m_context.getDeviceInterface();
716         const VkDevice                                  device                          = m_context.getDevice();
717         const VkQueue                                   queue                           = m_context.getUniversalQueue();
718         const deUint32                                  queueFamilyIndex        = m_context.getUniversalQueueFamilyIndex();
719
720         const Unique<VkShaderModule> shaderModule(createShaderModule(vk, device, m_context.getBinaryCollection().get("comp"), 0));
721
722         const VkDescriptorSetLayout descriptorSetLayout = prepareDescriptors();
723         const Unique<VkPipelineLayout> pipelineLayout(makePipelineLayout(vk, device, descriptorSetLayout));
724         const Unique<VkPipeline> pipeline(makeComputePipeline(vk, device, *pipelineLayout, *shaderModule));
725
726         const Unique<VkCommandPool> cmdPool(createCommandPool(vk, device, VK_COMMAND_POOL_CREATE_TRANSIENT_BIT, queueFamilyIndex));
727         const Unique<VkCommandBuffer> cmdBuffer(allocateCommandBuffer(vk, device, *cmdPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY));
728
729         beginCommandBuffer(vk, *cmdBuffer);
730
731         vk.cmdBindPipeline(*cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, *pipeline);
732         commandBeforeCompute(*cmdBuffer);
733
734         const tcu::IVec3 workSize = (m_singleLayerBind ? m_texture.layerSize() : m_texture.size());
735         const int loopNumLayers = (m_singleLayerBind ? m_texture.numLayers() : 1);
736         for (int layerNdx = 0; layerNdx < loopNumLayers; ++layerNdx)
737         {
738                 commandBindDescriptorsForLayer(*cmdBuffer, *pipelineLayout, layerNdx);
739
740                 if (layerNdx > 0)
741                         commandBetweenShaderInvocations(*cmdBuffer);
742
743                 vk.cmdDispatch(*cmdBuffer, workSize.x(), workSize.y(), workSize.z());
744         }
745
746         commandAfterCompute(*cmdBuffer);
747
748         endCommandBuffer(vk, *cmdBuffer);
749
750         submitCommandsAndWait(vk, device, queue, *cmdBuffer);
751
752         return verifyResult();
753 }
754
755 //! Base store test implementation
756 class StoreTestInstance : public BaseTestInstance
757 {
758 public:
759                                                                         StoreTestInstance                                               (Context&               context,
760                                                                                                                                                          const Texture& texture,
761                                                                                                                                                          const VkFormat format,
762                                                                                                                                                          const bool             declareImageFormatInShader,
763                                                                                                                                                          const bool             singleLayerBind,
764                                                                                                                                                          const bool             minalign,
765                                                                                                                                                          const bool             storeConstantValue);
766
767 protected:
768         virtual tcu::TestStatus                 verifyResult                                                    (void);
769
770         // Add empty implementations for functions that might be not needed
771         void                                                    commandBeforeCompute                                    (const VkCommandBuffer) {}
772         void                                                    commandBetweenShaderInvocations                 (const VkCommandBuffer) {}
773         void                                                    commandAfterCompute                                             (const VkCommandBuffer) {}
774
775         de::MovePtr<Buffer>                             m_imageBuffer;
776         const VkDeviceSize                              m_imageSizeBytes;
777         bool                                                    m_storeConstantValue;
778 };
779
780 deUint32 BaseTestInstance::getViewOffset(Context&                       context,
781                                                                                  const VkFormat         format,
782                                                                                  bool                           uniform)
783 {
784         if (m_minalign)
785         {
786                 if (!context.getTexelBufferAlignmentFeaturesEXT().texelBufferAlignment)
787                         return (deUint32)context.getDeviceProperties().limits.minTexelBufferOffsetAlignment;
788
789                 VkPhysicalDeviceTexelBufferAlignmentPropertiesEXT alignmentProperties;
790                 deMemset(&alignmentProperties, 0, sizeof(alignmentProperties));
791                 alignmentProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXEL_BUFFER_ALIGNMENT_PROPERTIES_EXT;
792
793                 VkPhysicalDeviceProperties2 properties2;
794                 deMemset(&properties2, 0, sizeof(properties2));
795                 properties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
796                 properties2.pNext = &alignmentProperties;
797
798                 context.getInstanceInterface().getPhysicalDeviceProperties2(context.getPhysicalDevice(), &properties2);
799
800                 VkBool32 singleTexelAlignment = uniform ? alignmentProperties.uniformTexelBufferOffsetSingleTexelAlignment :
801                                                                                                   alignmentProperties.storageTexelBufferOffsetSingleTexelAlignment;
802                 VkDeviceSize align = uniform ? alignmentProperties.uniformTexelBufferOffsetAlignmentBytes :
803                                                                            alignmentProperties.storageTexelBufferOffsetAlignmentBytes;
804
805                 VkDeviceSize texelSize = formatHasThreeComponents(format) ? tcu::getChannelSize(vk::mapVkFormat(format).type) : tcu::getPixelSize(vk::mapVkFormat(format));
806
807                 if (singleTexelAlignment)
808                         align = de::min(align, texelSize);
809
810                 return (deUint32)align;
811         }
812
813         return 0;
814 }
815
816 StoreTestInstance::StoreTestInstance (Context& context, const Texture& texture, const VkFormat format, const bool declareImageFormatInShader, const bool singleLayerBind, const bool minalign, const bool storeConstantValue)
817         : BaseTestInstance              (context, texture, format, declareImageFormatInShader, singleLayerBind, minalign, false)
818         , m_imageSizeBytes              (getImageSizeBytes(texture.size(), format))
819         , m_storeConstantValue  (storeConstantValue)
820 {
821         const DeviceInterface&  vk                      = m_context.getDeviceInterface();
822         const VkDevice                  device          = m_context.getDevice();
823         Allocator&                              allocator       = m_context.getDefaultAllocator();
824
825         // A helper buffer with enough space to hold the whole image. Usage flags accommodate all derived test instances.
826
827         m_imageBuffer = de::MovePtr<Buffer>(new Buffer(
828                 vk, device, allocator,
829                 makeBufferCreateInfo(m_imageSizeBytes + m_dstViewOffset, VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT),
830                 MemoryRequirement::HostVisible));
831 }
832
833 tcu::TestStatus StoreTestInstance::verifyResult (void)
834 {
835         const DeviceInterface&  vk              = m_context.getDeviceInterface();
836         const VkDevice                  device  = m_context.getDevice();
837
838         const tcu::IVec3 imageSize = m_texture.size();
839         const tcu::TextureLevel reference = generateReferenceImage(imageSize, m_format, m_storeConstantValue);
840
841         const Allocation& alloc = m_imageBuffer->getAllocation();
842         invalidateAlloc(vk, device, alloc);
843         const tcu::ConstPixelBufferAccess result(mapVkFormat(m_format), imageSize, (const char *)alloc.getHostPtr() + m_dstViewOffset);
844
845         if (comparePixelBuffers(m_context.getTestContext().getLog(), m_texture, m_format, reference.getAccess(), result))
846                 return tcu::TestStatus::pass("Passed");
847         else
848                 return tcu::TestStatus::fail("Image comparison failed");
849 }
850
851 //! Store test for images
852 class ImageStoreTestInstance : public StoreTestInstance
853 {
854 public:
855                                                                                 ImageStoreTestInstance                                  (Context&                               context,
856                                                                                                                                                                  const Texture&                 texture,
857                                                                                                                                                                  const VkFormat                 format,
858                                                                                                                                                                  const bool                             declareImageFormatInShader,
859                                                                                                                                                                  const bool                             singleLayerBind,
860                                                                                                                                                                  const bool                             minalign,
861                                                                                                                                                                  const bool                             storeConstantValue);
862
863 protected:
864         VkDescriptorSetLayout                           prepareDescriptors                                              (void);
865         void                                                            commandBeforeCompute                                    (const VkCommandBuffer  cmdBuffer);
866         void                                                            commandBetweenShaderInvocations                 (const VkCommandBuffer  cmdBuffer);
867         void                                                            commandAfterCompute                                             (const VkCommandBuffer  cmdBuffer);
868
869         void                                                            commandBindDescriptorsForLayer                  (const VkCommandBuffer  cmdBuffer,
870                                                                                                                                                                  const VkPipelineLayout pipelineLayout,
871                                                                                                                                                                  const int                              layerNdx);
872
873         de::MovePtr<Image>                                      m_image;
874         de::MovePtr<Buffer>                                     m_constantsBuffer;
875         const VkDeviceSize                                      m_constantsBufferChunkSizeBytes;
876         Move<VkDescriptorSetLayout>                     m_descriptorSetLayout;
877         Move<VkDescriptorPool>                          m_descriptorPool;
878         std::vector<SharedVkDescriptorSet>      m_allDescriptorSets;
879         std::vector<SharedVkImageView>          m_allImageViews;
880 };
881
882 ImageStoreTestInstance::ImageStoreTestInstance (Context&                context,
883                                                                                                 const Texture&  texture,
884                                                                                                 const VkFormat  format,
885                                                                                                 const bool              declareImageFormatInShader,
886                                                                                                 const bool              singleLayerBind,
887                                                                                                 const bool              minalign,
888                                                                                                 const bool              storeConstantValue)
889         : StoreTestInstance                                     (context, texture, format, declareImageFormatInShader, singleLayerBind, minalign, storeConstantValue)
890         , m_constantsBufferChunkSizeBytes       (getOptimalUniformBufferChunkSize(context.getInstanceInterface(), context.getPhysicalDevice(), sizeof(deUint32)))
891         , m_allDescriptorSets                           (texture.numLayers())
892         , m_allImageViews                                       (texture.numLayers())
893 {
894         const DeviceInterface&  vk                      = m_context.getDeviceInterface();
895         const VkDevice                  device          = m_context.getDevice();
896         Allocator&                              allocator       = m_context.getDefaultAllocator();
897
898         m_image = de::MovePtr<Image>(new Image(
899                 vk, device, allocator,
900                 makeImageCreateInfo(m_texture, m_format, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, 0u),
901                 MemoryRequirement::Any));
902
903         // This buffer will be used to pass constants to the shader
904
905         const int numLayers = m_texture.numLayers();
906         const VkDeviceSize constantsBufferSizeBytes = numLayers * m_constantsBufferChunkSizeBytes;
907         m_constantsBuffer = de::MovePtr<Buffer>(new Buffer(
908                 vk, device, allocator,
909                 makeBufferCreateInfo(constantsBufferSizeBytes, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT),
910                 MemoryRequirement::HostVisible));
911
912         {
913                 const Allocation& alloc = m_constantsBuffer->getAllocation();
914                 deUint8* const basePtr = static_cast<deUint8*>(alloc.getHostPtr());
915
916                 deMemset(alloc.getHostPtr(), 0, static_cast<size_t>(constantsBufferSizeBytes));
917
918                 for (int layerNdx = 0; layerNdx < numLayers; ++layerNdx)
919                 {
920                         deUint32* valuePtr = reinterpret_cast<deUint32*>(basePtr + layerNdx * m_constantsBufferChunkSizeBytes);
921                         *valuePtr = static_cast<deUint32>(layerNdx);
922                 }
923
924                 flushAlloc(vk, device, alloc);
925         }
926 }
927
928 VkDescriptorSetLayout ImageStoreTestInstance::prepareDescriptors (void)
929 {
930         const DeviceInterface&  vk              = m_context.getDeviceInterface();
931         const VkDevice                  device  = m_context.getDevice();
932
933         const int numLayers = m_texture.numLayers();
934         m_descriptorSetLayout = DescriptorSetLayoutBuilder()
935                 .addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT)
936                 .addSingleBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_COMPUTE_BIT)
937                 .build(vk, device);
938
939         m_descriptorPool = DescriptorPoolBuilder()
940                 .addType(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, numLayers)
941                 .addType(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, numLayers)
942                 .build(vk, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, numLayers);
943
944         if (m_singleLayerBind)
945         {
946                 for (int layerNdx = 0; layerNdx < numLayers; ++layerNdx)
947                 {
948                         m_allDescriptorSets[layerNdx]   = makeVkSharedPtr(makeDescriptorSet(vk, device, *m_descriptorPool, *m_descriptorSetLayout));
949                         m_allImageViews[layerNdx]               = makeVkSharedPtr(makeImageView(
950                                                                                                 vk, device, m_image->get(), mapImageViewType(getImageTypeForSingleLayer(m_texture.type())), m_format,
951                                                                                                 makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, layerNdx, 1u)));
952                 }
953         }
954         else // bind all layers at once
955         {
956                 m_allDescriptorSets[0] = makeVkSharedPtr(makeDescriptorSet(vk, device, *m_descriptorPool, *m_descriptorSetLayout));
957                 m_allImageViews[0] = makeVkSharedPtr(makeImageView(
958                                                                 vk, device, m_image->get(), mapImageViewType(m_texture.type()), m_format,
959                                                                 makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, numLayers)));
960         }
961
962         return *m_descriptorSetLayout;  // not passing the ownership
963 }
964
965 void ImageStoreTestInstance::commandBindDescriptorsForLayer (const VkCommandBuffer cmdBuffer, const VkPipelineLayout pipelineLayout, const int layerNdx)
966 {
967         const DeviceInterface&  vk              = m_context.getDeviceInterface();
968         const VkDevice                  device  = m_context.getDevice();
969
970         const VkDescriptorSet descriptorSet = **m_allDescriptorSets[layerNdx];
971         const VkImageView imageView = **m_allImageViews[layerNdx];
972
973         const VkDescriptorImageInfo descriptorImageInfo = makeDescriptorImageInfo(DE_NULL, imageView, VK_IMAGE_LAYOUT_GENERAL);
974
975         // Set the next chunk of the constants buffer. Each chunk begins with layer index that we've set before.
976         const VkDescriptorBufferInfo descriptorConstantsBufferInfo = makeDescriptorBufferInfo(
977                 m_constantsBuffer->get(), layerNdx*m_constantsBufferChunkSizeBytes, m_constantsBufferChunkSizeBytes);
978
979         DescriptorSetUpdateBuilder()
980                 .writeSingle(descriptorSet, DescriptorSetUpdateBuilder::Location::binding(0u), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &descriptorImageInfo)
981                 .writeSingle(descriptorSet, DescriptorSetUpdateBuilder::Location::binding(1u), VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, &descriptorConstantsBufferInfo)
982                 .update(vk, device);
983         vk.cmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0u, 1u, &descriptorSet, 0u, DE_NULL);
984 }
985
986 void ImageStoreTestInstance::commandBeforeCompute (const VkCommandBuffer cmdBuffer)
987 {
988         const DeviceInterface& vk = m_context.getDeviceInterface();
989
990         const VkImageSubresourceRange fullImageSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, m_texture.numLayers());
991         const VkImageMemoryBarrier setImageLayoutBarrier = makeImageMemoryBarrier(
992                 0u, VK_ACCESS_SHADER_WRITE_BIT,
993                 VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL,
994                 m_image->get(), fullImageSubresourceRange);
995
996         const VkDeviceSize constantsBufferSize = m_texture.numLayers() * m_constantsBufferChunkSizeBytes;
997         const VkBufferMemoryBarrier writeConstantsBarrier = makeBufferMemoryBarrier(
998                 VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT,
999                 m_constantsBuffer->get(), 0ull, constantsBufferSize);
1000
1001         vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &writeConstantsBarrier, 1, &setImageLayoutBarrier);
1002 }
1003
1004 void ImageStoreTestInstance::commandBetweenShaderInvocations (const VkCommandBuffer cmdBuffer)
1005 {
1006         commandImageWriteBarrierBetweenShaderInvocations(m_context, cmdBuffer, m_image->get(), m_texture);
1007 }
1008
1009 void ImageStoreTestInstance::commandAfterCompute (const VkCommandBuffer cmdBuffer)
1010 {
1011         commandCopyImageToBuffer(m_context, cmdBuffer, m_image->get(), m_imageBuffer->get(), m_imageSizeBytes, m_texture);
1012 }
1013
1014 //! Store test for buffers
1015 class BufferStoreTestInstance : public StoreTestInstance
1016 {
1017 public:
1018                                                                         BufferStoreTestInstance                                 (Context&                               context,
1019                                                                                                                                                          const Texture&                 texture,
1020                                                                                                                                                          const VkFormat                 format,
1021                                                                                                                                                          const bool                             declareImageFormatInShader,
1022                                                                                                                                                          const bool                             minalign,
1023                                                                                                                                                          const bool                             storeConstantValue);
1024
1025 protected:
1026         VkDescriptorSetLayout                   prepareDescriptors                                              (void);
1027         void                                                    commandAfterCompute                                             (const VkCommandBuffer  cmdBuffer);
1028
1029         void                                                    commandBindDescriptorsForLayer                  (const VkCommandBuffer  cmdBuffer,
1030                                                                                                                                                          const VkPipelineLayout pipelineLayout,
1031                                                                                                                                                          const int                              layerNdx);
1032
1033         Move<VkDescriptorSetLayout>             m_descriptorSetLayout;
1034         Move<VkDescriptorPool>                  m_descriptorPool;
1035         Move<VkDescriptorSet>                   m_descriptorSet;
1036         Move<VkBufferView>                              m_bufferView;
1037 };
1038
1039 BufferStoreTestInstance::BufferStoreTestInstance (Context&                      context,
1040                                                                                                   const Texture&        texture,
1041                                                                                                   const VkFormat        format,
1042                                                                                                   const bool            declareImageFormatInShader,
1043                                                                                                   const bool            minalign,
1044                                                                                                   const bool            storeConstantValue)
1045         : StoreTestInstance(context, texture, format, declareImageFormatInShader, false, minalign, storeConstantValue)
1046 {
1047 }
1048
1049 VkDescriptorSetLayout BufferStoreTestInstance::prepareDescriptors (void)
1050 {
1051         const DeviceInterface&  vk              = m_context.getDeviceInterface();
1052         const VkDevice                  device  = m_context.getDevice();
1053
1054         m_descriptorSetLayout = DescriptorSetLayoutBuilder()
1055                 .addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, VK_SHADER_STAGE_COMPUTE_BIT)
1056                 .build(vk, device);
1057
1058         m_descriptorPool = DescriptorPoolBuilder()
1059                 .addType(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER)
1060                 .build(vk, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u);
1061
1062         m_descriptorSet = makeDescriptorSet(vk, device, *m_descriptorPool, *m_descriptorSetLayout);
1063         m_bufferView = makeBufferView(vk, device, m_imageBuffer->get(), m_format, m_dstViewOffset, m_imageSizeBytes);
1064
1065         return *m_descriptorSetLayout;  // not passing the ownership
1066 }
1067
1068 void BufferStoreTestInstance::commandBindDescriptorsForLayer (const VkCommandBuffer cmdBuffer, const VkPipelineLayout pipelineLayout, const int layerNdx)
1069 {
1070         DE_ASSERT(layerNdx == 0);
1071         DE_UNREF(layerNdx);
1072
1073         const VkDevice                  device  = m_context.getDevice();
1074         const DeviceInterface&  vk              = m_context.getDeviceInterface();
1075
1076         DescriptorSetUpdateBuilder()
1077                 .writeSingle(*m_descriptorSet, DescriptorSetUpdateBuilder::Location::binding(0u), VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, &m_bufferView.get())
1078                 .update(vk, device);
1079         vk.cmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0u, 1u, &m_descriptorSet.get(), 0u, DE_NULL);
1080 }
1081
1082 void BufferStoreTestInstance::commandAfterCompute (const VkCommandBuffer cmdBuffer)
1083 {
1084         commandBufferWriteBarrierBeforeHostRead(m_context, cmdBuffer, m_imageBuffer->get(), m_imageSizeBytes + m_dstViewOffset);
1085 }
1086
1087 class LoadStoreTest : public TestCase
1088 {
1089 public:
1090         enum TestFlags
1091         {
1092                 FLAG_SINGLE_LAYER_BIND                          = 1 << 0,       //!< Run the shader multiple times, each time binding a different layer.
1093                 FLAG_RESTRICT_IMAGES                            = 1 << 1,       //!< If given, images in the shader will be qualified with "restrict".
1094                 FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER     = 1 << 2,       //!< Declare the format of the images in the shader code
1095                 FLAG_MINALIGN                                           = 1 << 3,       //!< Use bufferview offset that matches the advertised minimum alignment
1096                 FLAG_UNIFORM_TEXEL_BUFFER                       = 1 << 4,       //!< Load from a uniform texel buffer rather than a storage texel buffer
1097         };
1098
1099                                                         LoadStoreTest                   (tcu::TestContext&              testCtx,
1100                                                                                                          const std::string&             name,
1101                                                                                                          const std::string&             description,
1102                                                                                                          const Texture&                 texture,
1103                                                                                                          const VkFormat                 format,
1104                                                                                                          const VkFormat                 imageFormat,
1105                                                                                                          const deUint32                 flags = FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER,
1106                                                                                                          const deBool                   imageLoadStoreLodAMD = DE_FALSE);
1107
1108         virtual void                    checkSupport                    (Context&                               context) const;
1109         void                                    initPrograms                    (SourceCollections&             programCollection) const;
1110         TestInstance*                   createInstance                  (Context&                               context) const;
1111
1112 private:
1113         const Texture                   m_texture;
1114         const VkFormat                  m_format;                                               //!< Format as accessed in the shader
1115         const VkFormat                  m_imageFormat;                                  //!< Storage format
1116         const bool                              m_declareImageFormatInShader;   //!< Whether the shader will specify the format layout qualifier of the images
1117         const bool                              m_singleLayerBind;
1118         const bool                              m_restrictImages;
1119         const bool                              m_minalign;
1120         bool                                    m_bufferLoadUniform;
1121         const deBool                    m_imageLoadStoreLodAMD;
1122 };
1123
1124 LoadStoreTest::LoadStoreTest (tcu::TestContext&         testCtx,
1125                                                           const std::string&    name,
1126                                                           const std::string&    description,
1127                                                           const Texture&                texture,
1128                                                           const VkFormat                format,
1129                                                           const VkFormat                imageFormat,
1130                                                           const deUint32                flags,
1131                                                           const deBool                  imageLoadStoreLodAMD)
1132         : TestCase                                              (testCtx, name, description)
1133         , m_texture                                             (texture)
1134         , m_format                                              (format)
1135         , m_imageFormat                                 (imageFormat)
1136         , m_declareImageFormatInShader  ((flags & FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER) != 0)
1137         , m_singleLayerBind                             ((flags & FLAG_SINGLE_LAYER_BIND) != 0)
1138         , m_restrictImages                              ((flags & FLAG_RESTRICT_IMAGES) != 0)
1139         , m_minalign                                    ((flags & FLAG_MINALIGN) != 0)
1140         , m_bufferLoadUniform                   ((flags & FLAG_UNIFORM_TEXEL_BUFFER) != 0)
1141         , m_imageLoadStoreLodAMD                (imageLoadStoreLodAMD)
1142 {
1143         if (m_singleLayerBind)
1144                 DE_ASSERT(m_texture.numLayers() > 1);
1145
1146         DE_ASSERT(formatsAreCompatible(m_format, m_imageFormat));
1147 }
1148
1149 void LoadStoreTest::checkSupport (Context& context) const
1150 {
1151         const VkFormatProperties3 formatProperties (context.getFormatProperties(m_format));
1152         const VkFormatProperties3 imageFormatProperties (context.getFormatProperties(m_imageFormat));
1153
1154         if (m_imageLoadStoreLodAMD)
1155                 context.requireDeviceFunctionality("VK_AMD_shader_image_load_store_lod");
1156
1157         if (!m_bufferLoadUniform && !m_declareImageFormatInShader && !(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT_KHR))
1158                 TCU_THROW(NotSupportedError, "Format not supported for unformatted loads via storage images");
1159
1160         if (m_texture.type() == IMAGE_TYPE_CUBE_ARRAY)
1161                 context.requireDeviceCoreFeature(DEVICE_CORE_FEATURE_IMAGE_CUBE_ARRAY);
1162
1163         if ((m_texture.type() != IMAGE_TYPE_BUFFER) && !(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT))
1164                 TCU_THROW(NotSupportedError, "Format not supported for storage images");
1165
1166         if (m_texture.type() == IMAGE_TYPE_BUFFER && !(formatProperties.bufferFeatures & VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT))
1167                 TCU_THROW(NotSupportedError, "Format not supported for storage texel buffers");
1168
1169         if ((m_texture.type() != IMAGE_TYPE_BUFFER) && !(imageFormatProperties.optimalTilingFeatures))
1170                 TCU_THROW(NotSupportedError, "Underlying format not supported at all for images");
1171
1172         if ((m_texture.type() == IMAGE_TYPE_BUFFER) && !(imageFormatProperties.bufferFeatures))
1173                 TCU_THROW(NotSupportedError, "Underlying format not supported at all for buffers");
1174
1175         if (formatHasThreeComponents(m_format))
1176         {
1177                 // When the source buffer is three-component, the destination buffer is single-component.
1178                 VkFormat dstFormat = getSingleComponentFormat(m_format);
1179                 const VkFormatProperties3 dstFormatProperties (context.getFormatProperties(dstFormat));
1180
1181                 if (m_texture.type() == IMAGE_TYPE_BUFFER && !(dstFormatProperties.bufferFeatures & VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT))
1182                         TCU_THROW(NotSupportedError, "Format not supported for storage texel buffers");
1183         }
1184         else
1185                 if (m_texture.type() == IMAGE_TYPE_BUFFER && !(formatProperties.bufferFeatures & VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT))
1186                         TCU_THROW(NotSupportedError, "Format not supported for storage texel buffers");
1187
1188         if (m_bufferLoadUniform && m_texture.type() == IMAGE_TYPE_BUFFER && !(formatProperties.bufferFeatures & VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT))
1189                 TCU_THROW(NotSupportedError, "Format not supported for uniform texel buffers");
1190 }
1191
1192 void LoadStoreTest::initPrograms (SourceCollections& programCollection) const
1193 {
1194         const tcu::TextureFormat        texFormat                       = mapVkFormat(m_format);
1195         const int                                       dimension                       = (m_singleLayerBind ? m_texture.layerDimension() : m_texture.dimension());
1196         const ImageType                         usedImageType           = (m_singleLayerBind ? getImageTypeForSingleLayer(m_texture.type()) : m_texture.type());
1197         const std::string                       formatQualifierStr      = getShaderImageFormatQualifier(texFormat);
1198         const std::string                       uniformTypeStr          = getFormatPrefix(texFormat) + "textureBuffer";
1199         const std::string                       imageTypeStr            = getShaderImageType(texFormat, usedImageType);
1200         const std::string                       maybeRestrictStr        = (m_restrictImages ? "restrict " : "");
1201         const std::string                       xMax                            = de::toString(m_texture.size().x() - 1);
1202
1203         std::ostringstream src;
1204         src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
1205                 << "\n";
1206         if (!m_declareImageFormatInShader)
1207         {
1208                 src << "#extension GL_EXT_shader_image_load_formatted : require\n";
1209         }
1210
1211         if (m_imageLoadStoreLodAMD)
1212         {
1213                 src << "#extension GL_AMD_shader_image_load_store_lod : require\n";
1214         }
1215
1216         src << "layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;\n";
1217         if (m_bufferLoadUniform)
1218                 src << "layout (binding = 0) uniform " << uniformTypeStr << " u_image0;\n";
1219         else if (m_declareImageFormatInShader)
1220                 src << "layout (binding = 0, " << formatQualifierStr << ") " << maybeRestrictStr << "readonly uniform " << imageTypeStr << " u_image0;\n";
1221         else
1222                 src << "layout (binding = 0) " << maybeRestrictStr << "readonly uniform " << imageTypeStr << " u_image0;\n";
1223
1224         if (formatHasThreeComponents(m_format))
1225                 src << "layout (binding = 1) " << maybeRestrictStr << "writeonly uniform " << imageTypeStr << " u_image1;\n";
1226         else
1227                 src << "layout (binding = 1, " << formatQualifierStr << ") " << maybeRestrictStr << "writeonly uniform " << imageTypeStr << " u_image1;\n";
1228
1229         src << "\n"
1230                 << "void main (void)\n"
1231                 << "{\n";
1232         switch (dimension)
1233         {
1234         default: DE_ASSERT(0); // fallthrough
1235         case 1:
1236                 if (m_bufferLoadUniform)
1237                 {
1238                         // for three-component formats, the dst buffer is single-component and the shader
1239                         // expands the store into 3 component-wise stores.
1240                         std::string type = getFormatPrefix(texFormat) + "vec4";
1241                         src << "    int pos = int(gl_GlobalInvocationID.x);\n"
1242                                    "    " << type << " t = texelFetch(u_image0, " + xMax + "-pos);\n";
1243                         if (formatHasThreeComponents(m_format))
1244                         {
1245                                 src << "    imageStore(u_image1, 3*pos+0, " << type << "(t.x));\n";
1246                                 src << "    imageStore(u_image1, 3*pos+1, " << type << "(t.y));\n";
1247                                 src << "    imageStore(u_image1, 3*pos+2, " << type << "(t.z));\n";
1248                         }
1249                         else
1250                                 src << "    imageStore(u_image1, pos, t);\n";
1251                 }
1252                 else if (m_imageLoadStoreLodAMD)
1253                 {
1254                         src <<
1255                                 "    int pos = int(gl_GlobalInvocationID.x);\n";
1256
1257                         for (deInt32 levelNdx = 0; levelNdx < m_texture.numMipmapLevels(); levelNdx++)
1258                         {
1259                                 std::string xMaxSize = de::toString(deMax32(((m_texture.layerSize().x() >> levelNdx) - 1), 1u));
1260                                 src << "    imageStoreLodAMD(u_image1, pos, " + de::toString(levelNdx) + ", imageLoadLodAMD(u_image0, " + xMaxSize + "-pos, " + de::toString(levelNdx) + "));\n";
1261                         }
1262                 }
1263                 else
1264                 {
1265                         src <<
1266                                 "    int pos = int(gl_GlobalInvocationID.x);\n"
1267                                 "    imageStore(u_image1, pos, imageLoad(u_image0, " + xMax + "-pos));\n";
1268                 }
1269                 break;
1270         case 2:
1271                 if (m_imageLoadStoreLodAMD)
1272                 {
1273                         src << "    ivec2 pos = ivec2(gl_GlobalInvocationID.xy);\n";
1274
1275                         for (deInt32 levelNdx = 0; levelNdx < m_texture.numMipmapLevels(); levelNdx++)
1276                         {
1277                                 std::string xMaxSize = de::toString(deMax32(((m_texture.layerSize().x() >> levelNdx) - 1), 1u));
1278                                 src << "    imageStoreLodAMD(u_image1, pos, " + de::toString(levelNdx) + ", imageLoadLodAMD(u_image0, ivec2(" + xMaxSize + "-pos.x, pos.y), " + de::toString(levelNdx) + "));\n";
1279                         }
1280
1281                 }
1282                 else
1283                 {
1284                         src <<
1285                                 "    ivec2 pos = ivec2(gl_GlobalInvocationID.xy);\n"
1286                                 "    imageStore(u_image1, pos, imageLoad(u_image0, ivec2(" + xMax + "-pos.x, pos.y)));\n";
1287                 }
1288                 break;
1289         case 3:
1290                 if (m_imageLoadStoreLodAMD)
1291                 {
1292                         src << "    ivec3 pos = ivec3(gl_GlobalInvocationID);\n";
1293
1294                         for (deInt32 levelNdx = 0; levelNdx < m_texture.numMipmapLevels(); levelNdx++)
1295                         {
1296                                 std::string xMaxSize = de::toString(deMax32(((m_texture.layerSize().x() >> levelNdx) - 1), 1u));
1297                                 src << "    imageStoreLodAMD(u_image1, pos, " + de::toString(levelNdx) + ", imageLoadLodAMD(u_image0, ivec3(" + xMaxSize + "-pos.x, pos.y, pos.z), " + de::toString(levelNdx) + "));\n";
1298                         }
1299                 }
1300                 else
1301                 {
1302                         src <<
1303                                 "    ivec3 pos = ivec3(gl_GlobalInvocationID);\n"
1304                                 "    imageStore(u_image1, pos, imageLoad(u_image0, ivec3(" + xMax + "-pos.x, pos.y, pos.z)));\n";
1305                 }
1306                 break;
1307         }
1308         src << "}\n";
1309
1310         programCollection.glslSources.add("comp") << glu::ComputeSource(src.str());
1311 }
1312
1313 //! Load/store test base implementation
1314 class LoadStoreTestInstance : public BaseTestInstance
1315 {
1316 public:
1317                                                                         LoadStoreTestInstance                           (Context&                       context,
1318                                                                                                                                                  const Texture&         texture,
1319                                                                                                                                                  const VkFormat         format,
1320                                                                                                                                                  const VkFormat         imageFormat,
1321                                                                                                                                                  const bool                     declareImageFormatInShader,
1322                                                                                                                                                  const bool                     singleLayerBind,
1323                                                                                                                                                  const bool                     minalign,
1324                                                                                                                                                  const bool                     bufferLoadUniform);
1325
1326 protected:
1327         virtual Buffer*                                 getResultBuffer                                         (void) const = 0;       //!< Get the buffer that contains the result image
1328
1329         tcu::TestStatus                                 verifyResult                                            (void);
1330
1331         // Add empty implementations for functions that might be not needed
1332         void                                                    commandBeforeCompute                            (const VkCommandBuffer) {}
1333         void                                                    commandBetweenShaderInvocations         (const VkCommandBuffer) {}
1334         void                                                    commandAfterCompute                                     (const VkCommandBuffer) {}
1335
1336         de::MovePtr<Buffer>                             m_imageBuffer;          //!< Source data and helper buffer
1337         const VkDeviceSize                              m_imageSizeBytes;
1338         const VkFormat                                  m_imageFormat;          //!< Image format (for storage, may be different than texture format)
1339         tcu::TextureLevel                               m_referenceImage;       //!< Used as input data and later to verify result image
1340
1341         bool                                                    m_bufferLoadUniform;
1342         VkDescriptorType                                m_bufferLoadDescriptorType;
1343         VkBufferUsageFlagBits                   m_bufferLoadUsageBit;
1344 };
1345
1346 LoadStoreTestInstance::LoadStoreTestInstance (Context&                  context,
1347                                                                                           const Texture&        texture,
1348                                                                                           const VkFormat        format,
1349                                                                                           const VkFormat        imageFormat,
1350                                                                                           const bool            declareImageFormatInShader,
1351                                                                                           const bool            singleLayerBind,
1352                                                                                           const bool            minalign,
1353                                                                                           const bool            bufferLoadUniform)
1354         : BaseTestInstance              (context, texture, format, declareImageFormatInShader, singleLayerBind, minalign, bufferLoadUniform)
1355         , m_imageSizeBytes              (getImageSizeBytes(texture.size(), format))
1356         , m_imageFormat                 (imageFormat)
1357         , m_referenceImage              (generateReferenceImage(texture.size(), imageFormat, format))
1358         , m_bufferLoadUniform   (bufferLoadUniform)
1359 {
1360         const DeviceInterface&  vk                      = m_context.getDeviceInterface();
1361         const VkDevice                  device          = m_context.getDevice();
1362         Allocator&                              allocator       = m_context.getDefaultAllocator();
1363
1364         m_bufferLoadDescriptorType = m_bufferLoadUniform ? VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER : VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
1365         m_bufferLoadUsageBit = m_bufferLoadUniform ? VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT : VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT;
1366
1367         // A helper buffer with enough space to hold the whole image.
1368
1369         m_imageBuffer = de::MovePtr<Buffer>(new Buffer(
1370                 vk, device, allocator,
1371                 makeBufferCreateInfo(m_imageSizeBytes + m_srcViewOffset, m_bufferLoadUsageBit | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT),
1372                 MemoryRequirement::HostVisible));
1373
1374         // Copy reference data to buffer for subsequent upload to image.
1375
1376         const Allocation& alloc = m_imageBuffer->getAllocation();
1377         deMemcpy((char *)alloc.getHostPtr() + m_srcViewOffset, m_referenceImage.getAccess().getDataPtr(), static_cast<size_t>(m_imageSizeBytes));
1378         flushAlloc(vk, device, alloc);
1379 }
1380
1381 tcu::TestStatus LoadStoreTestInstance::verifyResult     (void)
1382 {
1383         const DeviceInterface&  vk              = m_context.getDeviceInterface();
1384         const VkDevice                  device  = m_context.getDevice();
1385
1386         // Apply the same transformation as done in the shader
1387         const tcu::PixelBufferAccess reference = m_referenceImage.getAccess();
1388         flipHorizontally(reference);
1389
1390         const Allocation& alloc = getResultBuffer()->getAllocation();
1391         invalidateAlloc(vk, device, alloc);
1392         const tcu::ConstPixelBufferAccess result(mapVkFormat(m_imageFormat), m_texture.size(), (const char *)alloc.getHostPtr() + m_dstViewOffset);
1393
1394         if (comparePixelBuffers(m_context.getTestContext().getLog(), m_texture, m_imageFormat, reference, result))
1395                 return tcu::TestStatus::pass("Passed");
1396         else
1397                 return tcu::TestStatus::fail("Image comparison failed");
1398 }
1399
1400 //! Load/store test for images
1401 class ImageLoadStoreTestInstance : public LoadStoreTestInstance
1402 {
1403 public:
1404                                                                                 ImageLoadStoreTestInstance                      (Context&                               context,
1405                                                                                                                                                          const Texture&                 texture,
1406                                                                                                                                                          const VkFormat                 format,
1407                                                                                                                                                          const VkFormat                 imageFormat,
1408                                                                                                                                                          const bool                             declareImageFormatInShader,
1409                                                                                                                                                          const bool                             singleLayerBind,
1410                                                                                                                                                          const bool                             minalign,
1411                                                                                                                                                          const bool                             bufferLoadUniform);
1412
1413 protected:
1414         VkDescriptorSetLayout                           prepareDescriptors                                      (void);
1415         void                                                            commandBeforeCompute                            (const VkCommandBuffer  cmdBuffer);
1416         void                                                            commandBetweenShaderInvocations         (const VkCommandBuffer  cmdBuffer);
1417         void                                                            commandAfterCompute                                     (const VkCommandBuffer  cmdBuffer);
1418
1419         void                                                            commandBindDescriptorsForLayer          (const VkCommandBuffer  cmdBuffer,
1420                                                                                                                                                          const VkPipelineLayout pipelineLayout,
1421                                                                                                                                                          const int                              layerNdx);
1422
1423         Buffer*                                                         getResultBuffer                                         (void) const { return m_imageBuffer.get(); }
1424
1425         de::MovePtr<Image>                                      m_imageSrc;
1426         de::MovePtr<Image>                                      m_imageDst;
1427         Move<VkDescriptorSetLayout>                     m_descriptorSetLayout;
1428         Move<VkDescriptorPool>                          m_descriptorPool;
1429         std::vector<SharedVkDescriptorSet> m_allDescriptorSets;
1430         std::vector<SharedVkImageView>     m_allSrcImageViews;
1431         std::vector<SharedVkImageView>     m_allDstImageViews;
1432 };
1433
1434 ImageLoadStoreTestInstance::ImageLoadStoreTestInstance (Context&                context,
1435                                                                                                                 const Texture&  texture,
1436                                                                                                                 const VkFormat  format,
1437                                                                                                                 const VkFormat  imageFormat,
1438                                                                                                                 const bool              declareImageFormatInShader,
1439                                                                                                                 const bool              singleLayerBind,
1440                                                                                                                 const bool              minalign,
1441                                                                                                                 const bool              bufferLoadUniform)
1442         : LoadStoreTestInstance (context, texture, format, imageFormat, declareImageFormatInShader, singleLayerBind, minalign, bufferLoadUniform)
1443         , m_allDescriptorSets   (texture.numLayers())
1444         , m_allSrcImageViews    (texture.numLayers())
1445         , m_allDstImageViews    (texture.numLayers())
1446 {
1447         const DeviceInterface&          vk                                      = m_context.getDeviceInterface();
1448         const VkDevice                          device                          = m_context.getDevice();
1449         Allocator&                                      allocator                       = m_context.getDefaultAllocator();
1450         const VkImageCreateFlags        imageFlags                      = (m_format == m_imageFormat ? 0u : (VkImageCreateFlags)VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT);
1451
1452         m_imageSrc = de::MovePtr<Image>(new Image(
1453                 vk, device, allocator,
1454                 makeImageCreateInfo(m_texture, m_imageFormat, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, imageFlags),
1455                 MemoryRequirement::Any));
1456
1457         m_imageDst = de::MovePtr<Image>(new Image(
1458                 vk, device, allocator,
1459                 makeImageCreateInfo(m_texture, m_imageFormat, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, imageFlags),
1460                 MemoryRequirement::Any));
1461 }
1462
1463 VkDescriptorSetLayout ImageLoadStoreTestInstance::prepareDescriptors (void)
1464 {
1465         const VkDevice                  device  = m_context.getDevice();
1466         const DeviceInterface&  vk              = m_context.getDeviceInterface();
1467
1468         const int numLayers = m_texture.numLayers();
1469         m_descriptorSetLayout = DescriptorSetLayoutBuilder()
1470                 .addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT)
1471                 .addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT)
1472                 .build(vk, device);
1473
1474         m_descriptorPool = DescriptorPoolBuilder()
1475                 .addType(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, numLayers)
1476                 .addType(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, numLayers)
1477                 .build(vk, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, numLayers);
1478
1479         if (m_singleLayerBind)
1480         {
1481                 for (int layerNdx = 0; layerNdx < numLayers; ++layerNdx)
1482                 {
1483                         const VkImageViewType viewType = mapImageViewType(getImageTypeForSingleLayer(m_texture.type()));
1484                         const VkImageSubresourceRange subresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, layerNdx, 1u);
1485
1486                         m_allDescriptorSets[layerNdx] = makeVkSharedPtr(makeDescriptorSet(vk, device, *m_descriptorPool, *m_descriptorSetLayout));
1487                         m_allSrcImageViews[layerNdx]  = makeVkSharedPtr(makeImageView(vk, device, m_imageSrc->get(), viewType, m_format, subresourceRange));
1488                         m_allDstImageViews[layerNdx]  = makeVkSharedPtr(makeImageView(vk, device, m_imageDst->get(), viewType, m_format, subresourceRange));
1489                 }
1490         }
1491         else // bind all layers at once
1492         {
1493                 const VkImageViewType viewType = mapImageViewType(m_texture.type());
1494                 const VkImageSubresourceRange subresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, numLayers);
1495
1496                 m_allDescriptorSets[0] = makeVkSharedPtr(makeDescriptorSet(vk, device, *m_descriptorPool, *m_descriptorSetLayout));
1497                 m_allSrcImageViews[0]  = makeVkSharedPtr(makeImageView(vk, device, m_imageSrc->get(), viewType, m_format, subresourceRange));
1498                 m_allDstImageViews[0]  = makeVkSharedPtr(makeImageView(vk, device, m_imageDst->get(), viewType, m_format, subresourceRange));
1499         }
1500
1501         return *m_descriptorSetLayout;  // not passing the ownership
1502 }
1503
1504 void ImageLoadStoreTestInstance::commandBindDescriptorsForLayer (const VkCommandBuffer cmdBuffer, const VkPipelineLayout pipelineLayout, const int layerNdx)
1505 {
1506         const VkDevice                  device  = m_context.getDevice();
1507         const DeviceInterface&  vk              = m_context.getDeviceInterface();
1508
1509         const VkDescriptorSet descriptorSet = **m_allDescriptorSets[layerNdx];
1510         const VkImageView         srcImageView  = **m_allSrcImageViews[layerNdx];
1511         const VkImageView         dstImageView  = **m_allDstImageViews[layerNdx];
1512
1513         const VkDescriptorImageInfo descriptorSrcImageInfo = makeDescriptorImageInfo(DE_NULL, srcImageView, VK_IMAGE_LAYOUT_GENERAL);
1514         const VkDescriptorImageInfo descriptorDstImageInfo = makeDescriptorImageInfo(DE_NULL, dstImageView, VK_IMAGE_LAYOUT_GENERAL);
1515
1516         DescriptorSetUpdateBuilder()
1517                 .writeSingle(descriptorSet, DescriptorSetUpdateBuilder::Location::binding(0u), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &descriptorSrcImageInfo)
1518                 .writeSingle(descriptorSet, DescriptorSetUpdateBuilder::Location::binding(1u), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &descriptorDstImageInfo)
1519                 .update(vk, device);
1520         vk.cmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0u, 1u, &descriptorSet, 0u, DE_NULL);
1521 }
1522
1523 void ImageLoadStoreTestInstance::commandBeforeCompute (const VkCommandBuffer cmdBuffer)
1524 {
1525         const DeviceInterface& vk = m_context.getDeviceInterface();
1526
1527         const VkImageSubresourceRange fullImageSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, m_texture.numLayers());
1528         {
1529                 const VkImageMemoryBarrier preCopyImageBarriers[] =
1530                 {
1531                         makeImageMemoryBarrier(
1532                                 0u, VK_ACCESS_TRANSFER_WRITE_BIT,
1533                                 VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1534                                 m_imageSrc->get(), fullImageSubresourceRange),
1535                         makeImageMemoryBarrier(
1536                                 0u, VK_ACCESS_SHADER_WRITE_BIT,
1537                                 VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL,
1538                                 m_imageDst->get(), fullImageSubresourceRange)
1539                 };
1540
1541                 const VkBufferMemoryBarrier barrierFlushHostWriteBeforeCopy = makeBufferMemoryBarrier(
1542                         VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT,
1543                         m_imageBuffer->get(), 0ull, m_imageSizeBytes + m_srcViewOffset);
1544
1545                 vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT,
1546                         (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &barrierFlushHostWriteBeforeCopy, DE_LENGTH_OF_ARRAY(preCopyImageBarriers), preCopyImageBarriers);
1547         }
1548         {
1549                 const VkImageMemoryBarrier barrierAfterCopy = makeImageMemoryBarrier(
1550                         VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT,
1551                         VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL,
1552                         m_imageSrc->get(), fullImageSubresourceRange);
1553
1554                 const VkBufferImageCopy copyRegion = makeBufferImageCopy(m_texture);
1555
1556                 vk.cmdCopyBufferToImage(cmdBuffer, m_imageBuffer->get(), m_imageSrc->get(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1u, &copyRegion);
1557                 vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 0, (const VkBufferMemoryBarrier*)DE_NULL, 1, &barrierAfterCopy);
1558         }
1559 }
1560
1561 void ImageLoadStoreTestInstance::commandBetweenShaderInvocations (const VkCommandBuffer cmdBuffer)
1562 {
1563         commandImageWriteBarrierBetweenShaderInvocations(m_context, cmdBuffer, m_imageDst->get(), m_texture);
1564 }
1565
1566 void ImageLoadStoreTestInstance::commandAfterCompute (const VkCommandBuffer cmdBuffer)
1567 {
1568         commandCopyImageToBuffer(m_context, cmdBuffer, m_imageDst->get(), m_imageBuffer->get(), m_imageSizeBytes, m_texture);
1569 }
1570
1571 //! Load/store Lod AMD test for images
1572 class ImageLoadStoreLodAMDTestInstance : public BaseTestInstance
1573 {
1574 public:
1575                                                                                 ImageLoadStoreLodAMDTestInstance        (Context&                               context,
1576                                                                                                                                                          const Texture&                 texture,
1577                                                                                                                                                          const VkFormat                 format,
1578                                                                                                                                                          const VkFormat                 imageFormat,
1579                                                                                                                                                          const bool                             declareImageFormatInShader,
1580                                                                                                                                                          const bool                             singleLayerBind,
1581                                                                                                                                                          const bool                             minalign,
1582                                                                                                                                                          const bool                             bufferLoadUniform);
1583
1584 protected:
1585         VkDescriptorSetLayout                           prepareDescriptors                                      (void);
1586         void                                                            commandBeforeCompute                            (const VkCommandBuffer  cmdBuffer);
1587         void                                                            commandBetweenShaderInvocations         (const VkCommandBuffer  cmdBuffer);
1588         void                                                            commandAfterCompute                                     (const VkCommandBuffer  cmdBuffer);
1589
1590         void                                                            commandBindDescriptorsForLayer          (const VkCommandBuffer  cmdBuffer,
1591                                                                                                                                                          const VkPipelineLayout pipelineLayout,
1592                                                                                                                                                          const int                              layerNdx);
1593
1594         Buffer*                                                         getResultBuffer                                         (void) const { return m_imageBuffer.get(); }
1595         tcu::TestStatus                                         verifyResult                                            (void);
1596
1597         de::MovePtr<Buffer>                                     m_imageBuffer;          //!< Source data and helper buffer
1598         const VkDeviceSize                                      m_imageSizeBytes;
1599         const VkFormat                                          m_imageFormat;          //!< Image format (for storage, may be different than texture format)
1600         std::vector<tcu::TextureLevel>          m_referenceImages;      //!< Used as input data and later to verify result image
1601
1602         bool                                                            m_bufferLoadUniform;
1603         VkDescriptorType                                        m_bufferLoadDescriptorType;
1604         VkBufferUsageFlagBits                           m_bufferLoadUsageBit;
1605
1606         de::MovePtr<Image>                                      m_imageSrc;
1607         de::MovePtr<Image>                                      m_imageDst;
1608         Move<VkDescriptorSetLayout>                     m_descriptorSetLayout;
1609         Move<VkDescriptorPool>                          m_descriptorPool;
1610         std::vector<SharedVkDescriptorSet>      m_allDescriptorSets;
1611         std::vector<SharedVkImageView>          m_allSrcImageViews;
1612         std::vector<SharedVkImageView>          m_allDstImageViews;
1613
1614 };
1615
1616 ImageLoadStoreLodAMDTestInstance::ImageLoadStoreLodAMDTestInstance (Context&            context,
1617                                                                                                                                         const Texture&  texture,
1618                                                                                                                                         const VkFormat  format,
1619                                                                                                                                         const VkFormat  imageFormat,
1620                                                                                                                                         const bool              declareImageFormatInShader,
1621                                                                                                                                         const bool              singleLayerBind,
1622                                                                                                                                         const bool              minalign,
1623                                                                                                                                         const bool              bufferLoadUniform)
1624         : BaseTestInstance                      (context, texture, format, declareImageFormatInShader, singleLayerBind, minalign, bufferLoadUniform)
1625         , m_imageSizeBytes                      (getMipmapImageTotalSizeBytes(texture, format))
1626         , m_imageFormat                         (imageFormat)
1627         , m_bufferLoadUniform           (bufferLoadUniform)
1628         , m_allDescriptorSets           (texture.numLayers())
1629         , m_allSrcImageViews            (texture.numLayers())
1630         , m_allDstImageViews            (texture.numLayers())
1631 {
1632         const DeviceInterface&          vk                                      = m_context.getDeviceInterface();
1633         const VkDevice                          device                          = m_context.getDevice();
1634         Allocator&                                      allocator                       = m_context.getDefaultAllocator();
1635         const VkImageCreateFlags        imageFlags                      = (m_format == m_imageFormat ? 0u : (VkImageCreateFlags)VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT);
1636
1637         const VkSampleCountFlagBits samples = static_cast<VkSampleCountFlagBits>(m_texture.numSamples());       // integer and bit mask are aligned, so we can cast like this
1638
1639         for (deInt32 levelNdx = 0; levelNdx < m_texture.numMipmapLevels(); levelNdx++)
1640         {
1641                 tcu::TextureLevel referenceImage = generateReferenceImage(texture.size(levelNdx), imageFormat, format);
1642                 m_referenceImages.push_back(referenceImage);
1643         }
1644
1645         m_bufferLoadDescriptorType = m_bufferLoadUniform ? VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER : VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
1646         m_bufferLoadUsageBit = m_bufferLoadUniform ? VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT : VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT;
1647
1648         // A helper buffer with enough space to hold the whole image.
1649         m_imageBuffer = de::MovePtr<Buffer>(new Buffer(
1650                                                                                                    vk, device, allocator,
1651                                                                                                    makeBufferCreateInfo(m_imageSizeBytes + m_srcViewOffset, m_bufferLoadUsageBit | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT),
1652                                                                                                    MemoryRequirement::HostVisible));
1653
1654         // Copy reference data to buffer for subsequent upload to image.
1655         {
1656                 const Allocation& alloc = m_imageBuffer->getAllocation();
1657                 VkDeviceSize bufferOffset = 0u;
1658                 for (deInt32 levelNdx = 0; levelNdx < m_texture.numMipmapLevels(); levelNdx++)
1659                 {
1660                         deMemcpy((char *)alloc.getHostPtr() + m_srcViewOffset + bufferOffset, m_referenceImages[levelNdx].getAccess().getDataPtr(), static_cast<size_t>(getMipmapLevelImageSizeBytes(m_texture, m_imageFormat, levelNdx)));
1661                         bufferOffset += getMipmapLevelImageSizeBytes(m_texture, m_imageFormat, levelNdx);
1662                 }
1663                 flushAlloc(vk, device, alloc);
1664         }
1665
1666         {
1667                 const VkImageCreateInfo imageParamsSrc =
1668                 {
1669                         VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,                                                                                                                            // VkStructureType                      sType;
1670                         DE_NULL,                                                                                                                                                                                        // const void*                          pNext;
1671                         (isCube(m_texture) ? (VkImageCreateFlags)VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT : 0u) | imageFlags,        // VkImageCreateFlags           flags;
1672                         mapImageType(m_texture.type()),                                                                                                                                         // VkImageType                          imageType;
1673                         m_imageFormat,                                                                                                                                                                          // VkFormat                                     format;
1674                         makeExtent3D(m_texture.layerSize()),                                                                                                                            // VkExtent3D                           extent;
1675                         (deUint32)m_texture.numMipmapLevels(),                                                                                                                          // deUint32                                     mipLevels;
1676                         (deUint32)m_texture.numLayers(),                                                                                                                                        // deUint32                                     arrayLayers;
1677                         samples,                                                                                                                                                                                        // VkSampleCountFlagBits        samples;
1678                         VK_IMAGE_TILING_OPTIMAL,                                                                                                                                                        // VkImageTiling                        tiling;
1679                         VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,                                                                           // VkImageUsageFlags            usage;
1680                         VK_SHARING_MODE_EXCLUSIVE,                                                                                                                                                      // VkSharingMode                        sharingMode;
1681                         0u,                                                                                                                                                                                                     // deUint32                                     queueFamilyIndexCount;
1682                         DE_NULL,                                                                                                                                                                                        // const deUint32*                      pQueueFamilyIndices;
1683                         VK_IMAGE_LAYOUT_UNDEFINED,                                                                                                                                                      // VkImageLayout                        initialLayout;
1684                 };
1685
1686                 m_imageSrc = de::MovePtr<Image>(new Image(
1687                                                                                                   vk, device, allocator,
1688                                                                                                   imageParamsSrc,
1689                                                                                                   MemoryRequirement::Any));
1690         }
1691
1692         {
1693                 const VkImageCreateInfo imageParamsDst =
1694                 {
1695                         VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,                                                                                                                            // VkStructureType                      sType;
1696                         DE_NULL,                                                                                                                                                                                        // const void*                          pNext;
1697                         (isCube(m_texture) ? (VkImageCreateFlags)VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT : 0u) | imageFlags,        // VkImageCreateFlags           flags;
1698                         mapImageType(m_texture.type()),                                                                                                                                         // VkImageType                          imageType;
1699                         m_imageFormat,                                                                                                                                                                          // VkFormat                                     format;
1700                         makeExtent3D(m_texture.layerSize()),                                                                                                                            // VkExtent3D                           extent;
1701                         (deUint32)m_texture.numMipmapLevels(),                                                                                                                          // deUint32                                     mipLevels;
1702                         (deUint32)m_texture.numLayers(),                                                                                                                                        // deUint32                                     arrayLayers;
1703                         samples,                                                                                                                                                                                        // VkSampleCountFlagBits        samples;
1704                         VK_IMAGE_TILING_OPTIMAL,                                                                                                                                                        // VkImageTiling                        tiling;
1705                         VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT,                                                                           // VkImageUsageFlags            usage;
1706                         VK_SHARING_MODE_EXCLUSIVE,                                                                                                                                                      // VkSharingMode                        sharingMode;
1707                         0u,                                                                                                                                                                                                     // deUint32                                     queueFamilyIndexCount;
1708                         DE_NULL,                                                                                                                                                                                        // const deUint32*                      pQueueFamilyIndices;
1709                         VK_IMAGE_LAYOUT_UNDEFINED,                                                                                                                                                      // VkImageLayout                        initialLayout;
1710                 };
1711
1712                 m_imageDst = de::MovePtr<Image>(new Image(
1713                                                                                                   vk, device, allocator,
1714                                                                                                   imageParamsDst,
1715                                                                                                   MemoryRequirement::Any));
1716         }
1717 }
1718
1719 tcu::TestStatus ImageLoadStoreLodAMDTestInstance::verifyResult  (void)
1720 {
1721         const DeviceInterface&  vk              = m_context.getDeviceInterface();
1722         const VkDevice                  device  = m_context.getDevice();
1723
1724         const Allocation& alloc = getResultBuffer()->getAllocation();
1725         invalidateAlloc(vk, device, alloc);
1726
1727     VkDeviceSize bufferOffset = 0;
1728         for (deInt32 levelNdx = 0; levelNdx < m_texture.numMipmapLevels(); levelNdx++)
1729         {
1730                 // Apply the same transformation as done in the shader
1731                 const tcu::PixelBufferAccess reference = m_referenceImages[levelNdx].getAccess();
1732                 flipHorizontally(reference);
1733
1734                 const tcu::ConstPixelBufferAccess result(mapVkFormat(m_imageFormat), m_texture.size(levelNdx), (const char *)alloc.getHostPtr() + m_dstViewOffset + bufferOffset);
1735
1736                 if (!comparePixelBuffers(m_context.getTestContext().getLog(), m_texture, m_imageFormat, reference, result, levelNdx))
1737                 {
1738                         std::ostringstream errorMessage;
1739                         errorMessage << "Image Level " << levelNdx << " comparison failed";
1740                         return tcu::TestStatus::fail(errorMessage.str());
1741                 }
1742                 bufferOffset += getMipmapLevelImageSizeBytes(m_texture, m_imageFormat, levelNdx);
1743         }
1744
1745         return tcu::TestStatus::pass("Passed");
1746 }
1747
1748 VkDescriptorSetLayout ImageLoadStoreLodAMDTestInstance::prepareDescriptors (void)
1749 {
1750         const VkDevice                  device  = m_context.getDevice();
1751         const DeviceInterface&  vk              = m_context.getDeviceInterface();
1752
1753         const int numLayers = m_texture.numLayers();
1754         m_descriptorSetLayout = DescriptorSetLayoutBuilder()
1755                 .addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT)
1756                 .addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT)
1757                 .build(vk, device);
1758
1759         m_descriptorPool = DescriptorPoolBuilder()
1760                 .addType(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, numLayers)
1761                 .addType(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, numLayers)
1762                 .build(vk, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, numLayers);
1763
1764         if (m_singleLayerBind)
1765         {
1766                 for (int layerNdx = 0; layerNdx < numLayers; ++layerNdx)
1767                 {
1768                         const VkImageViewType viewType = mapImageViewType(getImageTypeForSingleLayer(m_texture.type()));
1769                         const VkImageSubresourceRange subresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, m_texture.numMipmapLevels(), layerNdx, 1u);
1770
1771                         m_allDescriptorSets[layerNdx] = makeVkSharedPtr(makeDescriptorSet(vk, device, *m_descriptorPool, *m_descriptorSetLayout));
1772                         m_allSrcImageViews[layerNdx]  = makeVkSharedPtr(makeImageView(vk, device, m_imageSrc->get(), viewType, m_format, subresourceRange));
1773                         m_allDstImageViews[layerNdx]  = makeVkSharedPtr(makeImageView(vk, device, m_imageDst->get(), viewType, m_format, subresourceRange));
1774                 }
1775         }
1776         else // bind all layers at once
1777         {
1778                 const VkImageViewType viewType = mapImageViewType(m_texture.type());
1779                 const VkImageSubresourceRange subresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, m_texture.numMipmapLevels(), 0u, numLayers);
1780
1781                 m_allDescriptorSets[0] = makeVkSharedPtr(makeDescriptorSet(vk, device, *m_descriptorPool, *m_descriptorSetLayout));
1782                 m_allSrcImageViews[0]  = makeVkSharedPtr(makeImageView(vk, device, m_imageSrc->get(), viewType, m_format, subresourceRange));
1783                 m_allDstImageViews[0]  = makeVkSharedPtr(makeImageView(vk, device, m_imageDst->get(), viewType, m_format, subresourceRange));
1784         }
1785
1786         return *m_descriptorSetLayout;  // not passing the ownership
1787 }
1788
1789 void ImageLoadStoreLodAMDTestInstance::commandBindDescriptorsForLayer (const VkCommandBuffer cmdBuffer, const VkPipelineLayout pipelineLayout, const int layerNdx)
1790 {
1791         const VkDevice                  device  = m_context.getDevice();
1792         const DeviceInterface&  vk              = m_context.getDeviceInterface();
1793
1794         const VkDescriptorSet descriptorSet = **m_allDescriptorSets[layerNdx];
1795         const VkImageView         srcImageView  = **m_allSrcImageViews[layerNdx];
1796         const VkImageView         dstImageView  = **m_allDstImageViews[layerNdx];
1797
1798         const VkDescriptorImageInfo descriptorSrcImageInfo = makeDescriptorImageInfo(DE_NULL, srcImageView, VK_IMAGE_LAYOUT_GENERAL);
1799         const VkDescriptorImageInfo descriptorDstImageInfo = makeDescriptorImageInfo(DE_NULL, dstImageView, VK_IMAGE_LAYOUT_GENERAL);
1800
1801         DescriptorSetUpdateBuilder()
1802                 .writeSingle(descriptorSet, DescriptorSetUpdateBuilder::Location::binding(0u), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &descriptorSrcImageInfo)
1803                 .writeSingle(descriptorSet, DescriptorSetUpdateBuilder::Location::binding(1u), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &descriptorDstImageInfo)
1804                 .update(vk, device);
1805         vk.cmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0u, 1u, &descriptorSet, 0u, DE_NULL);
1806 }
1807
1808 void ImageLoadStoreLodAMDTestInstance::commandBeforeCompute (const VkCommandBuffer cmdBuffer)
1809 {
1810         const DeviceInterface& vk = m_context.getDeviceInterface();
1811         const VkImageSubresourceRange fullImageSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, m_texture.numMipmapLevels(), 0u, m_texture.numLayers());
1812         {
1813                 const VkImageMemoryBarrier preCopyImageBarriers[] =
1814                 {
1815                         makeImageMemoryBarrier(
1816                                 0u, VK_ACCESS_TRANSFER_WRITE_BIT,
1817                                 VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1818                                 m_imageSrc->get(), fullImageSubresourceRange),
1819                         makeImageMemoryBarrier(
1820                                 0u, VK_ACCESS_SHADER_WRITE_BIT,
1821                                 VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL,
1822                                 m_imageDst->get(), fullImageSubresourceRange)
1823                 };
1824
1825                 const VkBufferMemoryBarrier barrierFlushHostWriteBeforeCopy = makeBufferMemoryBarrier(
1826                         VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT,
1827                         m_imageBuffer->get(), 0ull, m_imageSizeBytes + m_srcViewOffset);
1828
1829                 vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT,
1830                         (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &barrierFlushHostWriteBeforeCopy, DE_LENGTH_OF_ARRAY(preCopyImageBarriers), preCopyImageBarriers);
1831         }
1832         {
1833                 const VkImageMemoryBarrier barrierAfterCopy = makeImageMemoryBarrier(
1834                         VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT,
1835                         VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL,
1836                         m_imageSrc->get(), fullImageSubresourceRange);
1837
1838                 std::vector<VkBufferImageCopy> copyRegions;
1839                 VkDeviceSize bufferOffset = 0u;
1840                 for (deInt32 levelNdx = 0; levelNdx < m_texture.numMipmapLevels(); levelNdx++)
1841                 {
1842                         const VkBufferImageCopy copyParams =
1843                         {
1844                                 bufferOffset,                                                                                                                                                                   //      VkDeviceSize                            bufferOffset;
1845                                 0u,                                                                                                                                                                                             //      deUint32                                        bufferRowLength;
1846                                 0u,                                                                                                                                                                                             //      deUint32                                        bufferImageHeight;
1847                                 makeImageSubresourceLayers(VK_IMAGE_ASPECT_COLOR_BIT, levelNdx, 0u, m_texture.numLayers()),             //      VkImageSubresourceLayers        imageSubresource;
1848                                 makeOffset3D(0, 0, 0),                                                                                                                                                  //      VkOffset3D                                      imageOffset;
1849                                 makeExtent3D(m_texture.layerSize(levelNdx)),                                                                                                    //      VkExtent3D                                      imageExtent;
1850                         };
1851                         copyRegions.push_back(copyParams);
1852                         bufferOffset += getMipmapLevelImageSizeBytes(m_texture, m_imageFormat, levelNdx);
1853                 }
1854
1855                 vk.cmdCopyBufferToImage(cmdBuffer, m_imageBuffer->get(), m_imageSrc->get(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, (deUint32) copyRegions.size(), copyRegions.data());
1856                 vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 0, (const VkBufferMemoryBarrier*)DE_NULL, 1, &barrierAfterCopy);
1857         }
1858 }
1859
1860 void ImageLoadStoreLodAMDTestInstance::commandBetweenShaderInvocations (const VkCommandBuffer cmdBuffer)
1861 {
1862         commandImageWriteBarrierBetweenShaderInvocations(m_context, cmdBuffer, m_imageDst->get(), m_texture);
1863 }
1864
1865 void ImageLoadStoreLodAMDTestInstance::commandAfterCompute (const VkCommandBuffer cmdBuffer)
1866 {
1867         commandCopyMipmapImageToBuffer(m_context, cmdBuffer, m_imageDst->get(), m_imageFormat, m_imageBuffer->get(), m_imageSizeBytes, m_texture);
1868 }
1869
1870 //! Load/store test for buffers
1871 class BufferLoadStoreTestInstance : public LoadStoreTestInstance
1872 {
1873 public:
1874                                                                         BufferLoadStoreTestInstance             (Context&                               context,
1875                                                                                                                                          const Texture&                 texture,
1876                                                                                                                                          const VkFormat                 format,
1877                                                                                                                                          const VkFormat                 imageFormat,
1878                                                                                                                                          const bool                             declareImageFormatInShader,
1879                                                                                                                                          const bool                             minalign,
1880                                                                                                                                          const bool                             bufferLoadUniform);
1881
1882 protected:
1883         VkDescriptorSetLayout                   prepareDescriptors                              (void);
1884         void                                                    commandAfterCompute                             (const VkCommandBuffer  cmdBuffer);
1885
1886         void                                                    commandBindDescriptorsForLayer  (const VkCommandBuffer  cmdBuffer,
1887                                                                                                                                          const VkPipelineLayout pipelineLayout,
1888                                                                                                                                          const int                              layerNdx);
1889
1890         Buffer*                                                 getResultBuffer                                 (void) const { return m_imageBufferDst.get(); }
1891
1892         de::MovePtr<Buffer>                             m_imageBufferDst;
1893         Move<VkDescriptorSetLayout>             m_descriptorSetLayout;
1894         Move<VkDescriptorPool>                  m_descriptorPool;
1895         Move<VkDescriptorSet>                   m_descriptorSet;
1896         Move<VkBufferView>                              m_bufferViewSrc;
1897         Move<VkBufferView>                              m_bufferViewDst;
1898 };
1899
1900 BufferLoadStoreTestInstance::BufferLoadStoreTestInstance (Context&                      context,
1901                                                                                                                   const Texture&        texture,
1902                                                                                                                   const VkFormat        format,
1903                                                                                                                   const VkFormat        imageFormat,
1904                                                                                                                   const bool            declareImageFormatInShader,
1905                                                                                                                   const bool            minalign,
1906                                                                                                                   const bool            bufferLoadUniform)
1907         : LoadStoreTestInstance(context, texture, format, imageFormat, declareImageFormatInShader, false, minalign, bufferLoadUniform)
1908 {
1909         const DeviceInterface&  vk                      = m_context.getDeviceInterface();
1910         const VkDevice                  device          = m_context.getDevice();
1911         Allocator&                              allocator       = m_context.getDefaultAllocator();
1912
1913         // Create a destination buffer.
1914
1915         m_imageBufferDst = de::MovePtr<Buffer>(new Buffer(
1916                 vk, device, allocator,
1917                 makeBufferCreateInfo(m_imageSizeBytes + m_dstViewOffset, VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT),
1918                 MemoryRequirement::HostVisible));
1919 }
1920
1921 VkDescriptorSetLayout BufferLoadStoreTestInstance::prepareDescriptors (void)
1922 {
1923         const DeviceInterface&  vk              = m_context.getDeviceInterface();
1924         const VkDevice                  device  = m_context.getDevice();
1925
1926         m_descriptorSetLayout = DescriptorSetLayoutBuilder()
1927                 .addSingleBinding(m_bufferLoadDescriptorType, VK_SHADER_STAGE_COMPUTE_BIT)
1928                 .addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, VK_SHADER_STAGE_COMPUTE_BIT)
1929                 .build(vk, device);
1930
1931         m_descriptorPool = DescriptorPoolBuilder()
1932                 .addType(m_bufferLoadDescriptorType)
1933                 .addType(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER)
1934                 .build(vk, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u);
1935
1936         VkFormat dstFormat = formatHasThreeComponents(m_format) ? getSingleComponentFormat(m_format) : m_format;
1937
1938         m_descriptorSet = makeDescriptorSet(vk, device, *m_descriptorPool, *m_descriptorSetLayout);
1939         m_bufferViewSrc = makeBufferView(vk, device, m_imageBuffer->get(), m_format, m_srcViewOffset, m_imageSizeBytes);
1940         m_bufferViewDst = makeBufferView(vk, device, m_imageBufferDst->get(), dstFormat, m_dstViewOffset, m_imageSizeBytes);
1941
1942         return *m_descriptorSetLayout;  // not passing the ownership
1943 }
1944
1945 void BufferLoadStoreTestInstance::commandBindDescriptorsForLayer (const VkCommandBuffer cmdBuffer, const VkPipelineLayout pipelineLayout, const int layerNdx)
1946 {
1947         DE_ASSERT(layerNdx == 0);
1948         DE_UNREF(layerNdx);
1949
1950         const VkDevice                  device  = m_context.getDevice();
1951         const DeviceInterface&  vk              = m_context.getDeviceInterface();
1952
1953         DescriptorSetUpdateBuilder()
1954                 .writeSingle(*m_descriptorSet, DescriptorSetUpdateBuilder::Location::binding(0u), m_bufferLoadDescriptorType, &m_bufferViewSrc.get())
1955                 .writeSingle(*m_descriptorSet, DescriptorSetUpdateBuilder::Location::binding(1u), VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, &m_bufferViewDst.get())
1956                 .update(vk, device);
1957         vk.cmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0u, 1u, &m_descriptorSet.get(), 0u, DE_NULL);
1958 }
1959
1960 void BufferLoadStoreTestInstance::commandAfterCompute (const VkCommandBuffer cmdBuffer)
1961 {
1962         commandBufferWriteBarrierBeforeHostRead(m_context, cmdBuffer, m_imageBufferDst->get(), m_imageSizeBytes + m_dstViewOffset);
1963 }
1964
1965 TestInstance* StoreTest::createInstance (Context& context) const
1966 {
1967         if (m_texture.type() == IMAGE_TYPE_BUFFER)
1968                 return new BufferStoreTestInstance(context, m_texture, m_format, m_declareImageFormatInShader, m_minalign, m_storeConstantValue);
1969         else
1970                 return new ImageStoreTestInstance(context, m_texture, m_format, m_declareImageFormatInShader, m_singleLayerBind, m_minalign, m_storeConstantValue);
1971 }
1972
1973 TestInstance* LoadStoreTest::createInstance (Context& context) const
1974 {
1975         if (m_imageLoadStoreLodAMD)
1976                 return new ImageLoadStoreLodAMDTestInstance(context, m_texture, m_format, m_imageFormat, m_declareImageFormatInShader, m_singleLayerBind, m_minalign, m_bufferLoadUniform);
1977
1978         if (m_texture.type() == IMAGE_TYPE_BUFFER)
1979                 return new BufferLoadStoreTestInstance(context, m_texture, m_format, m_imageFormat, m_declareImageFormatInShader, m_minalign, m_bufferLoadUniform);
1980         else
1981                 return new ImageLoadStoreTestInstance(context, m_texture, m_format, m_imageFormat, m_declareImageFormatInShader, m_singleLayerBind, m_minalign, m_bufferLoadUniform);
1982 }
1983
1984 class ImageExtendOperandTestInstance : public BaseTestInstance
1985 {
1986 public:
1987                                                                         ImageExtendOperandTestInstance                  (Context&                               context,
1988                                                                                                                                                          const Texture&                 texture,
1989                                                                                                                                                          const VkFormat                 readFormat,
1990                                                                                                                                                          const VkFormat                 writeFormat,
1991                                                                                                                                                          bool                                   relaxedPrecision);
1992
1993         virtual                                                 ~ImageExtendOperandTestInstance                 (void) {}
1994
1995 protected:
1996
1997         VkDescriptorSetLayout                   prepareDescriptors                                              (void);
1998         void                                                    commandBeforeCompute                                    (const VkCommandBuffer  cmdBuffer);
1999         void                                                    commandBetweenShaderInvocations                 (const VkCommandBuffer  cmdBuffer);
2000         void                                                    commandAfterCompute                                             (const VkCommandBuffer  cmdBuffer);
2001
2002         void                                                    commandBindDescriptorsForLayer                  (const VkCommandBuffer  cmdBuffer,
2003                                                                                                                                                          const VkPipelineLayout pipelineLayout,
2004                                                                                                                                                          const int                              layerNdx);
2005
2006         tcu::TestStatus                                 verifyResult                                                    (void);
2007
2008 protected:
2009
2010         bool                                                    m_isSigned;
2011         tcu::TextureLevel                               m_inputImageData;
2012
2013         de::MovePtr<Image>                              m_imageSrc;                             // source image
2014         SharedVkImageView                               m_imageSrcView;
2015         VkDeviceSize                                    m_imageSrcSize;
2016
2017         de::MovePtr<Image>                              m_imageDst;                             // dest image
2018         SharedVkImageView                               m_imageDstView;
2019         VkFormat                                                m_imageDstFormat;
2020         VkDeviceSize                                    m_imageDstSize;
2021
2022         de::MovePtr<Buffer>                             m_buffer;                               // result buffer
2023
2024         Move<VkDescriptorSetLayout>             m_descriptorSetLayout;
2025         Move<VkDescriptorPool>                  m_descriptorPool;
2026         SharedVkDescriptorSet                   m_descriptorSet;
2027
2028         bool                                                    m_relaxedPrecision;
2029 };
2030
2031 ImageExtendOperandTestInstance::ImageExtendOperandTestInstance (Context& context,
2032                                                                                                                                 const Texture& texture,
2033                                                                                                                                 const VkFormat readFormat,
2034                                                                                                                                 const VkFormat writeFormat,
2035                                                                                                                                 bool relaxedPrecision)
2036         : BaseTestInstance              (context, texture, readFormat, true, true, false, false)
2037         , m_imageDstFormat              (writeFormat)
2038         , m_relaxedPrecision    (relaxedPrecision)
2039 {
2040         const DeviceInterface&          vk                              = m_context.getDeviceInterface();
2041         const VkDevice                          device                  = m_context.getDevice();
2042         Allocator&                                      allocator               = m_context.getDefaultAllocator();
2043         const deInt32                           width                   = texture.size().x();
2044         const deInt32                           height                  = texture.size().y();
2045         const tcu::TextureFormat        textureFormat   = mapVkFormat(m_format);
2046
2047         // Generate reference image
2048         m_isSigned = (getTextureChannelClass(textureFormat.type) == tcu::TEXTURECHANNELCLASS_SIGNED_INTEGER);
2049         m_inputImageData.setStorage(textureFormat, width, height, 1);
2050
2051         const tcu::PixelBufferAccess    access          = m_inputImageData.getAccess();
2052         const int                                               valueStart      = (m_isSigned ? (-width / 2) : 0);
2053
2054         for (int x = 0; x < width; ++x)
2055         for (int y = 0; y < height; ++y)
2056         {
2057                 const tcu::IVec4 color(valueStart + x, valueStart + y, valueStart, valueStart);
2058                 access.setPixel(color, x, y);
2059         }
2060
2061         // Create source image
2062         m_imageSrc = de::MovePtr<Image>(new Image(
2063                 vk, device, allocator,
2064                 makeImageCreateInfo(m_texture, m_format, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, 0u),
2065                 MemoryRequirement::Any));
2066
2067         // Create destination image
2068         m_imageDst = de::MovePtr<Image>(new Image(
2069                 vk, device, allocator,
2070                 makeImageCreateInfo(m_texture, m_imageDstFormat, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, 0u),
2071                 MemoryRequirement::Any));
2072
2073         // Compute image and buffer sizes
2074         m_imageSrcSize                                  = width * height * tcu::getPixelSize(textureFormat);
2075         m_imageDstSize                                  = width * height * tcu::getPixelSize(mapVkFormat(m_imageDstFormat));
2076         VkDeviceSize bufferSizeBytes    = de::max(m_imageSrcSize, m_imageDstSize);
2077
2078         // Create helper buffer able to store input data and image write result
2079         m_buffer = de::MovePtr<Buffer>(new Buffer(
2080                 vk, device, allocator,
2081                 makeBufferCreateInfo(bufferSizeBytes, VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT),
2082                 MemoryRequirement::HostVisible));
2083
2084         const Allocation& alloc = m_buffer->getAllocation();
2085         deMemcpy(alloc.getHostPtr(), m_inputImageData.getAccess().getDataPtr(), static_cast<size_t>(m_imageSrcSize));
2086         flushAlloc(vk, device, alloc);
2087 }
2088
2089 VkDescriptorSetLayout ImageExtendOperandTestInstance::prepareDescriptors (void)
2090 {
2091         const DeviceInterface&  vk              = m_context.getDeviceInterface();
2092         const VkDevice                  device  = m_context.getDevice();
2093
2094         m_descriptorSetLayout = DescriptorSetLayoutBuilder()
2095                 .addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT)
2096                 .addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT)
2097                 .build(vk, device);
2098
2099         m_descriptorPool = DescriptorPoolBuilder()
2100                 .addType(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1)
2101                 .addType(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1)
2102                 .build(vk, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1);
2103
2104         const VkImageViewType viewType = mapImageViewType(m_texture.type());
2105         const VkImageSubresourceRange subresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, 1u);
2106
2107         m_descriptorSet = makeVkSharedPtr(makeDescriptorSet(vk, device, *m_descriptorPool, *m_descriptorSetLayout));
2108         m_imageSrcView  = makeVkSharedPtr(makeImageView(vk, device, m_imageSrc->get(), viewType, m_format, subresourceRange));
2109         m_imageDstView  = makeVkSharedPtr(makeImageView(vk, device, m_imageDst->get(), viewType, m_imageDstFormat, subresourceRange));
2110
2111         return *m_descriptorSetLayout;  // not passing the ownership
2112 }
2113
2114 void ImageExtendOperandTestInstance::commandBindDescriptorsForLayer (const VkCommandBuffer cmdBuffer, const VkPipelineLayout pipelineLayout, const int layerNdx)
2115 {
2116         DE_UNREF(layerNdx);
2117
2118         const DeviceInterface&  vk                              = m_context.getDeviceInterface();
2119         const VkDevice                  device                  = m_context.getDevice();
2120         const VkDescriptorSet   descriptorSet   = **m_descriptorSet;
2121
2122         const VkDescriptorImageInfo descriptorSrcImageInfo = makeDescriptorImageInfo(DE_NULL, **m_imageSrcView, VK_IMAGE_LAYOUT_GENERAL);
2123         const VkDescriptorImageInfo descriptorDstImageInfo = makeDescriptorImageInfo(DE_NULL, **m_imageDstView, VK_IMAGE_LAYOUT_GENERAL);
2124
2125         typedef DescriptorSetUpdateBuilder::Location DSUBL;
2126         DescriptorSetUpdateBuilder()
2127                 .writeSingle(descriptorSet, DSUBL::binding(0u), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &descriptorSrcImageInfo)
2128                 .writeSingle(descriptorSet, DSUBL::binding(1u), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &descriptorDstImageInfo)
2129                 .update(vk, device);
2130         vk.cmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0u, 1u, &descriptorSet, 0u, DE_NULL);
2131 }
2132
2133 void ImageExtendOperandTestInstance::commandBeforeCompute (const VkCommandBuffer cmdBuffer)
2134 {
2135         const DeviceInterface& vk = m_context.getDeviceInterface();
2136
2137         const VkImageSubresourceRange fullImageSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, m_texture.numLayers());
2138         {
2139                 const VkImageMemoryBarrier preCopyImageBarriers[] =
2140                 {
2141                         makeImageMemoryBarrier(
2142                                 0u, VK_ACCESS_TRANSFER_WRITE_BIT,
2143                                 VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
2144                                 m_imageSrc->get(), fullImageSubresourceRange),
2145                         makeImageMemoryBarrier(
2146                                 0u, VK_ACCESS_SHADER_WRITE_BIT,
2147                                 VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL,
2148                                 m_imageDst->get(), fullImageSubresourceRange)
2149                 };
2150
2151                 const VkBufferMemoryBarrier barrierFlushHostWriteBeforeCopy = makeBufferMemoryBarrier(
2152                         VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT,
2153                         m_buffer->get(), 0ull, m_imageSrcSize);
2154
2155                 vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT,
2156                         (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &barrierFlushHostWriteBeforeCopy, DE_LENGTH_OF_ARRAY(preCopyImageBarriers), preCopyImageBarriers);
2157         }
2158         {
2159                 const VkImageMemoryBarrier barrierAfterCopy = makeImageMemoryBarrier(
2160                         VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT,
2161                         VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL,
2162                         m_imageSrc->get(), fullImageSubresourceRange);
2163
2164                 const VkBufferImageCopy copyRegion = makeBufferImageCopy(m_texture);
2165
2166                 vk.cmdCopyBufferToImage(cmdBuffer, m_buffer->get(), m_imageSrc->get(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1u, &copyRegion);
2167                 vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 0, (const VkBufferMemoryBarrier*)DE_NULL, 1, &barrierAfterCopy);
2168         }
2169 }
2170
2171 void ImageExtendOperandTestInstance::commandBetweenShaderInvocations (const VkCommandBuffer cmdBuffer)
2172 {
2173         commandImageWriteBarrierBetweenShaderInvocations(m_context, cmdBuffer, m_imageDst->get(), m_texture);
2174 }
2175
2176 void ImageExtendOperandTestInstance::commandAfterCompute (const VkCommandBuffer cmdBuffer)
2177 {
2178         commandCopyImageToBuffer(m_context, cmdBuffer, m_imageDst->get(), m_buffer->get(), m_imageDstSize, m_texture);
2179 }
2180
2181 // Clears the high bits of every pixel in the pixel buffer, leaving only the lowest 16 bits of each component.
2182 void clearHighBits (const tcu::PixelBufferAccess& pixels, int width, int height)
2183 {
2184         for (int y = 0; y < height; ++y)
2185         for (int x = 0; x < width; ++x)
2186         {
2187                 auto color = pixels.getPixelUint(x, y);
2188                 for (int c = 0; c < decltype(color)::SIZE; ++c)
2189                         color[c] &= 0xFFFFull;
2190                 pixels.setPixel(color, x, y);
2191         }
2192 }
2193
2194 tcu::TestStatus ImageExtendOperandTestInstance::verifyResult (void)
2195 {
2196         const DeviceInterface&                  vk                      = m_context.getDeviceInterface();
2197         const VkDevice                                  device          = m_context.getDevice();
2198         const tcu::IVec3                                imageSize       = m_texture.size();
2199         const tcu::PixelBufferAccess    inputAccess     = m_inputImageData.getAccess();
2200         const deInt32                                   width           = inputAccess.getWidth();
2201         const deInt32                                   height          = inputAccess.getHeight();
2202         tcu::TextureLevel                               refImage        (mapVkFormat(m_imageDstFormat), width, height);
2203         tcu::PixelBufferAccess                  refAccess       = refImage.getAccess();
2204
2205         for (int x = 0; x < width; ++x)
2206         for (int y = 0; y < height; ++y)
2207         {
2208                 tcu::IVec4 color = inputAccess.getPixelInt(x, y);
2209                 refAccess.setPixel(color, x, y);
2210         }
2211
2212         const Allocation& alloc = m_buffer->getAllocation();
2213         invalidateAlloc(vk, device, alloc);
2214         const tcu::PixelBufferAccess result(mapVkFormat(m_imageDstFormat), imageSize, alloc.getHostPtr());
2215
2216         if (m_relaxedPrecision)
2217         {
2218                 // Preserve the lowest 16 bits of the reference and result pixels only.
2219                 clearHighBits(refAccess, width, height);
2220                 clearHighBits(result, width, height);
2221         }
2222
2223         if (tcu::intThresholdCompare (m_context.getTestContext().getLog(), "Comparison", "Comparison", refAccess, result, tcu::UVec4(0), tcu::COMPARE_LOG_RESULT, true/*use64Bits*/))
2224                 return tcu::TestStatus::pass("Passed");
2225         else
2226                 return tcu::TestStatus::fail("Image comparison failed");
2227 }
2228
2229 enum class ExtendTestType
2230 {
2231         READ                            = 0,
2232         WRITE,
2233         WRITE_NONTEMPORAL,
2234 };
2235
2236 enum class ExtendOperand
2237 {
2238         SIGN_EXTEND = 0,
2239         ZERO_EXTEND = 1
2240 };
2241
2242 class ImageExtendOperandTest : public TestCase
2243 {
2244 public:
2245                                                         ImageExtendOperandTest  (tcu::TestContext&                                      testCtx,
2246                                                                                                          const std::string&                                     name,
2247                                                                                                          const Texture                                          texture,
2248                                                                                                          const VkFormat                                         readFormat,
2249                                                                                                          const VkFormat                                         writeFormat,
2250                                                                                                          const bool                                                     signedInt,
2251                                                                                                          const bool                                                     relaxedPrecision,
2252                                                                                                          ExtendTestType                                         extendTestType);
2253
2254         void                                    checkSupport                    (Context&                               context) const;
2255         void                                    initPrograms                    (SourceCollections&             programCollection) const;
2256         TestInstance*                   createInstance                  (Context&                               context) const;
2257
2258 private:
2259         bool                                    isWriteTest                             () const { return (m_extendTestType == ExtendTestType::WRITE) ||
2260                                                                                                                                           (m_extendTestType == ExtendTestType::WRITE_NONTEMPORAL); }
2261
2262         const Texture                   m_texture;
2263         VkFormat                                m_readFormat;
2264         VkFormat                                m_writeFormat;
2265         bool                                    m_operandForce;                 // Use an operand that doesn't match SampledType?
2266         bool                                    m_relaxedPrecision;
2267         ExtendTestType                  m_extendTestType;
2268 };
2269
2270 ImageExtendOperandTest::ImageExtendOperandTest (tcu::TestContext&                               testCtx,
2271                                                                                                 const std::string&                              name,
2272                                                                                                 const Texture                                   texture,
2273                                                                                                 const VkFormat                                  readFormat,
2274                                                                                                 const VkFormat                                  writeFormat,
2275                                                                                                 const bool                                              operandForce,
2276                                                                                                 const bool                                              relaxedPrecision,
2277                                                                                                 ExtendTestType                                  extendTestType)
2278         : TestCase                                              (testCtx, name, "")
2279         , m_texture                                             (texture)
2280         , m_readFormat                                  (readFormat)
2281         , m_writeFormat                                 (writeFormat)
2282         , m_operandForce                                (operandForce)
2283         , m_relaxedPrecision                    (relaxedPrecision)
2284         , m_extendTestType                              (extendTestType)
2285 {
2286 }
2287
2288 void checkFormatProperties (Context& context, VkFormat format)
2289 {
2290         const VkFormatProperties3 formatProperties (context.getFormatProperties(format));
2291
2292         if (!(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT))
2293                 TCU_THROW(NotSupportedError, "Format not supported for storage images");
2294 }
2295
2296 void check64BitSupportIfNeeded (Context& context, VkFormat readFormat, VkFormat writeFormat)
2297 {
2298         if (is64BitIntegerFormat(readFormat) || is64BitIntegerFormat(writeFormat))
2299         {
2300                 const auto& features = context.getDeviceFeatures();
2301                 if (!features.shaderInt64)
2302                         TCU_THROW(NotSupportedError, "64-bit integers not supported in shaders");
2303         }
2304 }
2305
2306 void ImageExtendOperandTest::checkSupport (Context& context) const
2307 {
2308         if (!context.requireDeviceFunctionality("VK_KHR_spirv_1_4"))
2309                 TCU_THROW(NotSupportedError, "VK_KHR_spirv_1_4 not supported");
2310
2311         if ((m_extendTestType == ExtendTestType::WRITE_NONTEMPORAL) &&
2312                 (context.getUsedApiVersion() < VK_API_VERSION_1_3))
2313                 TCU_THROW(NotSupportedError, "Vulkan 1.3 or higher is required for this test to run");
2314
2315         check64BitSupportIfNeeded(context, m_readFormat, m_writeFormat);
2316
2317         checkFormatProperties(context, m_readFormat);
2318         checkFormatProperties(context, m_writeFormat);
2319 }
2320
2321 void ImageExtendOperandTest::initPrograms (SourceCollections& programCollection) const
2322 {
2323         tcu::StringTemplate shaderTemplate(
2324                 "OpCapability Shader\n"
2325                 "OpCapability StorageImageExtendedFormats\n"
2326
2327                 "${capability}"
2328                 "${extension}"
2329
2330                 "%std450 = OpExtInstImport \"GLSL.std.450\"\n"
2331                 "OpMemoryModel Logical GLSL450\n"
2332                 "OpEntryPoint GLCompute %main \"main\" %id %src_image_ptr %dst_image_ptr\n"
2333                 "OpExecutionMode %main LocalSize 1 1 1\n"
2334
2335                 // decorations
2336                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2337
2338                 "OpDecorate %src_image_ptr DescriptorSet 0\n"
2339                 "OpDecorate %src_image_ptr Binding 0\n"
2340                 "OpDecorate %src_image_ptr NonWritable\n"
2341
2342                 "${relaxed_precision}"
2343
2344                 "OpDecorate %dst_image_ptr DescriptorSet 0\n"
2345                 "OpDecorate %dst_image_ptr Binding 1\n"
2346                 "OpDecorate %dst_image_ptr NonReadable\n"
2347
2348                 // types
2349                 "%type_void                          = OpTypeVoid\n"
2350                 "%type_i32                           = OpTypeInt 32 1\n"
2351                 "%type_u32                           = OpTypeInt 32 0\n"
2352                 "%type_vec2_i32                      = OpTypeVector %type_i32 2\n"
2353                 "%type_vec2_u32                      = OpTypeVector %type_u32 2\n"
2354                 "%type_vec3_i32                      = OpTypeVector %type_i32 3\n"
2355                 "%type_vec3_u32                      = OpTypeVector %type_u32 3\n"
2356                 "%type_vec4_i32                      = OpTypeVector %type_i32 4\n"
2357                 "%type_vec4_u32                      = OpTypeVector %type_u32 4\n"
2358                 "${extra_types}"
2359
2360                 "%type_fun_void                      = OpTypeFunction %type_void\n"
2361
2362                 "${image_types}"
2363
2364                 "%type_ptr_in_vec3_u32               = OpTypePointer Input %type_vec3_u32\n"
2365                 "%type_ptr_in_u32                    = OpTypePointer Input %type_u32\n"
2366
2367                 "${image_uniforms}"
2368
2369                 // variables
2370                 "%id                                 = OpVariable %type_ptr_in_vec3_u32 Input\n"
2371
2372                 "${image_variables}"
2373
2374                 // main function
2375                 "%main                               = OpFunction %type_void None %type_fun_void\n"
2376                 "%label                              = OpLabel\n"
2377
2378                 "${image_load}"
2379
2380                 "%idvec                              = OpLoad %type_vec3_u32 %id\n"
2381                 "%id_xy                              = OpVectorShuffle %type_vec2_u32 %idvec %idvec 0 1\n"
2382                 "%coord                              = OpBitcast %type_vec2_i32 %id_xy\n"
2383                 "%value                              = OpImageRead ${sampled_type_vec4} %src_image %coord ${read_extend_operand}\n"
2384                 "                                      OpImageWrite %dst_image %coord %value ${write_extend_operand}\n"
2385                 "                                      OpReturn\n"
2386                 "                                      OpFunctionEnd\n");
2387
2388         const auto      testedFormat    = mapVkFormat(isWriteTest() ? m_writeFormat : m_readFormat);
2389         const bool      isSigned                = (getTextureChannelClass(testedFormat.type) == tcu::TEXTURECHANNELCLASS_SIGNED_INTEGER);
2390
2391         const auto isRead64             = is64BitIntegerFormat(m_readFormat);
2392         const auto isWrite64    = is64BitIntegerFormat(m_writeFormat);
2393         DE_ASSERT(isRead64 == isWrite64);
2394
2395         const bool using64Bits                          = (isRead64 || isWrite64);
2396
2397         // Additional capabilities when needed.
2398         std::string capability;
2399         std::string extension;
2400         std::string extraTypes;
2401
2402         if (using64Bits)
2403         {
2404                         extension  += "OpExtension \"SPV_EXT_shader_image_int64\"\n";
2405                         capability +=
2406                                 "OpCapability Int64\n"
2407                                 "OpCapability Int64ImageEXT\n"
2408                                 ;
2409                         extraTypes +=
2410                                 "%type_i64                           = OpTypeInt 64 1\n"
2411                                 "%type_u64                           = OpTypeInt 64 0\n"
2412                                 "%type_vec3_i64                      = OpTypeVector %type_i64 3\n"
2413                                 "%type_vec3_u64                      = OpTypeVector %type_u64 3\n"
2414                                 "%type_vec4_i64                      = OpTypeVector %type_i64 4\n"
2415                                 "%type_vec4_u64                      = OpTypeVector %type_u64 4\n"
2416                                 ;
2417         }
2418
2419         std::string relaxed = "";
2420         if (m_relaxedPrecision)
2421                 relaxed += "OpDecorate %src_image_ptr RelaxedPrecision\n";
2422
2423         // Sampled type depends on the format sign and mismatch force flag.
2424         const bool                      signedSampleType        = ((isSigned && !m_operandForce) || (!isSigned && m_operandForce));
2425         const std::string       bits                            = (using64Bits ? "64" : "32");
2426         const std::string       sampledTypePostfix      = (signedSampleType ? "i" : "u") + bits;
2427         const std::string       extendOperandStr        = (isSigned ? "SignExtend" : "ZeroExtend");
2428
2429         std::map<std::string, std::string> specializations
2430         {
2431                 { "image_type_id",                      "%type_image" },
2432                 { "image_uni_ptr_type_id",      "%type_ptr_uniform_const_image" },
2433                 { "image_var_id",                       "%src_image_ptr" },
2434                 { "image_id",                           "%src_image" },
2435                 { "capability",                         capability },
2436                 { "extension",                          extension },
2437                 { "extra_types",                        extraTypes },
2438                 { "relaxed_precision",          relaxed },
2439                 { "image_format",                       getSpirvFormat(m_readFormat) },
2440                 { "sampled_type",                       (std::string("%type_") + sampledTypePostfix) },
2441                 { "sampled_type_vec4",          (std::string("%type_vec4_") + sampledTypePostfix) },
2442                 { "read_extend_operand",        (!isWriteTest() ? extendOperandStr : "") },
2443                 { "write_extend_operand",       (isWriteTest()  ? extendOperandStr : "") },
2444         };
2445
2446         SpirvVersion    spirvVersion    = SPIRV_VERSION_1_4;
2447         bool                    allowSpirv14    = true;
2448         if (m_extendTestType == ExtendTestType::WRITE_NONTEMPORAL)
2449         {
2450                 spirvVersion    = SPIRV_VERSION_1_6;
2451                 allowSpirv14    = false;
2452                 specializations["write_extend_operand"] = "Nontemporal";
2453         }
2454
2455         // Addidtional parametrization is needed for a case when source and destination textures have same format
2456         tcu::StringTemplate imageTypeTemplate(
2457                 "${image_type_id}                     = OpTypeImage ${sampled_type} 2D 0 0 0 2 ${image_format}\n");
2458         tcu::StringTemplate imageUniformTypeTemplate(
2459                 "${image_uni_ptr_type_id}   = OpTypePointer UniformConstant ${image_type_id}\n");
2460         tcu::StringTemplate imageVariablesTemplate(
2461                 "${image_var_id}                      = OpVariable ${image_uni_ptr_type_id} UniformConstant\n");
2462         tcu::StringTemplate imageLoadTemplate(
2463                 "${image_id}                          = OpLoad ${image_type_id} ${image_var_id}\n");
2464
2465         std::string imageTypes;
2466         std::string imageUniformTypes;
2467         std::string imageVariables;
2468         std::string imageLoad;
2469
2470         // If input image format is the same as output there is less spir-v definitions
2471         if (m_readFormat == m_writeFormat)
2472         {
2473                 imageTypes                      = imageTypeTemplate.specialize(specializations);
2474                 imageUniformTypes       = imageUniformTypeTemplate.specialize(specializations);
2475                 imageVariables          = imageVariablesTemplate.specialize(specializations);
2476                 imageLoad                       = imageLoadTemplate.specialize(specializations);
2477
2478                 specializations["image_var_id"]                         = "%dst_image_ptr";
2479                 specializations["image_id"]                                     = "%dst_image";
2480                 imageVariables          += imageVariablesTemplate.specialize(specializations);
2481                 imageLoad                       += imageLoadTemplate.specialize(specializations);
2482         }
2483         else
2484         {
2485                 specializations["image_type_id"]                        = "%type_src_image";
2486                 specializations["image_uni_ptr_type_id"]        = "%type_ptr_uniform_const_src_image";
2487                 imageTypes                      = imageTypeTemplate.specialize(specializations);
2488                 imageUniformTypes       = imageUniformTypeTemplate.specialize(specializations);
2489                 imageVariables          = imageVariablesTemplate.specialize(specializations);
2490                 imageLoad                       = imageLoadTemplate.specialize(specializations);
2491
2492                 specializations["image_format"]                         = getSpirvFormat(m_writeFormat);
2493                 specializations["image_type_id"]                        = "%type_dst_image";
2494                 specializations["image_uni_ptr_type_id"]        = "%type_ptr_uniform_const_dst_image";
2495                 specializations["image_var_id"]                         = "%dst_image_ptr";
2496                 specializations["image_id"]                                     = "%dst_image";
2497                 imageTypes                      += imageTypeTemplate.specialize(specializations);
2498                 imageUniformTypes       += imageUniformTypeTemplate.specialize(specializations);
2499                 imageVariables          += imageVariablesTemplate.specialize(specializations);
2500                 imageLoad                       += imageLoadTemplate.specialize(specializations);
2501         }
2502
2503         specializations["image_types"]          = imageTypes;
2504         specializations["image_uniforms"]       = imageUniformTypes;
2505         specializations["image_variables"]      = imageVariables;
2506         specializations["image_load"]           = imageLoad;
2507
2508         // Specialize whole shader and add it to program collection
2509         programCollection.spirvAsmSources.add("comp") << shaderTemplate.specialize(specializations)
2510                 << vk::SpirVAsmBuildOptions(programCollection.usedVulkanVersion, spirvVersion, allowSpirv14);
2511 }
2512
2513 TestInstance* ImageExtendOperandTest::createInstance(Context& context) const
2514 {
2515         return new ImageExtendOperandTestInstance(context, m_texture, m_readFormat, m_writeFormat, m_relaxedPrecision);
2516 }
2517
2518 static const Texture s_textures[] =
2519 {
2520         Texture(IMAGE_TYPE_1D,                  tcu::IVec3(64,  1,      1),     1),
2521         Texture(IMAGE_TYPE_1D_ARRAY,    tcu::IVec3(64,  1,      1),     8),
2522         Texture(IMAGE_TYPE_2D,                  tcu::IVec3(64,  64,     1),     1),
2523         Texture(IMAGE_TYPE_2D_ARRAY,    tcu::IVec3(64,  64,     1),     8),
2524         Texture(IMAGE_TYPE_3D,                  tcu::IVec3(64,  64,     8),     1),
2525         Texture(IMAGE_TYPE_CUBE,                tcu::IVec3(64,  64,     1),     6),
2526         Texture(IMAGE_TYPE_CUBE_ARRAY,  tcu::IVec3(64,  64,     1),     2*6),
2527         Texture(IMAGE_TYPE_BUFFER,              tcu::IVec3(64,  1,      1),     1),
2528 };
2529
2530 const Texture& getTestTexture (const ImageType imageType)
2531 {
2532         for (int textureNdx = 0; textureNdx < DE_LENGTH_OF_ARRAY(s_textures); ++textureNdx)
2533                 if (s_textures[textureNdx].type() == imageType)
2534                         return s_textures[textureNdx];
2535
2536         DE_FATAL("Internal error");
2537         return s_textures[0];
2538 }
2539
2540 static const VkFormat s_formats[] =
2541 {
2542         VK_FORMAT_R32G32B32A32_SFLOAT,
2543         VK_FORMAT_R16G16B16A16_SFLOAT,
2544         VK_FORMAT_R32_SFLOAT,
2545
2546         VK_FORMAT_R32G32B32A32_UINT,
2547         VK_FORMAT_R16G16B16A16_UINT,
2548         VK_FORMAT_R8G8B8A8_UINT,
2549         VK_FORMAT_R32_UINT,
2550
2551         VK_FORMAT_R32G32B32A32_SINT,
2552         VK_FORMAT_R16G16B16A16_SINT,
2553         VK_FORMAT_R8G8B8A8_SINT,
2554         VK_FORMAT_R32_SINT,
2555
2556         VK_FORMAT_R8G8B8A8_UNORM,
2557
2558         VK_FORMAT_B8G8R8A8_UNORM,
2559         VK_FORMAT_B8G8R8A8_UINT,
2560
2561         VK_FORMAT_R8G8B8A8_SNORM,
2562
2563         VK_FORMAT_B10G11R11_UFLOAT_PACK32,
2564
2565         VK_FORMAT_R32G32_SFLOAT,
2566         VK_FORMAT_R16G16_SFLOAT,
2567         VK_FORMAT_R16_SFLOAT,
2568
2569         VK_FORMAT_A2B10G10R10_UINT_PACK32,
2570         VK_FORMAT_R32G32_UINT,
2571         VK_FORMAT_R16G16_UINT,
2572         VK_FORMAT_R16_UINT,
2573         VK_FORMAT_R8G8_UINT,
2574         VK_FORMAT_R8_UINT,
2575
2576         VK_FORMAT_R32G32_SINT,
2577         VK_FORMAT_R16G16_SINT,
2578         VK_FORMAT_R16_SINT,
2579         VK_FORMAT_R8G8_SINT,
2580         VK_FORMAT_R8_SINT,
2581
2582         VK_FORMAT_A2B10G10R10_UNORM_PACK32,
2583         VK_FORMAT_R16G16B16A16_UNORM,
2584         VK_FORMAT_R16G16B16A16_SNORM,
2585         VK_FORMAT_R16G16_UNORM,
2586         VK_FORMAT_R16_UNORM,
2587         VK_FORMAT_R8G8_UNORM,
2588         VK_FORMAT_R8_UNORM,
2589
2590         VK_FORMAT_R16G16_SNORM,
2591         VK_FORMAT_R16_SNORM,
2592         VK_FORMAT_R8G8_SNORM,
2593         VK_FORMAT_R8_SNORM
2594 };
2595
2596 static const VkFormat s_formatsThreeComponent[] =
2597 {
2598         VK_FORMAT_R8G8B8_UINT,
2599         VK_FORMAT_R8G8B8_SINT,
2600         VK_FORMAT_R8G8B8_UNORM,
2601         VK_FORMAT_R8G8B8_SNORM,
2602         VK_FORMAT_R16G16B16_UINT,
2603         VK_FORMAT_R16G16B16_SINT,
2604         VK_FORMAT_R16G16B16_UNORM,
2605         VK_FORMAT_R16G16B16_SNORM,
2606         VK_FORMAT_R16G16B16_SFLOAT,
2607         VK_FORMAT_R32G32B32_UINT,
2608         VK_FORMAT_R32G32B32_SINT,
2609         VK_FORMAT_R32G32B32_SFLOAT,
2610 };
2611
2612 } // anonymous ns
2613
2614 tcu::TestCaseGroup* createImageStoreTests (tcu::TestContext& testCtx)
2615 {
2616         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "store", "Plain imageStore() cases"));
2617         de::MovePtr<tcu::TestCaseGroup> testGroupWithFormat(new tcu::TestCaseGroup(testCtx, "with_format", "Declare a format layout qualifier for write images"));
2618         de::MovePtr<tcu::TestCaseGroup> testGroupWithoutFormat(new tcu::TestCaseGroup(testCtx, "without_format", "Do not declare a format layout qualifier for write images"));
2619
2620         for (int textureNdx = 0; textureNdx < DE_LENGTH_OF_ARRAY(s_textures); ++textureNdx)
2621         {
2622                 const Texture& texture = s_textures[textureNdx];
2623                 de::MovePtr<tcu::TestCaseGroup> groupWithFormatByImageViewType (new tcu::TestCaseGroup(testCtx, getImageTypeName(texture.type()).c_str(), ""));
2624                 de::MovePtr<tcu::TestCaseGroup> groupWithoutFormatByImageViewType (new tcu::TestCaseGroup(testCtx, getImageTypeName(texture.type()).c_str(), ""));
2625                 const bool isLayered = (texture.numLayers() > 1);
2626
2627                 for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(s_formats); ++formatNdx)
2628                 {
2629                         const bool hasSpirvFmt = hasSpirvFormat(s_formats[formatNdx]);
2630
2631                         if (hasSpirvFmt)
2632                         {
2633                                 groupWithFormatByImageViewType->addChild( new StoreTest(testCtx, getFormatShortString(s_formats[formatNdx]), "", texture, s_formats[formatNdx]));
2634                                 // Additional tests where the shader uses constant data for imageStore.
2635                                 groupWithFormatByImageViewType->addChild(new StoreTest(testCtx, getFormatShortString(s_formats[formatNdx]) + "_constant", "", texture, s_formats[formatNdx], StoreTest::FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER | StoreTest::FLAG_STORE_CONSTANT_VALUE));
2636                         }
2637                         groupWithoutFormatByImageViewType->addChild(new StoreTest(testCtx, getFormatShortString(s_formats[formatNdx]), "", texture, s_formats[formatNdx], 0));
2638
2639                         if (isLayered && hasSpirvFmt)
2640                                 groupWithFormatByImageViewType->addChild(new StoreTest(testCtx, getFormatShortString(s_formats[formatNdx]) + "_single_layer", "",
2641                                                                                                                  texture, s_formats[formatNdx],
2642                                                                                                                  StoreTest::FLAG_SINGLE_LAYER_BIND | StoreTest::FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER));
2643
2644                         if (texture.type() == IMAGE_TYPE_BUFFER)
2645                         {
2646                                 if (hasSpirvFmt)
2647                                         groupWithFormatByImageViewType->addChild(new StoreTest(testCtx, getFormatShortString(s_formats[formatNdx]) + "_minalign", "", texture, s_formats[formatNdx], StoreTest::FLAG_MINALIGN | StoreTest::FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER));
2648                                 groupWithoutFormatByImageViewType->addChild(new StoreTest(testCtx, getFormatShortString(s_formats[formatNdx]) + "_minalign", "", texture, s_formats[formatNdx], StoreTest::FLAG_MINALIGN));
2649                         }
2650                 }
2651
2652                 testGroupWithFormat->addChild(groupWithFormatByImageViewType.release());
2653                 testGroupWithoutFormat->addChild(groupWithoutFormatByImageViewType.release());
2654         }
2655
2656         testGroup->addChild(testGroupWithFormat.release());
2657         testGroup->addChild(testGroupWithoutFormat.release());
2658
2659         return testGroup.release();
2660 }
2661
2662 tcu::TestCaseGroup* createImageLoadStoreTests (tcu::TestContext& testCtx)
2663 {
2664         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "load_store", "Cases with imageLoad() followed by imageStore()"));
2665         de::MovePtr<tcu::TestCaseGroup> testGroupWithFormat(new tcu::TestCaseGroup(testCtx, "with_format", "Declare a format layout qualifier for read images"));
2666         de::MovePtr<tcu::TestCaseGroup> testGroupWithoutFormat(new tcu::TestCaseGroup(testCtx, "without_format", "Do not declare a format layout qualifier for read images"));
2667
2668         for (int textureNdx = 0; textureNdx < DE_LENGTH_OF_ARRAY(s_textures); ++textureNdx)
2669         {
2670                 const Texture& texture = s_textures[textureNdx];
2671                 de::MovePtr<tcu::TestCaseGroup> groupWithFormatByImageViewType (new tcu::TestCaseGroup(testCtx, getImageTypeName(texture.type()).c_str(), ""));
2672                 de::MovePtr<tcu::TestCaseGroup> groupWithoutFormatByImageViewType (new tcu::TestCaseGroup(testCtx, getImageTypeName(texture.type()).c_str(), ""));
2673                 const bool isLayered = (texture.numLayers() > 1);
2674
2675                 for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(s_formats); ++formatNdx)
2676                 {
2677                         // These tests always require a SPIR-V format for the write image, even if the read
2678                         // image is being used without a format.
2679                         if (!hasSpirvFormat(s_formats[formatNdx]))
2680                                 continue;
2681
2682                         groupWithFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formats[formatNdx]), "", texture, s_formats[formatNdx], s_formats[formatNdx]));
2683                         groupWithoutFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formats[formatNdx]), "", texture, s_formats[formatNdx], s_formats[formatNdx], 0));
2684
2685                         if (isLayered)
2686                                 groupWithFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formats[formatNdx]) + "_single_layer", "",
2687                                                                                                                  texture, s_formats[formatNdx], s_formats[formatNdx],
2688                                                                                                                  LoadStoreTest::FLAG_SINGLE_LAYER_BIND | LoadStoreTest::FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER));
2689                         if (texture.type() == IMAGE_TYPE_BUFFER)
2690                         {
2691                                 groupWithFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formats[formatNdx]) + "_minalign", "", texture, s_formats[formatNdx], s_formats[formatNdx], LoadStoreTest::FLAG_MINALIGN | LoadStoreTest::FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER));
2692                                 groupWithFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formats[formatNdx]) + "_minalign_uniform", "", texture, s_formats[formatNdx], s_formats[formatNdx], LoadStoreTest::FLAG_MINALIGN | LoadStoreTest::FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER | LoadStoreTest::FLAG_UNIFORM_TEXEL_BUFFER));
2693                                 groupWithoutFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formats[formatNdx]) + "_minalign", "", texture, s_formats[formatNdx], s_formats[formatNdx], LoadStoreTest::FLAG_MINALIGN));
2694                                 groupWithoutFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formats[formatNdx]) + "_minalign_uniform", "", texture, s_formats[formatNdx], s_formats[formatNdx], LoadStoreTest::FLAG_MINALIGN | LoadStoreTest::FLAG_UNIFORM_TEXEL_BUFFER));
2695                         }
2696                 }
2697
2698                 if (texture.type() == IMAGE_TYPE_BUFFER)
2699                 {
2700                         for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(s_formatsThreeComponent); ++formatNdx)
2701                         {
2702                                 groupWithoutFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formatsThreeComponent[formatNdx]) + "_uniform", "", texture, s_formatsThreeComponent[formatNdx], s_formatsThreeComponent[formatNdx], LoadStoreTest::FLAG_UNIFORM_TEXEL_BUFFER));
2703                                 groupWithoutFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formatsThreeComponent[formatNdx]) + "_minalign_uniform", "", texture, s_formatsThreeComponent[formatNdx], s_formatsThreeComponent[formatNdx], LoadStoreTest::FLAG_MINALIGN | LoadStoreTest::FLAG_UNIFORM_TEXEL_BUFFER));
2704                         }
2705                 }
2706
2707                 testGroupWithFormat->addChild(groupWithFormatByImageViewType.release());
2708                 testGroupWithoutFormat->addChild(groupWithoutFormatByImageViewType.release());
2709         }
2710
2711         testGroup->addChild(testGroupWithFormat.release());
2712         testGroup->addChild(testGroupWithoutFormat.release());
2713
2714         return testGroup.release();
2715 }
2716
2717 tcu::TestCaseGroup* createImageLoadStoreLodAMDTests (tcu::TestContext& testCtx)
2718 {
2719         static const Texture textures[] =
2720         {
2721                 Texture(IMAGE_TYPE_1D_ARRAY,    tcu::IVec3(64,  1,      1),     8, 1, 6),
2722                 Texture(IMAGE_TYPE_1D,                  tcu::IVec3(64,  1,      1),     1, 1, 6),
2723                 Texture(IMAGE_TYPE_2D,                  tcu::IVec3(64,  64,     1),     1, 1, 6),
2724                 Texture(IMAGE_TYPE_2D_ARRAY,    tcu::IVec3(64,  64,     1),     8, 1, 6),
2725                 Texture(IMAGE_TYPE_3D,                  tcu::IVec3(64,  64,     8),     1, 1, 6),
2726                 Texture(IMAGE_TYPE_CUBE,                tcu::IVec3(64,  64,     1),     6, 1, 6),
2727                 Texture(IMAGE_TYPE_CUBE_ARRAY,  tcu::IVec3(64,  64,     1),     2*6, 1, 6),
2728         };
2729
2730         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "load_store_lod", "Cases with imageLoad() followed by imageStore()"));
2731         de::MovePtr<tcu::TestCaseGroup> testGroupWithFormat(new tcu::TestCaseGroup(testCtx, "with_format", "Declare a format layout qualifier for read images"));
2732         de::MovePtr<tcu::TestCaseGroup> testGroupWithoutFormat(new tcu::TestCaseGroup(testCtx, "without_format", "Do not declare a format layout qualifier for read images"));
2733
2734         for (int textureNdx = 0; textureNdx < DE_LENGTH_OF_ARRAY(textures); ++textureNdx)
2735         {
2736                 const Texture& texture = textures[textureNdx];
2737                 de::MovePtr<tcu::TestCaseGroup> groupWithFormatByImageViewType (new tcu::TestCaseGroup(testCtx, getImageTypeName(texture.type()).c_str(), ""));
2738                 de::MovePtr<tcu::TestCaseGroup> groupWithoutFormatByImageViewType (new tcu::TestCaseGroup(testCtx, getImageTypeName(texture.type()).c_str(), ""));
2739                 const bool isLayered = (texture.numLayers() > 1);
2740
2741                 if (texture.type() == IMAGE_TYPE_BUFFER)
2742                         continue;
2743
2744                 for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(s_formats); ++formatNdx)
2745                 {
2746                         // These tests always require a SPIR-V format for the write image, even if the read
2747                         // image is being used without a format.
2748                         if (!hasSpirvFormat(s_formats[formatNdx]))
2749                                 continue;
2750
2751                         groupWithFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formats[formatNdx]), "", texture, s_formats[formatNdx], s_formats[formatNdx], LoadStoreTest::FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER, DE_TRUE));
2752                         groupWithoutFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formats[formatNdx]), "", texture, s_formats[formatNdx], s_formats[formatNdx], 0, DE_TRUE));
2753
2754                         if (isLayered)
2755                                 groupWithFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formats[formatNdx]) + "_single_layer", "",
2756                                                                                                                  texture, s_formats[formatNdx], s_formats[formatNdx],
2757                                                                                                                  LoadStoreTest::FLAG_SINGLE_LAYER_BIND | LoadStoreTest::FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER, DE_TRUE));
2758                 }
2759
2760                 testGroupWithFormat->addChild(groupWithFormatByImageViewType.release());
2761                 testGroupWithoutFormat->addChild(groupWithoutFormatByImageViewType.release());
2762         }
2763
2764         testGroup->addChild(testGroupWithFormat.release());
2765         testGroup->addChild(testGroupWithoutFormat.release());
2766
2767         return testGroup.release();
2768 }
2769
2770 tcu::TestCaseGroup* createImageFormatReinterpretTests (tcu::TestContext& testCtx)
2771 {
2772         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "format_reinterpret", "Cases with differing texture and image formats"));
2773
2774         for (int textureNdx = 0; textureNdx < DE_LENGTH_OF_ARRAY(s_textures); ++textureNdx)
2775         {
2776                 const Texture& texture = s_textures[textureNdx];
2777                 de::MovePtr<tcu::TestCaseGroup> groupByImageViewType (new tcu::TestCaseGroup(testCtx, getImageTypeName(texture.type()).c_str(), ""));
2778
2779                 for (int imageFormatNdx = 0; imageFormatNdx < DE_LENGTH_OF_ARRAY(s_formats); ++imageFormatNdx)
2780                 for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(s_formats); ++formatNdx)
2781                 {
2782                         if (!hasSpirvFormat(s_formats[formatNdx]))
2783                                 continue;
2784
2785                         const std::string caseName = getFormatShortString(s_formats[imageFormatNdx]) + "_" + getFormatShortString(s_formats[formatNdx]);
2786                         if (imageFormatNdx != formatNdx && formatsAreCompatible(s_formats[imageFormatNdx], s_formats[formatNdx]))
2787                                 groupByImageViewType->addChild(new LoadStoreTest(testCtx, caseName, "", texture, s_formats[formatNdx], s_formats[imageFormatNdx]));
2788                 }
2789                 testGroup->addChild(groupByImageViewType.release());
2790         }
2791
2792         return testGroup.release();
2793 }
2794
2795 de::MovePtr<TestCase> createImageQualifierRestrictCase (tcu::TestContext& testCtx, const ImageType imageType, const std::string& name)
2796 {
2797         const VkFormat format = VK_FORMAT_R32G32B32A32_UINT;
2798         const Texture& texture = getTestTexture(imageType);
2799         return de::MovePtr<TestCase>(new LoadStoreTest(testCtx, name, "", texture, format, format, LoadStoreTest::FLAG_RESTRICT_IMAGES | LoadStoreTest::FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER));
2800 }
2801
2802 namespace
2803 {
2804
2805 bool relaxedOK(VkFormat format)
2806 {
2807         tcu::IVec4 bitDepth = tcu::getTextureFormatBitDepth(mapVkFormat(format));
2808         int maxBitDepth = deMax32(deMax32(bitDepth[0], bitDepth[1]), deMax32(bitDepth[2], bitDepth[3]));
2809         return maxBitDepth <= 16;
2810 }
2811
2812 // Get a format used for reading or writing in extension operand tests. These formats allow representing the shader sampled type to
2813 // verify results from read or write operations.
2814 VkFormat getShaderExtensionOperandFormat (bool isSigned, bool is64Bit)
2815 {
2816         const VkFormat formats[] =
2817         {
2818                 VK_FORMAT_R32G32B32A32_UINT,
2819                 VK_FORMAT_R32G32B32A32_SINT,
2820                 VK_FORMAT_R64_UINT,
2821                 VK_FORMAT_R64_SINT,
2822         };
2823         return formats[2u * (is64Bit ? 1u : 0u) + (isSigned ? 1u : 0u)];
2824 }
2825
2826 // INT or UINT format?
2827 bool isIntegralFormat (VkFormat format)
2828 {
2829         return (isIntFormat(format) || isUintFormat(format));
2830 }
2831
2832 // Return the list of formats used for the extension operand tests (SignExten/ZeroExtend).
2833 std::vector<VkFormat> getExtensionOperandFormatList (void)
2834 {
2835         std::vector<VkFormat> formatList;
2836
2837         for (auto format : s_formats)
2838         {
2839                 if (isIntegralFormat(format))
2840                         formatList.push_back(format);
2841         }
2842
2843         formatList.push_back(VK_FORMAT_R64_SINT);
2844         formatList.push_back(VK_FORMAT_R64_UINT);
2845
2846         return formatList;
2847 }
2848
2849 } // anonymous
2850
2851 tcu::TestCaseGroup* createImageExtendOperandsTests(tcu::TestContext& testCtx)
2852 {
2853         using GroupPtr = de::MovePtr<tcu::TestCaseGroup>;
2854
2855         GroupPtr testGroup(new tcu::TestCaseGroup(testCtx, "extend_operands_spirv1p4", "Cases with SignExtend and ZeroExtend"));
2856
2857         const struct
2858         {
2859                 ExtendTestType  testType;
2860                 const char*             name;
2861         } testTypes[] =
2862         {
2863                 { ExtendTestType::READ,                                 "read"  },
2864                 { ExtendTestType::WRITE,                                "write" },
2865         };
2866
2867         const auto texture              = Texture(IMAGE_TYPE_2D, tcu::IVec3(8, 8, 1), 1);
2868         const auto formatList   = getExtensionOperandFormatList();
2869
2870         for (const auto format : formatList)
2871         {
2872                 const auto isInt                = isIntFormat(format);
2873                 const auto isUint               = isUintFormat(format);
2874                 const auto use64Bits    = is64BitIntegerFormat(format);
2875
2876                 DE_ASSERT(isInt || isUint);
2877
2878                 GroupPtr formatGroup (new tcu::TestCaseGroup(testCtx, getFormatShortString(format).c_str(), ""));
2879
2880                 for (const auto& testType : testTypes)
2881                 {
2882                         GroupPtr testTypeGroup (new tcu::TestCaseGroup(testCtx, testType.name, ""));
2883
2884                         for (int match = 0; match < 2; ++match)
2885                         {
2886                                 const bool      mismatched              = (match == 1);
2887                                 const char*     matchGroupName  = (mismatched ? "mismatched_sign" : "matched_sign");
2888
2889                                 // SPIR-V does not allow this kind of sampled type override.
2890                                 if (mismatched && isUint)
2891                                         continue;
2892
2893                                 GroupPtr matchGroup (new tcu::TestCaseGroup(testCtx, matchGroupName, ""));
2894
2895                                 for (int prec = 0; prec < 2; prec++)
2896                                 {
2897                                         const bool relaxedPrecision = (prec != 0);
2898
2899                                         const char* precisionName       = (relaxedPrecision ? "relaxed_precision" : "normal_precision");
2900                                         const auto  signedOther         = ((isInt && !mismatched) || (isUint && mismatched));
2901                                         const auto      otherFormat             = getShaderExtensionOperandFormat(signedOther, use64Bits);
2902                                         const auto  readFormat          = (testType.testType == ExtendTestType::READ ?  format : otherFormat);
2903                                         const auto  writeFormat         = (testType.testType == ExtendTestType::WRITE ? format : otherFormat);
2904
2905                                         if (relaxedPrecision && !relaxedOK(readFormat))
2906                                                 continue;
2907
2908                                         if (!hasSpirvFormat(readFormat) || !hasSpirvFormat(writeFormat))
2909                                                 continue;
2910
2911                                         matchGroup->addChild(new ImageExtendOperandTest(testCtx, precisionName, texture, readFormat, writeFormat, mismatched, relaxedPrecision, testType.testType));
2912                                 }
2913
2914                                 testTypeGroup->addChild(matchGroup.release());
2915                         }
2916
2917                         formatGroup->addChild(testTypeGroup.release());
2918                 }
2919
2920                 testGroup->addChild(formatGroup.release());
2921         }
2922
2923         return testGroup.release();
2924 }
2925
2926 tcu::TestCaseGroup* createImageNontemporalOperandTests(tcu::TestContext& testCtx)
2927 {
2928         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "nontemporal_operand", "Cases with Nontemporal image operand for SPOIR-V 1.6"));
2929
2930         const auto texture = Texture(IMAGE_TYPE_2D, tcu::IVec3(8, 8, 1), 1);
2931
2932         // using just integer formats for tests so that ImageExtendOperandTest could be reused
2933         const auto formatList = getExtensionOperandFormatList();
2934
2935         for (const auto format : formatList)
2936         {
2937                 const std::string       caseName        = getFormatShortString(format);
2938                 const auto                      readFormat      = format;
2939                 const auto                      writeFormat     = getShaderExtensionOperandFormat(isIntFormat(format), is64BitIntegerFormat(format));
2940
2941                 if (!hasSpirvFormat(readFormat) || !hasSpirvFormat(writeFormat))
2942                         continue;
2943
2944                 // note: just testing OpImageWrite as OpImageRead is tested with addComputeImageSamplerTest
2945                 testGroup->addChild(new ImageExtendOperandTest(testCtx, caseName, texture,
2946                         readFormat, writeFormat, false, false, ExtendTestType::WRITE_NONTEMPORAL));
2947         }
2948
2949         return testGroup.release();
2950 }
2951
2952 } // image
2953 } // vkt