blob: 5f0f9c8f5916250e97415f6468c546e184bf6b64 [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
Jeremy Gebben5570abe2021-05-16 18:35:13 -0600608 for (const auto& node: mem_info->ObjectBindings()) {
609 const auto& obj = node->Handle();
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600610 LogObjectList objlist(device);
611 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600612 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600613 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 -0600614 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600615 }
616
Camden5b184be2019-08-13 07:50:19 -0600617 return skip;
618}
619
620void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700621 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600622 if (memory != VK_NULL_HANDLE) {
623 num_mem_objects--;
624 }
625}
626
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000627bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600628 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500629 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600630
sfricke-samsunge2441192019-11-06 14:07:57 -0800631 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700632 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
633 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
634 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600635 }
636
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000637 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
638
639 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
640 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
641 skip |= LogPerformanceWarning(
642 device, kVUID_BestPractices_SmallDedicatedAllocation,
643 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600644 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
645 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000646 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
647 }
648
Camden Stockerb603cc82019-09-03 10:09:02 -0600649 return skip;
650}
651
652bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500653 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600654 bool skip = false;
655 const char* api_name = "BindBufferMemory()";
656
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000657 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600658
659 return skip;
660}
661
662bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500663 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600664 char api_name[64];
665 bool skip = false;
666
667 for (uint32_t i = 0; i < bindInfoCount; i++) {
668 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000669 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600670 }
671
672 return skip;
673}
Camden Stockerb603cc82019-09-03 10:09:02 -0600674
675bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500676 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600677 char api_name[64];
678 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600679
Camden Stocker8b798ab2019-09-03 10:33:28 -0600680 for (uint32_t i = 0; i < bindInfoCount; i++) {
681 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000682 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600683 }
684
685 return skip;
686}
687
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000688bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600689 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500690 const IMAGE_STATE* image_state = GetImageState(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600691
sfricke-samsung71bc6572020-04-29 15:49:43 -0700692 if (image_state->disjoint == false) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700693 if (!image_state->memory_requirements_checked && !image_state->external_memory_handle) {
694 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
695 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
696 api_name, report_data->FormatHandle(image).c_str());
697 }
698 } else {
699 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
700 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600701 }
702
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000703 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
704
705 if (mem_state->alloc_info.allocationSize == image_state->requirements.size &&
706 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
707 skip |= LogPerformanceWarning(
708 device, kVUID_BestPractices_SmallDedicatedAllocation,
709 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600710 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
711 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000712 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
713 }
714
715 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
716 // make sure this type is actually used.
717 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
718 // (i.e.most tile - based renderers)
719 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
720 bool supports_lazy = false;
721 uint32_t suggested_type = 0;
722
723 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
724 if ((1u << i) & image_state->requirements.memoryTypeBits) {
725 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
726 supports_lazy = true;
727 suggested_type = i;
728 break;
729 }
730 }
731 }
732
733 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
734
735 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
736 skip |= LogPerformanceWarning(
737 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600738 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000739 "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 -0600740 "%" PRIu64 " bytes of physical memory.",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000741 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements.size);
742 }
743 }
744
Camden Stocker8b798ab2019-09-03 10:33:28 -0600745 return skip;
746}
747
748bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500749 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600750 bool skip = false;
751 const char* api_name = "vkBindImageMemory()";
752
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000753 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600754
755 return skip;
756}
757
758bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500759 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600760 char api_name[64];
761 bool skip = false;
762
763 for (uint32_t i = 0; i < bindInfoCount; i++) {
764 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700765 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600766 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
767 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600768 }
769
770 return skip;
771}
772
773bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500774 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600775 char api_name[64];
776 bool skip = false;
777
778 for (uint32_t i = 0; i < bindInfoCount; i++) {
779 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000780 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600781 }
782
783 return skip;
784}
Camden83a9c372019-08-14 11:41:38 -0600785
Attilio Provenzano02859b22020-02-27 14:17:28 +0000786static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
787 switch (format) {
788 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
789 case VK_FORMAT_R16_SFLOAT:
790 case VK_FORMAT_R16G16_SFLOAT:
791 case VK_FORMAT_R16G16B16_SFLOAT:
792 case VK_FORMAT_R16G16B16A16_SFLOAT:
793 case VK_FORMAT_R32_SFLOAT:
794 case VK_FORMAT_R32G32_SFLOAT:
795 case VK_FORMAT_R32G32B32_SFLOAT:
796 case VK_FORMAT_R32G32B32A32_SFLOAT:
797 return false;
798
799 default:
800 return true;
801 }
802}
803
804bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
805 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
806 bool skip = false;
807
808 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700809 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000810
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700811 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
812 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
813 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000814 return skip;
815 }
816
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700817 auto rp_state = GetRenderPassState(create_info->renderPass);
818 auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000819
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700820 for (uint32_t j = 0; j < create_info->pColorBlendState->attachmentCount; j++) {
821 auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000822 uint32_t att = subpass.pColorAttachments[j].attachment;
823
824 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
825 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
826 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
827 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
828 "color attachment #%u makes use "
829 "of a format which cannot be blended at full throughput when using MSAA.",
830 VendorSpecificTag(kBPVendorArm), i, j);
831 }
832 }
833 }
834 }
835
836 return skip;
837}
838
Camden5b184be2019-08-13 07:50:19 -0600839bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
840 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600841 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500842 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600843 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
844 pAllocator, pPipelines, cgpl_state_data);
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600845 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600846
847 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700848 skip |= LogPerformanceWarning(
849 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
850 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
851 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600852 }
853
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000854 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700855 auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000856
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600857 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700858 auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600859 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700860 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
861 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600862 count++;
863 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000864 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600865 if (count > kMaxInstancedVertexBuffers) {
866 skip |= LogPerformanceWarning(
867 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
868 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
869 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
870 count, kMaxInstancedVertexBuffers);
871 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000872 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000873
Szilard Pappaaf2da32020-06-22 10:37:35 +0100874 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
875 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
876 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f)) {
877 skip |= VendorCheckEnabled(kBPVendorArm) &&
878 LogPerformanceWarning(
879 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
880 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
881 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
882 "efficiency during rasterization. Consider disabling depthBias or increasing either "
883 "depthBiasConstantFactor or depthBiasSlopeFactor.",
884 VendorSpecificTag(kBPVendorArm));
885 }
886
Attilio Provenzano02859b22020-02-27 14:17:28 +0000887 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000888 }
889
Camden5b184be2019-08-13 07:50:19 -0600890 return skip;
891}
892
Sam Walls0961ec02020-03-31 16:39:15 +0100893void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
894 const VkGraphicsPipelineCreateInfo* pCreateInfos,
895 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
896 VkResult result, void* cgpl_state_data) {
897 for (size_t i = 0; i < count; i++) {
898 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
899 const VkPipeline pipeline_handle = pPipelines[i];
900
901 // record depth stencil state and color blend states for depth pre-pass tracking purposes
902 auto gp_cis = graphicsPipelineCIs.find(pipeline_handle);
903
904 // add the tracking state if it doesn't exist
905 if (gp_cis == graphicsPipelineCIs.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700906 auto result = graphicsPipelineCIs.emplace(pipeline_handle, GraphicsPipelineCIs{});
Sam Walls0961ec02020-03-31 16:39:15 +0100907
908 if (!result.second) continue;
909
910 gp_cis = result.first;
911 }
912
Tony-LunarG412b1b72020-07-15 10:30:13 -0600913 gp_cis->second.colorBlendStateCI =
914 cgpl_state->pCreateInfos[i].pColorBlendState
915 ? new safe_VkPipelineColorBlendStateCreateInfo(cgpl_state->pCreateInfos[i].pColorBlendState)
916 : nullptr;
917 gp_cis->second.depthStencilStateCI =
918 cgpl_state->pCreateInfos[i].pDepthStencilState
919 ? new safe_VkPipelineDepthStencilStateCreateInfo(cgpl_state->pCreateInfos[i].pDepthStencilState)
920 : nullptr;
Sam Walls0961ec02020-03-31 16:39:15 +0100921 }
922}
923
Camden5b184be2019-08-13 07:50:19 -0600924bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
925 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600926 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500927 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600928 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
929 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600930
931 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700932 skip |= LogPerformanceWarning(
933 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
934 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
935 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600936 }
937
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100938 if (VendorCheckEnabled(kBPVendorArm)) {
939 for (size_t i = 0; i < createInfoCount; i++) {
940 skip |= ValidateCreateComputePipelineArm(pCreateInfos[i]);
941 }
942 }
943
944 return skip;
945}
946
947bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
948 bool skip = false;
949 auto* module = GetShaderModuleState(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -0800950 // Generate warnings about work group sizes based on active resources.
sfricke-samsung962cad92021-04-13 00:46:29 -0700951 auto entrypoint = module->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
sfricke-samsung8a7341a2021-02-28 07:30:21 -0800952 if (entrypoint == module->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100953
954 uint32_t x = 1, y = 1, z = 1;
sfricke-samsung962cad92021-04-13 00:46:29 -0700955 module->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100956
957 uint32_t thread_count = x * y * z;
958
959 // Generate a priori warnings about work group sizes.
960 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
961 skip |= LogPerformanceWarning(
962 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
963 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
964 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
965 "groups with less than %u threads, especially when using barrier() or shared memory.",
966 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
967 }
968
969 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
970 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
971 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
972 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
973 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
974 "%u, %u) is not aligned to %u "
975 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
976 "leave threads idle on the shader "
977 "core.",
978 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
979 kThreadGroupDispatchCountAlignmentArm);
980 }
981
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100982 bool has_writeable_descriptors = false;
locke-lunarg63e4daf2020-08-17 17:53:25 -0600983 bool has_atomic_descriptors = false;
sfricke-samsung962cad92021-04-13 00:46:29 -0700984 auto accessible_ids = module->MarkAccessibleIds(entrypoint);
locke-lunarg63e4daf2020-08-17 17:53:25 -0600985 auto descriptor_uses =
sfricke-samsung962cad92021-04-13 00:46:29 -0700986 module->CollectInterfaceByDescriptorSlot(accessible_ids, &has_writeable_descriptors, &has_atomic_descriptors);
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100987
988 unsigned dimensions = 0;
989 if (x > 1) dimensions++;
990 if (y > 1) dimensions++;
991 if (z > 1) dimensions++;
992 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
993 dimensions = std::max(dimensions, 1u);
994
995 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
996 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
997 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
998 bool accesses_2d = false;
999 for (const auto& usage : descriptor_uses) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001000 auto dim = module->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001001 if (dim < 0) continue;
1002 auto spvdim = spv::Dim(dim);
1003 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1004 }
1005
1006 if (accesses_2d && dimensions < 2) {
1007 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1008 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1009 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1010 "exhibiting poor spatial locality with respect to one or more shader resources.",
1011 VendorSpecificTag(kBPVendorArm), x, y, z);
1012 }
1013
Camden5b184be2019-08-13 07:50:19 -06001014 return skip;
1015}
1016
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001017bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001018 bool skip = false;
1019
1020 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001021 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1022 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001023 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001024 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1025 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001026 }
1027
1028 return skip;
1029}
1030
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001031bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1032 bool skip = false;
1033
1034 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1035 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1036 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1037 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1038 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1039 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1040 }
1041
1042 return skip;
1043}
1044
1045bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1046 bool skip = false;
1047 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1048
1049 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1050 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1051
1052 return skip;
1053}
1054
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001055void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001056 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1057 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1058 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1059 LogPerformanceWarning(
1060 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1061 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1062 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1063 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1064 "convenient opportunity.",
1065 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1066 }
1067 }
1068}
1069
Jeff Bolz5c801d12019-10-09 10:38:45 -05001070bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1071 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001072 bool skip = false;
1073
1074 for (uint32_t submit = 0; submit < submitCount; submit++) {
1075 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1076 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1077 }
1078 }
1079
1080 return skip;
1081}
1082
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001083bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1084 VkFence fence) const {
1085 bool skip = false;
1086
1087 for (uint32_t submit = 0; submit < submitCount; submit++) {
1088 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1089 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1090 }
1091 }
1092
1093 return skip;
1094}
1095
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001096bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1097 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1098 bool skip = false;
1099
1100 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1101 skip |= LogPerformanceWarning(
1102 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1103 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1104 "pool instead.");
1105 }
1106
1107 return skip;
1108}
1109
1110bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1111 const VkCommandBufferBeginInfo* pBeginInfo) const {
1112 bool skip = false;
1113
1114 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1115 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1116 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1117 }
1118
Attilio Provenzano02859b22020-02-27 14:17:28 +00001119 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT)) {
1120 skip |= VendorCheckEnabled(kBPVendorArm) &&
1121 LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
1122 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1123 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1124 VendorSpecificTag(kBPVendorArm));
1125 }
1126
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001127 return skip;
1128}
1129
Jeff Bolz5c801d12019-10-09 10:38:45 -05001130bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001131 bool skip = false;
1132
1133 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1134
1135 return skip;
1136}
1137
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001138bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1139 const VkDependencyInfoKHR* pDependencyInfo) const {
1140 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1141}
1142
Jeff Bolz5c801d12019-10-09 10:38:45 -05001143bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1144 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001145 bool skip = false;
1146
1147 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1148
1149 return skip;
1150}
1151
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001152bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1153 VkPipelineStageFlags2KHR stageMask) const {
1154 bool skip = false;
1155
1156 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1157
1158 return skip;
1159}
1160
Camden5b184be2019-08-13 07:50:19 -06001161bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1162 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1163 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1164 uint32_t bufferMemoryBarrierCount,
1165 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1166 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001167 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001168 bool skip = false;
1169
1170 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1171 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1172
1173 return skip;
1174}
1175
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001176bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1177 const VkDependencyInfoKHR* pDependencyInfos) const {
1178 bool skip = false;
1179 for (uint32_t i = 0; i < eventCount; i++) {
1180 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1181 }
1182
1183 return skip;
1184}
1185
Camden5b184be2019-08-13 07:50:19 -06001186bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1187 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1188 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1189 uint32_t bufferMemoryBarrierCount,
1190 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1191 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001192 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001193 bool skip = false;
1194
1195 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1196 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1197
1198 return skip;
1199}
1200
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001201bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1202 const VkDependencyInfoKHR* pDependencyInfo) const {
1203 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1204}
1205
Camden5b184be2019-08-13 07:50:19 -06001206bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001207 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001208 bool skip = false;
1209
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001210 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1211
1212 return skip;
1213}
1214
1215bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1216 VkQueryPool queryPool, uint32_t query) const {
1217 bool skip = false;
1218
1219 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001220
1221 return skip;
1222}
1223
Sam Walls0961ec02020-03-31 16:39:15 +01001224void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1225 VkPipeline pipeline) {
1226 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1227
1228 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1229 // check for depth/blend state tracking
1230 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1231 if (gp_cis != graphicsPipelineCIs.end()) {
1232 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1233 if (prepass_state == cbDepthPrePassStates.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001234 auto result = cbDepthPrePassStates.emplace(commandBuffer, DepthPrePassState{});
Sam Walls0961ec02020-03-31 16:39:15 +01001235
1236 if (!result.second) return;
1237
1238 prepass_state = result.first;
1239 }
1240
1241 const auto* blend_state = gp_cis->second.colorBlendStateCI;
1242 const auto* stencil_state = gp_cis->second.depthStencilStateCI;
1243
1244 if (blend_state) {
1245 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
1246 prepass_state->second.depthOnly = true;
1247 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1248 if (blend_state->pAttachments[i].colorWriteMask != 0) {
1249 prepass_state->second.depthOnly = false;
1250 }
1251 }
1252 }
1253
1254 // check for depth value usage
1255 prepass_state->second.depthEqualComparison = false;
1256
1257 if (stencil_state && stencil_state->depthTestEnable) {
1258 switch (stencil_state->depthCompareOp) {
1259 case VK_COMPARE_OP_EQUAL:
1260 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1261 case VK_COMPARE_OP_LESS_OR_EQUAL:
1262 prepass_state->second.depthEqualComparison = true;
1263 break;
1264 default:
1265 break;
1266 }
1267 }
1268 } else {
1269 // reset depth pre-pass tracking
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001270 cbDepthPrePassStates.emplace(commandBuffer, DepthPrePassState{});
Sam Walls0961ec02020-03-31 16:39:15 +01001271 }
1272 }
1273}
1274
Attilio Provenzano02859b22020-02-27 14:17:28 +00001275static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1276 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001277 auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001278
1279 // If an attachment is ever used as a color attachment,
1280 // resolve attachment or depth stencil attachment,
1281 // it needs to exist on tile at some point.
1282
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001283 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1284 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001285 }
1286
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001287 if (subpass_info.pResolveAttachments) {
1288 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1289 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1290 }
1291 }
1292
1293 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001294 }
1295
1296 return false;
1297}
1298
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001299static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1300 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1301 return false;
1302 }
1303
1304 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1305 auto& subpassInfo = createInfo.pSubpasses[subpass];
1306
1307 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1308 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1309 return true;
1310 }
1311 }
1312 }
1313
1314 return false;
1315}
1316
Attilio Provenzano02859b22020-02-27 14:17:28 +00001317bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1318 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1319 bool skip = false;
1320
1321 if (!pRenderPassBegin) {
1322 return skip;
1323 }
1324
1325 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1326 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001327 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001328 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001329 if (rpabi) {
1330 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1331 }
1332 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001333 // Check if any attachments have LOAD operation on them
1334 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1335 auto& attachment = rp_state->createInfo.pAttachments[att];
1336
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001337 bool attachment_has_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001338 if (!FormatHasStencil(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001339 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001340 }
1341
1342 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001343 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001344 }
1345
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001346 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001347
1348 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001349 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1350 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001351 }
1352
1353 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001354 if (attachment_needs_readback) {
Attilio Provenzano02859b22020-02-27 14:17:28 +00001355 skip |= VendorCheckEnabled(kBPVendorArm) &&
1356 LogPerformanceWarning(
1357 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1358 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1359 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
1360 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
1361 VendorSpecificTag(kBPVendorArm), att,
1362 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1363 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1364 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
1365 }
1366 }
1367 }
1368
1369 return skip;
1370}
1371
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001372void BestPractices::ValidateImageView(IMAGE_VIEW_STATE* view, const IMAGE_ATTACHMENT_USAGE& usage) {
1373 if (view) {
1374 ValidateImage(GetImageState(view->create_info.image), usage, view->create_info.subresourceRange);
1375 }
1376}
1377
1378void BestPractices::ValidateImage(IMAGE_STATE* image, const IMAGE_ATTACHMENT_USAGE& usage,
1379 const VkImageSubresourceRange& subresource_range) {
1380 uint32_t max_layers = image->createInfo.arrayLayers - subresource_range.baseArrayLayer;
1381 uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
1382 uint32_t max_levels = image->createInfo.mipLevels - subresource_range.baseMipLevel;
1383 uint32_t mip_levels = std::min(image->createInfo.mipLevels, max_levels);
1384
1385 for (uint32_t layer = 0; layer < array_layers; layer++) {
1386 for (uint32_t level = 0; level < mip_levels; level++) {
1387 ValidateImage(image, usage, layer + subresource_range.baseArrayLayer, level + subresource_range.baseMipLevel);
1388 }
1389 }
1390}
1391
1392void BestPractices::ValidateImage(IMAGE_STATE* image, const IMAGE_ATTACHMENT_USAGE& usage,
1393 const VkImageSubresourceLayers& subresource_layers) {
1394 uint32_t max_layers = image->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
1395 uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
1396
1397 for (uint32_t layer = 0; layer < array_layers; layer++) {
1398 ValidateImage(image, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
1399 }
1400}
1401
1402void BestPractices::ValidateImage(IMAGE_STATE* image, const IMAGE_ATTACHMENT_USAGE& usage, uint32_t array_layer,
1403 uint32_t mip_level) {
1404 // Resize usages
1405 if (static_cast<uint32_t>(image->usages.size()) != image->createInfo.arrayLayers) {
1406 image->usages.resize(image->createInfo.arrayLayers);
1407 }
1408 for (auto& mips : image->usages) {
1409 if (static_cast<uint32_t>(mips.size()) != image->createInfo.mipLevels) {
1410 mips.resize(image->createInfo.mipLevels, IMAGE_ATTACHMENT_USAGE::UNDEFINED);
1411 }
1412 }
1413
1414 IMAGE_ATTACHMENT_USAGE last_usage = image->usages[array_layer][mip_level];
1415
1416 // Swapchain images are implicitly read so clear after store is expected.
1417 if (usage == IMAGE_ATTACHMENT_USAGE::RENDER_PASS_CLEARED && last_usage == IMAGE_ATTACHMENT_USAGE::RENDER_PASS_STORED &&
1418 !image->is_swapchain_image) {
1419 VendorCheckEnabled(kBPVendorArm) &&
1420 LogPerformanceWarning(
1421 device, kVUID_BestPractices_RenderPass_RedundantStore,
1422 "%s Subresource (arrayLayer: %u, mipLevel: %u) of image was cleared as part of LOAD_OP_CLEAR, but last time "
1423 "image was used, it was written to with STORE_OP_STORE. "
1424 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1425 "architectures.",
1426 VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
1427
1428 } else if (usage == IMAGE_ATTACHMENT_USAGE::RENDER_PASS_CLEARED && last_usage == IMAGE_ATTACHMENT_USAGE::CLEARED) {
1429 VendorCheckEnabled(kBPVendorArm) &&
1430 LogPerformanceWarning(
1431 device, kVUID_BestPractices_RenderPass_RedundantClear,
1432 "%s Subresource (arrayLayer: %u, mipLevel: %u) of image was cleared as part of LOAD_OP_CLEAR, but last time "
1433 "image was used, it was written to with vkCmdClear*Image(). "
1434 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1435 "tile-based architectures."
1436 "architectures.",
1437 VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
1438 } else if (usage == IMAGE_ATTACHMENT_USAGE::RENDER_PASS_READ_TO_TILE && last_usage == IMAGE_ATTACHMENT_USAGE::CLEARED) {
1439 VendorCheckEnabled(kBPVendorArm) &&
1440 LogPerformanceWarning(
1441 device, kVUID_BestPractices_RenderPass_InefficientClear,
1442 "%s Subresource (arrayLayer: %u, mipLevel: %u) of image was loaded to tile as part of LOAD_OP_LOAD, but last "
1443 "time image was used, it was written to with vkCmdClear*Image(). "
1444 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1445 "tile-based architectures. "
1446 "Use LOAD_OP_CLEAR instead to clear the image for free.",
1447 VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
1448 }
1449
1450 image->usages[array_layer][mip_level] = usage;
1451}
1452
1453void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1454 VkSubpassContents contents) {
1455 if (!pRenderPassBegin) {
1456 return;
1457 }
1458
1459 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1460 if (rp_state) {
1461 // Check load ops
1462 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1463 auto& attachment = rp_state->createInfo.pAttachments[att];
1464
1465 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
1466 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1467 continue;
1468 }
1469
1470 IMAGE_ATTACHMENT_USAGE usage = IMAGE_ATTACHMENT_USAGE::UNDEFINED;
1471
1472 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
1473 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
1474 usage = IMAGE_ATTACHMENT_USAGE::RENDER_PASS_READ_TO_TILE;
1475 }
1476
1477 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
1478 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
1479 usage = IMAGE_ATTACHMENT_USAGE::RENDER_PASS_CLEARED;
1480 }
1481
1482 if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
1483 usage = IMAGE_ATTACHMENT_USAGE::RESOURCE_READ;
1484 }
1485
1486 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001487 IMAGE_VIEW_STATE* image_view = nullptr;
1488
1489 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
1490 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1491 if (rpabi) {
1492 image_view = GetImageViewState(rpabi->pAttachments[att]);
1493 }
1494 } else {
1495 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1496 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001497
1498 ValidateImageView(image_view, usage);
1499 }
1500
1501 // Check store ops
1502 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1503 auto& attachment = rp_state->createInfo.pAttachments[att];
1504
1505 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1506 continue;
1507 }
1508
1509 IMAGE_ATTACHMENT_USAGE usage = IMAGE_ATTACHMENT_USAGE::RENDER_PASS_DISCARDED;
1510
1511 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
1512 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
1513 usage = IMAGE_ATTACHMENT_USAGE::RENDER_PASS_STORED;
1514 }
1515
1516 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001517
1518 IMAGE_VIEW_STATE* image_view = nullptr;
1519 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
1520 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1521 if (rpabi) {
1522 image_view = GetImageViewState(rpabi->pAttachments[att]);
1523 }
1524 } else {
1525 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1526 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001527
1528 ValidateImageView(image_view, usage);
1529 }
1530 }
1531}
1532
Attilio Provenzano02859b22020-02-27 14:17:28 +00001533bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1534 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001535 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1536 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001537 return skip;
1538}
1539
1540bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1541 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001542 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001543 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1544 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001545 return skip;
1546}
1547
1548bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001549 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001550 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1551 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001552 return skip;
1553}
1554
Sam Walls0961ec02020-03-31 16:39:15 +01001555void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1556 const VkRenderPassBeginInfo* pRenderPassBegin) {
1557 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1558
1559 // add the tracking state if it doesn't exist
1560 if (prepass_state == cbDepthPrePassStates.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001561 auto result = cbDepthPrePassStates.emplace(commandBuffer, DepthPrePassState{});
Sam Walls0961ec02020-03-31 16:39:15 +01001562
1563 if (!result.second) return;
1564
1565 prepass_state = result.first;
1566 }
1567
1568 // reset the renderpass state
1569 prepass_state->second = {};
1570
1571 const auto* cb_state = GetCBState(commandBuffer);
locke-lunargaecf2152020-05-12 17:15:41 -06001572 const auto* rp_state = cb_state->activeRenderPass.get();
Sam Walls0961ec02020-03-31 16:39:15 +01001573
1574 // track depth / color attachment usage within the renderpass
1575 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1576 // record if depth/color attachments are in use for this renderpass
1577 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) prepass_state->second.depthAttachment = true;
1578
1579 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) prepass_state->second.colorAttachment = true;
1580 }
1581}
1582
1583void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1584 VkSubpassContents contents) {
1585 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1586 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1587}
1588
1589void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1590 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1591 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1592 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1593}
1594
1595void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1596 const VkRenderPassBeginInfo* pRenderPassBegin,
1597 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1598 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1599 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1600}
1601
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001602// Generic function to handle validation for all CmdDraw* type functions
1603bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1604 bool skip = false;
1605 const CMD_BUFFER_STATE* cb_state = GetCBState(cmd_buffer);
1606 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001607 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1608 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001609 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001610
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001611 // Verify vertex binding
1612 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1613 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001614 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001615 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001616 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
1617 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001618 }
1619 }
1620 }
1621 return skip;
1622}
1623
Sam Walls0961ec02020-03-31 16:39:15 +01001624void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1625 if (VendorCheckEnabled(kBPVendorArm)) {
1626 RecordCmdDrawTypeArm(cmd_buffer, draw_count, caller);
1627 }
1628}
1629
1630void BestPractices::RecordCmdDrawTypeArm(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1631 auto prepass_state = cbDepthPrePassStates.find(cmd_buffer);
1632 if (prepass_state != cbDepthPrePassStates.end() && draw_count >= kDepthPrePassMinDrawCountArm) {
1633 if (prepass_state->second.depthOnly) prepass_state->second.numDrawCallsDepthOnly++;
1634
1635 if (prepass_state->second.depthEqualComparison) prepass_state->second.numDrawCallsDepthEqualCompare++;
1636 }
1637}
1638
Camden5b184be2019-08-13 07:50:19 -06001639bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001640 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001641 bool skip = false;
1642
1643 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001644 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1645 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001646 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001647 }
1648
1649 return skip;
1650}
1651
Sam Walls0961ec02020-03-31 16:39:15 +01001652void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1653 uint32_t firstVertex, uint32_t firstInstance) {
1654 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
1655 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
1656}
1657
Camden5b184be2019-08-13 07:50:19 -06001658bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001659 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001660 bool skip = false;
1661
1662 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001663 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1664 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001665 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001666 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1667
Attilio Provenzano02859b22020-02-27 14:17:28 +00001668 // Check if we reached the limit for small indexed draw calls.
1669 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1670 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1671 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
1672 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1)) {
1673 skip |= VendorCheckEnabled(kBPVendorArm) &&
1674 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06001675 "%s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00001676 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1677 "You can try batching drawcalls or instancing when applicable.",
1678 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1679 }
1680
Sam Walls8e77e4f2020-03-16 20:47:40 +00001681 if (VendorCheckEnabled(kBPVendorArm)) {
1682 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1683 }
1684
1685 return skip;
1686}
1687
1688bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1689 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1690 bool skip = false;
1691
1692 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1693 const auto* cmd_state = GetCBState(commandBuffer);
1694 if (cmd_state == nullptr) return skip;
1695
locke-lunarg1ae57d62020-11-18 10:49:19 -07001696 const auto* ib_state = cmd_state->index_buffer_binding.buffer_state.get();
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06001697 if (ib_state == nullptr || cmd_state->index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001698
1699 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
1700 const auto& ib_mem_state = *ib_state->binding.mem_state;
1701 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1702 const void* ib_mem = ib_mem_state.p_driver_data;
1703 bool primitive_restart_enable = false;
1704
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001705 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1706 const auto& pipeline_binding_iter = cmd_state->lastBound[lv_bind_point];
1707 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001708
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001709 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001710 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001711 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00001712
1713 // 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 -06001714 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00001715 uint32_t scan_stride;
1716 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1717 scan_stride = sizeof(uint8_t);
1718 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1719 scan_stride = sizeof(uint16_t);
1720 } else {
1721 scan_stride = sizeof(uint32_t);
1722 }
1723
1724 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1725 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1726
1727 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1728 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1729 // irrespective of whether or not they're part of the draw call.
1730
1731 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1732 uint32_t min_index = ~0u;
1733 // start with maximum as 0 and adjust to indices in the buffer
1734 uint32_t max_index = 0u;
1735
1736 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
1737 // for the given index buffer
1738 uint32_t vertex_shade_count = 0;
1739
1740 PostTransformLRUCacheModel post_transform_cache;
1741
1742 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
1743 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
1744 // target architecture.
1745 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
1746 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
1747 post_transform_cache.resize(32);
1748
1749 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1750 uint32_t scan_index;
1751 uint32_t primitive_restart_value;
1752 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1753 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1754 primitive_restart_value = 0xFF;
1755 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1756 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1757 primitive_restart_value = 0xFFFF;
1758 } else {
1759 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1760 primitive_restart_value = 0xFFFFFFFF;
1761 }
1762
1763 max_index = std::max(max_index, scan_index);
1764 min_index = std::min(min_index, scan_index);
1765
1766 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
1767 bool in_cache = post_transform_cache.query_cache(scan_index);
1768 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
1769 if (!in_cache) vertex_shade_count++;
1770 }
1771 }
1772
1773 // 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 +01001774 // 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
1775 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001776
1777 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07001778 skip |=
1779 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1780 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
1781 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
1782 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
1783 "maximum would be loaded, and possibly shaded, whether or not they are used.",
1784 VendorSpecificTag(kBPVendorArm),
1785 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001786 return skip;
1787 }
1788
1789 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
1790 // 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 +01001791 const size_t refs_per_bucket = 64;
1792 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
1793
1794 const uint32_t n_indices = max_index - min_index + 1;
1795 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
1796 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
1797
1798 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
1799 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00001800
1801 // To avoid using too much memory, we run over the indices again.
1802 // Knowing the size from the last scan allows us to record index usage with bitsets
1803 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1804 uint32_t scan_index;
1805 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1806 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1807 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1808 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1809 } else {
1810 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1811 }
1812 // keep track of the set of all indices used to reference vertices in the draw call
1813 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01001814 size_t bitset_bucket_index = index_offset / refs_per_bucket;
1815 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001816 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
1817 }
1818
1819 uint32_t vertex_reference_count = 0;
1820 for (const auto& bitset : vertex_reference_buckets) {
1821 vertex_reference_count += static_cast<uint32_t>(bitset.count());
1822 }
1823
1824 // 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 -07001825 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001826 // 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 -07001827 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001828
1829 if (utilization < 0.5f) {
1830 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1831 "%s The indices which were specified for the draw call only utilise approximately "
1832 "%.02f%% of the bound vertex buffer.",
1833 VendorSpecificTag(kBPVendorArm), utilization);
1834 }
1835
1836 if (cache_hit_rate <= 0.5f) {
1837 skip |=
1838 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
1839 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
1840 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
1841 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
1842 "recently shaded vertices.",
1843 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
1844 }
1845 }
1846
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001847 return skip;
1848}
1849
Attilio Provenzano02859b22020-02-27 14:17:28 +00001850void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1851 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1852 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
1853 firstInstance);
1854
1855 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1856 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
1857 cmd_state->small_indexed_draw_call_count++;
1858 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001859
1860 ValidateBoundDescriptorSets(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001861}
1862
Sam Walls0961ec02020-03-31 16:39:15 +01001863void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1864 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1865 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1866 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
1867}
1868
sfricke-samsung681ab7b2020-10-29 01:53:35 -07001869bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1870 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
1871 uint32_t maxDrawCount, uint32_t stride) const {
1872 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
1873
1874 return skip;
1875}
1876
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001877bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
1878 VkDeviceSize offset, VkBuffer countBuffer,
1879 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
1880 uint32_t stride) const {
1881 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06001882
1883 return skip;
1884}
1885
1886bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001887 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001888 bool skip = false;
1889
1890 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001891 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1892 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001893 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001894 }
1895
1896 return skip;
1897}
1898
Sam Walls0961ec02020-03-31 16:39:15 +01001899void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1900 uint32_t count, uint32_t stride) {
1901 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
1902 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
1903}
1904
Camden5b184be2019-08-13 07:50:19 -06001905bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001906 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001907 bool skip = false;
1908
1909 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001910 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1911 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001912 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001913 }
1914
1915 return skip;
1916}
1917
Sam Walls0961ec02020-03-31 16:39:15 +01001918void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1919 uint32_t count, uint32_t stride) {
1920 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
1921 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
1922}
1923
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001924void BestPractices::ValidateBoundDescriptorSets(VkCommandBuffer commandBuffer) {
1925 const CMD_BUFFER_STATE* cb_state = GetCBState(commandBuffer);
1926
1927 if (cb_state) {
1928 for (auto descriptor_set : cb_state->validated_descriptor_sets) {
1929 for (uint32_t binding = 0; binding < descriptor_set->GetBindingCount(); ++binding) {
1930 auto index_range = descriptor_set->GetGlobalIndexRangeFromBinding(binding);
1931 for (uint32_t i = index_range.start; i < index_range.end; ++i) {
ZandroFargnoliacf12f02020-06-18 16:50:00 +01001932 VkImageView image_view{VK_NULL_HANDLE};
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001933
1934 auto descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
1935 switch (descriptor->GetClass()) {
1936 case cvdescriptorset::DescriptorClass::Image: {
1937 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
1938 image_view = image_descriptor->GetImageView();
1939 }
1940 }
1941 case cvdescriptorset::DescriptorClass::ImageSampler: {
1942 if (const auto image_sampler_descriptor =
1943 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
1944 image_view = image_sampler_descriptor->GetImageView();
1945 }
1946 }
ZandroFargnoliacf12f02020-06-18 16:50:00 +01001947 default:
1948 continue;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001949 }
1950
1951 if (image_view) {
1952 IMAGE_VIEW_STATE* image_view_state = GetImageViewState(image_view);
1953
1954 if (descriptor_set->GetTypeFromIndex(i) == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) {
1955 ValidateImageView(image_view_state, IMAGE_ATTACHMENT_USAGE::RESOURCE_READ);
1956 }
1957
1958 if (descriptor_set->GetTypeFromIndex(i) == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) {
1959 ValidateImageView(image_view_state, IMAGE_ATTACHMENT_USAGE::RESOURCE_WRITE);
1960 }
1961 }
1962 }
1963 }
1964 }
1965 }
1966}
1967
1968void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1969 uint32_t firstVertex, uint32_t firstInstance) {
1970 ValidateBoundDescriptorSets(commandBuffer);
1971}
1972
1973void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1974 uint32_t drawCount, uint32_t stride) {
1975 ValidateBoundDescriptorSets(commandBuffer);
1976}
1977
1978void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1979 uint32_t drawCount, uint32_t stride) {
1980 ValidateBoundDescriptorSets(commandBuffer);
1981}
1982
Camden5b184be2019-08-13 07:50:19 -06001983bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001984 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06001985 bool skip = false;
1986
1987 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001988 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
1989 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
1990 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
1991 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06001992 }
1993
1994 return skip;
1995}
Camden83a9c372019-08-14 11:41:38 -06001996
Sam Walls0961ec02020-03-31 16:39:15 +01001997bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
1998 bool skip = false;
1999
2000 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
2001
2002 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
2003
2004 if (prepass_state == cbDepthPrePassStates.end()) return skip;
2005
2006 bool uses_depth = (prepass_state->second.depthAttachment || prepass_state->second.colorAttachment) &&
2007 prepass_state->second.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2008 prepass_state->second.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
2009 if (uses_depth) {
2010 skip |= LogPerformanceWarning(
2011 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
2012 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
2013 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
2014 "case, using depth pre-passes for hidden surface removal may worsen performance.",
2015 VendorSpecificTag(kBPVendorArm));
2016 }
2017
2018 return skip;
2019}
2020
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002021void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
2022 ValidateBoundDescriptorSets(commandBuffer);
2023}
2024
2025void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
2026 ValidateBoundDescriptorSets(commandBuffer);
2027}
2028
Camden Stocker9c051442019-11-06 14:28:43 -08002029bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2030 const char* api_name) const {
2031 bool skip = false;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002032 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002033
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002034 if (bp_pd_state) {
2035 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2036 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2037 "Potential problem with calling %s() without first retrieving properties from "
2038 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2039 api_name);
2040 }
Camden Stocker9c051442019-11-06 14:28:43 -08002041 }
2042
2043 return skip;
2044}
2045
Camden83a9c372019-08-14 11:41:38 -06002046bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002047 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002048 bool skip = false;
2049
Camden Stocker9c051442019-11-06 14:28:43 -08002050 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002051
Camden Stocker9c051442019-11-06 14:28:43 -08002052 return skip;
2053}
2054
2055bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2056 uint32_t planeIndex,
2057 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2058 bool skip = false;
2059
2060 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2061
2062 return skip;
2063}
2064
2065bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2066 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2067 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2068 bool skip = false;
2069
2070 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002071
2072 return skip;
2073}
Camden05de2d42019-08-19 10:23:56 -06002074
2075bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002076 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002077 bool skip = false;
2078
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002079 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
Camden05de2d42019-08-19 10:23:56 -06002080
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002081 if ((swapchain_state_itr != swapchain_bp_state_map.cend()) && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002082 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002083 if (swapchain_state_itr->second.vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002084 skip |=
2085 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2086 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2087 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002088 }
2089 }
2090
2091 return skip;
2092}
2093
2094// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002095bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
2096 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002097 const CALL_STATE call_state,
2098 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002099 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002100 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2101 if (UNCALLED == call_state) {
2102 skip |= LogWarning(
2103 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
2104 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2105 "recommended "
2106 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2107 caller_name, caller_name);
2108 // Then verify that pCount that is passed in on second call matches what was returned
2109 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
2110 skip |= LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
2111 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2112 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2113 ". It is recommended to instead receive all the properties by calling %s with "
2114 "pQueueFamilyPropertyCount that was "
2115 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
2116 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
2117 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002118 }
2119
2120 return skip;
2121}
2122
Jeff Bolz5c801d12019-10-09 10:38:45 -05002123bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2124 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002125 bool skip = false;
2126
2127 for (uint32_t i = 0; i < bindInfoCount; i++) {
sourav parmarcd5fb182020-07-17 12:58:44 -07002128 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureStateNV(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002129 if (!as_state->memory_requirements_checked) {
2130 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2131 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2132 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002133 skip |= LogWarning(
2134 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002135 "vkBindAccelerationStructureMemoryNV(): "
2136 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
2137 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
2138 }
2139 }
2140
2141 return skip;
2142}
2143
Camden05de2d42019-08-19 10:23:56 -06002144bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2145 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002146 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002147 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2148 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002149 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2150 if (pQueueFamilyProperties && bp_pd_state) {
2151 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2152 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2153 "vkGetPhysicalDeviceQueueFamilyProperties()");
2154 }
2155 return false;
Camden05de2d42019-08-19 10:23:56 -06002156}
2157
Mike Schuchardt2df08912020-12-15 16:28:09 -08002158bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2159 uint32_t* pQueueFamilyPropertyCount,
2160 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002161 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2162 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002163 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2164 if (pQueueFamilyProperties && bp_pd_state) {
2165 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2166 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2167 "vkGetPhysicalDeviceQueueFamilyProperties2()");
2168 }
2169 return false;
Camden05de2d42019-08-19 10:23:56 -06002170}
2171
Jeff Bolz5c801d12019-10-09 10:38:45 -05002172bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08002173 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002174 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2175 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002176 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2177 if (pQueueFamilyProperties && bp_pd_state) {
2178 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2179 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2180 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
2181 }
2182 return false;
Camden05de2d42019-08-19 10:23:56 -06002183}
2184
2185bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2186 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002187 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06002188 if (!pSurfaceFormats) return false;
2189 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002190 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2191 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06002192 bool skip = false;
2193 if (call_state == UNCALLED) {
2194 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
2195 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002196 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
2197 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
2198 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06002199 } else {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002200 auto prev_format_count = static_cast<uint32_t>(physical_device_state->surface_formats.size());
Peter Chene191bd72019-09-16 13:04:37 -04002201 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002202 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
2203 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
2204 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
2205 "when pSurfaceFormatCount was NULL.",
2206 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06002207 }
2208 }
2209 return skip;
2210}
Camden Stocker23cc47d2019-09-03 14:53:57 -06002211
2212bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002213 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002214 bool skip = false;
2215
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002216 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2217 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002218 // 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 -07002219 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002220 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
2221 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002222 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06002223 // 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 -07002224 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
2225 const auto& image_bind = bind_info.pImageBinds[i];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002226 auto image_state = GetImageState(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002227 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002228 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002229 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002230 sparse_images.insert(image_state);
2231 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2232 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2233 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002234 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002235 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2236 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002237 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002238 }
2239 }
2240 if (!image_state->memory_requirements_checked) {
2241 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002242 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002243 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2244 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002245 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002246 }
2247 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002248 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2249 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
2250 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
2251 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002252 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002253 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002254 sparse_images.insert(image_state);
2255 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2256 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2257 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002258 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002259 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2260 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002261 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002262 }
2263 }
2264 if (!image_state->memory_requirements_checked) {
2265 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002266 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002267 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2268 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002269 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002270 }
2271 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2272 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002273 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06002274 }
2275 }
2276 }
2277 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002278 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
2279 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002280 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002281 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002282 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
2283 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002284 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002285 }
2286 }
2287 }
2288
2289 return skip;
2290}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002291
Mark Lobodzinski84101d72020-04-24 09:43:48 -06002292void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
2293 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002294 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002295 return;
2296 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002297
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002298 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2299 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
2300 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2301 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
2302 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
2303 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002304 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002305 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002306 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2307 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
2308 image_state->sparse_metadata_bound = true;
2309 }
2310 }
2311 }
2312 }
2313}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002314
2315bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06002316 const VkClearAttachment* pAttachments, uint32_t rectCount,
2317 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002318 bool skip = false;
2319 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
2320 if (!cb_node) return skip;
2321
Camden Stockerf55721f2019-09-09 11:04:49 -06002322 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002323 if (!cb_node->hasDrawCmd && (cb_node->activeRenderPassBeginInfo.renderArea.extent.width == pRects[0].rect.extent.width) &&
2324 (cb_node->activeRenderPassBeginInfo.renderArea.extent.height == pRects[0].rect.extent.height)) {
2325 // There are times where app needs to use ClearAttachments (generally when reusing a buffer inside of a render pass)
2326 // This warning should be made more specific. It'd be best to avoid triggering this test if it's a use that must call
2327 // CmdClearAttachments.
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07002328 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
2329 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds. It is recommended you "
2330 "use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
2331 report_data->FormatHandle(commandBuffer).c_str());
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002332 }
2333
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002334 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
2335 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06002336 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002337 if (rp) {
2338 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
2339
2340 for (uint32_t i = 0; i < attachmentCount; i++) {
2341 auto& attachment = pAttachments[i];
2342 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
2343 uint32_t color_attachment = attachment.colorAttachment;
2344 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
2345
2346 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2347 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2348 skip |= LogPerformanceWarning(
2349 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2350 "vkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
2351 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2352 "it is more efficient.",
2353 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
2354 }
2355 }
2356 }
2357
2358 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
2359 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2360
2361 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2362 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2363 skip |= LogPerformanceWarning(
2364 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2365 "vkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
2366 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2367 "it is more efficient.",
2368 report_data->FormatHandle(commandBuffer).c_str());
2369 }
2370 }
2371 }
2372
2373 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
2374 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2375
2376 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2377 if (rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2378 skip |= LogPerformanceWarning(
2379 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2380 "vkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
2381 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2382 "it is more efficient.",
2383 report_data->FormatHandle(commandBuffer).c_str());
2384 }
2385 }
2386 }
2387 }
2388 }
2389
Camden Stockerf55721f2019-09-09 11:04:49 -06002390 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002391}
Attilio Provenzano02859b22020-02-27 14:17:28 +00002392
2393bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2394 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2395 const VkImageResolve* pRegions) const {
2396 bool skip = false;
2397
2398 skip |= VendorCheckEnabled(kBPVendorArm) &&
2399 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
2400 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
2401 "This is a very slow and extremely bandwidth intensive path. "
2402 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2403 VendorSpecificTag(kBPVendorArm));
2404
2405 return skip;
2406}
2407
Jeff Leger178b1e52020-10-05 12:22:23 -04002408bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2409 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
2410 bool skip = false;
2411
2412 skip |= VendorCheckEnabled(kBPVendorArm) &&
2413 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
2414 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
2415 "This is a very slow and extremely bandwidth intensive path. "
2416 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2417 VendorSpecificTag(kBPVendorArm));
2418
2419 return skip;
2420}
2421
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002422void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2423 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2424 const VkImageResolve* pRegions) {
2425 auto* src = GetImageState(srcImage);
2426 auto* dst = GetImageState(dstImage);
2427
2428 for (uint32_t i = 0; i < regionCount; i++) {
2429 ValidateImage(src, IMAGE_ATTACHMENT_USAGE::RESOURCE_READ, pRegions[i].srcSubresource);
2430 ValidateImage(dst, IMAGE_ATTACHMENT_USAGE::RESOURCE_WRITE, pRegions[i].dstSubresource);
2431 }
2432}
2433
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01002434void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2435 const VkResolveImageInfo2KHR* pResolveImageInfo) {
2436 auto* src = GetImageState(pResolveImageInfo->srcImage);
2437 auto* dst = GetImageState(pResolveImageInfo->dstImage);
2438 uint32_t regionCount = pResolveImageInfo->regionCount;
2439
2440 for (uint32_t i = 0; i < regionCount; i++) {
2441 ValidateImage(src, IMAGE_ATTACHMENT_USAGE::RESOURCE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
2442 ValidateImage(dst, IMAGE_ATTACHMENT_USAGE::RESOURCE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
2443 }
2444}
2445
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002446void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
2447 const VkClearColorValue* pColor, uint32_t rangeCount,
2448 const VkImageSubresourceRange* pRanges) {
2449 auto* dst = GetImageState(image);
2450
2451 for (uint32_t i = 0; i < rangeCount; i++) {
2452 ValidateImage(dst, IMAGE_ATTACHMENT_USAGE::CLEARED, pRanges[i]);
2453 }
2454}
2455
2456void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
2457 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
2458 const VkImageSubresourceRange* pRanges) {
2459 auto* dst = GetImageState(image);
2460
2461 for (uint32_t i = 0; i < rangeCount; i++) {
2462 ValidateImage(dst, IMAGE_ATTACHMENT_USAGE::CLEARED, pRanges[i]);
2463 }
2464}
2465
2466void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2467 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2468 const VkImageCopy* pRegions) {
2469 auto* src = GetImageState(srcImage);
2470 auto* dst = GetImageState(dstImage);
2471
2472 for (uint32_t i = 0; i < regionCount; i++) {
2473 ValidateImage(src, IMAGE_ATTACHMENT_USAGE::RESOURCE_READ, pRegions[i].srcSubresource);
2474 ValidateImage(dst, IMAGE_ATTACHMENT_USAGE::RESOURCE_WRITE, pRegions[i].dstSubresource);
2475 }
2476}
2477
2478void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
2479 VkImageLayout dstImageLayout, uint32_t regionCount,
2480 const VkBufferImageCopy* pRegions) {
2481 auto* dst = GetImageState(dstImage);
2482
2483 for (uint32_t i = 0; i < regionCount; i++) {
2484 ValidateImage(dst, IMAGE_ATTACHMENT_USAGE::RESOURCE_WRITE, pRegions[i].imageSubresource);
2485 }
2486}
2487
2488void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2489 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
2490 auto* src = GetImageState(srcImage);
2491
2492 for (uint32_t i = 0; i < regionCount; i++) {
2493 ValidateImage(src, IMAGE_ATTACHMENT_USAGE::RESOURCE_READ, pRegions[i].imageSubresource);
2494 }
2495}
2496
2497void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2498 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2499 const VkImageBlit* pRegions, VkFilter filter) {
2500 auto* src = GetImageState(srcImage);
2501 auto* dst = GetImageState(dstImage);
2502
2503 for (uint32_t i = 0; i < regionCount; i++) {
2504 ValidateImage(src, IMAGE_ATTACHMENT_USAGE::RESOURCE_READ, pRegions[i].srcSubresource);
2505 ValidateImage(dst, IMAGE_ATTACHMENT_USAGE::RESOURCE_WRITE, pRegions[i].dstSubresource);
2506 }
2507}
2508
Attilio Provenzano02859b22020-02-27 14:17:28 +00002509bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
2510 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
2511 bool skip = false;
2512
2513 if (VendorCheckEnabled(kBPVendorArm)) {
2514 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
2515 skip |= LogPerformanceWarning(
2516 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
2517 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
2518 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
2519 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06002520 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002521 }
2522
2523 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
2524 skip |= LogPerformanceWarning(
2525 device, kVUID_BestPractices_CreateSampler_LodClamping,
2526 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
2527 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
2528 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
2529 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
2530 }
2531
2532 if (pCreateInfo->mipLodBias != 0.0f) {
2533 skip |=
2534 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
2535 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
2536 "descriptors being created and may cause reduced performance.",
2537 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
2538 }
2539
2540 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2541 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2542 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
2543 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
2544 skip |= LogPerformanceWarning(
2545 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
2546 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
2547 "This will lead to less efficient descriptors being created and may cause reduced performance. "
2548 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
2549 VendorSpecificTag(kBPVendorArm));
2550 }
2551
2552 if (pCreateInfo->unnormalizedCoordinates) {
2553 skip |= LogPerformanceWarning(
2554 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
2555 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
2556 "descriptors being created and may cause reduced performance.",
2557 VendorSpecificTag(kBPVendorArm));
2558 }
2559
2560 if (pCreateInfo->anisotropyEnable) {
2561 skip |= LogPerformanceWarning(
2562 device, kVUID_BestPractices_CreateSampler_Anisotropy,
2563 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
2564 "and may cause reduced performance.",
2565 VendorSpecificTag(kBPVendorArm));
2566 }
2567 }
2568
2569 return skip;
2570}
Sam Walls8e77e4f2020-03-16 20:47:40 +00002571
2572void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
2573
2574bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
2575 // look for a cache hit
2576 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
2577 if (hit != _entries.end()) {
2578 // mark the cache hit as being most recently used
2579 hit->age = iteration++;
2580 return true;
2581 }
2582
2583 // if there's no cache hit, we need to model the entry being inserted into the cache
2584 CacheEntry new_entry = {value, iteration};
2585 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
2586 // if there is still space left in the cache, use the next available slot
2587 *(_entries.begin() + iteration) = new_entry;
2588 } else {
2589 // otherwise replace the least recently used cache entry
2590 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
2591 *lru = new_entry;
2592 }
2593 iteration++;
2594 return false;
2595}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002596
2597bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
2598 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
2599 const auto swapchain_data = GetSwapchainState(swapchain);
2600 bool skip = false;
2601 if (swapchain_data && swapchain_data->images.size() == 0) {
2602 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
2603 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
2604 "vkGetSwapchainImagesKHR after swapchain creation.");
2605 }
2606 return skip;
2607}
2608
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002609void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
2610 if (no_pointer) {
2611 if (UNCALLED == call_state) {
2612 call_state = QUERY_COUNT;
2613 }
2614 } else { // Save queue family properties
2615 call_state = QUERY_DETAILS;
2616 }
2617}
2618
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002619void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2620 uint32_t* pQueueFamilyPropertyCount,
2621 VkQueueFamilyProperties* pQueueFamilyProperties) {
2622 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
2623 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002624 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002625 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002626 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2627 nullptr == pQueueFamilyProperties);
2628 }
2629}
2630
2631void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2632 uint32_t* pQueueFamilyPropertyCount,
2633 VkQueueFamilyProperties2* pQueueFamilyProperties) {
2634 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
2635 pQueueFamilyProperties);
2636 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2637 if (bp_pd_state) {
2638 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2639 nullptr == pQueueFamilyProperties);
2640 }
2641}
2642
2643void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
2644 uint32_t* pQueueFamilyPropertyCount,
2645 VkQueueFamilyProperties2* pQueueFamilyProperties) {
2646 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
2647 pQueueFamilyProperties);
2648 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2649 if (bp_pd_state) {
2650 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2651 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002652 }
2653}
2654
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002655void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
2656 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002657 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2658 if (bp_pd_state) {
2659 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2660 }
2661}
2662
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002663void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
2664 VkPhysicalDeviceFeatures2* pFeatures) {
2665 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002666 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2667 if (bp_pd_state) {
2668 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2669 }
2670}
2671
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002672void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
2673 VkPhysicalDeviceFeatures2* pFeatures) {
2674 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002675 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2676 if (bp_pd_state) {
2677 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2678 }
2679}
2680
2681void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
2682 VkSurfaceKHR surface,
2683 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
2684 VkResult result) {
2685 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2686 if (bp_pd_state) {
2687 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2688 }
2689}
2690
2691void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
2692 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2693 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
2694 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2695 if (bp_pd_state) {
2696 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2697 }
2698}
2699
2700void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
2701 VkSurfaceKHR surface,
2702 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
2703 VkResult result) {
2704 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2705 if (bp_pd_state) {
2706 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2707 }
2708}
2709
2710void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
2711 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
2712 VkPresentModeKHR* pPresentModes, VkResult result) {
2713 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2714 if (bp_pd_data) {
2715 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
2716
2717 if (*pPresentModeCount) {
2718 if (call_state < QUERY_COUNT) {
2719 call_state = QUERY_COUNT;
2720 }
2721 }
2722 if (pPresentModes) {
2723 if (call_state < QUERY_DETAILS) {
2724 call_state = QUERY_DETAILS;
2725 }
2726 }
2727 }
2728}
2729
2730void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2731 uint32_t* pSurfaceFormatCount,
2732 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
2733 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2734 if (bp_pd_data) {
2735 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
2736
2737 if (*pSurfaceFormatCount) {
2738 if (call_state < QUERY_COUNT) {
2739 call_state = QUERY_COUNT;
2740 }
2741 }
2742 if (pSurfaceFormats) {
2743 if (call_state < QUERY_DETAILS) {
2744 call_state = QUERY_DETAILS;
2745 }
2746 }
2747 }
2748}
2749
2750void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
2751 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2752 uint32_t* pSurfaceFormatCount,
2753 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
2754 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2755 if (bp_pd_data) {
2756 if (*pSurfaceFormatCount) {
2757 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
2758 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
2759 }
2760 }
2761 if (pSurfaceFormats) {
2762 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
2763 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
2764 }
2765 }
2766 }
2767}
2768
2769void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
2770 uint32_t* pPropertyCount,
2771 VkDisplayPlanePropertiesKHR* pProperties,
2772 VkResult result) {
2773 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2774 if (bp_pd_data) {
2775 if (*pPropertyCount) {
2776 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
2777 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
2778 }
2779 }
2780 if (pProperties) {
2781 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
2782 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
2783 }
2784 }
2785 }
2786}
2787
2788void BestPractices::ManualPostCallRecordCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
2789 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain,
2790 VkResult result) {
2791 if (VK_SUCCESS == result) {
2792 swapchain_bp_state_map.emplace(*pSwapchain, SWAPCHAIN_STATE_BP{});
2793 }
2794}
2795
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002796void BestPractices::PostCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain,
2797 const VkAllocationCallbacks* pAllocator) {
2798 ValidationStateTracker::PostCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002799 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2800 if (swapchain_state_itr != swapchain_bp_state_map.cend()) {
2801 swapchain_bp_state_map.erase(swapchain_state_itr);
2802 }
2803}
2804
2805void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
2806 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
2807 VkResult result) {
2808 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2809 assert(swapchain_state_itr != swapchain_bp_state_map.cend());
2810 auto& swapchain_state = swapchain_state_itr->second;
2811 if (pSwapchainImages || *pSwapchainImageCount) {
2812 if (swapchain_state.vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
2813 swapchain_state.vkGetSwapchainImagesKHRState = QUERY_DETAILS;
2814 }
2815 }
2816}
2817
2818void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
2819 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
2820 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
2821 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
2822 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
2823 }
2824 }
2825}
2826
2827void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo*, const VkAllocationCallbacks*,
2828 VkDevice*, VkResult result) {
2829 if (VK_SUCCESS == result) {
2830 instance_device_bp_state = &phys_device_bp_state_map[gpu];
2831 }
2832}
2833
2834PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
2835 if (phys_device_bp_state_map.count(phys_device) > 0) {
2836 return &phys_device_bp_state_map.at(phys_device);
2837 } else {
2838 return nullptr;
2839 }
2840}
2841
2842const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
2843 if (phys_device_bp_state_map.count(phys_device) > 0) {
2844 return &phys_device_bp_state_map.at(phys_device);
2845 } else {
2846 return nullptr;
2847 }
2848}
2849
2850PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
2851 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2852 if (bp_state) {
2853 return bp_state;
2854 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2855 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2856 } else {
2857 return nullptr;
2858 }
2859}
2860
2861const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
2862 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2863 if (bp_state) {
2864 return bp_state;
2865 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2866 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2867 } else {
2868 return nullptr;
2869 }
2870}