blob: 372cd92d464727a190624f83f41c68a4e108a383 [file] [log] [blame]
Nathaniel Cesario56a96652020-12-30 13:23:42 -07001/* Copyright (c) 2015-2021 The Khronos Group Inc.
2 * Copyright (c) 2015-2021 Valve Corporation
3 * Copyright (c) 2015-2021 LunarG, Inc.
Camdeneaa86ea2019-07-26 11:00:09 -06004 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author: Camden Stocker <camden@lunarg.com>
18 */
19
Mark Lobodzinski57b8ae82020-02-20 16:37:14 -070020#include "best_practices_validation.h"
Camden5b184be2019-08-13 07:50:19 -060021#include "layer_chassis_dispatch.h"
Camden Stocker0a660ce2019-08-27 15:30:40 -060022#include "best_practices_error_enums.h"
Sam Wallsd7ab6db2020-06-19 20:41:54 +010023#include "shader_validation.h"
Jeremy Gebbena3705f42021-01-19 16:47:43 -070024#include "sync_utils.h"
Jeremy Gebben159b3cc2021-06-03 09:09:03 -060025#include "cmd_buffer_state.h"
26#include "device_state.h"
27#include "render_pass_state.h"
Camden5b184be2019-08-13 07:50:19 -060028
29#include <string>
Sam Walls8e77e4f2020-03-16 20:47:40 +000030#include <bitset>
Sam Wallsd7ab6db2020-06-19 20:41:54 +010031#include <memory>
Camden5b184be2019-08-13 07:50:19 -060032
Attilio Provenzano19d6a982020-02-27 12:41:41 +000033struct VendorSpecificInfo {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060034 EnableFlags vendor_id;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000035 std::string name;
36};
37
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070038const std::map<BPVendorFlagBits, VendorSpecificInfo> kVendorInfo = {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060039 {kBPVendorArm, {vendor_specific_arm, "Arm"}},
Attilio Provenzano19d6a982020-02-27 12:41:41 +000040};
41
42bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070043 for (const auto& vendor : kVendorInfo) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060044 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000045 return true;
46 }
47 }
48 return false;
49}
50
51const char* VendorSpecificTag(BPVendorFlags vendors) {
52 // Cache built vendor tags in a map
Jeremy Gebbencbf22862021-03-03 12:01:22 -070053 static layer_data::unordered_map<BPVendorFlags, std::string> tag_map;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000054
55 auto res = tag_map.find(vendors);
56 if (res == tag_map.end()) {
57 // Build the vendor tag string
58 std::stringstream vendor_tag;
59
60 vendor_tag << "[";
61 bool first_vendor = true;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070062 for (const auto& vendor : kVendorInfo) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000063 if (vendors & vendor.first) {
64 if (!first_vendor) {
65 vendor_tag << ", ";
66 }
67 vendor_tag << vendor.second.name;
68 first_vendor = false;
69 }
70 }
71 vendor_tag << "]";
72
73 tag_map[vendors] = vendor_tag.str();
74 res = tag_map.find(vendors);
75 }
76
77 return res->second.c_str();
78}
79
Mark Lobodzinski6167e102020-02-24 17:03:55 -070080const char* DepReasonToString(ExtDeprecationReason reason) {
81 switch (reason) {
82 case kExtPromoted:
83 return "promoted to";
84 break;
85 case kExtObsoleted:
86 return "obsoleted by";
87 break;
88 case kExtDeprecated:
89 return "deprecated by";
90 break;
91 default:
92 return "";
93 break;
94 }
95}
96
97bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
98 const char* vuid) const {
99 bool skip = false;
100 auto dep_info_it = deprecated_extensions.find(extension_name);
101 if (dep_info_it != deprecated_extensions.end()) {
102 auto dep_info = dep_info_it->second;
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600103 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
104 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700105 skip |=
106 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
107 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600108 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700109 if (dep_info.target.length() == 0) {
110 skip |= LogWarning(instance, vuid,
111 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
112 "without replacement.",
113 api_name, extension_name);
114 } else {
115 skip |= LogWarning(instance, vuid,
116 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
117 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
118 }
119 }
120 }
121 return skip;
122}
123
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700124bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const char* vuid) const {
125 bool skip = false;
126 auto dep_info_it = special_use_extensions.find(extension_name);
127
128 if (dep_info_it != special_use_extensions.end()) {
129 auto special_uses = dep_info_it->second;
130 std::string message("is intended to support the following uses: ");
131 if (special_uses.find("cadsupport") != std::string::npos) {
132 message.append("specialized functionality used by CAD/CAM applications, ");
133 }
134 if (special_uses.find("d3demulation") != std::string::npos) {
135 message.append("D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D, ");
136 }
137 if (special_uses.find("devtools") != std::string::npos) {
138 message.append(" developer tools such as capture-replay libraries, ");
139 }
140 if (special_uses.find("debugging") != std::string::npos) {
141 message.append("use by applications when debugging, ");
142 }
143 if (special_uses.find("glemulation") != std::string::npos) {
144 message.append(
145 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
146 "specific to those APIs, ");
147 }
148 message.append("and it is strongly recommended that they be otherwise avoided");
149
150 skip |= LogWarning(instance, vuid, "%s(): Attempting to enable extension %s, but this extension %s.", api_name,
151 extension_name, message.c_str());
152 }
153 return skip;
154}
155
Camden5b184be2019-08-13 07:50:19 -0600156bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500157 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600158 bool skip = false;
159
160 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
161 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800162 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700163 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
164 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600165 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600166 uint32_t specified_version =
167 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
168 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700169 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Mark Lobodzinskia431b772020-11-10 08:12:13 -0700170 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i],
171 kVUID_BestPractices_CreateInstance_SpecialUseExtension);
Camden5b184be2019-08-13 07:50:19 -0600172 }
173
174 return skip;
175}
176
177void BestPractices::PreCallRecordCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
178 VkInstance* pInstance) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700179 ValidationStateTracker::PreCallRecordCreateInstance(pCreateInfo, pAllocator, pInstance);
Sam Walls53bf7652020-04-21 17:35:15 +0100180
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700181 if (pCreateInfo != nullptr && pCreateInfo->pApplicationInfo != nullptr) {
Sam Walls53bf7652020-04-21 17:35:15 +0100182 instance_api_version = pCreateInfo->pApplicationInfo->apiVersion;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700183 } else {
Sam Walls53bf7652020-04-21 17:35:15 +0100184 instance_api_version = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700185 }
Camden5b184be2019-08-13 07:50:19 -0600186}
187
188bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500189 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600190 bool skip = false;
191
192 // get API version of physical device passed when creating device.
193 VkPhysicalDeviceProperties physical_device_properties{};
194 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500195 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600196
197 // check api versions and warn if instance api Version is higher than version on device.
198 if (instance_api_version > device_api_version) {
Mark Lobodzinski60880782020-08-11 08:02:07 -0600199 std::string inst_api_name = StringAPIVersion(instance_api_version);
200 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600201
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700202 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
203 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
204 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600205 }
206
207 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
208 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800209 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700210 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
211 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600212 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700213 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], instance_api_version,
214 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Mark Lobodzinskia431b772020-11-10 08:12:13 -0700215 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i],
216 kVUID_BestPractices_CreateDevice_SpecialUseExtension);
Camden5b184be2019-08-13 07:50:19 -0600217 }
218
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600219 const auto bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
220 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700221 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
222 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600223 }
224
Szilard Papp7d2c7952020-06-22 14:38:13 +0100225 if ((VendorCheckEnabled(kBPVendorArm)) && (pCreateInfo->pEnabledFeatures != nullptr) &&
226 (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
227 skip |= LogPerformanceWarning(
228 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
229 "%s vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
230 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
231 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
232 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
233 VendorSpecificTag(kBPVendorArm));
234 }
235
Camden5b184be2019-08-13 07:50:19 -0600236 return skip;
237}
238
239bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500240 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600241 bool skip = false;
242
243 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700244 std::stringstream buffer_hex;
245 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600246
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700247 skip |= LogWarning(
248 device, kVUID_BestPractices_SharingModeExclusive,
249 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
250 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700251 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600252 }
253
254 return skip;
255}
256
257bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500258 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600259 bool skip = false;
260
261 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700262 std::stringstream image_hex;
263 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600264
265 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700266 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
267 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
268 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700269 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600270 }
271
Attilio Provenzano02859b22020-02-27 14:17:28 +0000272 if (VendorCheckEnabled(kBPVendorArm)) {
273 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
274 skip |= LogPerformanceWarning(
275 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
276 "%s vkCreateImage(): Trying to create an image with %u samples. "
277 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
278 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
279 }
280
281 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
282 skip |= LogPerformanceWarning(
283 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
284 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
285 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
286 "and do not need to be backed by physical storage. "
287 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
288 VendorSpecificTag(kBPVendorArm));
289 }
290 }
291
Camden5b184be2019-08-13 07:50:19 -0600292 return skip;
293}
294
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100295void BestPractices::PreCallRecordDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
296 ValidationStateTracker::PreCallRecordDestroyImage(device, image, pAllocator);
297 ReleaseImageUsageState(image);
298}
299
Hans-Kristian Arntzen92664eb2021-03-29 12:19:48 +0200300void BestPractices::PreCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain, const VkAllocationCallbacks* pAllocator) {
Tony-LunarG299187b2021-05-28 09:29:12 -0600301 if (VK_NULL_HANDLE != swapchain) {
302 SWAPCHAIN_NODE* chain = GetSwapchainState(swapchain);
303 for (auto& image : chain->images) {
304 if (image.image_state) {
305 ReleaseImageUsageState(image.image_state->image());
306 }
307 }
Hans-Kristian Arntzen92664eb2021-03-29 12:19:48 +0200308 }
309 ValidationStateTracker::PreCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
310}
311
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100312IMAGE_STATE_BP* BestPractices::GetImageUsageState(VkImage vk_image) {
313 auto itr = imageUsageMap.find(vk_image);
314 if (itr != imageUsageMap.end()) {
315 return &itr->second;
316 } else {
317 auto& state = imageUsageMap[vk_image];
318 IMAGE_STATE* image = GetImageState(vk_image);
319 state.image = image;
320 state.usages.resize(image->createInfo.arrayLayers);
321 for (auto& mips : state.usages) {
322 mips.resize(image->createInfo.mipLevels, IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED);
323 }
324 return &state;
325 }
326}
327
328void BestPractices::ReleaseImageUsageState(VkImage image) {
329 auto itr = imageUsageMap.find(image);
330 if (itr != imageUsageMap.end()) {
331 imageUsageMap.erase(itr);
332 }
333}
334
Camden5b184be2019-08-13 07:50:19 -0600335bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500336 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600337 bool skip = false;
338
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600339 const auto* bp_pd_state = GetPhysicalDeviceStateBP();
340 if (bp_pd_state) {
341 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
342 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
343 "vkCreateSwapchainKHR() called before getting surface capabilities from "
344 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
345 }
Camden83a9c372019-08-14 11:41:38 -0600346
Shannon McPherson73e58c82021-03-05 17:14:26 -0700347 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
348 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600349 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
350 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
351 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
352 }
Camden83a9c372019-08-14 11:41:38 -0600353
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600354 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
355 skip |= LogWarning(
356 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
357 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
358 }
Camden83a9c372019-08-14 11:41:38 -0600359 }
360
Camden5b184be2019-08-13 07:50:19 -0600361 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700362 skip |=
363 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600364 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700365 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
366 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600367 }
368
Szilard Papp48a6da32020-06-10 14:41:59 +0100369 if (pCreateInfo->minImageCount == 2) {
370 skip |= LogPerformanceWarning(
371 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
372 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
373 ", which means double buffering is going "
374 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
375 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
376 "3 to use triple buffering to maximize performance in such cases.",
377 pCreateInfo->minImageCount);
378 }
379
Szilard Pappd5f0f812020-06-22 09:01:29 +0100380 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
381 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
382 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
383 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
384 "Presentation modes which are not FIFO will present the latest available frame and discard other "
385 "frame(s) if any.",
386 VendorSpecificTag(kBPVendorArm));
387 }
388
Camden5b184be2019-08-13 07:50:19 -0600389 return skip;
390}
391
392bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
393 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500394 const VkAllocationCallbacks* pAllocator,
395 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600396 bool skip = false;
397
398 for (uint32_t i = 0; i < swapchainCount; i++) {
399 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700400 skip |= LogWarning(
401 device, kVUID_BestPractices_SharingModeExclusive,
402 "Warning: A shared swapchain (index %" PRIu32
403 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
404 "queues (queueFamilyIndexCount of %" PRIu32 ").",
405 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600406 }
407 }
408
409 return skip;
410}
411
412bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500413 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600414 bool skip = false;
415
416 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
417 VkFormat format = pCreateInfo->pAttachments[i].format;
418 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
419 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
420 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700421 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
422 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
423 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
424 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
425 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600426 }
427 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700428 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
429 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
430 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
431 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
432 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600433 }
434 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000435
436 const auto& attachment = pCreateInfo->pAttachments[i];
437 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
438 bool access_requires_memory =
439 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
440
441 if (FormatHasStencil(format)) {
442 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
443 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
444 }
445
446 if (access_requires_memory) {
447 skip |= LogPerformanceWarning(
448 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
449 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
450 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
451 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
452 i, static_cast<uint32_t>(attachment.samples));
453 }
454 }
Camden5b184be2019-08-13 07:50:19 -0600455 }
456
457 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
458 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
459 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
460 }
461
462 return skip;
463}
464
Tony-LunarG767180f2020-04-23 14:03:59 -0600465bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
466 const VkImageView* image_views) const {
467 bool skip = false;
468
469 // Check for non-transient attachments that should be transient and vice versa
470 for (uint32_t i = 0; i < attachmentCount; ++i) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200471 const auto& attachment = rpci->pAttachments[i];
Tony-LunarG767180f2020-04-23 14:03:59 -0600472 bool attachment_should_be_transient =
473 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
474
475 if (FormatHasStencil(attachment.format)) {
476 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
477 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
478 }
479
480 auto view_state = GetImageViewState(image_views[i]);
481 if (view_state) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200482 const auto& ivci = view_state->create_info;
483 const auto& ici = GetImageState(ivci.image)->createInfo;
Tony-LunarG767180f2020-04-23 14:03:59 -0600484
485 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
486
487 // The check for an image that should not be transient applies to all GPUs
488 if (!attachment_should_be_transient && image_is_transient) {
489 skip |= LogPerformanceWarning(
490 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
491 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
492 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
493 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
494 i);
495 }
496
497 bool supports_lazy = false;
498 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
499 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
500 supports_lazy = true;
501 }
502 }
503
504 // The check for an image that should be transient only applies to GPUs supporting
505 // lazily allocated memory
506 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
507 skip |= LogPerformanceWarning(
508 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
509 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
510 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
511 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
512 i);
513 }
514 }
515 }
516 return skip;
517}
518
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000519bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
520 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
521 bool skip = false;
522
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000523 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800524 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600525 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000526 }
527
528 return skip;
529}
530
Sam Wallse746d522020-03-16 21:20:23 +0000531bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
532 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
533 bool skip = false;
534 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
535
536 if (!skip) {
537 const auto& pool_handle = pAllocateInfo->descriptorPool;
538 auto iter = descriptor_pool_freed_count.find(pool_handle);
539 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
540 // this warning is specific to Arm
541 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
542 skip |= LogPerformanceWarning(
543 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
544 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
545 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
546 VendorSpecificTag(kBPVendorArm));
547 }
548 }
549
550 return skip;
551}
552
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600553void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
554 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000555 if (result == VK_SUCCESS) {
556 // find the free count for the pool we allocated into
557 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
558 if (iter != descriptor_pool_freed_count.end()) {
559 // we record successful allocations by subtracting the allocation count from the last recorded free count
560 const auto alloc_count = pAllocateInfo->descriptorSetCount;
561 // clamp the unsigned subtraction to the range [0, last_free_count]
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700562 if (iter->second > alloc_count) {
Sam Wallse746d522020-03-16 21:20:23 +0000563 iter->second -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700564 } else {
Sam Wallse746d522020-03-16 21:20:23 +0000565 iter->second = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700566 }
Sam Wallse746d522020-03-16 21:20:23 +0000567 }
568 }
569}
570
571void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
572 const VkDescriptorSet* pDescriptorSets, VkResult result) {
573 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
574 if (result == VK_SUCCESS) {
575 // we want to track frees because we're interested in suggesting re-use
576 auto iter = descriptor_pool_freed_count.find(descriptorPool);
577 if (iter == descriptor_pool_freed_count.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700578 descriptor_pool_freed_count.emplace(descriptorPool, descriptorSetCount);
Sam Wallse746d522020-03-16 21:20:23 +0000579 } else {
580 iter->second += descriptorSetCount;
581 }
582 }
583}
584
Camden5b184be2019-08-13 07:50:19 -0600585bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500586 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600587 bool skip = false;
588
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500589 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700590 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
591 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600592 }
593
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000594 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
595 skip |= LogPerformanceWarning(
596 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600597 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
598 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000599 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
600 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
601 }
602
Camden83a9c372019-08-14 11:41:38 -0600603 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
604
605 return skip;
606}
607
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600608void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
609 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
610 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700611 if (result != VK_SUCCESS) {
612 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
613 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800614 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700615 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600616 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700617 return;
618 }
619 num_mem_objects++;
620}
Camden Stocker9738af92019-10-16 13:54:03 -0700621
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600622void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
623 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700624 auto error = std::find(error_codes.begin(), error_codes.end(), result);
625 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000626 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
627 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
628
629 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
630 if (common_failure != common_failure_codes.end()) {
631 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
632 } else {
633 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
634 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700635 return;
636 }
637 auto success = std::find(success_codes.begin(), success_codes.end(), result);
638 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600639 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
640 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500641 }
642}
643
Jeff Bolz5c801d12019-10-09 10:38:45 -0500644bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
645 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700646 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600647 bool skip = false;
648
Camden Stocker9738af92019-10-16 13:54:03 -0700649 const DEVICE_MEMORY_STATE* mem_info = ValidationStateTracker::GetDevMemState(memory);
Camden83a9c372019-08-14 11:41:38 -0600650
Jeremy Gebben5570abe2021-05-16 18:35:13 -0600651 for (const auto& node: mem_info->ObjectBindings()) {
652 const auto& obj = node->Handle();
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600653 LogObjectList objlist(device);
654 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600655 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600656 skip |= LogWarning(objlist, layer_name.c_str(), "VK Object %s still has a reference to mem obj %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600657 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600658 }
659
Camden5b184be2019-08-13 07:50:19 -0600660 return skip;
661}
662
663void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700664 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600665 if (memory != VK_NULL_HANDLE) {
666 num_mem_objects--;
667 }
668}
669
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000670bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600671 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500672 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600673
sfricke-samsunge2441192019-11-06 14:07:57 -0800674 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700675 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
676 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
677 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600678 }
679
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000680 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
681
682 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
683 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
684 skip |= LogPerformanceWarning(
685 device, kVUID_BestPractices_SmallDedicatedAllocation,
686 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600687 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
688 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000689 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
690 }
691
Camden Stockerb603cc82019-09-03 10:09:02 -0600692 return skip;
693}
694
695bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500696 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600697 bool skip = false;
698 const char* api_name = "BindBufferMemory()";
699
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000700 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600701
702 return skip;
703}
704
705bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500706 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600707 char api_name[64];
708 bool skip = false;
709
710 for (uint32_t i = 0; i < bindInfoCount; i++) {
711 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000712 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600713 }
714
715 return skip;
716}
Camden Stockerb603cc82019-09-03 10:09:02 -0600717
718bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500719 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600720 char api_name[64];
721 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600722
Camden Stocker8b798ab2019-09-03 10:33:28 -0600723 for (uint32_t i = 0; i < bindInfoCount; i++) {
724 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000725 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600726 }
727
728 return skip;
729}
730
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000731bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600732 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500733 const IMAGE_STATE* image_state = GetImageState(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600734
sfricke-samsung71bc6572020-04-29 15:49:43 -0700735 if (image_state->disjoint == false) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600736 if (!image_state->memory_requirements_checked[0] && !image_state->external_memory_handle) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700737 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
738 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
739 api_name, report_data->FormatHandle(image).c_str());
740 }
741 } else {
742 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
743 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600744 }
745
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000746 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
747
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600748 if (mem_state->alloc_info.allocationSize == image_state->requirements[0].size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000749 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
750 skip |= LogPerformanceWarning(
751 device, kVUID_BestPractices_SmallDedicatedAllocation,
752 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600753 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
754 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000755 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
756 }
757
758 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
759 // make sure this type is actually used.
760 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
761 // (i.e.most tile - based renderers)
762 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
763 bool supports_lazy = false;
764 uint32_t suggested_type = 0;
765
766 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600767 if ((1u << i) & image_state->requirements[0].memoryTypeBits) {
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000768 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
769 supports_lazy = true;
770 suggested_type = i;
771 break;
772 }
773 }
774 }
775
776 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
777
778 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
779 skip |= LogPerformanceWarning(
780 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600781 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000782 "but this memory type is not LAZILY_ALLOCATED_BIT. You should use memory type %u here instead to save "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600783 "%" PRIu64 " bytes of physical memory.",
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600784 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements[0].size);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000785 }
786 }
787
Camden Stocker8b798ab2019-09-03 10:33:28 -0600788 return skip;
789}
790
791bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500792 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600793 bool skip = false;
794 const char* api_name = "vkBindImageMemory()";
795
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000796 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600797
798 return skip;
799}
800
801bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500802 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600803 char api_name[64];
804 bool skip = false;
805
806 for (uint32_t i = 0; i < bindInfoCount; i++) {
807 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700808 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600809 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
810 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600811 }
812
813 return skip;
814}
815
816bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500817 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600818 char api_name[64];
819 bool skip = false;
820
821 for (uint32_t i = 0; i < bindInfoCount; i++) {
822 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000823 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600824 }
825
826 return skip;
827}
Camden83a9c372019-08-14 11:41:38 -0600828
Attilio Provenzano02859b22020-02-27 14:17:28 +0000829static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
830 switch (format) {
831 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
832 case VK_FORMAT_R16_SFLOAT:
833 case VK_FORMAT_R16G16_SFLOAT:
834 case VK_FORMAT_R16G16B16_SFLOAT:
835 case VK_FORMAT_R16G16B16A16_SFLOAT:
836 case VK_FORMAT_R32_SFLOAT:
837 case VK_FORMAT_R32G32_SFLOAT:
838 case VK_FORMAT_R32G32B32_SFLOAT:
839 case VK_FORMAT_R32G32B32A32_SFLOAT:
840 return false;
841
842 default:
843 return true;
844 }
845}
846
847bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
848 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
849 bool skip = false;
850
851 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700852 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000853
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700854 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
855 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
856 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000857 return skip;
858 }
859
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700860 auto rp_state = GetRenderPassState(create_info->renderPass);
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200861 const auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000862
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +0200863 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
864 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info->pColorBlendState->attachmentCount);
865
866 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200867 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000868 uint32_t att = subpass.pColorAttachments[j].attachment;
869
870 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
871 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
872 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
873 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
874 "color attachment #%u makes use "
875 "of a format which cannot be blended at full throughput when using MSAA.",
876 VendorSpecificTag(kBPVendorArm), i, j);
877 }
878 }
879 }
880 }
881
882 return skip;
883}
884
Camden5b184be2019-08-13 07:50:19 -0600885bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
886 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600887 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500888 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600889 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
890 pAllocator, pPipelines, cgpl_state_data);
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600891 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600892
893 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700894 skip |= LogPerformanceWarning(
895 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
896 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
897 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600898 }
899
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000900 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200901 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000902
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600903 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200904 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600905 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700906 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
907 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600908 count++;
909 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000910 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600911 if (count > kMaxInstancedVertexBuffers) {
912 skip |= LogPerformanceWarning(
913 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
914 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
915 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
916 count, kMaxInstancedVertexBuffers);
917 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000918 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000919
Szilard Pappaaf2da32020-06-22 10:37:35 +0100920 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
921 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +0200922 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
923 VendorCheckEnabled(kBPVendorArm)) {
924 skip |= LogPerformanceWarning(
925 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
926 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
927 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
928 "efficiency during rasterization. Consider disabling depthBias or increasing either "
929 "depthBiasConstantFactor or depthBiasSlopeFactor.",
930 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +0100931 }
932
Attilio Provenzano02859b22020-02-27 14:17:28 +0000933 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000934 }
935
Camden5b184be2019-08-13 07:50:19 -0600936 return skip;
937}
938
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +0200939void BestPractices::PreCallRecordDestroyPipeline(VkDevice device, VkPipeline pipeline, const VkAllocationCallbacks *pAllocator)
940{
941 auto itr = graphicsPipelineCIs.find(pipeline);
942 if (itr != graphicsPipelineCIs.end()) {
943 graphicsPipelineCIs.erase(itr);
944 }
945 ValidationStateTracker::PreCallRecordDestroyPipeline(device, pipeline, pAllocator);
946}
947
Sam Walls0961ec02020-03-31 16:39:15 +0100948void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
949 const VkGraphicsPipelineCreateInfo* pCreateInfos,
950 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
951 VkResult result, void* cgpl_state_data) {
952 for (size_t i = 0; i < count; i++) {
953 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
954 const VkPipeline pipeline_handle = pPipelines[i];
955
956 // record depth stencil state and color blend states for depth pre-pass tracking purposes
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +0200957 GraphicsPipelineCIs& cis = graphicsPipelineCIs[pipeline_handle];
Sam Walls0961ec02020-03-31 16:39:15 +0100958
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200959 auto& create_info = cgpl_state->pCreateInfos[i];
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200960
961 cis.colorBlendStateCI =
962 create_info.pColorBlendState
963 ? new safe_VkPipelineColorBlendStateCreateInfo(create_info.pColorBlendState)
Tony-LunarG412b1b72020-07-15 10:30:13 -0600964 : nullptr;
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200965 cis.depthStencilStateCI =
Tony-LunarG412b1b72020-07-15 10:30:13 -0600966 cgpl_state->pCreateInfos[i].pDepthStencilState
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200967 ? new safe_VkPipelineDepthStencilStateCreateInfo(create_info.pDepthStencilState)
Tony-LunarG412b1b72020-07-15 10:30:13 -0600968 : nullptr;
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200969
970 // Record which frame buffer attachments we should consider to be accessed when a draw call is performed.
971 RENDER_PASS_STATE* rp = GetRenderPassState(create_info.renderPass);
972 auto& subpass = rp->createInfo.pSubpasses[create_info.subpass];
973 cis.accessFramebufferAttachments.clear();
974
975 if (cis.colorBlendStateCI) {
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +0200976 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
977 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, cis.colorBlendStateCI->attachmentCount);
978 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200979 if (cis.colorBlendStateCI->pAttachments[j].colorWriteMask != 0) {
980 uint32_t attachment = subpass.pColorAttachments[j].attachment;
981 if (attachment != VK_ATTACHMENT_UNUSED) {
982 cis.accessFramebufferAttachments.push_back({ attachment, VK_IMAGE_ASPECT_COLOR_BIT });
983 }
984 }
985 }
986 }
987
988 if (cis.depthStencilStateCI && (cis.depthStencilStateCI->depthTestEnable ||
989 cis.depthStencilStateCI->depthBoundsTestEnable ||
990 cis.depthStencilStateCI->stencilTestEnable)) {
991 uint32_t attachment = subpass.pDepthStencilAttachment ?
992 subpass.pDepthStencilAttachment->attachment :
993 VK_ATTACHMENT_UNUSED;
994 if (attachment != VK_ATTACHMENT_UNUSED) {
995 VkImageAspectFlags aspects = 0;
996 if (cis.depthStencilStateCI->depthTestEnable || cis.depthStencilStateCI->depthBoundsTestEnable) {
997 aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
998 }
999 if (cis.depthStencilStateCI->stencilTestEnable) {
1000 aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1001 }
1002 cis.accessFramebufferAttachments.push_back({ attachment, aspects });
1003 }
1004 }
Sam Walls0961ec02020-03-31 16:39:15 +01001005 }
1006}
1007
Camden5b184be2019-08-13 07:50:19 -06001008bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1009 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001010 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001011 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001012 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1013 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001014
1015 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001016 skip |= LogPerformanceWarning(
1017 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1018 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
1019 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001020 }
1021
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001022 if (VendorCheckEnabled(kBPVendorArm)) {
1023 for (size_t i = 0; i < createInfoCount; i++) {
1024 skip |= ValidateCreateComputePipelineArm(pCreateInfos[i]);
1025 }
1026 }
1027
1028 return skip;
1029}
1030
1031bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
1032 bool skip = false;
1033 auto* module = GetShaderModuleState(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001034 // Generate warnings about work group sizes based on active resources.
sfricke-samsung962cad92021-04-13 00:46:29 -07001035 auto entrypoint = module->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001036 if (entrypoint == module->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001037
1038 uint32_t x = 1, y = 1, z = 1;
sfricke-samsung962cad92021-04-13 00:46:29 -07001039 module->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001040
1041 uint32_t thread_count = x * y * z;
1042
1043 // Generate a priori warnings about work group sizes.
1044 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
1045 skip |= LogPerformanceWarning(
1046 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
1047 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1048 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1049 "groups with less than %u threads, especially when using barrier() or shared memory.",
1050 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1051 }
1052
1053 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1054 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1055 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1056 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1057 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1058 "%u, %u) is not aligned to %u "
1059 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1060 "leave threads idle on the shader "
1061 "core.",
1062 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1063 kThreadGroupDispatchCountAlignmentArm);
1064 }
1065
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001066 bool has_writeable_descriptors = false;
locke-lunarg63e4daf2020-08-17 17:53:25 -06001067 bool has_atomic_descriptors = false;
sfricke-samsung962cad92021-04-13 00:46:29 -07001068 auto accessible_ids = module->MarkAccessibleIds(entrypoint);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001069 auto descriptor_uses =
sfricke-samsung962cad92021-04-13 00:46:29 -07001070 module->CollectInterfaceByDescriptorSlot(accessible_ids, &has_writeable_descriptors, &has_atomic_descriptors);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001071
1072 unsigned dimensions = 0;
1073 if (x > 1) dimensions++;
1074 if (y > 1) dimensions++;
1075 if (z > 1) dimensions++;
1076 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1077 dimensions = std::max(dimensions, 1u);
1078
1079 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1080 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1081 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1082 bool accesses_2d = false;
1083 for (const auto& usage : descriptor_uses) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001084 auto dim = module->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001085 if (dim < 0) continue;
1086 auto spvdim = spv::Dim(dim);
1087 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1088 }
1089
1090 if (accesses_2d && dimensions < 2) {
1091 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1092 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1093 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1094 "exhibiting poor spatial locality with respect to one or more shader resources.",
1095 VendorSpecificTag(kBPVendorArm), x, y, z);
1096 }
1097
Camden5b184be2019-08-13 07:50:19 -06001098 return skip;
1099}
1100
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001101bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001102 bool skip = false;
1103
1104 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001105 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1106 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001107 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001108 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1109 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001110 }
1111
1112 return skip;
1113}
1114
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001115bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1116 bool skip = false;
1117
1118 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1119 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1120 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1121 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1122 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1123 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1124 }
1125
1126 return skip;
1127}
1128
1129bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1130 bool skip = false;
1131 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1132
1133 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1134 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1135
1136 return skip;
1137}
1138
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001139void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001140 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1141 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1142 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1143 LogPerformanceWarning(
1144 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1145 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1146 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1147 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1148 "convenient opportunity.",
1149 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1150 }
1151 }
1152}
1153
Jeff Bolz5c801d12019-10-09 10:38:45 -05001154bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1155 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001156 bool skip = false;
1157
1158 for (uint32_t submit = 0; submit < submitCount; submit++) {
1159 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1160 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1161 }
1162 }
1163
1164 return skip;
1165}
1166
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001167bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1168 VkFence fence) const {
1169 bool skip = false;
1170
1171 for (uint32_t submit = 0; submit < submitCount; submit++) {
1172 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1173 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1174 }
1175 }
1176
1177 return skip;
1178}
1179
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001180bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1181 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1182 bool skip = false;
1183
1184 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1185 skip |= LogPerformanceWarning(
1186 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1187 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1188 "pool instead.");
1189 }
1190
1191 return skip;
1192}
1193
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001194void BestPractices::PreCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo)
1195{
1196 // Clear state in case we are a secondary command buffer.
1197 auto& state = cbRenderPassState[commandBuffer];
1198 state = {};
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02001199 auto* cb = GetCBState(commandBuffer);
1200 cb->hasDrawCmd = false;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001201 ValidationStateTracker::PreCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo);
1202}
1203
1204void BestPractices::PreCallRecordDestroyCommandPool(VkDevice device, VkCommandPool commandPool,
1205 const VkAllocationCallbacks *pAllocation)
1206{
1207 COMMAND_POOL_STATE* pool = GetCommandPoolState(commandPool);
1208 if (pool) {
1209 for (auto& cb : pool->commandBuffers) {
1210 auto itr = cbRenderPassState.find(cb);
1211 if (itr != cbRenderPassState.end()) {
1212 cbRenderPassState.erase(itr);
1213 }
1214 }
1215 }
1216 ValidationStateTracker::PreCallRecordDestroyCommandPool(device, commandPool, pAllocation);
1217}
1218
1219void BestPractices::PreCallRecordFreeCommandBuffers(VkDevice device, VkCommandPool commandPool,
1220 uint32_t commandBufferCount, const VkCommandBuffer* pCommandBuffers) {
1221 for (uint32_t i = 0; i < commandBufferCount; i++) {
1222 auto itr = cbRenderPassState.find(pCommandBuffers[i]);
1223 if (itr != cbRenderPassState.end()) {
1224 cbRenderPassState.erase(itr);
1225 }
1226 }
1227 ValidationStateTracker::PreCallRecordFreeCommandBuffers(device, commandPool, commandBufferCount, pCommandBuffers);
1228}
1229
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001230bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1231 const VkCommandBufferBeginInfo* pBeginInfo) const {
1232 bool skip = false;
1233
1234 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1235 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1236 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1237 }
1238
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001239 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && VendorCheckEnabled(kBPVendorArm)) {
1240 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Attilio Provenzano02859b22020-02-27 14:17:28 +00001241 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1242 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1243 VendorSpecificTag(kBPVendorArm));
1244 }
1245
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001246 return skip;
1247}
1248
Jeff Bolz5c801d12019-10-09 10:38:45 -05001249bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001250 bool skip = false;
1251
1252 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1253
1254 return skip;
1255}
1256
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001257bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1258 const VkDependencyInfoKHR* pDependencyInfo) const {
1259 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1260}
1261
Jeff Bolz5c801d12019-10-09 10:38:45 -05001262bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1263 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001264 bool skip = false;
1265
1266 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1267
1268 return skip;
1269}
1270
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001271bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1272 VkPipelineStageFlags2KHR stageMask) const {
1273 bool skip = false;
1274
1275 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1276
1277 return skip;
1278}
1279
Camden5b184be2019-08-13 07:50:19 -06001280bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1281 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1282 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1283 uint32_t bufferMemoryBarrierCount,
1284 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1285 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001286 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001287 bool skip = false;
1288
1289 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1290 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1291
1292 return skip;
1293}
1294
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001295bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1296 const VkDependencyInfoKHR* pDependencyInfos) const {
1297 bool skip = false;
1298 for (uint32_t i = 0; i < eventCount; i++) {
1299 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1300 }
1301
1302 return skip;
1303}
1304
Camden5b184be2019-08-13 07:50:19 -06001305bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1306 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1307 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1308 uint32_t bufferMemoryBarrierCount,
1309 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1310 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001311 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001312 bool skip = false;
1313
1314 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1315 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1316
1317 return skip;
1318}
1319
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001320bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1321 const VkDependencyInfoKHR* pDependencyInfo) const {
1322 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1323}
1324
Camden5b184be2019-08-13 07:50:19 -06001325bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001326 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001327 bool skip = false;
1328
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001329 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1330
1331 return skip;
1332}
1333
1334bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1335 VkQueryPool queryPool, uint32_t query) const {
1336 bool skip = false;
1337
1338 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001339
1340 return skip;
1341}
1342
Sam Walls0961ec02020-03-31 16:39:15 +01001343void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1344 VkPipeline pipeline) {
1345 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1346
1347 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1348 // check for depth/blend state tracking
1349 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1350 if (gp_cis != graphicsPipelineCIs.end()) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001351 auto& render_pass_state = cbRenderPassState[commandBuffer];
Sam Walls0961ec02020-03-31 16:39:15 +01001352
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001353 render_pass_state.nextDrawTouchesAttachments = gp_cis->second.accessFramebufferAttachments;
1354 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001355
Sam Walls0961ec02020-03-31 16:39:15 +01001356 const auto* blend_state = gp_cis->second.colorBlendStateCI;
1357 const auto* stencil_state = gp_cis->second.depthStencilStateCI;
1358
1359 if (blend_state) {
1360 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001361 render_pass_state.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001362 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1363 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001364 render_pass_state.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001365 }
1366 }
1367 }
1368
1369 // check for depth value usage
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001370 render_pass_state.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001371
1372 if (stencil_state && stencil_state->depthTestEnable) {
1373 switch (stencil_state->depthCompareOp) {
1374 case VK_COMPARE_OP_EQUAL:
1375 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1376 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001377 render_pass_state.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001378 break;
1379 default:
1380 break;
1381 }
1382 }
Sam Walls0961ec02020-03-31 16:39:15 +01001383 }
1384 }
1385}
1386
Attilio Provenzano02859b22020-02-27 14:17:28 +00001387static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1388 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001389 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001390
1391 // If an attachment is ever used as a color attachment,
1392 // resolve attachment or depth stencil attachment,
1393 // it needs to exist on tile at some point.
1394
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001395 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1396 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001397 }
1398
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001399 if (subpass_info.pResolveAttachments) {
1400 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1401 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1402 }
1403 }
1404
1405 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001406 }
1407
1408 return false;
1409}
1410
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001411static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1412 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1413 return false;
1414 }
1415
1416 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001417 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001418
1419 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1420 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1421 return true;
1422 }
1423 }
1424 }
1425
1426 return false;
1427}
1428
Attilio Provenzano02859b22020-02-27 14:17:28 +00001429bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1430 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1431 bool skip = false;
1432
1433 if (!pRenderPassBegin) {
1434 return skip;
1435 }
1436
1437 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1438 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001439 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001440 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001441 if (rpabi) {
1442 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1443 }
1444 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001445 // Check if any attachments have LOAD operation on them
1446 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001447 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001448
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001449 bool attachment_has_readback = false;
Hans-Kristian Arntzen4afb59b2021-06-18 12:41:36 +02001450 if (!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001451 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001452 }
1453
1454 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001455 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001456 }
1457
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001458 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001459
1460 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001461 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1462 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001463 }
1464
1465 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001466 if (attachment_needs_readback && VendorCheckEnabled(kBPVendorArm)) {
1467 skip |= LogPerformanceWarning(
1468 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1469 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1470 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
1471 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
1472 VendorSpecificTag(kBPVendorArm), att,
1473 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1474 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1475 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001476 }
1477 }
1478 }
1479
1480 return skip;
1481}
1482
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001483void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
1484 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001485 if (view) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001486 QueueValidateImage(funcs, function_name, GetImageUsageState(view->create_info.image), usage, view->create_info.subresourceRange);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001487 }
1488}
1489
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001490void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1491 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001492 const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001493 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001494
1495 // If we're viewing a 3D slice, ignore base array layer.
1496 // The entire 3D subresource is accessed as one atomic unit.
1497 const uint32_t base_array_layer = image->createInfo.imageType == VK_IMAGE_TYPE_3D ? 0 : subresource_range.baseArrayLayer;
1498
1499 const uint32_t max_layers = image->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001500 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
1501 const uint32_t max_levels = image->createInfo.mipLevels - subresource_range.baseMipLevel;
1502 const uint32_t mip_levels = std::min(image->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001503
1504 for (uint32_t layer = 0; layer < array_layers; layer++) {
1505 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001506 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
1507 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001508 }
1509 }
1510}
1511
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001512void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1513 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001514 const VkImageSubresourceLayers& subresource_layers) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001515 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001516 const uint32_t max_layers = image->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
1517 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001518
1519 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001520 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001521 }
1522}
1523
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001524void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1525 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001526 uint32_t array_layer, uint32_t mip_level) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001527 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](const ValidationStateTracker*, const QUEUE_STATE*) -> bool {
1528 ValidateImageInQueue(function_name, state, usage, array_layer, mip_level);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001529 return false;
1530 });
1531}
1532
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001533void BestPractices::ValidateImageInQueueArm(const char* function_name, IMAGE_STATE* image,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001534 IMAGE_SUBRESOURCE_USAGE_BP last_usage,
1535 IMAGE_SUBRESOURCE_USAGE_BP usage,
1536 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001537 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001538 if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED && last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED &&
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001539 !image->is_swapchain_image) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001540 LogPerformanceWarning(
1541 device, kVUID_BestPractices_RenderPass_RedundantStore,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001542 "%s: %s Subresource (arrayLayer: %u, mipLevel: %u) of image was cleared as part of LOAD_OP_CLEAR, but last time "
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001543 "image was used, it was written to with STORE_OP_STORE. "
1544 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1545 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001546 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001547 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED && last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001548 LogPerformanceWarning(
1549 device, kVUID_BestPractices_RenderPass_RedundantClear,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001550 "%s: %s Subresource (arrayLayer: %u, mipLevel: %u) of image was cleared as part of LOAD_OP_CLEAR, but last time "
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001551 "image was used, it was written to with vkCmdClear*Image(). "
1552 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1553 "tile-based architectures."
1554 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001555 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001556 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
1557 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE ||
1558 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
1559 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE ||
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001560 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001561 const char *last_cmd = nullptr;
1562 const char *vuid = nullptr;
1563 const char *suggestion = nullptr;
1564
1565 switch (last_usage) {
1566 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
1567 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
1568 last_cmd = "vkCmdBlitImage";
1569 suggestion =
1570 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1571 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
1572 "which avoids the memory roundtrip.";
1573 break;
1574 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
1575 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
1576 last_cmd = "vkCmdClear*Image";
1577 suggestion =
1578 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1579 "tile-based architectures. "
1580 "Use LOAD_OP_CLEAR instead to clear the image for free.";
1581 break;
1582 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
1583 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
1584 last_cmd = "vkCmdCopy*Image";
1585 suggestion =
1586 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1587 "Rather than copying, just render the source image in a fragment shader in this render pass, "
1588 "which avoids the memory roundtrip.";
1589 break;
1590 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
1591 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
1592 last_cmd = "vkCmdResolveImage";
1593 suggestion =
1594 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
1595 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
1596 "which avoids the memory roundtrip.";
1597 break;
1598 default:
1599 break;
1600 }
1601
1602 LogPerformanceWarning(
1603 device, vuid,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001604 "%s: %s Subresource (arrayLayer: %u, mipLevel: %u) of image was loaded to tile as part of LOAD_OP_LOAD, but last "
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001605 "time image was used, it was written to with %s. %s",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001606 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level, last_cmd, suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001607 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001608}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001609
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001610void BestPractices::ValidateImageInQueue(const char* function_name, IMAGE_STATE_BP* state,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001611 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer,
1612 uint32_t mip_level) {
1613 IMAGE_STATE* image = state->image;
1614 IMAGE_SUBRESOURCE_USAGE_BP last_usage = state->usages[array_layer][mip_level];
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001615 state->usages[array_layer][mip_level] = usage;
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001616 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001617 ValidateImageInQueueArm(function_name, image, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001618 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001619}
1620
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001621void BestPractices::AddDeferredQueueOperations(CMD_BUFFER_STATE* cb) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001622 cb->queue_submit_functions.insert(cb->queue_submit_functions.end(),
Hans-Kristian Arntzenf44df192021-06-14 11:42:08 +02001623 cb->queue_submit_functions_after_render_pass.begin(),
1624 cb->queue_submit_functions_after_render_pass.end());
1625 cb->queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001626}
1627
1628void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
1629 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001630 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001631}
1632
1633void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
1634 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001635 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001636}
1637
1638void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
1639 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001640 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001641}
1642
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001643void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer,
1644 const VkRenderPassBeginInfo* pRenderPassBegin,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001645 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001646 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001647 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1648}
1649
1650void BestPractices::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer,
1651 const VkRenderPassBeginInfo* pRenderPassBegin,
1652 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1653 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1654 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1655}
1656
1657void BestPractices::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1658 const VkRenderPassBeginInfo* pRenderPassBegin,
1659 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1660 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1661 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1662}
1663
1664void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001665
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001666 if (!pRenderPassBegin) {
1667 return;
1668 }
1669
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001670 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
1671
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001672 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1673 if (rp_state) {
1674 // Check load ops
1675 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001676 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001677
1678 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
1679 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1680 continue;
1681 }
1682
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001683 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001684
1685 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
1686 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001687 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001688 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
1689 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001690 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001691 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001692 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001693 }
1694
1695 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001696 IMAGE_VIEW_STATE* image_view = nullptr;
1697
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001698 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001699 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1700 if (rpabi) {
1701 image_view = GetImageViewState(rpabi->pAttachments[att]);
1702 }
1703 } else {
1704 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1705 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001706
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001707 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view, usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001708 }
1709
1710 // Check store ops
1711 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001712 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001713
1714 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1715 continue;
1716 }
1717
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001718 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001719
1720 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
1721 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001722 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001723 }
1724
1725 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001726
1727 IMAGE_VIEW_STATE* image_view = nullptr;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001728 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001729 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1730 if (rpabi) {
1731 image_view = GetImageViewState(rpabi->pAttachments[att]);
1732 }
1733 } else {
1734 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1735 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001736
Hans-Kristian Arntzenf44df192021-06-14 11:42:08 +02001737 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view, usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001738 }
1739 }
1740}
1741
Attilio Provenzano02859b22020-02-27 14:17:28 +00001742bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1743 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001744 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1745 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001746 return skip;
1747}
1748
1749bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1750 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001751 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001752 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1753 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001754 return skip;
1755}
1756
1757bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001758 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001759 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1760 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001761 return skip;
1762}
1763
Sam Walls0961ec02020-03-31 16:39:15 +01001764void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1765 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001766 // Reset the renderpass state
1767 auto& render_pass_state = cbRenderPassState[commandBuffer];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02001768 render_pass_state.touchesAttachments.clear();
1769 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001770 render_pass_state.numDrawCallsDepthOnly = 0;
1771 render_pass_state.numDrawCallsDepthEqualCompare = 0;
1772 render_pass_state.colorAttachment = false;
1773 render_pass_state.depthAttachment = false;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001774 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001775 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01001776
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02001777 auto* cb = GetCBState(commandBuffer);
1778 cb->hasDrawCmd = false;
1779
Hans-Kristian Arntzena1a92cc2021-03-17 13:09:33 +01001780 const auto* rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01001781
1782 // track depth / color attachment usage within the renderpass
1783 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1784 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001785 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001786
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001787 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001788 }
1789}
1790
1791void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1792 VkSubpassContents contents) {
1793 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1794 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1795}
1796
1797void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1798 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1799 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1800 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1801}
1802
1803void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1804 const VkRenderPassBeginInfo* pRenderPassBegin,
1805 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1806 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1807 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1808}
1809
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001810// Generic function to handle validation for all CmdDraw* type functions
1811bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1812 bool skip = false;
1813 const CMD_BUFFER_STATE* cb_state = GetCBState(cmd_buffer);
1814 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001815 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1816 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001817 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001818
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001819 // Verify vertex binding
1820 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1821 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001822 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001823 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001824 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
1825 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001826 }
1827 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001828
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06001829 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001830 if (pipe) {
1831 const auto* rp_state = pipe->rp_state.get();
1832 if (rp_state) {
1833 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
1834 const auto& subpass = rp_state->createInfo.pSubpasses[i];
1835 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(
1836 pipe->graphicsPipelineCI.pDepthStencilState, subpass.pDepthStencilAttachment);
1837 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && pipe->graphicsPipelineCI.pRasterizationState &&
1838 pipe->graphicsPipelineCI.pRasterizationState->depthBiasEnable == VK_TRUE) {
1839 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
1840 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
1841 }
1842 }
1843 }
1844 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001845 }
1846 return skip;
1847}
1848
Sam Walls0961ec02020-03-31 16:39:15 +01001849void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001850 auto& render_pass_state = cbRenderPassState[cmd_buffer];
Sam Walls0961ec02020-03-31 16:39:15 +01001851 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001852 RecordCmdDrawTypeArm(render_pass_state, draw_count, caller);
1853 }
1854
1855 if (render_pass_state.drawTouchAttachments) {
1856 for (auto& touch : render_pass_state.nextDrawTouchesAttachments) {
1857 RecordAttachmentAccess(render_pass_state, touch.framebufferAttachment, touch.aspects);
1858 }
1859 // No need to touch the same attachments over and over.
1860 render_pass_state.drawTouchAttachments = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001861 }
1862}
1863
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001864void BestPractices::RecordCmdDrawTypeArm(RenderPassState& render_pass_state, uint32_t draw_count, const char* caller) {
1865 if (draw_count >= kDepthPrePassMinDrawCountArm) {
1866 if (render_pass_state.depthOnly) render_pass_state.numDrawCallsDepthOnly++;
1867 if (render_pass_state.depthEqualComparison) render_pass_state.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01001868 }
1869}
1870
Camden5b184be2019-08-13 07:50:19 -06001871bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001872 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001873 bool skip = false;
1874
1875 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001876 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1877 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001878 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001879 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001880
1881 return skip;
1882}
1883
Sam Walls0961ec02020-03-31 16:39:15 +01001884void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1885 uint32_t firstVertex, uint32_t firstInstance) {
1886 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
1887 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
1888}
1889
Camden5b184be2019-08-13 07:50:19 -06001890bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001891 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001892 bool skip = false;
1893
1894 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001895 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1896 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001897 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001898 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1899
Attilio Provenzano02859b22020-02-27 14:17:28 +00001900 // Check if we reached the limit for small indexed draw calls.
1901 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1902 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1903 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001904 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
1905 VendorCheckEnabled(kBPVendorArm)) {
1906 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06001907 "%s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00001908 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1909 "You can try batching drawcalls or instancing when applicable.",
1910 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1911 }
1912
Sam Walls8e77e4f2020-03-16 20:47:40 +00001913 if (VendorCheckEnabled(kBPVendorArm)) {
1914 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1915 }
1916
1917 return skip;
1918}
1919
1920bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1921 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1922 bool skip = false;
1923
1924 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1925 const auto* cmd_state = GetCBState(commandBuffer);
1926 if (cmd_state == nullptr) return skip;
1927
locke-lunarg1ae57d62020-11-18 10:49:19 -07001928 const auto* ib_state = cmd_state->index_buffer_binding.buffer_state.get();
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06001929 if (ib_state == nullptr || cmd_state->index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001930
1931 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06001932 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00001933 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1934 const void* ib_mem = ib_mem_state.p_driver_data;
1935 bool primitive_restart_enable = false;
1936
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001937 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1938 const auto& pipeline_binding_iter = cmd_state->lastBound[lv_bind_point];
1939 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001940
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001941 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001942 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001943 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00001944
1945 // no point checking index buffer if the memory is nonexistant/unmapped, or if there is no graphics pipeline bound to this CB
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001946 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00001947 uint32_t scan_stride;
1948 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1949 scan_stride = sizeof(uint8_t);
1950 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1951 scan_stride = sizeof(uint16_t);
1952 } else {
1953 scan_stride = sizeof(uint32_t);
1954 }
1955
1956 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1957 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1958
1959 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1960 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1961 // irrespective of whether or not they're part of the draw call.
1962
1963 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1964 uint32_t min_index = ~0u;
1965 // start with maximum as 0 and adjust to indices in the buffer
1966 uint32_t max_index = 0u;
1967
1968 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
1969 // for the given index buffer
1970 uint32_t vertex_shade_count = 0;
1971
1972 PostTransformLRUCacheModel post_transform_cache;
1973
1974 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
1975 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
1976 // target architecture.
1977 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
1978 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
1979 post_transform_cache.resize(32);
1980
1981 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1982 uint32_t scan_index;
1983 uint32_t primitive_restart_value;
1984 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1985 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1986 primitive_restart_value = 0xFF;
1987 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1988 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1989 primitive_restart_value = 0xFFFF;
1990 } else {
1991 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1992 primitive_restart_value = 0xFFFFFFFF;
1993 }
1994
1995 max_index = std::max(max_index, scan_index);
1996 min_index = std::min(min_index, scan_index);
1997
1998 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
1999 bool in_cache = post_transform_cache.query_cache(scan_index);
2000 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
2001 if (!in_cache) vertex_shade_count++;
2002 }
2003 }
2004
2005 // if the max and min values were not set, then we either have no indices, or all primitive restarts, exit...
Sam Walls61b06892020-07-23 16:20:50 +01002006 // if the max and min are the same, then it implies all the indices are the same, then we don't need to do anything
2007 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002008
2009 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07002010 skip |=
2011 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2012 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
2013 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
2014 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
2015 "maximum would be loaded, and possibly shaded, whether or not they are used.",
2016 VendorSpecificTag(kBPVendorArm),
2017 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002018 return skip;
2019 }
2020
2021 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
2022 // each bit of the n-th bucket contains the inclusion information for indices (n*n_buckets) to ((n+1)*n_buckets)
Sam Walls61b06892020-07-23 16:20:50 +01002023 const size_t refs_per_bucket = 64;
2024 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
2025
2026 const uint32_t n_indices = max_index - min_index + 1;
2027 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
2028 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
2029
2030 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
2031 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00002032
2033 // To avoid using too much memory, we run over the indices again.
2034 // Knowing the size from the last scan allows us to record index usage with bitsets
2035 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2036 uint32_t scan_index;
2037 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2038 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2039 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2040 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2041 } else {
2042 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2043 }
2044 // keep track of the set of all indices used to reference vertices in the draw call
2045 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01002046 size_t bitset_bucket_index = index_offset / refs_per_bucket;
2047 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002048 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
2049 }
2050
2051 uint32_t vertex_reference_count = 0;
2052 for (const auto& bitset : vertex_reference_buckets) {
2053 vertex_reference_count += static_cast<uint32_t>(bitset.count());
2054 }
2055
2056 // low index buffer utilization implies that: of the vertices available to the draw call, not all are utilized
Mark Young0ec6b062020-11-19 15:32:17 -07002057 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002058 // low hit rate (high miss rate) implies the order of indices in the draw call may be possible to improve
Mark Young0ec6b062020-11-19 15:32:17 -07002059 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002060
2061 if (utilization < 0.5f) {
2062 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2063 "%s The indices which were specified for the draw call only utilise approximately "
2064 "%.02f%% of the bound vertex buffer.",
2065 VendorSpecificTag(kBPVendorArm), utilization);
2066 }
2067
2068 if (cache_hit_rate <= 0.5f) {
2069 skip |=
2070 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
2071 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
2072 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
2073 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
2074 "recently shaded vertices.",
2075 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
2076 }
2077 }
2078
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002079 return skip;
2080}
2081
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002082bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2083 const VkCommandBuffer* pCommandBuffers) const {
2084 bool skip = false;
2085 const CMD_BUFFER_STATE* primary = GetCBState(commandBuffer);
2086 for (uint32_t i = 0; i < commandBufferCount; i++) {
2087 auto secondary_itr = cbRenderPassState.find(pCommandBuffers[i]);
2088 if (secondary_itr == cbRenderPassState.end()) {
2089 continue;
2090 }
2091 auto& secondary = secondary_itr->second;
2092 for (auto& clear : secondary.earlyClearAttachments) {
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002093 if (ClearAttachmentsIsFullClear(primary, uint32_t(clear.rects.size()), clear.rects.data())) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002094 skip |= ValidateClearAttachment(commandBuffer, primary,
2095 clear.framebufferAttachment, clear.colorAttachment,
2096 clear.aspects, true);
2097 }
2098 }
2099 }
2100 return skip;
2101}
2102
2103void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2104 const VkCommandBuffer* pCommandBuffers) {
2105 CMD_BUFFER_STATE* primary = GetCBState(commandBuffer);
2106 auto& primary_state = cbRenderPassState[commandBuffer];
2107
2108 for (uint32_t i = 0; i < commandBufferCount; i++) {
2109 auto& secondary = cbRenderPassState[pCommandBuffers[i]];
2110
2111 for (auto& early_clear : secondary.earlyClearAttachments) {
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002112 if (ClearAttachmentsIsFullClear(primary, uint32_t(early_clear.rects.size()), early_clear.rects.data())) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002113 RecordAttachmentClearAttachments(primary, primary_state, early_clear.framebufferAttachment,
2114 early_clear.colorAttachment, early_clear.aspects,
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002115 uint32_t(early_clear.rects.size()), early_clear.rects.data());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002116 } else {
2117 RecordAttachmentAccess(primary_state, early_clear.framebufferAttachment,
2118 early_clear.aspects);
2119 }
2120 }
2121
2122 for (auto& touch : secondary.touchesAttachments) {
2123 RecordAttachmentAccess(primary_state, touch.framebufferAttachment,
2124 touch.aspects);
2125 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02002126
2127 primary_state.numDrawCallsDepthEqualCompare += secondary.numDrawCallsDepthEqualCompare;
2128 primary_state.numDrawCallsDepthOnly += secondary.numDrawCallsDepthOnly;
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002129
2130 CMD_BUFFER_STATE* second_state = GetCBState(pCommandBuffers[i]);
2131 if (second_state->hasDrawCmd) {
2132 primary->hasDrawCmd = true;
2133 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002134 }
2135
2136 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2137}
2138
2139void BestPractices::RecordAttachmentAccess(RenderPassState& state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
2140 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
2141 auto itr = std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002142 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002143 return info.framebufferAttachment == fb_attachment;
2144 });
2145
2146 if (itr != state.touchesAttachments.end()) {
2147 itr->aspects |= aspects;
2148 } else {
2149 state.touchesAttachments.push_back({ fb_attachment, aspects });
2150 }
2151}
2152
2153void BestPractices::RecordAttachmentClearAttachments(CMD_BUFFER_STATE* cmd_state, RenderPassState& state,
2154 uint32_t fb_attachment, uint32_t color_attachment,
2155 VkImageAspectFlags aspects, uint32_t rectCount,
2156 const VkClearRect *pRects) {
2157 // If we observe a full clear before any other access to a frame buffer attachment,
2158 // we have candidate for redundant clear attachments.
2159 auto itr = std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002160 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002161 return info.framebufferAttachment == fb_attachment;
2162 });
2163
2164 uint32_t new_aspects = aspects;
2165 if (itr != state.touchesAttachments.end()) {
2166 new_aspects = aspects & ~itr->aspects;
2167 itr->aspects |= aspects;
2168 } else {
2169 state.touchesAttachments.push_back({ fb_attachment, aspects });
2170 }
2171
2172 if (new_aspects == 0) {
2173 return;
2174 }
2175
2176 if (cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2177 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
2178 // CmdExecuteCommands.
2179 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
2180 std::vector<VkClearRect>{pRects, pRects + rectCount} });
2181 }
2182}
2183
2184void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
2185 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
2186 uint32_t rectCount, const VkClearRect* pRects) {
2187 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
2188 RENDER_PASS_STATE* rp_state = cmd_state->activeRenderPass.get();
2189 FRAMEBUFFER_STATE* fb_state = cmd_state->activeFramebuffer.get();
2190 RenderPassState& tracking_state = cbRenderPassState[commandBuffer];
2191 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
2192
2193 if (rectCount == 0 || !rp_state) {
2194 return;
2195 }
2196
2197 if (!is_secondary && !fb_state) {
2198 return;
2199 }
2200
2201 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
2202 bool full_clear = ClearAttachmentsIsFullClear(cmd_state, rectCount, pRects);
2203
2204 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
2205 for (uint32_t i = 0; i < attachmentCount; i++) {
2206 auto& attachment = pClearAttachments[i];
2207 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
2208 VkImageAspectFlags aspects = attachment.aspectMask;
2209
2210 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
2211 if (subpass.pDepthStencilAttachment) {
2212 fb_attachment = subpass.pDepthStencilAttachment->attachment;
2213 }
2214 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
2215 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
2216 }
2217
2218 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2219 if (full_clear) {
2220 RecordAttachmentClearAttachments(cmd_state, tracking_state,
2221 fb_attachment, attachment.colorAttachment, aspects,
2222 rectCount, pRects);
2223 } else {
2224 RecordAttachmentAccess(tracking_state, fb_attachment, aspects);
2225 }
2226 }
2227 }
2228
2229 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments,
2230 rectCount, pRects);
2231}
2232
Attilio Provenzano02859b22020-02-27 14:17:28 +00002233void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2234 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2235 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
2236 firstInstance);
2237
2238 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
2239 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
2240 cmd_state->small_indexed_draw_call_count++;
2241 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002242
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002243 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00002244}
2245
Sam Walls0961ec02020-03-31 16:39:15 +01002246void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2247 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2248 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2249 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
2250}
2251
sfricke-samsung681ab7b2020-10-29 01:53:35 -07002252bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2253 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
2254 uint32_t maxDrawCount, uint32_t stride) const {
2255 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
2256
2257 return skip;
2258}
2259
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002260bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
2261 VkDeviceSize offset, VkBuffer countBuffer,
2262 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
2263 uint32_t stride) const {
2264 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06002265
2266 return skip;
2267}
2268
2269bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002270 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002271 bool skip = false;
2272
2273 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002274 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2275 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002276 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002277 }
2278
2279 return skip;
2280}
2281
Sam Walls0961ec02020-03-31 16:39:15 +01002282void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2283 uint32_t count, uint32_t stride) {
2284 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
2285 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
2286}
2287
Camden5b184be2019-08-13 07:50:19 -06002288bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002289 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002290 bool skip = false;
2291
2292 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002293 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2294 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002295 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002296 }
2297
2298 return skip;
2299}
2300
Sam Walls0961ec02020-03-31 16:39:15 +01002301void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2302 uint32_t count, uint32_t stride) {
2303 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
2304 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
2305}
2306
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002307void BestPractices::ValidateBoundDescriptorSets(VkCommandBuffer commandBuffer, const char* function_name) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002308 CMD_BUFFER_STATE* cb_state = GetCBState(commandBuffer);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002309
2310 if (cb_state) {
2311 for (auto descriptor_set : cb_state->validated_descriptor_sets) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002312 const auto& layout = *descriptor_set->GetLayout();
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002313
2314 for (uint32_t index = 0; index < descriptor_set->GetBindingCount(); ++index) {
2315 // For bindless scenarios, we should not attempt to track descriptor set state.
2316 // It is highly uncertain which resources are actually bound.
2317 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
2318 VkDescriptorBindingFlags flags = layout.GetDescriptorBindingFlagsFromIndex(index);
2319 if (flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT |
2320 VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
2321 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
2322 continue;
2323 }
2324
2325 auto index_range = layout.GetGlobalIndexRangeFromIndex(index);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002326 for (uint32_t i = index_range.start; i < index_range.end; ++i) {
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002327 VkImageView image_view{VK_NULL_HANDLE};
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002328
2329 auto descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2330 switch (descriptor->GetClass()) {
2331 case cvdescriptorset::DescriptorClass::Image: {
2332 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
2333 image_view = image_descriptor->GetImageView();
2334 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002335 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002336 }
2337 case cvdescriptorset::DescriptorClass::ImageSampler: {
2338 if (const auto image_sampler_descriptor =
2339 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
2340 image_view = image_sampler_descriptor->GetImageView();
2341 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002342 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002343 }
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002344 default:
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002345 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002346 }
2347
2348 if (image_view) {
2349 IMAGE_VIEW_STATE* image_view_state = GetImageViewState(image_view);
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002350 QueueValidateImageView(cb_state->queue_submit_functions, function_name,
2351 image_view_state, IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002352 }
2353 }
2354 }
2355 }
2356 }
2357}
2358
2359void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2360 uint32_t firstVertex, uint32_t firstInstance) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002361 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002362}
2363
2364void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2365 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002366 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002367}
2368
2369void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2370 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002371 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002372}
2373
Camden5b184be2019-08-13 07:50:19 -06002374bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002375 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06002376 bool skip = false;
2377
2378 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002379 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
2380 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
2381 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
2382 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06002383 }
2384
2385 return skip;
2386}
Camden83a9c372019-08-14 11:41:38 -06002387
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002388bool BestPractices::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2389 bool skip = false;
2390 skip |= StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
2391 skip |= ValidateCmdEndRenderPass(commandBuffer);
2392 return skip;
2393}
2394
2395bool BestPractices::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2396 bool skip = false;
2397 skip |= StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
2398 skip |= ValidateCmdEndRenderPass(commandBuffer);
2399 return skip;
2400}
2401
Sam Walls0961ec02020-03-31 16:39:15 +01002402bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2403 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002404 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002405 skip |= ValidateCmdEndRenderPass(commandBuffer);
2406 return skip;
2407}
2408
2409bool BestPractices::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2410 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002411
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02002412 auto render_pass_state = cbRenderPassState.find(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01002413
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02002414 if (render_pass_state == cbRenderPassState.end()) return skip;
Sam Walls0961ec02020-03-31 16:39:15 +01002415
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02002416 bool uses_depth = (render_pass_state->second.depthAttachment || render_pass_state->second.colorAttachment) &&
2417 render_pass_state->second.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2418 render_pass_state->second.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
Sam Walls0961ec02020-03-31 16:39:15 +01002419 if (uses_depth) {
2420 skip |= LogPerformanceWarning(
2421 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
2422 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
2423 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
2424 "case, using depth pre-passes for hidden surface removal may worsen performance.",
2425 VendorSpecificTag(kBPVendorArm));
2426 }
2427
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002428 const CMD_BUFFER_STATE* cmd = GetCBState(commandBuffer);
2429 RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2430
2431 if (VendorCheckEnabled(kBPVendorArm) && rp) {
2432
2433 // If we use an attachment on-tile, we should access it in some way. Otherwise,
2434 // it is redundant to have it be part of the render pass.
2435 // Only consider it redundant if it will actually consume bandwidth, i.e.
2436 // LOAD_OP_LOAD is used or STORE_OP_STORE. CLEAR -> DONT_CARE is benign,
2437 // as is using pure input attachments.
2438 // CLEAR -> STORE might be considered a "useful" thing to do, but
2439 // the optimal thing to do is to defer the clear until you're actually
2440 // going to render to the image.
2441
2442 uint32_t num_attachments = rp->createInfo.attachmentCount;
2443 for (uint32_t i = 0; i < num_attachments; i++) {
2444 if (!RenderPassUsesAttachmentOnTile(rp->createInfo, i)) {
2445 continue;
2446 }
2447
2448 auto& attachment = rp->createInfo.pAttachments[i];
2449
2450 VkImageAspectFlags bandwidth_aspects = 0;
2451
2452 if (!FormatIsStencilOnly(attachment.format) &&
2453 (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2454 attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2455 if (FormatHasDepth(attachment.format)) {
2456 bandwidth_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
2457 } else {
2458 bandwidth_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
2459 }
2460 }
2461
2462 if (FormatHasStencil(attachment.format) &&
2463 (attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2464 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2465 bandwidth_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
2466 }
2467
2468 if (!bandwidth_aspects) {
2469 continue;
2470 }
2471
2472 auto itr = std::find_if(render_pass_state->second.touchesAttachments.begin(),
2473 render_pass_state->second.touchesAttachments.end(),
2474 [&](const AttachmentInfo& info) {
2475 return info.framebufferAttachment == i;
2476 });
2477 uint32_t untouched_aspects = bandwidth_aspects;
2478 if (itr != render_pass_state->second.touchesAttachments.end()) {
2479 untouched_aspects &= ~itr->aspects;
2480 }
2481
2482 if (untouched_aspects) {
2483 skip |= LogPerformanceWarning(
2484 device, kVUID_BestPractices_EndRenderPass_RedundantAttachmentOnTile,
2485 "%s Render pass was ended, but attachment #%u (format: %u, untouched aspects 0x%x) "
2486 "was never accessed by a pipeline or clear command. "
2487 "On tile-based architectures, LOAD_OP_LOAD and STORE_OP_STORE consume bandwidth and should not be part of the render pass "
2488 "if the attachments are not intended to be accessed.",
2489 VendorSpecificTag(kBPVendorArm), i, attachment.format, untouched_aspects);
2490 }
2491 }
2492 }
2493
Sam Walls0961ec02020-03-31 16:39:15 +01002494 return skip;
2495}
2496
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002497void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002498 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002499}
2500
2501void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002502 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002503}
2504
Camden Stocker9c051442019-11-06 14:28:43 -08002505bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2506 const char* api_name) const {
2507 bool skip = false;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002508 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002509
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002510 if (bp_pd_state) {
2511 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2512 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2513 "Potential problem with calling %s() without first retrieving properties from "
2514 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2515 api_name);
2516 }
Camden Stocker9c051442019-11-06 14:28:43 -08002517 }
2518
2519 return skip;
2520}
2521
Camden83a9c372019-08-14 11:41:38 -06002522bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002523 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002524 bool skip = false;
2525
Camden Stocker9c051442019-11-06 14:28:43 -08002526 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002527
Camden Stocker9c051442019-11-06 14:28:43 -08002528 return skip;
2529}
2530
2531bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2532 uint32_t planeIndex,
2533 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2534 bool skip = false;
2535
2536 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2537
2538 return skip;
2539}
2540
2541bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2542 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2543 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2544 bool skip = false;
2545
2546 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002547
2548 return skip;
2549}
Camden05de2d42019-08-19 10:23:56 -06002550
2551bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002552 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002553 bool skip = false;
2554
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002555 const auto* swapchain_state = static_cast<SWAPCHAIN_STATE_BP*>(Get<SWAPCHAIN_NODE>(swapchain));
Camden05de2d42019-08-19 10:23:56 -06002556
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002557 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002558 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002559 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002560 skip |=
2561 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2562 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2563 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002564 }
Camden05de2d42019-08-19 10:23:56 -06002565
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002566 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
2567 skip |= LogWarning(
2568 device, kVUID_BestPractices_Swapchain_InvalidCount,
2569 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
2570 "value (%d) that is greater than the value (%d) that was returned when pSwapchainImages was NULL.",
2571 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
2572 }
2573 }
2574
Camden05de2d42019-08-19 10:23:56 -06002575 return skip;
2576}
2577
2578// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002579bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
2580 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002581 const CALL_STATE call_state,
2582 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002583 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002584 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2585 if (UNCALLED == call_state) {
2586 skip |= LogWarning(
2587 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
2588 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2589 "recommended "
2590 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2591 caller_name, caller_name);
2592 // Then verify that pCount that is passed in on second call matches what was returned
2593 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
2594 skip |= LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
2595 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2596 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2597 ". It is recommended to instead receive all the properties by calling %s with "
2598 "pQueueFamilyPropertyCount that was "
2599 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
2600 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
2601 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002602 }
2603
2604 return skip;
2605}
2606
Jeff Bolz5c801d12019-10-09 10:38:45 -05002607bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2608 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002609 bool skip = false;
2610
2611 for (uint32_t i = 0; i < bindInfoCount; i++) {
sourav parmarcd5fb182020-07-17 12:58:44 -07002612 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureStateNV(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002613 if (!as_state->memory_requirements_checked) {
2614 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2615 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2616 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002617 skip |= LogWarning(
2618 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002619 "vkBindAccelerationStructureMemoryNV(): "
2620 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
2621 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
2622 }
2623 }
2624
2625 return skip;
2626}
2627
Camden05de2d42019-08-19 10:23:56 -06002628bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2629 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002630 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002631 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2632 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002633 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2634 if (pQueueFamilyProperties && bp_pd_state) {
2635 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2636 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2637 "vkGetPhysicalDeviceQueueFamilyProperties()");
2638 }
2639 return false;
Camden05de2d42019-08-19 10:23:56 -06002640}
2641
Mike Schuchardt2df08912020-12-15 16:28:09 -08002642bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2643 uint32_t* pQueueFamilyPropertyCount,
2644 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002645 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2646 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002647 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2648 if (pQueueFamilyProperties && bp_pd_state) {
2649 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2650 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2651 "vkGetPhysicalDeviceQueueFamilyProperties2()");
2652 }
2653 return false;
Camden05de2d42019-08-19 10:23:56 -06002654}
2655
Jeff Bolz5c801d12019-10-09 10:38:45 -05002656bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08002657 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002658 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2659 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002660 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2661 if (pQueueFamilyProperties && bp_pd_state) {
2662 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2663 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2664 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
2665 }
2666 return false;
Camden05de2d42019-08-19 10:23:56 -06002667}
2668
2669bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2670 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002671 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06002672 if (!pSurfaceFormats) return false;
2673 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002674 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2675 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06002676 bool skip = false;
2677 if (call_state == UNCALLED) {
2678 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
2679 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002680 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
2681 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
2682 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06002683 } else {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002684 auto prev_format_count = static_cast<uint32_t>(physical_device_state->surface_formats.size());
Peter Chene191bd72019-09-16 13:04:37 -04002685 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002686 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
2687 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
2688 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
2689 "when pSurfaceFormatCount was NULL.",
2690 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06002691 }
2692 }
2693 return skip;
2694}
Camden Stocker23cc47d2019-09-03 14:53:57 -06002695
2696bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002697 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002698 bool skip = false;
2699
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002700 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2701 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002702 // Store sparse binding image_state and after binding is complete make sure that any requiring metadata have it bound
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002703 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002704 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
2705 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002706 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06002707 // If we're binding sparse image memory make sure reqs were queried and note if metadata is required and bound
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002708 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
2709 const auto& image_bind = bind_info.pImageBinds[i];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002710 auto image_state = GetImageState(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002711 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002712 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002713 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002714 sparse_images.insert(image_state);
2715 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2716 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2717 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002718 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002719 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2720 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002721 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002722 }
2723 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002724 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002725 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002726 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002727 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2728 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002729 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002730 }
2731 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002732 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2733 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
2734 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
2735 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002736 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002737 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002738 sparse_images.insert(image_state);
2739 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2740 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2741 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002742 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002743 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2744 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002745 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002746 }
2747 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002748 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002749 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002750 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002751 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2752 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002753 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002754 }
2755 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2756 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002757 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06002758 }
2759 }
2760 }
2761 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002762 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
2763 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002764 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002765 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002766 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
2767 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002768 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002769 }
2770 }
2771 }
2772
2773 return skip;
2774}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002775
Mark Lobodzinski84101d72020-04-24 09:43:48 -06002776void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
2777 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002778 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002779 return;
2780 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002781
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002782 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2783 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
2784 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2785 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
2786 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
2787 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002788 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002789 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002790 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2791 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
2792 image_state->sparse_metadata_bound = true;
2793 }
2794 }
2795 }
2796 }
2797}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002798
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002799bool BestPractices::ClearAttachmentsIsFullClear(const CMD_BUFFER_STATE* cmd,
2800 uint32_t rectCount, const VkClearRect* pRects) const {
2801 if (cmd->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2802 // We don't know the accurate render area in a secondary,
2803 // so assume we clear the entire frame buffer.
2804 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
2805 return true;
2806 }
2807
2808 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
2809 for (uint32_t i = 0; i < rectCount; i++) {
2810 auto& rect = pRects[i];
2811 auto& render_area = cmd->activeRenderPassBeginInfo.renderArea;
2812 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
2813 return true;
2814 }
2815 }
2816
2817 return false;
2818}
2819
2820bool BestPractices::ValidateClearAttachment(VkCommandBuffer commandBuffer, const CMD_BUFFER_STATE* cmd,
2821 uint32_t fb_attachment, uint32_t color_attachment,
2822 VkImageAspectFlags aspects, bool secondary) const {
2823 const RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2824 bool skip = false;
2825
2826 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
2827 return skip;
2828 }
2829
2830 auto rp_itr = cbRenderPassState.find(commandBuffer);
2831 if (rp_itr == cbRenderPassState.end()) {
2832 return skip;
2833 }
2834
2835 auto attachment_itr = std::find_if(rp_itr->second.touchesAttachments.begin(), rp_itr->second.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002836 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002837 return info.framebufferAttachment == fb_attachment;
2838 });
2839
2840 // Only report aspects which haven't been touched yet.
2841 VkImageAspectFlags new_aspects = aspects;
2842 if (attachment_itr != rp_itr->second.touchesAttachments.end()) {
2843 new_aspects &= ~attachment_itr->aspects;
2844 }
2845
2846 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
2847 if (!cmd->hasDrawCmd) {
2848 skip |= LogPerformanceWarning(
2849 commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
Hans-Kristian Arntzen4ddd6182021-06-18 12:16:33 +02002850 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds in current render pass. It is recommended you "
2851 "use RenderPass LOAD_OP_CLEAR on attachments instead.",
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002852 report_data->FormatHandle(commandBuffer).c_str());
2853 }
2854
2855 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
2856 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2857 skip |= LogPerformanceWarning(
2858 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2859 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
2860 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2861 "it is more efficient.",
2862 secondary ? "vkCmdExecuteCommands(): " : "",
2863 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
2864 }
2865
2866 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
2867 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2868 skip |= LogPerformanceWarning(
2869 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2870 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
2871 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2872 "it is more efficient.",
2873 secondary ? "vkCmdExecuteCommands(): " : "",
2874 report_data->FormatHandle(commandBuffer).c_str());
2875 }
2876
2877 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
2878 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2879 skip |= LogPerformanceWarning(
2880 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2881 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
2882 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2883 "it is more efficient.",
2884 secondary ? "vkCmdExecuteCommands(): " : "",
2885 report_data->FormatHandle(commandBuffer).c_str());
2886 }
2887
2888 return skip;
2889}
2890
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002891bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06002892 const VkClearAttachment* pAttachments, uint32_t rectCount,
2893 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002894 bool skip = false;
2895 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
2896 if (!cb_node) return skip;
2897
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002898 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2899 // Defer checks to ExecuteCommands.
2900 return skip;
2901 }
2902
2903 // Only care about full clears, partial clears might have legitimate uses.
2904 if (!ClearAttachmentsIsFullClear(cb_node, rectCount, pRects)) {
2905 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002906 }
2907
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002908 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
2909 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06002910 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002911 if (rp) {
2912 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
2913
2914 for (uint32_t i = 0; i < attachmentCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002915 const auto& attachment = pAttachments[i];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002916
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002917 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
2918 uint32_t color_attachment = attachment.colorAttachment;
2919 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002920 skip |= ValidateClearAttachment(commandBuffer, cb_node,
2921 fb_attachment, color_attachment,
2922 attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002923 }
2924
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002925 if (subpass.pDepthStencilAttachment &&
2926 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002927 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002928 skip |= ValidateClearAttachment(commandBuffer, cb_node,
2929 fb_attachment, VK_ATTACHMENT_UNUSED,
2930 attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002931 }
2932 }
2933 }
2934
Camden Stockerf55721f2019-09-09 11:04:49 -06002935 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002936}
Attilio Provenzano02859b22020-02-27 14:17:28 +00002937
2938bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2939 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2940 const VkImageResolve* pRegions) const {
2941 bool skip = false;
2942
2943 skip |= VendorCheckEnabled(kBPVendorArm) &&
2944 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
2945 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
2946 "This is a very slow and extremely bandwidth intensive path. "
2947 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2948 VendorSpecificTag(kBPVendorArm));
2949
2950 return skip;
2951}
2952
Jeff Leger178b1e52020-10-05 12:22:23 -04002953bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2954 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
2955 bool skip = false;
2956
2957 skip |= VendorCheckEnabled(kBPVendorArm) &&
2958 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
2959 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
2960 "This is a very slow and extremely bandwidth intensive path. "
2961 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2962 VendorSpecificTag(kBPVendorArm));
2963
2964 return skip;
2965}
2966
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002967void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2968 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2969 const VkImageResolve* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002970 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002971 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002972 auto* src = GetImageUsageState(srcImage);
2973 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002974
2975 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002976 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
2977 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002978 }
2979}
2980
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01002981void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2982 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002983 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002984 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002985 auto* src = GetImageUsageState(pResolveImageInfo->srcImage);
2986 auto* dst = GetImageUsageState(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01002987 uint32_t regionCount = pResolveImageInfo->regionCount;
2988
2989 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002990 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
2991 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01002992 }
2993}
2994
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002995void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
2996 const VkClearColorValue* pColor, uint32_t rangeCount,
2997 const VkImageSubresourceRange* pRanges) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002998 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002999 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003000 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003001
3002 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003003 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003004 }
3005}
3006
3007void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3008 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3009 const VkImageSubresourceRange* pRanges) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003010 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003011 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003012 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003013
3014 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003015 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003016 }
3017}
3018
3019void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3020 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3021 const VkImageCopy* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003022 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003023 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003024 auto* src = GetImageUsageState(srcImage);
3025 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003026
3027 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003028 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
3029 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003030 }
3031}
3032
3033void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3034 VkImageLayout dstImageLayout, uint32_t regionCount,
3035 const VkBufferImageCopy* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003036 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003037 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003038 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003039
3040 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003041 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003042 }
3043}
3044
3045void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3046 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003047 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003048 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003049 auto* src = GetImageUsageState(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003050
3051 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003052 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003053 }
3054}
3055
3056void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3057 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3058 const VkImageBlit* pRegions, VkFilter filter) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003059 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003060 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003061 auto* src = GetImageUsageState(srcImage);
3062 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003063
3064 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003065 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
3066 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003067 }
3068}
3069
Attilio Provenzano02859b22020-02-27 14:17:28 +00003070bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
3071 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
3072 bool skip = false;
3073
3074 if (VendorCheckEnabled(kBPVendorArm)) {
3075 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
3076 skip |= LogPerformanceWarning(
3077 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
3078 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
3079 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
3080 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06003081 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003082 }
3083
3084 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
3085 skip |= LogPerformanceWarning(
3086 device, kVUID_BestPractices_CreateSampler_LodClamping,
3087 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
3088 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
3089 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
3090 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
3091 }
3092
3093 if (pCreateInfo->mipLodBias != 0.0f) {
3094 skip |=
3095 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
3096 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
3097 "descriptors being created and may cause reduced performance.",
3098 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
3099 }
3100
3101 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3102 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3103 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
3104 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
3105 skip |= LogPerformanceWarning(
3106 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
3107 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
3108 "This will lead to less efficient descriptors being created and may cause reduced performance. "
3109 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
3110 VendorSpecificTag(kBPVendorArm));
3111 }
3112
3113 if (pCreateInfo->unnormalizedCoordinates) {
3114 skip |= LogPerformanceWarning(
3115 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
3116 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
3117 "descriptors being created and may cause reduced performance.",
3118 VendorSpecificTag(kBPVendorArm));
3119 }
3120
3121 if (pCreateInfo->anisotropyEnable) {
3122 skip |= LogPerformanceWarning(
3123 device, kVUID_BestPractices_CreateSampler_Anisotropy,
3124 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
3125 "and may cause reduced performance.",
3126 VendorSpecificTag(kBPVendorArm));
3127 }
3128 }
3129
3130 return skip;
3131}
Sam Walls8e77e4f2020-03-16 20:47:40 +00003132
3133void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
3134
3135bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
3136 // look for a cache hit
3137 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
3138 if (hit != _entries.end()) {
3139 // mark the cache hit as being most recently used
3140 hit->age = iteration++;
3141 return true;
3142 }
3143
3144 // if there's no cache hit, we need to model the entry being inserted into the cache
3145 CacheEntry new_entry = {value, iteration};
3146 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
3147 // if there is still space left in the cache, use the next available slot
3148 *(_entries.begin() + iteration) = new_entry;
3149 } else {
3150 // otherwise replace the least recently used cache entry
3151 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
3152 *lru = new_entry;
3153 }
3154 iteration++;
3155 return false;
3156}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003157
3158bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
3159 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
3160 const auto swapchain_data = GetSwapchainState(swapchain);
3161 bool skip = false;
3162 if (swapchain_data && swapchain_data->images.size() == 0) {
3163 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
3164 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
3165 "vkGetSwapchainImagesKHR after swapchain creation.");
3166 }
3167 return skip;
3168}
3169
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003170void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
3171 if (no_pointer) {
3172 if (UNCALLED == call_state) {
3173 call_state = QUERY_COUNT;
3174 }
3175 } else { // Save queue family properties
3176 call_state = QUERY_DETAILS;
3177 }
3178}
3179
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003180void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
3181 uint32_t* pQueueFamilyPropertyCount,
3182 VkQueueFamilyProperties* pQueueFamilyProperties) {
3183 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
3184 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003185 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003186 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003187 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
3188 nullptr == pQueueFamilyProperties);
3189 }
3190}
3191
3192void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
3193 uint32_t* pQueueFamilyPropertyCount,
3194 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3195 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
3196 pQueueFamilyProperties);
3197 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3198 if (bp_pd_state) {
3199 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
3200 nullptr == pQueueFamilyProperties);
3201 }
3202}
3203
3204void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
3205 uint32_t* pQueueFamilyPropertyCount,
3206 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3207 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
3208 pQueueFamilyProperties);
3209 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3210 if (bp_pd_state) {
3211 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
3212 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003213 }
3214}
3215
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003216void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
3217 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003218 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3219 if (bp_pd_state) {
3220 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3221 }
3222}
3223
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003224void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
3225 VkPhysicalDeviceFeatures2* pFeatures) {
3226 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003227 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3228 if (bp_pd_state) {
3229 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3230 }
3231}
3232
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003233void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
3234 VkPhysicalDeviceFeatures2* pFeatures) {
3235 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003236 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3237 if (bp_pd_state) {
3238 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3239 }
3240}
3241
3242void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
3243 VkSurfaceKHR surface,
3244 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
3245 VkResult result) {
3246 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3247 if (bp_pd_state) {
3248 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3249 }
3250}
3251
3252void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
3253 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3254 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
3255 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3256 if (bp_pd_state) {
3257 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3258 }
3259}
3260
3261void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
3262 VkSurfaceKHR surface,
3263 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
3264 VkResult result) {
3265 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3266 if (bp_pd_state) {
3267 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3268 }
3269}
3270
3271void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
3272 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
3273 VkPresentModeKHR* pPresentModes, VkResult result) {
3274 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3275 if (bp_pd_data) {
3276 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
3277
3278 if (*pPresentModeCount) {
3279 if (call_state < QUERY_COUNT) {
3280 call_state = QUERY_COUNT;
3281 }
3282 }
3283 if (pPresentModes) {
3284 if (call_state < QUERY_DETAILS) {
3285 call_state = QUERY_DETAILS;
3286 }
3287 }
3288 }
3289}
3290
3291void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
3292 uint32_t* pSurfaceFormatCount,
3293 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
3294 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3295 if (bp_pd_data) {
3296 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
3297
3298 if (*pSurfaceFormatCount) {
3299 if (call_state < QUERY_COUNT) {
3300 call_state = QUERY_COUNT;
3301 }
3302 }
3303 if (pSurfaceFormats) {
3304 if (call_state < QUERY_DETAILS) {
3305 call_state = QUERY_DETAILS;
3306 }
3307 }
3308 }
3309}
3310
3311void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
3312 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3313 uint32_t* pSurfaceFormatCount,
3314 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
3315 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3316 if (bp_pd_data) {
3317 if (*pSurfaceFormatCount) {
3318 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
3319 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
3320 }
3321 }
3322 if (pSurfaceFormats) {
3323 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
3324 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
3325 }
3326 }
3327 }
3328}
3329
3330void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
3331 uint32_t* pPropertyCount,
3332 VkDisplayPlanePropertiesKHR* pProperties,
3333 VkResult result) {
3334 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3335 if (bp_pd_data) {
3336 if (*pPropertyCount) {
3337 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
3338 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
3339 }
3340 }
3341 if (pProperties) {
3342 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
3343 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
3344 }
3345 }
3346 }
3347}
3348
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003349void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
3350 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
3351 VkResult result) {
Nathaniel Cesario39152e62021-07-02 13:04:16 -06003352 auto* swapchain_state = static_cast<SWAPCHAIN_STATE_BP*>(Get<SWAPCHAIN_NODE>(swapchain));
3353 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
3354 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
3355 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003356 }
3357 }
3358}
3359
3360void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
3361 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
3362 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
3363 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
3364 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
3365 }
3366 }
3367}
3368
3369void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo*, const VkAllocationCallbacks*,
3370 VkDevice*, VkResult result) {
3371 if (VK_SUCCESS == result) {
3372 instance_device_bp_state = &phys_device_bp_state_map[gpu];
3373 }
3374}
3375
3376PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
3377 if (phys_device_bp_state_map.count(phys_device) > 0) {
3378 return &phys_device_bp_state_map.at(phys_device);
3379 } else {
3380 return nullptr;
3381 }
3382}
3383
3384const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
3385 if (phys_device_bp_state_map.count(phys_device) > 0) {
3386 return &phys_device_bp_state_map.at(phys_device);
3387 } else {
3388 return nullptr;
3389 }
3390}
3391
3392PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
3393 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
3394 if (bp_state) {
3395 return bp_state;
3396 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
3397 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
3398 } else {
3399 return nullptr;
3400 }
3401}
3402
3403const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
3404 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
3405 if (bp_state) {
3406 return bp_state;
3407 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
3408 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
3409 } else {
3410 return nullptr;
3411 }
3412}
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003413
3414void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
3415 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
3416
3417 QUEUE_STATE* queue_state = GetQueueState(queue);
3418 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003419 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003420 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
3421 CMD_BUFFER_STATE* cb = GetCBState(submit_info.pCommandBuffers[cb_index]);
3422 for (auto &func : cb->queue_submit_functions) {
3423 func(this, queue_state);
3424 }
3425 }
3426 }
3427}