blob: 5a30d7b750f1825160c92f287fd29e51f156c714 [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"
Camden5b184be2019-08-13 07:50:19 -060025
26#include <string>
Sam Walls8e77e4f2020-03-16 20:47:40 +000027#include <bitset>
Sam Wallsd7ab6db2020-06-19 20:41:54 +010028#include <memory>
Camden5b184be2019-08-13 07:50:19 -060029
Attilio Provenzano19d6a982020-02-27 12:41:41 +000030struct VendorSpecificInfo {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060031 EnableFlags vendor_id;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000032 std::string name;
33};
34
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070035const std::map<BPVendorFlagBits, VendorSpecificInfo> kVendorInfo = {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060036 {kBPVendorArm, {vendor_specific_arm, "Arm"}},
Attilio Provenzano19d6a982020-02-27 12:41:41 +000037};
38
39bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070040 for (const auto& vendor : kVendorInfo) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060041 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000042 return true;
43 }
44 }
45 return false;
46}
47
48const char* VendorSpecificTag(BPVendorFlags vendors) {
49 // Cache built vendor tags in a map
Jeremy Gebbencbf22862021-03-03 12:01:22 -070050 static layer_data::unordered_map<BPVendorFlags, std::string> tag_map;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000051
52 auto res = tag_map.find(vendors);
53 if (res == tag_map.end()) {
54 // Build the vendor tag string
55 std::stringstream vendor_tag;
56
57 vendor_tag << "[";
58 bool first_vendor = true;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070059 for (const auto& vendor : kVendorInfo) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000060 if (vendors & vendor.first) {
61 if (!first_vendor) {
62 vendor_tag << ", ";
63 }
64 vendor_tag << vendor.second.name;
65 first_vendor = false;
66 }
67 }
68 vendor_tag << "]";
69
70 tag_map[vendors] = vendor_tag.str();
71 res = tag_map.find(vendors);
72 }
73
74 return res->second.c_str();
75}
76
Mark Lobodzinski6167e102020-02-24 17:03:55 -070077const char* DepReasonToString(ExtDeprecationReason reason) {
78 switch (reason) {
79 case kExtPromoted:
80 return "promoted to";
81 break;
82 case kExtObsoleted:
83 return "obsoleted by";
84 break;
85 case kExtDeprecated:
86 return "deprecated by";
87 break;
88 default:
89 return "";
90 break;
91 }
92}
93
94bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
95 const char* vuid) const {
96 bool skip = false;
97 auto dep_info_it = deprecated_extensions.find(extension_name);
98 if (dep_info_it != deprecated_extensions.end()) {
99 auto dep_info = dep_info_it->second;
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600100 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
101 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700102 skip |=
103 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
104 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600105 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700106 if (dep_info.target.length() == 0) {
107 skip |= LogWarning(instance, vuid,
108 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
109 "without replacement.",
110 api_name, extension_name);
111 } else {
112 skip |= LogWarning(instance, vuid,
113 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
114 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
115 }
116 }
117 }
118 return skip;
119}
120
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700121bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const char* vuid) const {
122 bool skip = false;
123 auto dep_info_it = special_use_extensions.find(extension_name);
124
125 if (dep_info_it != special_use_extensions.end()) {
126 auto special_uses = dep_info_it->second;
127 std::string message("is intended to support the following uses: ");
128 if (special_uses.find("cadsupport") != std::string::npos) {
129 message.append("specialized functionality used by CAD/CAM applications, ");
130 }
131 if (special_uses.find("d3demulation") != std::string::npos) {
132 message.append("D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D, ");
133 }
134 if (special_uses.find("devtools") != std::string::npos) {
135 message.append(" developer tools such as capture-replay libraries, ");
136 }
137 if (special_uses.find("debugging") != std::string::npos) {
138 message.append("use by applications when debugging, ");
139 }
140 if (special_uses.find("glemulation") != std::string::npos) {
141 message.append(
142 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
143 "specific to those APIs, ");
144 }
145 message.append("and it is strongly recommended that they be otherwise avoided");
146
147 skip |= LogWarning(instance, vuid, "%s(): Attempting to enable extension %s, but this extension %s.", api_name,
148 extension_name, message.c_str());
149 }
150 return skip;
151}
152
Camden5b184be2019-08-13 07:50:19 -0600153bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500154 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600155 bool skip = false;
156
157 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
158 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800159 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700160 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
161 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600162 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600163 uint32_t specified_version =
164 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
165 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700166 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Mark Lobodzinskia431b772020-11-10 08:12:13 -0700167 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i],
168 kVUID_BestPractices_CreateInstance_SpecialUseExtension);
Camden5b184be2019-08-13 07:50:19 -0600169 }
170
171 return skip;
172}
173
174void BestPractices::PreCallRecordCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
175 VkInstance* pInstance) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700176 ValidationStateTracker::PreCallRecordCreateInstance(pCreateInfo, pAllocator, pInstance);
Sam Walls53bf7652020-04-21 17:35:15 +0100177
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700178 if (pCreateInfo != nullptr && pCreateInfo->pApplicationInfo != nullptr) {
Sam Walls53bf7652020-04-21 17:35:15 +0100179 instance_api_version = pCreateInfo->pApplicationInfo->apiVersion;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700180 } else {
Sam Walls53bf7652020-04-21 17:35:15 +0100181 instance_api_version = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700182 }
Camden5b184be2019-08-13 07:50:19 -0600183}
184
185bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500186 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600187 bool skip = false;
188
189 // get API version of physical device passed when creating device.
190 VkPhysicalDeviceProperties physical_device_properties{};
191 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500192 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600193
194 // check api versions and warn if instance api Version is higher than version on device.
195 if (instance_api_version > device_api_version) {
Mark Lobodzinski60880782020-08-11 08:02:07 -0600196 std::string inst_api_name = StringAPIVersion(instance_api_version);
197 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600198
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700199 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
200 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
201 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600202 }
203
204 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
205 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800206 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700207 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
208 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600209 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700210 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], instance_api_version,
211 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Mark Lobodzinskia431b772020-11-10 08:12:13 -0700212 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i],
213 kVUID_BestPractices_CreateDevice_SpecialUseExtension);
Camden5b184be2019-08-13 07:50:19 -0600214 }
215
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600216 const auto bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
217 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700218 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
219 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600220 }
221
Szilard Papp7d2c7952020-06-22 14:38:13 +0100222 if ((VendorCheckEnabled(kBPVendorArm)) && (pCreateInfo->pEnabledFeatures != nullptr) &&
223 (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
224 skip |= LogPerformanceWarning(
225 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
226 "%s vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
227 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
228 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
229 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
230 VendorSpecificTag(kBPVendorArm));
231 }
232
Camden5b184be2019-08-13 07:50:19 -0600233 return skip;
234}
235
236bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500237 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600238 bool skip = false;
239
240 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700241 std::stringstream buffer_hex;
242 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600243
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700244 skip |= LogWarning(
245 device, kVUID_BestPractices_SharingModeExclusive,
246 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
247 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700248 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600249 }
250
251 return skip;
252}
253
254bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500255 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600256 bool skip = false;
257
258 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700259 std::stringstream image_hex;
260 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600261
262 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700263 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
264 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
265 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700266 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600267 }
268
Attilio Provenzano02859b22020-02-27 14:17:28 +0000269 if (VendorCheckEnabled(kBPVendorArm)) {
270 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
271 skip |= LogPerformanceWarning(
272 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
273 "%s vkCreateImage(): Trying to create an image with %u samples. "
274 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
275 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
276 }
277
278 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
279 skip |= LogPerformanceWarning(
280 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
281 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
282 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
283 "and do not need to be backed by physical storage. "
284 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
285 VendorSpecificTag(kBPVendorArm));
286 }
287 }
288
Camden5b184be2019-08-13 07:50:19 -0600289 return skip;
290}
291
292bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500293 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600294 bool skip = false;
295
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600296 const auto* bp_pd_state = GetPhysicalDeviceStateBP();
297 if (bp_pd_state) {
298 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
299 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
300 "vkCreateSwapchainKHR() called before getting surface capabilities from "
301 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
302 }
Camden83a9c372019-08-14 11:41:38 -0600303
Shannon McPherson73e58c82021-03-05 17:14:26 -0700304 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
305 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600306 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
307 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
308 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
309 }
Camden83a9c372019-08-14 11:41:38 -0600310
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600311 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
312 skip |= LogWarning(
313 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
314 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
315 }
Camden83a9c372019-08-14 11:41:38 -0600316 }
317
Camden5b184be2019-08-13 07:50:19 -0600318 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700319 skip |=
320 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600321 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700322 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
323 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600324 }
325
Szilard Papp48a6da32020-06-10 14:41:59 +0100326 if (pCreateInfo->minImageCount == 2) {
327 skip |= LogPerformanceWarning(
328 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
329 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
330 ", which means double buffering is going "
331 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
332 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
333 "3 to use triple buffering to maximize performance in such cases.",
334 pCreateInfo->minImageCount);
335 }
336
Szilard Pappd5f0f812020-06-22 09:01:29 +0100337 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
338 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
339 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
340 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
341 "Presentation modes which are not FIFO will present the latest available frame and discard other "
342 "frame(s) if any.",
343 VendorSpecificTag(kBPVendorArm));
344 }
345
Camden5b184be2019-08-13 07:50:19 -0600346 return skip;
347}
348
349bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
350 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500351 const VkAllocationCallbacks* pAllocator,
352 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600353 bool skip = false;
354
355 for (uint32_t i = 0; i < swapchainCount; i++) {
356 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700357 skip |= LogWarning(
358 device, kVUID_BestPractices_SharingModeExclusive,
359 "Warning: A shared swapchain (index %" PRIu32
360 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
361 "queues (queueFamilyIndexCount of %" PRIu32 ").",
362 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600363 }
364 }
365
366 return skip;
367}
368
369bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500370 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600371 bool skip = false;
372
373 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
374 VkFormat format = pCreateInfo->pAttachments[i].format;
375 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
376 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
377 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700378 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
379 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
380 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
381 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
382 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600383 }
384 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700385 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
386 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
387 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
388 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
389 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600390 }
391 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000392
393 const auto& attachment = pCreateInfo->pAttachments[i];
394 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
395 bool access_requires_memory =
396 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
397
398 if (FormatHasStencil(format)) {
399 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
400 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
401 }
402
403 if (access_requires_memory) {
404 skip |= LogPerformanceWarning(
405 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
406 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
407 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
408 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
409 i, static_cast<uint32_t>(attachment.samples));
410 }
411 }
Camden5b184be2019-08-13 07:50:19 -0600412 }
413
414 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
415 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
416 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
417 }
418
419 return skip;
420}
421
Tony-LunarG767180f2020-04-23 14:03:59 -0600422bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
423 const VkImageView* image_views) const {
424 bool skip = false;
425
426 // Check for non-transient attachments that should be transient and vice versa
427 for (uint32_t i = 0; i < attachmentCount; ++i) {
428 auto& attachment = rpci->pAttachments[i];
429 bool attachment_should_be_transient =
430 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
431
432 if (FormatHasStencil(attachment.format)) {
433 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
434 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
435 }
436
437 auto view_state = GetImageViewState(image_views[i]);
438 if (view_state) {
439 auto& ivci = view_state->create_info;
440 auto& ici = GetImageState(ivci.image)->createInfo;
441
442 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
443
444 // The check for an image that should not be transient applies to all GPUs
445 if (!attachment_should_be_transient && image_is_transient) {
446 skip |= LogPerformanceWarning(
447 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
448 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
449 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
450 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
451 i);
452 }
453
454 bool supports_lazy = false;
455 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
456 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
457 supports_lazy = true;
458 }
459 }
460
461 // The check for an image that should be transient only applies to GPUs supporting
462 // lazily allocated memory
463 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
464 skip |= LogPerformanceWarning(
465 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
466 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
467 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
468 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
469 i);
470 }
471 }
472 }
473 return skip;
474}
475
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000476bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
477 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
478 bool skip = false;
479
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000480 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800481 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600482 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000483 }
484
485 return skip;
486}
487
Sam Wallse746d522020-03-16 21:20:23 +0000488bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
489 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
490 bool skip = false;
491 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
492
493 if (!skip) {
494 const auto& pool_handle = pAllocateInfo->descriptorPool;
495 auto iter = descriptor_pool_freed_count.find(pool_handle);
496 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
497 // this warning is specific to Arm
498 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
499 skip |= LogPerformanceWarning(
500 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
501 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
502 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
503 VendorSpecificTag(kBPVendorArm));
504 }
505 }
506
507 return skip;
508}
509
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600510void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
511 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000512 if (result == VK_SUCCESS) {
513 // find the free count for the pool we allocated into
514 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
515 if (iter != descriptor_pool_freed_count.end()) {
516 // we record successful allocations by subtracting the allocation count from the last recorded free count
517 const auto alloc_count = pAllocateInfo->descriptorSetCount;
518 // clamp the unsigned subtraction to the range [0, last_free_count]
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700519 if (iter->second > alloc_count) {
Sam Wallse746d522020-03-16 21:20:23 +0000520 iter->second -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700521 } else {
Sam Wallse746d522020-03-16 21:20:23 +0000522 iter->second = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700523 }
Sam Wallse746d522020-03-16 21:20:23 +0000524 }
525 }
526}
527
528void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
529 const VkDescriptorSet* pDescriptorSets, VkResult result) {
530 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
531 if (result == VK_SUCCESS) {
532 // we want to track frees because we're interested in suggesting re-use
533 auto iter = descriptor_pool_freed_count.find(descriptorPool);
534 if (iter == descriptor_pool_freed_count.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700535 descriptor_pool_freed_count.emplace(descriptorPool, descriptorSetCount);
Sam Wallse746d522020-03-16 21:20:23 +0000536 } else {
537 iter->second += descriptorSetCount;
538 }
539 }
540}
541
Camden5b184be2019-08-13 07:50:19 -0600542bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500543 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600544 bool skip = false;
545
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500546 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700547 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
548 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600549 }
550
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000551 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
552 skip |= LogPerformanceWarning(
553 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600554 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
555 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000556 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
557 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
558 }
559
Camden83a9c372019-08-14 11:41:38 -0600560 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
561
562 return skip;
563}
564
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600565void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
566 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
567 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700568 if (result != VK_SUCCESS) {
569 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
570 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800571 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700572 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600573 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700574 return;
575 }
576 num_mem_objects++;
577}
Camden Stocker9738af92019-10-16 13:54:03 -0700578
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600579void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
580 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700581 auto error = std::find(error_codes.begin(), error_codes.end(), result);
582 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000583 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
584 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
585
586 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
587 if (common_failure != common_failure_codes.end()) {
588 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
589 } else {
590 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
591 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700592 return;
593 }
594 auto success = std::find(success_codes.begin(), success_codes.end(), result);
595 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600596 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
597 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500598 }
599}
600
Jeff Bolz5c801d12019-10-09 10:38:45 -0500601bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
602 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700603 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600604 bool skip = false;
605
Camden Stocker9738af92019-10-16 13:54:03 -0700606 const DEVICE_MEMORY_STATE* mem_info = ValidationStateTracker::GetDevMemState(memory);
Camden83a9c372019-08-14 11:41:38 -0600607
608 for (auto& obj : mem_info->obj_bindings) {
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600609 LogObjectList objlist(device);
610 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600611 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600612 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 -0600613 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600614 }
615
Camden5b184be2019-08-13 07:50:19 -0600616 return skip;
617}
618
619void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700620 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600621 if (memory != VK_NULL_HANDLE) {
622 num_mem_objects--;
623 }
624}
625
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000626bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600627 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500628 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600629
sfricke-samsunge2441192019-11-06 14:07:57 -0800630 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700631 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
632 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
633 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600634 }
635
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000636 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
637
638 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
639 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
640 skip |= LogPerformanceWarning(
641 device, kVUID_BestPractices_SmallDedicatedAllocation,
642 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600643 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
644 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000645 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
646 }
647
Camden Stockerb603cc82019-09-03 10:09:02 -0600648 return skip;
649}
650
651bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500652 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600653 bool skip = false;
654 const char* api_name = "BindBufferMemory()";
655
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000656 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600657
658 return skip;
659}
660
661bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500662 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600663 char api_name[64];
664 bool skip = false;
665
666 for (uint32_t i = 0; i < bindInfoCount; i++) {
667 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000668 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600669 }
670
671 return skip;
672}
Camden Stockerb603cc82019-09-03 10:09:02 -0600673
674bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500675 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600676 char api_name[64];
677 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600678
Camden Stocker8b798ab2019-09-03 10:33:28 -0600679 for (uint32_t i = 0; i < bindInfoCount; i++) {
680 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000681 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600682 }
683
684 return skip;
685}
686
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000687bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600688 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500689 const IMAGE_STATE* image_state = GetImageState(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600690
sfricke-samsung71bc6572020-04-29 15:49:43 -0700691 if (image_state->disjoint == false) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700692 if (!image_state->memory_requirements_checked && !image_state->external_memory_handle) {
693 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
694 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
695 api_name, report_data->FormatHandle(image).c_str());
696 }
697 } else {
698 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
699 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600700 }
701
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000702 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
703
704 if (mem_state->alloc_info.allocationSize == image_state->requirements.size &&
705 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
706 skip |= LogPerformanceWarning(
707 device, kVUID_BestPractices_SmallDedicatedAllocation,
708 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600709 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
710 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000711 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
712 }
713
714 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
715 // make sure this type is actually used.
716 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
717 // (i.e.most tile - based renderers)
718 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
719 bool supports_lazy = false;
720 uint32_t suggested_type = 0;
721
722 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
723 if ((1u << i) & image_state->requirements.memoryTypeBits) {
724 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
725 supports_lazy = true;
726 suggested_type = i;
727 break;
728 }
729 }
730 }
731
732 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
733
734 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
735 skip |= LogPerformanceWarning(
736 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600737 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000738 "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 -0600739 "%" PRIu64 " bytes of physical memory.",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000740 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements.size);
741 }
742 }
743
Camden Stocker8b798ab2019-09-03 10:33:28 -0600744 return skip;
745}
746
747bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500748 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600749 bool skip = false;
750 const char* api_name = "vkBindImageMemory()";
751
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000752 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600753
754 return skip;
755}
756
757bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500758 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600759 char api_name[64];
760 bool skip = false;
761
762 for (uint32_t i = 0; i < bindInfoCount; i++) {
763 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700764 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600765 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
766 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600767 }
768
769 return skip;
770}
771
772bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500773 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600774 char api_name[64];
775 bool skip = false;
776
777 for (uint32_t i = 0; i < bindInfoCount; i++) {
778 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000779 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600780 }
781
782 return skip;
783}
Camden83a9c372019-08-14 11:41:38 -0600784
Attilio Provenzano02859b22020-02-27 14:17:28 +0000785static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
786 switch (format) {
787 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
788 case VK_FORMAT_R16_SFLOAT:
789 case VK_FORMAT_R16G16_SFLOAT:
790 case VK_FORMAT_R16G16B16_SFLOAT:
791 case VK_FORMAT_R16G16B16A16_SFLOAT:
792 case VK_FORMAT_R32_SFLOAT:
793 case VK_FORMAT_R32G32_SFLOAT:
794 case VK_FORMAT_R32G32B32_SFLOAT:
795 case VK_FORMAT_R32G32B32A32_SFLOAT:
796 return false;
797
798 default:
799 return true;
800 }
801}
802
803bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
804 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
805 bool skip = false;
806
807 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700808 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000809
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700810 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
811 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
812 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000813 return skip;
814 }
815
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700816 auto rp_state = GetRenderPassState(create_info->renderPass);
817 auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000818
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700819 for (uint32_t j = 0; j < create_info->pColorBlendState->attachmentCount; j++) {
820 auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000821 uint32_t att = subpass.pColorAttachments[j].attachment;
822
823 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
824 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
825 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
826 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
827 "color attachment #%u makes use "
828 "of a format which cannot be blended at full throughput when using MSAA.",
829 VendorSpecificTag(kBPVendorArm), i, j);
830 }
831 }
832 }
833 }
834
835 return skip;
836}
837
Camden5b184be2019-08-13 07:50:19 -0600838bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
839 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600840 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500841 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600842 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
843 pAllocator, pPipelines, cgpl_state_data);
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600844 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600845
846 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700847 skip |= LogPerformanceWarning(
848 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
849 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
850 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600851 }
852
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000853 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700854 auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000855
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600856 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700857 auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600858 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700859 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
860 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600861 count++;
862 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000863 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600864 if (count > kMaxInstancedVertexBuffers) {
865 skip |= LogPerformanceWarning(
866 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
867 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
868 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
869 count, kMaxInstancedVertexBuffers);
870 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000871 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000872
Szilard Pappaaf2da32020-06-22 10:37:35 +0100873 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
874 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
875 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f)) {
876 skip |= VendorCheckEnabled(kBPVendorArm) &&
877 LogPerformanceWarning(
878 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
879 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
880 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
881 "efficiency during rasterization. Consider disabling depthBias or increasing either "
882 "depthBiasConstantFactor or depthBiasSlopeFactor.",
883 VendorSpecificTag(kBPVendorArm));
884 }
885
Attilio Provenzano02859b22020-02-27 14:17:28 +0000886 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000887 }
888
Camden5b184be2019-08-13 07:50:19 -0600889 return skip;
890}
891
Sam Walls0961ec02020-03-31 16:39:15 +0100892void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
893 const VkGraphicsPipelineCreateInfo* pCreateInfos,
894 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
895 VkResult result, void* cgpl_state_data) {
896 for (size_t i = 0; i < count; i++) {
897 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
898 const VkPipeline pipeline_handle = pPipelines[i];
899
900 // record depth stencil state and color blend states for depth pre-pass tracking purposes
901 auto gp_cis = graphicsPipelineCIs.find(pipeline_handle);
902
903 // add the tracking state if it doesn't exist
904 if (gp_cis == graphicsPipelineCIs.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700905 auto result = graphicsPipelineCIs.emplace(pipeline_handle, GraphicsPipelineCIs{});
Sam Walls0961ec02020-03-31 16:39:15 +0100906
907 if (!result.second) continue;
908
909 gp_cis = result.first;
910 }
911
Tony-LunarG412b1b72020-07-15 10:30:13 -0600912 gp_cis->second.colorBlendStateCI =
913 cgpl_state->pCreateInfos[i].pColorBlendState
914 ? new safe_VkPipelineColorBlendStateCreateInfo(cgpl_state->pCreateInfos[i].pColorBlendState)
915 : nullptr;
916 gp_cis->second.depthStencilStateCI =
917 cgpl_state->pCreateInfos[i].pDepthStencilState
918 ? new safe_VkPipelineDepthStencilStateCreateInfo(cgpl_state->pCreateInfos[i].pDepthStencilState)
919 : nullptr;
Sam Walls0961ec02020-03-31 16:39:15 +0100920 }
921}
922
Camden5b184be2019-08-13 07:50:19 -0600923bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
924 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600925 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500926 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600927 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
928 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600929
930 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700931 skip |= LogPerformanceWarning(
932 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
933 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
934 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600935 }
936
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100937 if (VendorCheckEnabled(kBPVendorArm)) {
938 for (size_t i = 0; i < createInfoCount; i++) {
939 skip |= ValidateCreateComputePipelineArm(pCreateInfos[i]);
940 }
941 }
942
943 return skip;
944}
945
946bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
947 bool skip = false;
948 auto* module = GetShaderModuleState(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -0800949 // Generate warnings about work group sizes based on active resources.
sfricke-samsung962cad92021-04-13 00:46:29 -0700950 auto entrypoint = module->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
sfricke-samsung8a7341a2021-02-28 07:30:21 -0800951 if (entrypoint == module->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100952
953 uint32_t x = 1, y = 1, z = 1;
sfricke-samsung962cad92021-04-13 00:46:29 -0700954 module->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100955
956 uint32_t thread_count = x * y * z;
957
958 // Generate a priori warnings about work group sizes.
959 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
960 skip |= LogPerformanceWarning(
961 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
962 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
963 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
964 "groups with less than %u threads, especially when using barrier() or shared memory.",
965 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
966 }
967
968 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
969 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
970 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
971 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
972 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
973 "%u, %u) is not aligned to %u "
974 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
975 "leave threads idle on the shader "
976 "core.",
977 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
978 kThreadGroupDispatchCountAlignmentArm);
979 }
980
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100981 bool has_writeable_descriptors = false;
locke-lunarg63e4daf2020-08-17 17:53:25 -0600982 bool has_atomic_descriptors = false;
sfricke-samsung962cad92021-04-13 00:46:29 -0700983 auto accessible_ids = module->MarkAccessibleIds(entrypoint);
locke-lunarg63e4daf2020-08-17 17:53:25 -0600984 auto descriptor_uses =
sfricke-samsung962cad92021-04-13 00:46:29 -0700985 module->CollectInterfaceByDescriptorSlot(accessible_ids, &has_writeable_descriptors, &has_atomic_descriptors);
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100986
987 unsigned dimensions = 0;
988 if (x > 1) dimensions++;
989 if (y > 1) dimensions++;
990 if (z > 1) dimensions++;
991 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
992 dimensions = std::max(dimensions, 1u);
993
994 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
995 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
996 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
997 bool accesses_2d = false;
998 for (const auto& usage : descriptor_uses) {
sfricke-samsung962cad92021-04-13 00:46:29 -0700999 auto dim = module->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001000 if (dim < 0) continue;
1001 auto spvdim = spv::Dim(dim);
1002 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1003 }
1004
1005 if (accesses_2d && dimensions < 2) {
1006 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1007 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1008 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1009 "exhibiting poor spatial locality with respect to one or more shader resources.",
1010 VendorSpecificTag(kBPVendorArm), x, y, z);
1011 }
1012
Camden5b184be2019-08-13 07:50:19 -06001013 return skip;
1014}
1015
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001016bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001017 bool skip = false;
1018
1019 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001020 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1021 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001022 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001023 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1024 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001025 }
1026
1027 return skip;
1028}
1029
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001030bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1031 bool skip = false;
1032
1033 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1034 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1035 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1036 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1037 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1038 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1039 }
1040
1041 return skip;
1042}
1043
1044bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1045 bool skip = false;
1046 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1047
1048 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1049 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1050
1051 return skip;
1052}
1053
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001054void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001055 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1056 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1057 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1058 LogPerformanceWarning(
1059 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1060 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1061 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1062 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1063 "convenient opportunity.",
1064 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1065 }
1066 }
1067}
1068
Jeff Bolz5c801d12019-10-09 10:38:45 -05001069bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1070 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001071 bool skip = false;
1072
1073 for (uint32_t submit = 0; submit < submitCount; submit++) {
1074 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1075 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1076 }
1077 }
1078
1079 return skip;
1080}
1081
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001082bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1083 VkFence fence) const {
1084 bool skip = false;
1085
1086 for (uint32_t submit = 0; submit < submitCount; submit++) {
1087 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1088 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1089 }
1090 }
1091
1092 return skip;
1093}
1094
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001095bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1096 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1097 bool skip = false;
1098
1099 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1100 skip |= LogPerformanceWarning(
1101 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1102 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1103 "pool instead.");
1104 }
1105
1106 return skip;
1107}
1108
1109bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1110 const VkCommandBufferBeginInfo* pBeginInfo) const {
1111 bool skip = false;
1112
1113 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1114 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1115 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1116 }
1117
Attilio Provenzano02859b22020-02-27 14:17:28 +00001118 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT)) {
1119 skip |= VendorCheckEnabled(kBPVendorArm) &&
1120 LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
1121 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1122 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1123 VendorSpecificTag(kBPVendorArm));
1124 }
1125
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001126 return skip;
1127}
1128
Jeff Bolz5c801d12019-10-09 10:38:45 -05001129bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001130 bool skip = false;
1131
1132 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1133
1134 return skip;
1135}
1136
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001137bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1138 const VkDependencyInfoKHR* pDependencyInfo) const {
1139 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1140}
1141
Jeff Bolz5c801d12019-10-09 10:38:45 -05001142bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1143 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001144 bool skip = false;
1145
1146 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1147
1148 return skip;
1149}
1150
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001151bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1152 VkPipelineStageFlags2KHR stageMask) const {
1153 bool skip = false;
1154
1155 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1156
1157 return skip;
1158}
1159
Camden5b184be2019-08-13 07:50:19 -06001160bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1161 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1162 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1163 uint32_t bufferMemoryBarrierCount,
1164 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1165 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001166 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001167 bool skip = false;
1168
1169 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1170 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1171
1172 return skip;
1173}
1174
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001175bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1176 const VkDependencyInfoKHR* pDependencyInfos) const {
1177 bool skip = false;
1178 for (uint32_t i = 0; i < eventCount; i++) {
1179 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1180 }
1181
1182 return skip;
1183}
1184
Camden5b184be2019-08-13 07:50:19 -06001185bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1186 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1187 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1188 uint32_t bufferMemoryBarrierCount,
1189 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1190 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001191 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001192 bool skip = false;
1193
1194 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1195 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1196
1197 return skip;
1198}
1199
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001200bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1201 const VkDependencyInfoKHR* pDependencyInfo) const {
1202 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1203}
1204
Camden5b184be2019-08-13 07:50:19 -06001205bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001206 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001207 bool skip = false;
1208
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001209 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1210
1211 return skip;
1212}
1213
1214bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1215 VkQueryPool queryPool, uint32_t query) const {
1216 bool skip = false;
1217
1218 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001219
1220 return skip;
1221}
1222
Sam Walls0961ec02020-03-31 16:39:15 +01001223void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1224 VkPipeline pipeline) {
1225 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1226
1227 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1228 // check for depth/blend state tracking
1229 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1230 if (gp_cis != graphicsPipelineCIs.end()) {
1231 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1232 if (prepass_state == cbDepthPrePassStates.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001233 auto result = cbDepthPrePassStates.emplace(commandBuffer, DepthPrePassState{});
Sam Walls0961ec02020-03-31 16:39:15 +01001234
1235 if (!result.second) return;
1236
1237 prepass_state = result.first;
1238 }
1239
1240 const auto* blend_state = gp_cis->second.colorBlendStateCI;
1241 const auto* stencil_state = gp_cis->second.depthStencilStateCI;
1242
1243 if (blend_state) {
1244 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
1245 prepass_state->second.depthOnly = true;
1246 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1247 if (blend_state->pAttachments[i].colorWriteMask != 0) {
1248 prepass_state->second.depthOnly = false;
1249 }
1250 }
1251 }
1252
1253 // check for depth value usage
1254 prepass_state->second.depthEqualComparison = false;
1255
1256 if (stencil_state && stencil_state->depthTestEnable) {
1257 switch (stencil_state->depthCompareOp) {
1258 case VK_COMPARE_OP_EQUAL:
1259 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1260 case VK_COMPARE_OP_LESS_OR_EQUAL:
1261 prepass_state->second.depthEqualComparison = true;
1262 break;
1263 default:
1264 break;
1265 }
1266 }
1267 } else {
1268 // reset depth pre-pass tracking
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001269 cbDepthPrePassStates.emplace(commandBuffer, DepthPrePassState{});
Sam Walls0961ec02020-03-31 16:39:15 +01001270 }
1271 }
1272}
1273
Attilio Provenzano02859b22020-02-27 14:17:28 +00001274static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1275 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001276 auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001277
1278 // If an attachment is ever used as a color attachment,
1279 // resolve attachment or depth stencil attachment,
1280 // it needs to exist on tile at some point.
1281
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001282 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1283 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001284 }
1285
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001286 if (subpass_info.pResolveAttachments) {
1287 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1288 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1289 }
1290 }
1291
1292 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001293 }
1294
1295 return false;
1296}
1297
1298bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1299 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1300 bool skip = false;
1301
1302 if (!pRenderPassBegin) {
1303 return skip;
1304 }
1305
1306 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1307 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001308 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001309 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001310 if (rpabi) {
1311 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1312 }
1313 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001314 // Check if any attachments have LOAD operation on them
1315 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1316 auto& attachment = rp_state->createInfo.pAttachments[att];
1317
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001318 bool attachment_has_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001319 if (!FormatHasStencil(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001320 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001321 }
1322
1323 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001324 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001325 }
1326
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001327 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001328
1329 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001330 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1331 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001332 }
1333
1334 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001335 if (attachment_needs_readback) {
Attilio Provenzano02859b22020-02-27 14:17:28 +00001336 skip |= VendorCheckEnabled(kBPVendorArm) &&
1337 LogPerformanceWarning(
1338 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1339 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1340 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
1341 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
1342 VendorSpecificTag(kBPVendorArm), att,
1343 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1344 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1345 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
1346 }
1347 }
1348 }
1349
1350 return skip;
1351}
1352
1353bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1354 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001355 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1356 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001357 return skip;
1358}
1359
1360bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1361 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001362 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001363 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1364 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001365 return skip;
1366}
1367
1368bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001369 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001370 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1371 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001372 return skip;
1373}
1374
Sam Walls0961ec02020-03-31 16:39:15 +01001375void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1376 const VkRenderPassBeginInfo* pRenderPassBegin) {
1377 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1378
1379 // add the tracking state if it doesn't exist
1380 if (prepass_state == cbDepthPrePassStates.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001381 auto result = cbDepthPrePassStates.emplace(commandBuffer, DepthPrePassState{});
Sam Walls0961ec02020-03-31 16:39:15 +01001382
1383 if (!result.second) return;
1384
1385 prepass_state = result.first;
1386 }
1387
1388 // reset the renderpass state
1389 prepass_state->second = {};
1390
1391 const auto* cb_state = GetCBState(commandBuffer);
locke-lunargaecf2152020-05-12 17:15:41 -06001392 const auto* rp_state = cb_state->activeRenderPass.get();
Sam Walls0961ec02020-03-31 16:39:15 +01001393
1394 // track depth / color attachment usage within the renderpass
1395 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1396 // record if depth/color attachments are in use for this renderpass
1397 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) prepass_state->second.depthAttachment = true;
1398
1399 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) prepass_state->second.colorAttachment = true;
1400 }
1401}
1402
1403void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1404 VkSubpassContents contents) {
1405 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1406 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1407}
1408
1409void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1410 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1411 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1412 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1413}
1414
1415void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1416 const VkRenderPassBeginInfo* pRenderPassBegin,
1417 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1418 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1419 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1420}
1421
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001422// Generic function to handle validation for all CmdDraw* type functions
1423bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1424 bool skip = false;
1425 const CMD_BUFFER_STATE* cb_state = GetCBState(cmd_buffer);
1426 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001427 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1428 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001429 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001430
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001431 // Verify vertex binding
1432 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1433 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001434 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001435 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001436 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
1437 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001438 }
1439 }
1440 }
1441 return skip;
1442}
1443
Sam Walls0961ec02020-03-31 16:39:15 +01001444void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1445 if (VendorCheckEnabled(kBPVendorArm)) {
1446 RecordCmdDrawTypeArm(cmd_buffer, draw_count, caller);
1447 }
1448}
1449
1450void BestPractices::RecordCmdDrawTypeArm(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1451 auto prepass_state = cbDepthPrePassStates.find(cmd_buffer);
1452 if (prepass_state != cbDepthPrePassStates.end() && draw_count >= kDepthPrePassMinDrawCountArm) {
1453 if (prepass_state->second.depthOnly) prepass_state->second.numDrawCallsDepthOnly++;
1454
1455 if (prepass_state->second.depthEqualComparison) prepass_state->second.numDrawCallsDepthEqualCompare++;
1456 }
1457}
1458
Camden5b184be2019-08-13 07:50:19 -06001459bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001460 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001461 bool skip = false;
1462
1463 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001464 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1465 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001466 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001467 }
1468
1469 return skip;
1470}
1471
Sam Walls0961ec02020-03-31 16:39:15 +01001472void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1473 uint32_t firstVertex, uint32_t firstInstance) {
1474 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
1475 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
1476}
1477
Camden5b184be2019-08-13 07:50:19 -06001478bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001479 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001480 bool skip = false;
1481
1482 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001483 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1484 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001485 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001486 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1487
Attilio Provenzano02859b22020-02-27 14:17:28 +00001488 // Check if we reached the limit for small indexed draw calls.
1489 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1490 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1491 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
1492 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1)) {
1493 skip |= VendorCheckEnabled(kBPVendorArm) &&
1494 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06001495 "%s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00001496 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1497 "You can try batching drawcalls or instancing when applicable.",
1498 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1499 }
1500
Sam Walls8e77e4f2020-03-16 20:47:40 +00001501 if (VendorCheckEnabled(kBPVendorArm)) {
1502 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1503 }
1504
1505 return skip;
1506}
1507
1508bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1509 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1510 bool skip = false;
1511
1512 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1513 const auto* cmd_state = GetCBState(commandBuffer);
1514 if (cmd_state == nullptr) return skip;
1515
locke-lunarg1ae57d62020-11-18 10:49:19 -07001516 const auto* ib_state = cmd_state->index_buffer_binding.buffer_state.get();
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06001517 if (ib_state == nullptr || cmd_state->index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001518
1519 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
1520 const auto& ib_mem_state = *ib_state->binding.mem_state;
1521 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1522 const void* ib_mem = ib_mem_state.p_driver_data;
1523 bool primitive_restart_enable = false;
1524
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001525 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1526 const auto& pipeline_binding_iter = cmd_state->lastBound[lv_bind_point];
1527 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001528
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001529 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001530 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001531 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00001532
1533 // 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 -06001534 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00001535 uint32_t scan_stride;
1536 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1537 scan_stride = sizeof(uint8_t);
1538 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1539 scan_stride = sizeof(uint16_t);
1540 } else {
1541 scan_stride = sizeof(uint32_t);
1542 }
1543
1544 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1545 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1546
1547 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1548 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1549 // irrespective of whether or not they're part of the draw call.
1550
1551 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1552 uint32_t min_index = ~0u;
1553 // start with maximum as 0 and adjust to indices in the buffer
1554 uint32_t max_index = 0u;
1555
1556 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
1557 // for the given index buffer
1558 uint32_t vertex_shade_count = 0;
1559
1560 PostTransformLRUCacheModel post_transform_cache;
1561
1562 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
1563 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
1564 // target architecture.
1565 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
1566 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
1567 post_transform_cache.resize(32);
1568
1569 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1570 uint32_t scan_index;
1571 uint32_t primitive_restart_value;
1572 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1573 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1574 primitive_restart_value = 0xFF;
1575 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1576 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1577 primitive_restart_value = 0xFFFF;
1578 } else {
1579 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1580 primitive_restart_value = 0xFFFFFFFF;
1581 }
1582
1583 max_index = std::max(max_index, scan_index);
1584 min_index = std::min(min_index, scan_index);
1585
1586 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
1587 bool in_cache = post_transform_cache.query_cache(scan_index);
1588 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
1589 if (!in_cache) vertex_shade_count++;
1590 }
1591 }
1592
1593 // 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 +01001594 // 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
1595 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001596
1597 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07001598 skip |=
1599 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1600 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
1601 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
1602 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
1603 "maximum would be loaded, and possibly shaded, whether or not they are used.",
1604 VendorSpecificTag(kBPVendorArm),
1605 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001606 return skip;
1607 }
1608
1609 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
1610 // 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 +01001611 const size_t refs_per_bucket = 64;
1612 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
1613
1614 const uint32_t n_indices = max_index - min_index + 1;
1615 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
1616 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
1617
1618 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
1619 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00001620
1621 // To avoid using too much memory, we run over the indices again.
1622 // Knowing the size from the last scan allows us to record index usage with bitsets
1623 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1624 uint32_t scan_index;
1625 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1626 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1627 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1628 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1629 } else {
1630 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1631 }
1632 // keep track of the set of all indices used to reference vertices in the draw call
1633 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01001634 size_t bitset_bucket_index = index_offset / refs_per_bucket;
1635 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001636 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
1637 }
1638
1639 uint32_t vertex_reference_count = 0;
1640 for (const auto& bitset : vertex_reference_buckets) {
1641 vertex_reference_count += static_cast<uint32_t>(bitset.count());
1642 }
1643
1644 // 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 -07001645 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001646 // 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 -07001647 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001648
1649 if (utilization < 0.5f) {
1650 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1651 "%s The indices which were specified for the draw call only utilise approximately "
1652 "%.02f%% of the bound vertex buffer.",
1653 VendorSpecificTag(kBPVendorArm), utilization);
1654 }
1655
1656 if (cache_hit_rate <= 0.5f) {
1657 skip |=
1658 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
1659 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
1660 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
1661 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
1662 "recently shaded vertices.",
1663 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
1664 }
1665 }
1666
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001667 return skip;
1668}
1669
Attilio Provenzano02859b22020-02-27 14:17:28 +00001670void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1671 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1672 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
1673 firstInstance);
1674
1675 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1676 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
1677 cmd_state->small_indexed_draw_call_count++;
1678 }
1679}
1680
Sam Walls0961ec02020-03-31 16:39:15 +01001681void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1682 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1683 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1684 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
1685}
1686
sfricke-samsung681ab7b2020-10-29 01:53:35 -07001687bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1688 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
1689 uint32_t maxDrawCount, uint32_t stride) const {
1690 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
1691
1692 return skip;
1693}
1694
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001695bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
1696 VkDeviceSize offset, VkBuffer countBuffer,
1697 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
1698 uint32_t stride) const {
1699 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06001700
1701 return skip;
1702}
1703
1704bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001705 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001706 bool skip = false;
1707
1708 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001709 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1710 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001711 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001712 }
1713
1714 return skip;
1715}
1716
Sam Walls0961ec02020-03-31 16:39:15 +01001717void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1718 uint32_t count, uint32_t stride) {
1719 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
1720 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
1721}
1722
Camden5b184be2019-08-13 07:50:19 -06001723bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001724 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001725 bool skip = false;
1726
1727 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001728 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1729 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001730 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001731 }
1732
1733 return skip;
1734}
1735
Sam Walls0961ec02020-03-31 16:39:15 +01001736void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1737 uint32_t count, uint32_t stride) {
1738 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
1739 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
1740}
1741
Camden5b184be2019-08-13 07:50:19 -06001742bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001743 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06001744 bool skip = false;
1745
1746 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001747 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
1748 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
1749 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
1750 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06001751 }
1752
1753 return skip;
1754}
Camden83a9c372019-08-14 11:41:38 -06001755
Sam Walls0961ec02020-03-31 16:39:15 +01001756bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
1757 bool skip = false;
1758
1759 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
1760
1761 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1762
1763 if (prepass_state == cbDepthPrePassStates.end()) return skip;
1764
1765 bool uses_depth = (prepass_state->second.depthAttachment || prepass_state->second.colorAttachment) &&
1766 prepass_state->second.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
1767 prepass_state->second.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
1768 if (uses_depth) {
1769 skip |= LogPerformanceWarning(
1770 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
1771 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
1772 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
1773 "case, using depth pre-passes for hidden surface removal may worsen performance.",
1774 VendorSpecificTag(kBPVendorArm));
1775 }
1776
1777 return skip;
1778}
1779
Camden Stocker9c051442019-11-06 14:28:43 -08001780bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
1781 const char* api_name) const {
1782 bool skip = false;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001783 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08001784
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001785 if (bp_pd_state) {
1786 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
1787 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
1788 "Potential problem with calling %s() without first retrieving properties from "
1789 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
1790 api_name);
1791 }
Camden Stocker9c051442019-11-06 14:28:43 -08001792 }
1793
1794 return skip;
1795}
1796
Camden83a9c372019-08-14 11:41:38 -06001797bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001798 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06001799 bool skip = false;
1800
Camden Stocker9c051442019-11-06 14:28:43 -08001801 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06001802
Camden Stocker9c051442019-11-06 14:28:43 -08001803 return skip;
1804}
1805
1806bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
1807 uint32_t planeIndex,
1808 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
1809 bool skip = false;
1810
1811 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
1812
1813 return skip;
1814}
1815
1816bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
1817 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
1818 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
1819 bool skip = false;
1820
1821 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06001822
1823 return skip;
1824}
Camden05de2d42019-08-19 10:23:56 -06001825
1826bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001827 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06001828 bool skip = false;
1829
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001830 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
Camden05de2d42019-08-19 10:23:56 -06001831
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001832 if ((swapchain_state_itr != swapchain_bp_state_map.cend()) && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06001833 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001834 if (swapchain_state_itr->second.vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001835 skip |=
1836 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
1837 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
1838 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06001839 }
1840 }
1841
1842 return skip;
1843}
1844
1845// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001846bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
1847 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07001848 const CALL_STATE call_state,
1849 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06001850 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07001851 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
1852 if (UNCALLED == call_state) {
1853 skip |= LogWarning(
1854 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
1855 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
1856 "recommended "
1857 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
1858 caller_name, caller_name);
1859 // Then verify that pCount that is passed in on second call matches what was returned
1860 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
1861 skip |= LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
1862 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
1863 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
1864 ". It is recommended to instead receive all the properties by calling %s with "
1865 "pQueueFamilyPropertyCount that was "
1866 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
1867 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
1868 caller_name);
Camden05de2d42019-08-19 10:23:56 -06001869 }
1870
1871 return skip;
1872}
1873
Jeff Bolz5c801d12019-10-09 10:38:45 -05001874bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
1875 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06001876 bool skip = false;
1877
1878 for (uint32_t i = 0; i < bindInfoCount; i++) {
sourav parmarcd5fb182020-07-17 12:58:44 -07001879 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureStateNV(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06001880 if (!as_state->memory_requirements_checked) {
1881 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
1882 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
1883 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001884 skip |= LogWarning(
1885 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06001886 "vkBindAccelerationStructureMemoryNV(): "
1887 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
1888 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
1889 }
1890 }
1891
1892 return skip;
1893}
1894
Camden05de2d42019-08-19 10:23:56 -06001895bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
1896 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001897 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001898 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1899 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07001900 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
1901 if (pQueueFamilyProperties && bp_pd_state) {
1902 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
1903 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
1904 "vkGetPhysicalDeviceQueueFamilyProperties()");
1905 }
1906 return false;
Camden05de2d42019-08-19 10:23:56 -06001907}
1908
Mike Schuchardt2df08912020-12-15 16:28:09 -08001909bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
1910 uint32_t* pQueueFamilyPropertyCount,
1911 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001912 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1913 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07001914 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
1915 if (pQueueFamilyProperties && bp_pd_state) {
1916 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
1917 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
1918 "vkGetPhysicalDeviceQueueFamilyProperties2()");
1919 }
1920 return false;
Camden05de2d42019-08-19 10:23:56 -06001921}
1922
Jeff Bolz5c801d12019-10-09 10:38:45 -05001923bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08001924 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001925 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1926 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07001927 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
1928 if (pQueueFamilyProperties && bp_pd_state) {
1929 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
1930 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
1931 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
1932 }
1933 return false;
Camden05de2d42019-08-19 10:23:56 -06001934}
1935
1936bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
1937 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001938 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06001939 if (!pSurfaceFormats) return false;
1940 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001941 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
1942 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06001943 bool skip = false;
1944 if (call_state == UNCALLED) {
1945 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
1946 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001947 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
1948 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
1949 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06001950 } else {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001951 auto prev_format_count = static_cast<uint32_t>(physical_device_state->surface_formats.size());
Peter Chene191bd72019-09-16 13:04:37 -04001952 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001953 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
1954 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
1955 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
1956 "when pSurfaceFormatCount was NULL.",
1957 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06001958 }
1959 }
1960 return skip;
1961}
Camden Stocker23cc47d2019-09-03 14:53:57 -06001962
1963bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001964 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001965 bool skip = false;
1966
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001967 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
1968 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06001969 // 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 -07001970 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001971 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
1972 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001973 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06001974 // 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 -07001975 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
1976 const auto& image_bind = bind_info.pImageBinds[i];
Camden Stocker23cc47d2019-09-03 14:53:57 -06001977 auto image_state = GetImageState(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001978 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001979 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001980 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06001981 sparse_images.insert(image_state);
1982 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1983 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1984 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001985 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001986 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1987 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001988 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001989 }
1990 }
1991 if (!image_state->memory_requirements_checked) {
1992 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001993 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001994 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1995 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001996 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001997 }
1998 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001999 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2000 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
2001 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
2002 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002003 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002004 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002005 sparse_images.insert(image_state);
2006 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2007 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2008 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002009 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002010 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2011 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002012 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002013 }
2014 }
2015 if (!image_state->memory_requirements_checked) {
2016 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002017 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002018 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2019 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002020 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002021 }
2022 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2023 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002024 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06002025 }
2026 }
2027 }
2028 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002029 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
2030 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002031 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002032 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002033 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
2034 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002035 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002036 }
2037 }
2038 }
2039
2040 return skip;
2041}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002042
Mark Lobodzinski84101d72020-04-24 09:43:48 -06002043void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
2044 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002045 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002046 return;
2047 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002048
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002049 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2050 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
2051 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2052 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
2053 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
2054 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002055 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002056 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002057 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2058 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
2059 image_state->sparse_metadata_bound = true;
2060 }
2061 }
2062 }
2063 }
2064}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002065
2066bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06002067 const VkClearAttachment* pAttachments, uint32_t rectCount,
2068 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002069 bool skip = false;
2070 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
2071 if (!cb_node) return skip;
2072
Camden Stockerf55721f2019-09-09 11:04:49 -06002073 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002074 if (!cb_node->hasDrawCmd && (cb_node->activeRenderPassBeginInfo.renderArea.extent.width == pRects[0].rect.extent.width) &&
2075 (cb_node->activeRenderPassBeginInfo.renderArea.extent.height == pRects[0].rect.extent.height)) {
2076 // There are times where app needs to use ClearAttachments (generally when reusing a buffer inside of a render pass)
2077 // This warning should be made more specific. It'd be best to avoid triggering this test if it's a use that must call
2078 // CmdClearAttachments.
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07002079 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
2080 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds. It is recommended you "
2081 "use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
2082 report_data->FormatHandle(commandBuffer).c_str());
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002083 }
2084
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002085 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
2086 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06002087 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002088 if (rp) {
2089 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
2090
2091 for (uint32_t i = 0; i < attachmentCount; i++) {
2092 auto& attachment = pAttachments[i];
2093 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
2094 uint32_t color_attachment = attachment.colorAttachment;
2095 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
2096
2097 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2098 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2099 skip |= LogPerformanceWarning(
2100 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2101 "vkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
2102 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2103 "it is more efficient.",
2104 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
2105 }
2106 }
2107 }
2108
2109 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
2110 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2111
2112 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2113 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2114 skip |= LogPerformanceWarning(
2115 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2116 "vkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
2117 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2118 "it is more efficient.",
2119 report_data->FormatHandle(commandBuffer).c_str());
2120 }
2121 }
2122 }
2123
2124 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
2125 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2126
2127 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2128 if (rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2129 skip |= LogPerformanceWarning(
2130 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2131 "vkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
2132 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2133 "it is more efficient.",
2134 report_data->FormatHandle(commandBuffer).c_str());
2135 }
2136 }
2137 }
2138 }
2139 }
2140
Camden Stockerf55721f2019-09-09 11:04:49 -06002141 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002142}
Attilio Provenzano02859b22020-02-27 14:17:28 +00002143
2144bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2145 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2146 const VkImageResolve* pRegions) const {
2147 bool skip = false;
2148
2149 skip |= VendorCheckEnabled(kBPVendorArm) &&
2150 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
2151 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
2152 "This is a very slow and extremely bandwidth intensive path. "
2153 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2154 VendorSpecificTag(kBPVendorArm));
2155
2156 return skip;
2157}
2158
Jeff Leger178b1e52020-10-05 12:22:23 -04002159bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2160 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
2161 bool skip = false;
2162
2163 skip |= VendorCheckEnabled(kBPVendorArm) &&
2164 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
2165 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
2166 "This is a very slow and extremely bandwidth intensive path. "
2167 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2168 VendorSpecificTag(kBPVendorArm));
2169
2170 return skip;
2171}
2172
Attilio Provenzano02859b22020-02-27 14:17:28 +00002173bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
2174 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
2175 bool skip = false;
2176
2177 if (VendorCheckEnabled(kBPVendorArm)) {
2178 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
2179 skip |= LogPerformanceWarning(
2180 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
2181 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
2182 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
2183 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06002184 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002185 }
2186
2187 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
2188 skip |= LogPerformanceWarning(
2189 device, kVUID_BestPractices_CreateSampler_LodClamping,
2190 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
2191 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
2192 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
2193 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
2194 }
2195
2196 if (pCreateInfo->mipLodBias != 0.0f) {
2197 skip |=
2198 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
2199 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
2200 "descriptors being created and may cause reduced performance.",
2201 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
2202 }
2203
2204 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2205 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2206 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
2207 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
2208 skip |= LogPerformanceWarning(
2209 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
2210 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
2211 "This will lead to less efficient descriptors being created and may cause reduced performance. "
2212 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
2213 VendorSpecificTag(kBPVendorArm));
2214 }
2215
2216 if (pCreateInfo->unnormalizedCoordinates) {
2217 skip |= LogPerformanceWarning(
2218 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
2219 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
2220 "descriptors being created and may cause reduced performance.",
2221 VendorSpecificTag(kBPVendorArm));
2222 }
2223
2224 if (pCreateInfo->anisotropyEnable) {
2225 skip |= LogPerformanceWarning(
2226 device, kVUID_BestPractices_CreateSampler_Anisotropy,
2227 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
2228 "and may cause reduced performance.",
2229 VendorSpecificTag(kBPVendorArm));
2230 }
2231 }
2232
2233 return skip;
2234}
Sam Walls8e77e4f2020-03-16 20:47:40 +00002235
2236void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
2237
2238bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
2239 // look for a cache hit
2240 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
2241 if (hit != _entries.end()) {
2242 // mark the cache hit as being most recently used
2243 hit->age = iteration++;
2244 return true;
2245 }
2246
2247 // if there's no cache hit, we need to model the entry being inserted into the cache
2248 CacheEntry new_entry = {value, iteration};
2249 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
2250 // if there is still space left in the cache, use the next available slot
2251 *(_entries.begin() + iteration) = new_entry;
2252 } else {
2253 // otherwise replace the least recently used cache entry
2254 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
2255 *lru = new_entry;
2256 }
2257 iteration++;
2258 return false;
2259}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002260
2261bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
2262 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
2263 const auto swapchain_data = GetSwapchainState(swapchain);
2264 bool skip = false;
2265 if (swapchain_data && swapchain_data->images.size() == 0) {
2266 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
2267 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
2268 "vkGetSwapchainImagesKHR after swapchain creation.");
2269 }
2270 return skip;
2271}
2272
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002273void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
2274 if (no_pointer) {
2275 if (UNCALLED == call_state) {
2276 call_state = QUERY_COUNT;
2277 }
2278 } else { // Save queue family properties
2279 call_state = QUERY_DETAILS;
2280 }
2281}
2282
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002283void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2284 uint32_t* pQueueFamilyPropertyCount,
2285 VkQueueFamilyProperties* pQueueFamilyProperties) {
2286 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
2287 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002288 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002289 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002290 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2291 nullptr == pQueueFamilyProperties);
2292 }
2293}
2294
2295void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2296 uint32_t* pQueueFamilyPropertyCount,
2297 VkQueueFamilyProperties2* pQueueFamilyProperties) {
2298 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
2299 pQueueFamilyProperties);
2300 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2301 if (bp_pd_state) {
2302 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2303 nullptr == pQueueFamilyProperties);
2304 }
2305}
2306
2307void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
2308 uint32_t* pQueueFamilyPropertyCount,
2309 VkQueueFamilyProperties2* pQueueFamilyProperties) {
2310 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
2311 pQueueFamilyProperties);
2312 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2313 if (bp_pd_state) {
2314 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2315 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002316 }
2317}
2318
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002319void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
2320 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002321 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2322 if (bp_pd_state) {
2323 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2324 }
2325}
2326
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002327void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
2328 VkPhysicalDeviceFeatures2* pFeatures) {
2329 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002330 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2331 if (bp_pd_state) {
2332 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2333 }
2334}
2335
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002336void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
2337 VkPhysicalDeviceFeatures2* pFeatures) {
2338 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002339 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2340 if (bp_pd_state) {
2341 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2342 }
2343}
2344
2345void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
2346 VkSurfaceKHR surface,
2347 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
2348 VkResult result) {
2349 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2350 if (bp_pd_state) {
2351 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2352 }
2353}
2354
2355void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
2356 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2357 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
2358 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2359 if (bp_pd_state) {
2360 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2361 }
2362}
2363
2364void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
2365 VkSurfaceKHR surface,
2366 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
2367 VkResult result) {
2368 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2369 if (bp_pd_state) {
2370 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2371 }
2372}
2373
2374void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
2375 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
2376 VkPresentModeKHR* pPresentModes, VkResult result) {
2377 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2378 if (bp_pd_data) {
2379 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
2380
2381 if (*pPresentModeCount) {
2382 if (call_state < QUERY_COUNT) {
2383 call_state = QUERY_COUNT;
2384 }
2385 }
2386 if (pPresentModes) {
2387 if (call_state < QUERY_DETAILS) {
2388 call_state = QUERY_DETAILS;
2389 }
2390 }
2391 }
2392}
2393
2394void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2395 uint32_t* pSurfaceFormatCount,
2396 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
2397 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2398 if (bp_pd_data) {
2399 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
2400
2401 if (*pSurfaceFormatCount) {
2402 if (call_state < QUERY_COUNT) {
2403 call_state = QUERY_COUNT;
2404 }
2405 }
2406 if (pSurfaceFormats) {
2407 if (call_state < QUERY_DETAILS) {
2408 call_state = QUERY_DETAILS;
2409 }
2410 }
2411 }
2412}
2413
2414void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
2415 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2416 uint32_t* pSurfaceFormatCount,
2417 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
2418 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2419 if (bp_pd_data) {
2420 if (*pSurfaceFormatCount) {
2421 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
2422 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
2423 }
2424 }
2425 if (pSurfaceFormats) {
2426 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
2427 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
2428 }
2429 }
2430 }
2431}
2432
2433void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
2434 uint32_t* pPropertyCount,
2435 VkDisplayPlanePropertiesKHR* pProperties,
2436 VkResult result) {
2437 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2438 if (bp_pd_data) {
2439 if (*pPropertyCount) {
2440 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
2441 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
2442 }
2443 }
2444 if (pProperties) {
2445 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
2446 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
2447 }
2448 }
2449 }
2450}
2451
2452void BestPractices::ManualPostCallRecordCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
2453 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain,
2454 VkResult result) {
2455 if (VK_SUCCESS == result) {
2456 swapchain_bp_state_map.emplace(*pSwapchain, SWAPCHAIN_STATE_BP{});
2457 }
2458}
2459
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002460void BestPractices::PostCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain,
2461 const VkAllocationCallbacks* pAllocator) {
2462 ValidationStateTracker::PostCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002463 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2464 if (swapchain_state_itr != swapchain_bp_state_map.cend()) {
2465 swapchain_bp_state_map.erase(swapchain_state_itr);
2466 }
2467}
2468
2469void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
2470 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
2471 VkResult result) {
2472 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2473 assert(swapchain_state_itr != swapchain_bp_state_map.cend());
2474 auto& swapchain_state = swapchain_state_itr->second;
2475 if (pSwapchainImages || *pSwapchainImageCount) {
2476 if (swapchain_state.vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
2477 swapchain_state.vkGetSwapchainImagesKHRState = QUERY_DETAILS;
2478 }
2479 }
2480}
2481
2482void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
2483 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
2484 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
2485 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
2486 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
2487 }
2488 }
2489}
2490
2491void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo*, const VkAllocationCallbacks*,
2492 VkDevice*, VkResult result) {
2493 if (VK_SUCCESS == result) {
2494 instance_device_bp_state = &phys_device_bp_state_map[gpu];
2495 }
2496}
2497
2498PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
2499 if (phys_device_bp_state_map.count(phys_device) > 0) {
2500 return &phys_device_bp_state_map.at(phys_device);
2501 } else {
2502 return nullptr;
2503 }
2504}
2505
2506const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
2507 if (phys_device_bp_state_map.count(phys_device) > 0) {
2508 return &phys_device_bp_state_map.at(phys_device);
2509 } else {
2510 return nullptr;
2511 }
2512}
2513
2514PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
2515 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2516 if (bp_state) {
2517 return bp_state;
2518 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2519 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2520 } else {
2521 return nullptr;
2522 }
2523}
2524
2525const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
2526 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2527 if (bp_state) {
2528 return bp_state;
2529 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2530 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2531 } else {
2532 return nullptr;
2533 }
2534}