blob: c580debaec76fdff72ed1fa8f6b15b1c174732c4 [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) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700736 if (!image_state->memory_requirements_checked && !image_state->external_memory_handle) {
737 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
748 if (mem_state->alloc_info.allocationSize == image_state->requirements.size &&
749 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++) {
767 if ((1u << i) & image_state->requirements.memoryTypeBits) {
768 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.",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000784 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements.size);
785 }
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
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700863 for (uint32_t j = 0; j < create_info->pColorBlendState->attachmentCount; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200864 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000865 uint32_t att = subpass.pColorAttachments[j].attachment;
866
867 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
868 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
869 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
870 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
871 "color attachment #%u makes use "
872 "of a format which cannot be blended at full throughput when using MSAA.",
873 VendorSpecificTag(kBPVendorArm), i, j);
874 }
875 }
876 }
877 }
878
879 return skip;
880}
881
Camden5b184be2019-08-13 07:50:19 -0600882bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
883 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600884 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500885 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600886 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
887 pAllocator, pPipelines, cgpl_state_data);
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600888 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600889
890 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700891 skip |= LogPerformanceWarning(
892 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
893 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
894 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600895 }
896
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000897 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200898 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000899
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600900 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200901 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600902 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700903 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
904 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600905 count++;
906 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000907 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600908 if (count > kMaxInstancedVertexBuffers) {
909 skip |= LogPerformanceWarning(
910 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
911 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
912 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
913 count, kMaxInstancedVertexBuffers);
914 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000915 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000916
Szilard Pappaaf2da32020-06-22 10:37:35 +0100917 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
918 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +0200919 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
920 VendorCheckEnabled(kBPVendorArm)) {
921 skip |= LogPerformanceWarning(
922 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
923 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
924 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
925 "efficiency during rasterization. Consider disabling depthBias or increasing either "
926 "depthBiasConstantFactor or depthBiasSlopeFactor.",
927 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +0100928 }
929
Attilio Provenzano02859b22020-02-27 14:17:28 +0000930 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000931 }
932
Camden5b184be2019-08-13 07:50:19 -0600933 return skip;
934}
935
Sam Walls0961ec02020-03-31 16:39:15 +0100936void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
937 const VkGraphicsPipelineCreateInfo* pCreateInfos,
938 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
939 VkResult result, void* cgpl_state_data) {
940 for (size_t i = 0; i < count; i++) {
941 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
942 const VkPipeline pipeline_handle = pPipelines[i];
943
944 // record depth stencil state and color blend states for depth pre-pass tracking purposes
945 auto gp_cis = graphicsPipelineCIs.find(pipeline_handle);
946
947 // add the tracking state if it doesn't exist
948 if (gp_cis == graphicsPipelineCIs.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700949 auto result = graphicsPipelineCIs.emplace(pipeline_handle, GraphicsPipelineCIs{});
Sam Walls0961ec02020-03-31 16:39:15 +0100950
951 if (!result.second) continue;
952
953 gp_cis = result.first;
954 }
955
Tony-LunarG412b1b72020-07-15 10:30:13 -0600956 gp_cis->second.colorBlendStateCI =
957 cgpl_state->pCreateInfos[i].pColorBlendState
958 ? new safe_VkPipelineColorBlendStateCreateInfo(cgpl_state->pCreateInfos[i].pColorBlendState)
959 : nullptr;
960 gp_cis->second.depthStencilStateCI =
961 cgpl_state->pCreateInfos[i].pDepthStencilState
962 ? new safe_VkPipelineDepthStencilStateCreateInfo(cgpl_state->pCreateInfos[i].pDepthStencilState)
963 : nullptr;
Sam Walls0961ec02020-03-31 16:39:15 +0100964 }
965}
966
Camden5b184be2019-08-13 07:50:19 -0600967bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
968 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600969 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500970 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600971 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
972 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600973
974 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700975 skip |= LogPerformanceWarning(
976 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
977 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
978 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600979 }
980
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100981 if (VendorCheckEnabled(kBPVendorArm)) {
982 for (size_t i = 0; i < createInfoCount; i++) {
983 skip |= ValidateCreateComputePipelineArm(pCreateInfos[i]);
984 }
985 }
986
987 return skip;
988}
989
990bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
991 bool skip = false;
992 auto* module = GetShaderModuleState(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -0800993 // Generate warnings about work group sizes based on active resources.
sfricke-samsung962cad92021-04-13 00:46:29 -0700994 auto entrypoint = module->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
sfricke-samsung8a7341a2021-02-28 07:30:21 -0800995 if (entrypoint == module->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100996
997 uint32_t x = 1, y = 1, z = 1;
sfricke-samsung962cad92021-04-13 00:46:29 -0700998 module->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100999
1000 uint32_t thread_count = x * y * z;
1001
1002 // Generate a priori warnings about work group sizes.
1003 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
1004 skip |= LogPerformanceWarning(
1005 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
1006 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1007 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1008 "groups with less than %u threads, especially when using barrier() or shared memory.",
1009 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1010 }
1011
1012 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1013 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1014 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1015 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1016 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1017 "%u, %u) is not aligned to %u "
1018 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1019 "leave threads idle on the shader "
1020 "core.",
1021 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1022 kThreadGroupDispatchCountAlignmentArm);
1023 }
1024
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001025 bool has_writeable_descriptors = false;
locke-lunarg63e4daf2020-08-17 17:53:25 -06001026 bool has_atomic_descriptors = false;
sfricke-samsung962cad92021-04-13 00:46:29 -07001027 auto accessible_ids = module->MarkAccessibleIds(entrypoint);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001028 auto descriptor_uses =
sfricke-samsung962cad92021-04-13 00:46:29 -07001029 module->CollectInterfaceByDescriptorSlot(accessible_ids, &has_writeable_descriptors, &has_atomic_descriptors);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001030
1031 unsigned dimensions = 0;
1032 if (x > 1) dimensions++;
1033 if (y > 1) dimensions++;
1034 if (z > 1) dimensions++;
1035 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1036 dimensions = std::max(dimensions, 1u);
1037
1038 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1039 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1040 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1041 bool accesses_2d = false;
1042 for (const auto& usage : descriptor_uses) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001043 auto dim = module->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001044 if (dim < 0) continue;
1045 auto spvdim = spv::Dim(dim);
1046 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1047 }
1048
1049 if (accesses_2d && dimensions < 2) {
1050 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1051 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1052 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1053 "exhibiting poor spatial locality with respect to one or more shader resources.",
1054 VendorSpecificTag(kBPVendorArm), x, y, z);
1055 }
1056
Camden5b184be2019-08-13 07:50:19 -06001057 return skip;
1058}
1059
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001060bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001061 bool skip = false;
1062
1063 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001064 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1065 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001066 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001067 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1068 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001069 }
1070
1071 return skip;
1072}
1073
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001074bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1075 bool skip = false;
1076
1077 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1078 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1079 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1080 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1081 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1082 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1083 }
1084
1085 return skip;
1086}
1087
1088bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1089 bool skip = false;
1090 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1091
1092 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1093 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1094
1095 return skip;
1096}
1097
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001098void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001099 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1100 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1101 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1102 LogPerformanceWarning(
1103 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1104 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1105 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1106 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1107 "convenient opportunity.",
1108 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1109 }
1110 }
1111}
1112
Jeff Bolz5c801d12019-10-09 10:38:45 -05001113bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1114 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001115 bool skip = false;
1116
1117 for (uint32_t submit = 0; submit < submitCount; submit++) {
1118 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1119 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1120 }
1121 }
1122
1123 return skip;
1124}
1125
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001126bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1127 VkFence fence) const {
1128 bool skip = false;
1129
1130 for (uint32_t submit = 0; submit < submitCount; submit++) {
1131 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1132 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1133 }
1134 }
1135
1136 return skip;
1137}
1138
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001139bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1140 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1141 bool skip = false;
1142
1143 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1144 skip |= LogPerformanceWarning(
1145 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1146 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1147 "pool instead.");
1148 }
1149
1150 return skip;
1151}
1152
1153bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1154 const VkCommandBufferBeginInfo* pBeginInfo) const {
1155 bool skip = false;
1156
1157 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1158 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1159 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1160 }
1161
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001162 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && VendorCheckEnabled(kBPVendorArm)) {
1163 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Attilio Provenzano02859b22020-02-27 14:17:28 +00001164 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1165 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1166 VendorSpecificTag(kBPVendorArm));
1167 }
1168
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001169 return skip;
1170}
1171
Jeff Bolz5c801d12019-10-09 10:38:45 -05001172bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001173 bool skip = false;
1174
1175 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1176
1177 return skip;
1178}
1179
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001180bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1181 const VkDependencyInfoKHR* pDependencyInfo) const {
1182 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1183}
1184
Jeff Bolz5c801d12019-10-09 10:38:45 -05001185bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1186 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001187 bool skip = false;
1188
1189 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1190
1191 return skip;
1192}
1193
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001194bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1195 VkPipelineStageFlags2KHR stageMask) const {
1196 bool skip = false;
1197
1198 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1199
1200 return skip;
1201}
1202
Camden5b184be2019-08-13 07:50:19 -06001203bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1204 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1205 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1206 uint32_t bufferMemoryBarrierCount,
1207 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1208 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001209 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001210 bool skip = false;
1211
1212 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1213 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1214
1215 return skip;
1216}
1217
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001218bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1219 const VkDependencyInfoKHR* pDependencyInfos) const {
1220 bool skip = false;
1221 for (uint32_t i = 0; i < eventCount; i++) {
1222 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1223 }
1224
1225 return skip;
1226}
1227
Camden5b184be2019-08-13 07:50:19 -06001228bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1229 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1230 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1231 uint32_t bufferMemoryBarrierCount,
1232 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1233 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001234 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001235 bool skip = false;
1236
1237 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1238 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1239
1240 return skip;
1241}
1242
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001243bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1244 const VkDependencyInfoKHR* pDependencyInfo) const {
1245 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1246}
1247
Camden5b184be2019-08-13 07:50:19 -06001248bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001249 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001250 bool skip = false;
1251
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001252 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1253
1254 return skip;
1255}
1256
1257bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1258 VkQueryPool queryPool, uint32_t query) const {
1259 bool skip = false;
1260
1261 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001262
1263 return skip;
1264}
1265
Sam Walls0961ec02020-03-31 16:39:15 +01001266void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1267 VkPipeline pipeline) {
1268 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1269
1270 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1271 // check for depth/blend state tracking
1272 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1273 if (gp_cis != graphicsPipelineCIs.end()) {
1274 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1275 if (prepass_state == cbDepthPrePassStates.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001276 auto result = cbDepthPrePassStates.emplace(commandBuffer, DepthPrePassState{});
Sam Walls0961ec02020-03-31 16:39:15 +01001277
1278 if (!result.second) return;
1279
1280 prepass_state = result.first;
1281 }
1282
1283 const auto* blend_state = gp_cis->second.colorBlendStateCI;
1284 const auto* stencil_state = gp_cis->second.depthStencilStateCI;
1285
1286 if (blend_state) {
1287 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
1288 prepass_state->second.depthOnly = true;
1289 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1290 if (blend_state->pAttachments[i].colorWriteMask != 0) {
1291 prepass_state->second.depthOnly = false;
1292 }
1293 }
1294 }
1295
1296 // check for depth value usage
1297 prepass_state->second.depthEqualComparison = false;
1298
1299 if (stencil_state && stencil_state->depthTestEnable) {
1300 switch (stencil_state->depthCompareOp) {
1301 case VK_COMPARE_OP_EQUAL:
1302 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1303 case VK_COMPARE_OP_LESS_OR_EQUAL:
1304 prepass_state->second.depthEqualComparison = true;
1305 break;
1306 default:
1307 break;
1308 }
1309 }
1310 } else {
1311 // reset depth pre-pass tracking
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001312 cbDepthPrePassStates.emplace(commandBuffer, DepthPrePassState{});
Sam Walls0961ec02020-03-31 16:39:15 +01001313 }
1314 }
1315}
1316
Attilio Provenzano02859b22020-02-27 14:17:28 +00001317static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1318 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001319 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001320
1321 // If an attachment is ever used as a color attachment,
1322 // resolve attachment or depth stencil attachment,
1323 // it needs to exist on tile at some point.
1324
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001325 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1326 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001327 }
1328
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001329 if (subpass_info.pResolveAttachments) {
1330 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1331 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1332 }
1333 }
1334
1335 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001336 }
1337
1338 return false;
1339}
1340
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001341static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1342 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1343 return false;
1344 }
1345
1346 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001347 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001348
1349 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1350 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1351 return true;
1352 }
1353 }
1354 }
1355
1356 return false;
1357}
1358
Attilio Provenzano02859b22020-02-27 14:17:28 +00001359bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1360 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1361 bool skip = false;
1362
1363 if (!pRenderPassBegin) {
1364 return skip;
1365 }
1366
1367 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1368 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001369 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001370 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001371 if (rpabi) {
1372 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1373 }
1374 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001375 // Check if any attachments have LOAD operation on them
1376 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001377 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001378
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001379 bool attachment_has_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001380 if (!FormatHasStencil(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001381 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001382 }
1383
1384 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001385 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001386 }
1387
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001388 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001389
1390 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001391 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1392 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001393 }
1394
1395 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001396 if (attachment_needs_readback && VendorCheckEnabled(kBPVendorArm)) {
1397 skip |= LogPerformanceWarning(
1398 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1399 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1400 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
1401 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
1402 VendorSpecificTag(kBPVendorArm), att,
1403 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1404 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1405 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001406 }
1407 }
1408 }
1409
1410 return skip;
1411}
1412
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001413void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
1414 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001415 if (view) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001416 QueueValidateImage(funcs, function_name, GetImageUsageState(view->create_info.image), usage, view->create_info.subresourceRange);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001417 }
1418}
1419
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001420void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1421 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001422 const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001423 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001424
1425 // If we're viewing a 3D slice, ignore base array layer.
1426 // The entire 3D subresource is accessed as one atomic unit.
1427 const uint32_t base_array_layer = image->createInfo.imageType == VK_IMAGE_TYPE_3D ? 0 : subresource_range.baseArrayLayer;
1428
1429 const uint32_t max_layers = image->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001430 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
1431 const uint32_t max_levels = image->createInfo.mipLevels - subresource_range.baseMipLevel;
1432 const uint32_t mip_levels = std::min(image->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001433
1434 for (uint32_t layer = 0; layer < array_layers; layer++) {
1435 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001436 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
1437 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001438 }
1439 }
1440}
1441
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001442void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1443 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001444 const VkImageSubresourceLayers& subresource_layers) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001445 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001446 const uint32_t max_layers = image->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
1447 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001448
1449 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001450 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001451 }
1452}
1453
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001454void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1455 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001456 uint32_t array_layer, uint32_t mip_level) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001457 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](const ValidationStateTracker*, const QUEUE_STATE*) -> bool {
1458 ValidateImageInQueue(function_name, state, usage, array_layer, mip_level);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001459 return false;
1460 });
1461}
1462
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001463void BestPractices::ValidateImageInQueueArm(const char* function_name, IMAGE_STATE* image,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001464 IMAGE_SUBRESOURCE_USAGE_BP last_usage,
1465 IMAGE_SUBRESOURCE_USAGE_BP usage,
1466 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001467 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001468 if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED && last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED &&
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001469 !image->is_swapchain_image) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001470 LogPerformanceWarning(
1471 device, kVUID_BestPractices_RenderPass_RedundantStore,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001472 "%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 +02001473 "image was used, it was written to with STORE_OP_STORE. "
1474 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1475 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001476 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001477 } 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 +02001478 LogPerformanceWarning(
1479 device, kVUID_BestPractices_RenderPass_RedundantClear,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001480 "%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 +02001481 "image was used, it was written to with vkCmdClear*Image(). "
1482 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1483 "tile-based architectures."
1484 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001485 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001486 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
1487 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE ||
1488 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
1489 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE ||
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001490 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001491 const char *last_cmd = nullptr;
1492 const char *vuid = nullptr;
1493 const char *suggestion = nullptr;
1494
1495 switch (last_usage) {
1496 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
1497 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
1498 last_cmd = "vkCmdBlitImage";
1499 suggestion =
1500 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1501 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
1502 "which avoids the memory roundtrip.";
1503 break;
1504 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
1505 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
1506 last_cmd = "vkCmdClear*Image";
1507 suggestion =
1508 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1509 "tile-based architectures. "
1510 "Use LOAD_OP_CLEAR instead to clear the image for free.";
1511 break;
1512 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
1513 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
1514 last_cmd = "vkCmdCopy*Image";
1515 suggestion =
1516 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1517 "Rather than copying, just render the source image in a fragment shader in this render pass, "
1518 "which avoids the memory roundtrip.";
1519 break;
1520 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
1521 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
1522 last_cmd = "vkCmdResolveImage";
1523 suggestion =
1524 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
1525 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
1526 "which avoids the memory roundtrip.";
1527 break;
1528 default:
1529 break;
1530 }
1531
1532 LogPerformanceWarning(
1533 device, vuid,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001534 "%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 +01001535 "time image was used, it was written to with %s. %s",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001536 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level, last_cmd, suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001537 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001538}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001539
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001540void BestPractices::ValidateImageInQueue(const char* function_name, IMAGE_STATE_BP* state,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001541 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer,
1542 uint32_t mip_level) {
1543 IMAGE_STATE* image = state->image;
1544 IMAGE_SUBRESOURCE_USAGE_BP last_usage = state->usages[array_layer][mip_level];
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001545 state->usages[array_layer][mip_level] = usage;
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001546 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001547 ValidateImageInQueueArm(function_name, image, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001548 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001549}
1550
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001551void BestPractices::AddDeferredQueueOperations(CMD_BUFFER_STATE* cb) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001552 cb->queue_submit_functions.insert(cb->queue_submit_functions.end(),
1553 queue_submit_functions_after_render_pass.begin(),
1554 queue_submit_functions_after_render_pass.end());
1555 queue_submit_functions_after_render_pass.clear();
1556}
1557
1558void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
1559 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001560 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001561}
1562
1563void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
1564 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001565 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001566}
1567
1568void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
1569 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001570 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001571}
1572
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001573void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1574 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001575 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1576
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001577 if (!pRenderPassBegin) {
1578 return;
1579 }
1580
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001581 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
1582
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001583 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1584 if (rp_state) {
1585 // Check load ops
1586 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001587 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001588
1589 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
1590 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1591 continue;
1592 }
1593
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001594 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001595
1596 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
1597 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001598 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001599 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
1600 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001601 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001602 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001603 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001604 }
1605
1606 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001607 IMAGE_VIEW_STATE* image_view = nullptr;
1608
1609 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
1610 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1611 if (rpabi) {
1612 image_view = GetImageViewState(rpabi->pAttachments[att]);
1613 }
1614 } else {
1615 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1616 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001617
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001618 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view, usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001619 }
1620
1621 // Check store ops
1622 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001623 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001624
1625 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1626 continue;
1627 }
1628
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001629 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001630
1631 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
1632 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001633 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001634 }
1635
1636 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001637
1638 IMAGE_VIEW_STATE* image_view = nullptr;
1639 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
1640 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1641 if (rpabi) {
1642 image_view = GetImageViewState(rpabi->pAttachments[att]);
1643 }
1644 } else {
1645 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1646 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001647
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001648 QueueValidateImageView(queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view, usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001649 }
1650 }
1651}
1652
Attilio Provenzano02859b22020-02-27 14:17:28 +00001653bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1654 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001655 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1656 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001657 return skip;
1658}
1659
1660bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1661 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001662 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001663 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1664 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001665 return skip;
1666}
1667
1668bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001669 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001670 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1671 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001672 return skip;
1673}
1674
Sam Walls0961ec02020-03-31 16:39:15 +01001675void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1676 const VkRenderPassBeginInfo* pRenderPassBegin) {
1677 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1678
1679 // add the tracking state if it doesn't exist
1680 if (prepass_state == cbDepthPrePassStates.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001681 auto result = cbDepthPrePassStates.emplace(commandBuffer, DepthPrePassState{});
Sam Walls0961ec02020-03-31 16:39:15 +01001682
1683 if (!result.second) return;
1684
1685 prepass_state = result.first;
1686 }
1687
1688 // reset the renderpass state
1689 prepass_state->second = {};
1690
Hans-Kristian Arntzena1a92cc2021-03-17 13:09:33 +01001691 const auto* rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01001692
1693 // track depth / color attachment usage within the renderpass
1694 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1695 // record if depth/color attachments are in use for this renderpass
1696 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) prepass_state->second.depthAttachment = true;
1697
1698 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) prepass_state->second.colorAttachment = true;
1699 }
1700}
1701
1702void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1703 VkSubpassContents contents) {
1704 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1705 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1706}
1707
1708void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1709 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1710 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1711 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1712}
1713
1714void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1715 const VkRenderPassBeginInfo* pRenderPassBegin,
1716 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1717 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1718 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1719}
1720
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001721// Generic function to handle validation for all CmdDraw* type functions
1722bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1723 bool skip = false;
1724 const CMD_BUFFER_STATE* cb_state = GetCBState(cmd_buffer);
1725 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001726 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1727 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001728 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001729
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001730 // Verify vertex binding
1731 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1732 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001733 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001734 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001735 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
1736 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001737 }
1738 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001739
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06001740 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001741 if (pipe) {
1742 const auto* rp_state = pipe->rp_state.get();
1743 if (rp_state) {
1744 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
1745 const auto& subpass = rp_state->createInfo.pSubpasses[i];
1746 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(
1747 pipe->graphicsPipelineCI.pDepthStencilState, subpass.pDepthStencilAttachment);
1748 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && pipe->graphicsPipelineCI.pRasterizationState &&
1749 pipe->graphicsPipelineCI.pRasterizationState->depthBiasEnable == VK_TRUE) {
1750 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
1751 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
1752 }
1753 }
1754 }
1755 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001756 }
1757 return skip;
1758}
1759
Sam Walls0961ec02020-03-31 16:39:15 +01001760void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1761 if (VendorCheckEnabled(kBPVendorArm)) {
1762 RecordCmdDrawTypeArm(cmd_buffer, draw_count, caller);
1763 }
1764}
1765
1766void BestPractices::RecordCmdDrawTypeArm(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1767 auto prepass_state = cbDepthPrePassStates.find(cmd_buffer);
1768 if (prepass_state != cbDepthPrePassStates.end() && draw_count >= kDepthPrePassMinDrawCountArm) {
1769 if (prepass_state->second.depthOnly) prepass_state->second.numDrawCallsDepthOnly++;
1770
1771 if (prepass_state->second.depthEqualComparison) prepass_state->second.numDrawCallsDepthEqualCompare++;
1772 }
1773}
1774
Camden5b184be2019-08-13 07:50:19 -06001775bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001776 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001777 bool skip = false;
1778
1779 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001780 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1781 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001782 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001783 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001784
1785 return skip;
1786}
1787
Sam Walls0961ec02020-03-31 16:39:15 +01001788void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1789 uint32_t firstVertex, uint32_t firstInstance) {
1790 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
1791 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
1792}
1793
Camden5b184be2019-08-13 07:50:19 -06001794bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001795 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001796 bool skip = false;
1797
1798 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001799 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1800 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001801 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001802 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1803
Attilio Provenzano02859b22020-02-27 14:17:28 +00001804 // Check if we reached the limit for small indexed draw calls.
1805 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1806 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1807 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001808 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
1809 VendorCheckEnabled(kBPVendorArm)) {
1810 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06001811 "%s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00001812 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1813 "You can try batching drawcalls or instancing when applicable.",
1814 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1815 }
1816
Sam Walls8e77e4f2020-03-16 20:47:40 +00001817 if (VendorCheckEnabled(kBPVendorArm)) {
1818 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1819 }
1820
1821 return skip;
1822}
1823
1824bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1825 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1826 bool skip = false;
1827
1828 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1829 const auto* cmd_state = GetCBState(commandBuffer);
1830 if (cmd_state == nullptr) return skip;
1831
locke-lunarg1ae57d62020-11-18 10:49:19 -07001832 const auto* ib_state = cmd_state->index_buffer_binding.buffer_state.get();
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06001833 if (ib_state == nullptr || cmd_state->index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001834
1835 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
1836 const auto& ib_mem_state = *ib_state->binding.mem_state;
1837 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1838 const void* ib_mem = ib_mem_state.p_driver_data;
1839 bool primitive_restart_enable = false;
1840
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001841 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1842 const auto& pipeline_binding_iter = cmd_state->lastBound[lv_bind_point];
1843 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001844
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001845 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001846 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001847 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00001848
1849 // 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 -06001850 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00001851 uint32_t scan_stride;
1852 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1853 scan_stride = sizeof(uint8_t);
1854 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1855 scan_stride = sizeof(uint16_t);
1856 } else {
1857 scan_stride = sizeof(uint32_t);
1858 }
1859
1860 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1861 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1862
1863 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1864 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1865 // irrespective of whether or not they're part of the draw call.
1866
1867 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1868 uint32_t min_index = ~0u;
1869 // start with maximum as 0 and adjust to indices in the buffer
1870 uint32_t max_index = 0u;
1871
1872 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
1873 // for the given index buffer
1874 uint32_t vertex_shade_count = 0;
1875
1876 PostTransformLRUCacheModel post_transform_cache;
1877
1878 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
1879 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
1880 // target architecture.
1881 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
1882 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
1883 post_transform_cache.resize(32);
1884
1885 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1886 uint32_t scan_index;
1887 uint32_t primitive_restart_value;
1888 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1889 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1890 primitive_restart_value = 0xFF;
1891 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1892 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1893 primitive_restart_value = 0xFFFF;
1894 } else {
1895 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1896 primitive_restart_value = 0xFFFFFFFF;
1897 }
1898
1899 max_index = std::max(max_index, scan_index);
1900 min_index = std::min(min_index, scan_index);
1901
1902 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
1903 bool in_cache = post_transform_cache.query_cache(scan_index);
1904 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
1905 if (!in_cache) vertex_shade_count++;
1906 }
1907 }
1908
1909 // 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 +01001910 // 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
1911 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001912
1913 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07001914 skip |=
1915 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1916 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
1917 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
1918 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
1919 "maximum would be loaded, and possibly shaded, whether or not they are used.",
1920 VendorSpecificTag(kBPVendorArm),
1921 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001922 return skip;
1923 }
1924
1925 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
1926 // 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 +01001927 const size_t refs_per_bucket = 64;
1928 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
1929
1930 const uint32_t n_indices = max_index - min_index + 1;
1931 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
1932 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
1933
1934 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
1935 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00001936
1937 // To avoid using too much memory, we run over the indices again.
1938 // Knowing the size from the last scan allows us to record index usage with bitsets
1939 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1940 uint32_t scan_index;
1941 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1942 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1943 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1944 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1945 } else {
1946 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1947 }
1948 // keep track of the set of all indices used to reference vertices in the draw call
1949 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01001950 size_t bitset_bucket_index = index_offset / refs_per_bucket;
1951 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001952 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
1953 }
1954
1955 uint32_t vertex_reference_count = 0;
1956 for (const auto& bitset : vertex_reference_buckets) {
1957 vertex_reference_count += static_cast<uint32_t>(bitset.count());
1958 }
1959
1960 // 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 -07001961 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001962 // 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 -07001963 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001964
1965 if (utilization < 0.5f) {
1966 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1967 "%s The indices which were specified for the draw call only utilise approximately "
1968 "%.02f%% of the bound vertex buffer.",
1969 VendorSpecificTag(kBPVendorArm), utilization);
1970 }
1971
1972 if (cache_hit_rate <= 0.5f) {
1973 skip |=
1974 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
1975 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
1976 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
1977 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
1978 "recently shaded vertices.",
1979 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
1980 }
1981 }
1982
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001983 return skip;
1984}
1985
Attilio Provenzano02859b22020-02-27 14:17:28 +00001986void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1987 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1988 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
1989 firstInstance);
1990
1991 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1992 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
1993 cmd_state->small_indexed_draw_call_count++;
1994 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001995
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001996 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00001997}
1998
Sam Walls0961ec02020-03-31 16:39:15 +01001999void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2000 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2001 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2002 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
2003}
2004
sfricke-samsung681ab7b2020-10-29 01:53:35 -07002005bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2006 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
2007 uint32_t maxDrawCount, uint32_t stride) const {
2008 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
2009
2010 return skip;
2011}
2012
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002013bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
2014 VkDeviceSize offset, VkBuffer countBuffer,
2015 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
2016 uint32_t stride) const {
2017 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06002018
2019 return skip;
2020}
2021
2022bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002023 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002024 bool skip = false;
2025
2026 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002027 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2028 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002029 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002030 }
2031
2032 return skip;
2033}
2034
Sam Walls0961ec02020-03-31 16:39:15 +01002035void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2036 uint32_t count, uint32_t stride) {
2037 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
2038 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
2039}
2040
Camden5b184be2019-08-13 07:50:19 -06002041bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002042 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002043 bool skip = false;
2044
2045 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002046 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2047 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002048 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002049 }
2050
2051 return skip;
2052}
2053
Sam Walls0961ec02020-03-31 16:39:15 +01002054void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2055 uint32_t count, uint32_t stride) {
2056 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
2057 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
2058}
2059
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002060void BestPractices::ValidateBoundDescriptorSets(VkCommandBuffer commandBuffer, const char* function_name) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002061 CMD_BUFFER_STATE* cb_state = GetCBState(commandBuffer);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002062
2063 if (cb_state) {
2064 for (auto descriptor_set : cb_state->validated_descriptor_sets) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002065 const auto& layout = *descriptor_set->GetLayout();
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002066
2067 for (uint32_t index = 0; index < descriptor_set->GetBindingCount(); ++index) {
2068 // For bindless scenarios, we should not attempt to track descriptor set state.
2069 // It is highly uncertain which resources are actually bound.
2070 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
2071 VkDescriptorBindingFlags flags = layout.GetDescriptorBindingFlagsFromIndex(index);
2072 if (flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT |
2073 VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
2074 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
2075 continue;
2076 }
2077
2078 auto index_range = layout.GetGlobalIndexRangeFromIndex(index);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002079 for (uint32_t i = index_range.start; i < index_range.end; ++i) {
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002080 VkImageView image_view{VK_NULL_HANDLE};
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002081
2082 auto descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2083 switch (descriptor->GetClass()) {
2084 case cvdescriptorset::DescriptorClass::Image: {
2085 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
2086 image_view = image_descriptor->GetImageView();
2087 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002088 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002089 }
2090 case cvdescriptorset::DescriptorClass::ImageSampler: {
2091 if (const auto image_sampler_descriptor =
2092 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
2093 image_view = image_sampler_descriptor->GetImageView();
2094 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002095 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002096 }
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002097 default:
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002098 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002099 }
2100
2101 if (image_view) {
2102 IMAGE_VIEW_STATE* image_view_state = GetImageViewState(image_view);
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002103 QueueValidateImageView(cb_state->queue_submit_functions, function_name,
2104 image_view_state, IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002105 }
2106 }
2107 }
2108 }
2109 }
2110}
2111
2112void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2113 uint32_t firstVertex, uint32_t firstInstance) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002114 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002115}
2116
2117void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2118 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002119 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002120}
2121
2122void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2123 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002124 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002125}
2126
Camden5b184be2019-08-13 07:50:19 -06002127bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002128 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06002129 bool skip = false;
2130
2131 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002132 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
2133 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
2134 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
2135 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06002136 }
2137
2138 return skip;
2139}
Camden83a9c372019-08-14 11:41:38 -06002140
Sam Walls0961ec02020-03-31 16:39:15 +01002141bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2142 bool skip = false;
2143
2144 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
2145
2146 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
2147
2148 if (prepass_state == cbDepthPrePassStates.end()) return skip;
2149
2150 bool uses_depth = (prepass_state->second.depthAttachment || prepass_state->second.colorAttachment) &&
2151 prepass_state->second.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2152 prepass_state->second.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
2153 if (uses_depth) {
2154 skip |= LogPerformanceWarning(
2155 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
2156 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
2157 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
2158 "case, using depth pre-passes for hidden surface removal may worsen performance.",
2159 VendorSpecificTag(kBPVendorArm));
2160 }
2161
2162 return skip;
2163}
2164
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002165void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002166 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002167}
2168
2169void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002170 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002171}
2172
Camden Stocker9c051442019-11-06 14:28:43 -08002173bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2174 const char* api_name) const {
2175 bool skip = false;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002176 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002177
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002178 if (bp_pd_state) {
2179 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2180 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2181 "Potential problem with calling %s() without first retrieving properties from "
2182 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2183 api_name);
2184 }
Camden Stocker9c051442019-11-06 14:28:43 -08002185 }
2186
2187 return skip;
2188}
2189
Camden83a9c372019-08-14 11:41:38 -06002190bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002191 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002192 bool skip = false;
2193
Camden Stocker9c051442019-11-06 14:28:43 -08002194 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002195
Camden Stocker9c051442019-11-06 14:28:43 -08002196 return skip;
2197}
2198
2199bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2200 uint32_t planeIndex,
2201 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2202 bool skip = false;
2203
2204 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2205
2206 return skip;
2207}
2208
2209bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2210 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2211 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2212 bool skip = false;
2213
2214 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002215
2216 return skip;
2217}
Camden05de2d42019-08-19 10:23:56 -06002218
2219bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002220 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002221 bool skip = false;
2222
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002223 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
Camden05de2d42019-08-19 10:23:56 -06002224
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002225 if ((swapchain_state_itr != swapchain_bp_state_map.cend()) && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002226 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002227 if (swapchain_state_itr->second.vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002228 skip |=
2229 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2230 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2231 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002232 }
2233 }
2234
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002235 const auto swapchain_state = GetSwapchainState(swapchain);
2236 if (swapchain_state && pSwapchainImages) {
2237 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
2238 skip |= LogWarning(
2239 device, kVUID_BestPractices_Swapchain_InvalidCount,
2240 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
2241 "value (%d) that is greater than the value (%d) that was returned when pSwapchainImages was NULL.",
2242 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
2243 }
2244 }
2245
Camden05de2d42019-08-19 10:23:56 -06002246 return skip;
2247}
2248
2249// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002250bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
2251 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002252 const CALL_STATE call_state,
2253 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002254 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002255 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2256 if (UNCALLED == call_state) {
2257 skip |= LogWarning(
2258 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
2259 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2260 "recommended "
2261 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2262 caller_name, caller_name);
2263 // Then verify that pCount that is passed in on second call matches what was returned
2264 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
2265 skip |= LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
2266 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2267 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2268 ". It is recommended to instead receive all the properties by calling %s with "
2269 "pQueueFamilyPropertyCount that was "
2270 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
2271 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
2272 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002273 }
2274
2275 return skip;
2276}
2277
Jeff Bolz5c801d12019-10-09 10:38:45 -05002278bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2279 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002280 bool skip = false;
2281
2282 for (uint32_t i = 0; i < bindInfoCount; i++) {
sourav parmarcd5fb182020-07-17 12:58:44 -07002283 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureStateNV(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002284 if (!as_state->memory_requirements_checked) {
2285 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2286 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2287 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002288 skip |= LogWarning(
2289 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002290 "vkBindAccelerationStructureMemoryNV(): "
2291 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
2292 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
2293 }
2294 }
2295
2296 return skip;
2297}
2298
Camden05de2d42019-08-19 10:23:56 -06002299bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2300 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002301 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002302 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2303 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002304 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2305 if (pQueueFamilyProperties && bp_pd_state) {
2306 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2307 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2308 "vkGetPhysicalDeviceQueueFamilyProperties()");
2309 }
2310 return false;
Camden05de2d42019-08-19 10:23:56 -06002311}
2312
Mike Schuchardt2df08912020-12-15 16:28:09 -08002313bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2314 uint32_t* pQueueFamilyPropertyCount,
2315 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002316 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2317 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002318 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2319 if (pQueueFamilyProperties && bp_pd_state) {
2320 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2321 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2322 "vkGetPhysicalDeviceQueueFamilyProperties2()");
2323 }
2324 return false;
Camden05de2d42019-08-19 10:23:56 -06002325}
2326
Jeff Bolz5c801d12019-10-09 10:38:45 -05002327bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08002328 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002329 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2330 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002331 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2332 if (pQueueFamilyProperties && bp_pd_state) {
2333 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2334 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2335 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
2336 }
2337 return false;
Camden05de2d42019-08-19 10:23:56 -06002338}
2339
2340bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2341 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002342 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06002343 if (!pSurfaceFormats) return false;
2344 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002345 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2346 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06002347 bool skip = false;
2348 if (call_state == UNCALLED) {
2349 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
2350 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002351 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
2352 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
2353 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06002354 } else {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002355 auto prev_format_count = static_cast<uint32_t>(physical_device_state->surface_formats.size());
Peter Chene191bd72019-09-16 13:04:37 -04002356 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002357 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
2358 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
2359 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
2360 "when pSurfaceFormatCount was NULL.",
2361 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06002362 }
2363 }
2364 return skip;
2365}
Camden Stocker23cc47d2019-09-03 14:53:57 -06002366
2367bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002368 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002369 bool skip = false;
2370
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002371 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2372 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002373 // 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 -07002374 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002375 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
2376 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002377 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06002378 // 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 -07002379 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
2380 const auto& image_bind = bind_info.pImageBinds[i];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002381 auto image_state = GetImageState(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002382 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002383 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002384 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002385 sparse_images.insert(image_state);
2386 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2387 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2388 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002389 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002390 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2391 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002392 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002393 }
2394 }
2395 if (!image_state->memory_requirements_checked) {
2396 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002397 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002398 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2399 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002400 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002401 }
2402 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002403 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2404 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
2405 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
2406 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002407 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002408 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002409 sparse_images.insert(image_state);
2410 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2411 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2412 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002413 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002414 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2415 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002416 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002417 }
2418 }
2419 if (!image_state->memory_requirements_checked) {
2420 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002421 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002422 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2423 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002424 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002425 }
2426 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2427 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002428 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06002429 }
2430 }
2431 }
2432 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002433 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
2434 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002435 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002436 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002437 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
2438 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002439 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002440 }
2441 }
2442 }
2443
2444 return skip;
2445}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002446
Mark Lobodzinski84101d72020-04-24 09:43:48 -06002447void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
2448 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002449 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002450 return;
2451 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002452
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002453 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2454 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
2455 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2456 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
2457 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
2458 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002459 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002460 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002461 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2462 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
2463 image_state->sparse_metadata_bound = true;
2464 }
2465 }
2466 }
2467 }
2468}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002469
2470bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06002471 const VkClearAttachment* pAttachments, uint32_t rectCount,
2472 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002473 bool skip = false;
2474 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
2475 if (!cb_node) return skip;
2476
Camden Stockerf55721f2019-09-09 11:04:49 -06002477 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002478 if (!cb_node->hasDrawCmd && (cb_node->activeRenderPassBeginInfo.renderArea.extent.width == pRects[0].rect.extent.width) &&
2479 (cb_node->activeRenderPassBeginInfo.renderArea.extent.height == pRects[0].rect.extent.height)) {
2480 // There are times where app needs to use ClearAttachments (generally when reusing a buffer inside of a render pass)
2481 // This warning should be made more specific. It'd be best to avoid triggering this test if it's a use that must call
2482 // CmdClearAttachments.
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07002483 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
2484 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds. It is recommended you "
2485 "use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
2486 report_data->FormatHandle(commandBuffer).c_str());
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002487 }
2488
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002489 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
2490 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06002491 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002492 if (rp) {
2493 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
2494
2495 for (uint32_t i = 0; i < attachmentCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002496 const auto& attachment = pAttachments[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002497 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
2498 uint32_t color_attachment = attachment.colorAttachment;
2499 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
2500
2501 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2502 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2503 skip |= LogPerformanceWarning(
2504 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2505 "vkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
2506 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2507 "it is more efficient.",
2508 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
2509 }
2510 }
2511 }
2512
2513 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
2514 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2515
2516 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2517 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2518 skip |= LogPerformanceWarning(
2519 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2520 "vkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
2521 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2522 "it is more efficient.",
2523 report_data->FormatHandle(commandBuffer).c_str());
2524 }
2525 }
2526 }
2527
2528 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
2529 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2530
2531 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2532 if (rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2533 skip |= LogPerformanceWarning(
2534 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2535 "vkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
2536 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2537 "it is more efficient.",
2538 report_data->FormatHandle(commandBuffer).c_str());
2539 }
2540 }
2541 }
2542 }
2543 }
2544
Camden Stockerf55721f2019-09-09 11:04:49 -06002545 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002546}
Attilio Provenzano02859b22020-02-27 14:17:28 +00002547
2548bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2549 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2550 const VkImageResolve* pRegions) const {
2551 bool skip = false;
2552
2553 skip |= VendorCheckEnabled(kBPVendorArm) &&
2554 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
2555 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
2556 "This is a very slow and extremely bandwidth intensive path. "
2557 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2558 VendorSpecificTag(kBPVendorArm));
2559
2560 return skip;
2561}
2562
Jeff Leger178b1e52020-10-05 12:22:23 -04002563bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2564 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
2565 bool skip = false;
2566
2567 skip |= VendorCheckEnabled(kBPVendorArm) &&
2568 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
2569 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
2570 "This is a very slow and extremely bandwidth intensive path. "
2571 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2572 VendorSpecificTag(kBPVendorArm));
2573
2574 return skip;
2575}
2576
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002577void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2578 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2579 const VkImageResolve* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002580 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002581 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002582 auto* src = GetImageUsageState(srcImage);
2583 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002584
2585 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002586 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
2587 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002588 }
2589}
2590
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01002591void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2592 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002593 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002594 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002595 auto* src = GetImageUsageState(pResolveImageInfo->srcImage);
2596 auto* dst = GetImageUsageState(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01002597 uint32_t regionCount = pResolveImageInfo->regionCount;
2598
2599 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002600 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
2601 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01002602 }
2603}
2604
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002605void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
2606 const VkClearColorValue* pColor, uint32_t rangeCount,
2607 const VkImageSubresourceRange* pRanges) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002608 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002609 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002610 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002611
2612 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002613 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002614 }
2615}
2616
2617void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
2618 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
2619 const VkImageSubresourceRange* pRanges) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002620 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002621 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002622 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002623
2624 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002625 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002626 }
2627}
2628
2629void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2630 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2631 const VkImageCopy* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002632 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002633 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002634 auto* src = GetImageUsageState(srcImage);
2635 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002636
2637 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002638 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
2639 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002640 }
2641}
2642
2643void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
2644 VkImageLayout dstImageLayout, uint32_t regionCount,
2645 const VkBufferImageCopy* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002646 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002647 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002648 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002649
2650 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002651 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002652 }
2653}
2654
2655void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2656 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002657 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002658 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002659 auto* src = GetImageUsageState(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002660
2661 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002662 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002663 }
2664}
2665
2666void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2667 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2668 const VkImageBlit* pRegions, VkFilter filter) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002669 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002670 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002671 auto* src = GetImageUsageState(srcImage);
2672 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002673
2674 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002675 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
2676 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002677 }
2678}
2679
Attilio Provenzano02859b22020-02-27 14:17:28 +00002680bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
2681 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
2682 bool skip = false;
2683
2684 if (VendorCheckEnabled(kBPVendorArm)) {
2685 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
2686 skip |= LogPerformanceWarning(
2687 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
2688 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
2689 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
2690 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06002691 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002692 }
2693
2694 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
2695 skip |= LogPerformanceWarning(
2696 device, kVUID_BestPractices_CreateSampler_LodClamping,
2697 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
2698 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
2699 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
2700 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
2701 }
2702
2703 if (pCreateInfo->mipLodBias != 0.0f) {
2704 skip |=
2705 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
2706 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
2707 "descriptors being created and may cause reduced performance.",
2708 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
2709 }
2710
2711 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2712 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2713 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
2714 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
2715 skip |= LogPerformanceWarning(
2716 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
2717 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
2718 "This will lead to less efficient descriptors being created and may cause reduced performance. "
2719 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
2720 VendorSpecificTag(kBPVendorArm));
2721 }
2722
2723 if (pCreateInfo->unnormalizedCoordinates) {
2724 skip |= LogPerformanceWarning(
2725 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
2726 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
2727 "descriptors being created and may cause reduced performance.",
2728 VendorSpecificTag(kBPVendorArm));
2729 }
2730
2731 if (pCreateInfo->anisotropyEnable) {
2732 skip |= LogPerformanceWarning(
2733 device, kVUID_BestPractices_CreateSampler_Anisotropy,
2734 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
2735 "and may cause reduced performance.",
2736 VendorSpecificTag(kBPVendorArm));
2737 }
2738 }
2739
2740 return skip;
2741}
Sam Walls8e77e4f2020-03-16 20:47:40 +00002742
2743void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
2744
2745bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
2746 // look for a cache hit
2747 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
2748 if (hit != _entries.end()) {
2749 // mark the cache hit as being most recently used
2750 hit->age = iteration++;
2751 return true;
2752 }
2753
2754 // if there's no cache hit, we need to model the entry being inserted into the cache
2755 CacheEntry new_entry = {value, iteration};
2756 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
2757 // if there is still space left in the cache, use the next available slot
2758 *(_entries.begin() + iteration) = new_entry;
2759 } else {
2760 // otherwise replace the least recently used cache entry
2761 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
2762 *lru = new_entry;
2763 }
2764 iteration++;
2765 return false;
2766}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002767
2768bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
2769 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
2770 const auto swapchain_data = GetSwapchainState(swapchain);
2771 bool skip = false;
2772 if (swapchain_data && swapchain_data->images.size() == 0) {
2773 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
2774 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
2775 "vkGetSwapchainImagesKHR after swapchain creation.");
2776 }
2777 return skip;
2778}
2779
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002780void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
2781 if (no_pointer) {
2782 if (UNCALLED == call_state) {
2783 call_state = QUERY_COUNT;
2784 }
2785 } else { // Save queue family properties
2786 call_state = QUERY_DETAILS;
2787 }
2788}
2789
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002790void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2791 uint32_t* pQueueFamilyPropertyCount,
2792 VkQueueFamilyProperties* pQueueFamilyProperties) {
2793 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
2794 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002795 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002796 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002797 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2798 nullptr == pQueueFamilyProperties);
2799 }
2800}
2801
2802void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2803 uint32_t* pQueueFamilyPropertyCount,
2804 VkQueueFamilyProperties2* pQueueFamilyProperties) {
2805 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
2806 pQueueFamilyProperties);
2807 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2808 if (bp_pd_state) {
2809 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2810 nullptr == pQueueFamilyProperties);
2811 }
2812}
2813
2814void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
2815 uint32_t* pQueueFamilyPropertyCount,
2816 VkQueueFamilyProperties2* pQueueFamilyProperties) {
2817 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
2818 pQueueFamilyProperties);
2819 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2820 if (bp_pd_state) {
2821 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2822 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002823 }
2824}
2825
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002826void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
2827 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002828 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2829 if (bp_pd_state) {
2830 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2831 }
2832}
2833
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002834void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
2835 VkPhysicalDeviceFeatures2* pFeatures) {
2836 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002837 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2838 if (bp_pd_state) {
2839 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2840 }
2841}
2842
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002843void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
2844 VkPhysicalDeviceFeatures2* pFeatures) {
2845 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002846 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2847 if (bp_pd_state) {
2848 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2849 }
2850}
2851
2852void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
2853 VkSurfaceKHR surface,
2854 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
2855 VkResult result) {
2856 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2857 if (bp_pd_state) {
2858 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2859 }
2860}
2861
2862void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
2863 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2864 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
2865 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2866 if (bp_pd_state) {
2867 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2868 }
2869}
2870
2871void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
2872 VkSurfaceKHR surface,
2873 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
2874 VkResult result) {
2875 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2876 if (bp_pd_state) {
2877 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2878 }
2879}
2880
2881void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
2882 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
2883 VkPresentModeKHR* pPresentModes, VkResult result) {
2884 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2885 if (bp_pd_data) {
2886 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
2887
2888 if (*pPresentModeCount) {
2889 if (call_state < QUERY_COUNT) {
2890 call_state = QUERY_COUNT;
2891 }
2892 }
2893 if (pPresentModes) {
2894 if (call_state < QUERY_DETAILS) {
2895 call_state = QUERY_DETAILS;
2896 }
2897 }
2898 }
2899}
2900
2901void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2902 uint32_t* pSurfaceFormatCount,
2903 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
2904 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2905 if (bp_pd_data) {
2906 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
2907
2908 if (*pSurfaceFormatCount) {
2909 if (call_state < QUERY_COUNT) {
2910 call_state = QUERY_COUNT;
2911 }
2912 }
2913 if (pSurfaceFormats) {
2914 if (call_state < QUERY_DETAILS) {
2915 call_state = QUERY_DETAILS;
2916 }
2917 }
2918 }
2919}
2920
2921void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
2922 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2923 uint32_t* pSurfaceFormatCount,
2924 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
2925 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2926 if (bp_pd_data) {
2927 if (*pSurfaceFormatCount) {
2928 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
2929 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
2930 }
2931 }
2932 if (pSurfaceFormats) {
2933 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
2934 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
2935 }
2936 }
2937 }
2938}
2939
2940void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
2941 uint32_t* pPropertyCount,
2942 VkDisplayPlanePropertiesKHR* pProperties,
2943 VkResult result) {
2944 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2945 if (bp_pd_data) {
2946 if (*pPropertyCount) {
2947 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
2948 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
2949 }
2950 }
2951 if (pProperties) {
2952 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
2953 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
2954 }
2955 }
2956 }
2957}
2958
2959void BestPractices::ManualPostCallRecordCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
2960 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain,
2961 VkResult result) {
2962 if (VK_SUCCESS == result) {
2963 swapchain_bp_state_map.emplace(*pSwapchain, SWAPCHAIN_STATE_BP{});
2964 }
2965}
2966
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002967void BestPractices::PostCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain,
2968 const VkAllocationCallbacks* pAllocator) {
2969 ValidationStateTracker::PostCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002970 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2971 if (swapchain_state_itr != swapchain_bp_state_map.cend()) {
2972 swapchain_bp_state_map.erase(swapchain_state_itr);
2973 }
2974}
2975
2976void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
2977 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
2978 VkResult result) {
2979 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2980 assert(swapchain_state_itr != swapchain_bp_state_map.cend());
2981 auto& swapchain_state = swapchain_state_itr->second;
2982 if (pSwapchainImages || *pSwapchainImageCount) {
2983 if (swapchain_state.vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
2984 swapchain_state.vkGetSwapchainImagesKHRState = QUERY_DETAILS;
2985 }
2986 }
2987}
2988
2989void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
2990 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
2991 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
2992 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
2993 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
2994 }
2995 }
2996}
2997
2998void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo*, const VkAllocationCallbacks*,
2999 VkDevice*, VkResult result) {
3000 if (VK_SUCCESS == result) {
3001 instance_device_bp_state = &phys_device_bp_state_map[gpu];
3002 }
3003}
3004
3005PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
3006 if (phys_device_bp_state_map.count(phys_device) > 0) {
3007 return &phys_device_bp_state_map.at(phys_device);
3008 } else {
3009 return nullptr;
3010 }
3011}
3012
3013const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
3014 if (phys_device_bp_state_map.count(phys_device) > 0) {
3015 return &phys_device_bp_state_map.at(phys_device);
3016 } else {
3017 return nullptr;
3018 }
3019}
3020
3021PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
3022 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
3023 if (bp_state) {
3024 return bp_state;
3025 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
3026 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
3027 } else {
3028 return nullptr;
3029 }
3030}
3031
3032const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
3033 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
3034 if (bp_state) {
3035 return bp_state;
3036 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
3037 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
3038 } else {
3039 return nullptr;
3040 }
3041}
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003042
3043void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
3044 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
3045
3046 QUEUE_STATE* queue_state = GetQueueState(queue);
3047 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003048 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003049 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
3050 CMD_BUFFER_STATE* cb = GetCBState(submit_info.pCommandBuffers[cb_index]);
3051 for (auto &func : cb->queue_submit_functions) {
3052 func(this, queue_state);
3053 }
3054 }
3055 }
3056}
Hans-Kristian Arntzen7a5fdc52021-03-29 11:39:51 +02003057
3058void BestPractices::PreCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo* pBeginInfo) {
3059 ValidationStateTracker::PreCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo);
3060 // This should not be required, but guards against buggy applications which do not call EndRenderPass correctly.
3061 queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02003062}