blob: dae7283525d5a26d3f71515df2466d4cedd1c360 [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"
Camden5b184be2019-08-13 07:50:19 -060024
25#include <string>
Sam Walls8e77e4f2020-03-16 20:47:40 +000026#include <bitset>
Sam Wallsd7ab6db2020-06-19 20:41:54 +010027#include <memory>
Camden5b184be2019-08-13 07:50:19 -060028
Attilio Provenzano19d6a982020-02-27 12:41:41 +000029struct VendorSpecificInfo {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060030 EnableFlags vendor_id;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000031 std::string name;
32};
33
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070034const std::map<BPVendorFlagBits, VendorSpecificInfo> kVendorInfo = {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060035 {kBPVendorArm, {vendor_specific_arm, "Arm"}},
Attilio Provenzano19d6a982020-02-27 12:41:41 +000036};
37
38bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070039 for (const auto& vendor : kVendorInfo) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060040 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000041 return true;
42 }
43 }
44 return false;
45}
46
47const char* VendorSpecificTag(BPVendorFlags vendors) {
48 // Cache built vendor tags in a map
49 static std::unordered_map<BPVendorFlags, std::string> tag_map;
50
51 auto res = tag_map.find(vendors);
52 if (res == tag_map.end()) {
53 // Build the vendor tag string
54 std::stringstream vendor_tag;
55
56 vendor_tag << "[";
57 bool first_vendor = true;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070058 for (const auto& vendor : kVendorInfo) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000059 if (vendors & vendor.first) {
60 if (!first_vendor) {
61 vendor_tag << ", ";
62 }
63 vendor_tag << vendor.second.name;
64 first_vendor = false;
65 }
66 }
67 vendor_tag << "]";
68
69 tag_map[vendors] = vendor_tag.str();
70 res = tag_map.find(vendors);
71 }
72
73 return res->second.c_str();
74}
75
Mark Lobodzinski6167e102020-02-24 17:03:55 -070076const char* DepReasonToString(ExtDeprecationReason reason) {
77 switch (reason) {
78 case kExtPromoted:
79 return "promoted to";
80 break;
81 case kExtObsoleted:
82 return "obsoleted by";
83 break;
84 case kExtDeprecated:
85 return "deprecated by";
86 break;
87 default:
88 return "";
89 break;
90 }
91}
92
93bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
94 const char* vuid) const {
95 bool skip = false;
96 auto dep_info_it = deprecated_extensions.find(extension_name);
97 if (dep_info_it != deprecated_extensions.end()) {
98 auto dep_info = dep_info_it->second;
Mark Lobodzinski6a149702020-05-14 12:21:34 -060099 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
100 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700101 skip |=
102 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
103 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600104 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700105 if (dep_info.target.length() == 0) {
106 skip |= LogWarning(instance, vuid,
107 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
108 "without replacement.",
109 api_name, extension_name);
110 } else {
111 skip |= LogWarning(instance, vuid,
112 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
113 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
114 }
115 }
116 }
117 return skip;
118}
119
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700120bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const char* vuid) const {
121 bool skip = false;
122 auto dep_info_it = special_use_extensions.find(extension_name);
123
124 if (dep_info_it != special_use_extensions.end()) {
125 auto special_uses = dep_info_it->second;
126 std::string message("is intended to support the following uses: ");
127 if (special_uses.find("cadsupport") != std::string::npos) {
128 message.append("specialized functionality used by CAD/CAM applications, ");
129 }
130 if (special_uses.find("d3demulation") != std::string::npos) {
131 message.append("D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D, ");
132 }
133 if (special_uses.find("devtools") != std::string::npos) {
134 message.append(" developer tools such as capture-replay libraries, ");
135 }
136 if (special_uses.find("debugging") != std::string::npos) {
137 message.append("use by applications when debugging, ");
138 }
139 if (special_uses.find("glemulation") != std::string::npos) {
140 message.append(
141 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
142 "specific to those APIs, ");
143 }
144 message.append("and it is strongly recommended that they be otherwise avoided");
145
146 skip |= LogWarning(instance, vuid, "%s(): Attempting to enable extension %s, but this extension %s.", api_name,
147 extension_name, message.c_str());
148 }
149 return skip;
150}
151
Camden5b184be2019-08-13 07:50:19 -0600152bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500153 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600154 bool skip = false;
155
156 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
157 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800158 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700159 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
160 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600161 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600162 uint32_t specified_version =
163 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
164 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700165 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Mark Lobodzinskia431b772020-11-10 08:12:13 -0700166 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i],
167 kVUID_BestPractices_CreateInstance_SpecialUseExtension);
Camden5b184be2019-08-13 07:50:19 -0600168 }
169
170 return skip;
171}
172
173void BestPractices::PreCallRecordCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
174 VkInstance* pInstance) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700175 ValidationStateTracker::PreCallRecordCreateInstance(pCreateInfo, pAllocator, pInstance);
Sam Walls53bf7652020-04-21 17:35:15 +0100176
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700177 if (pCreateInfo != nullptr && pCreateInfo->pApplicationInfo != nullptr) {
Sam Walls53bf7652020-04-21 17:35:15 +0100178 instance_api_version = pCreateInfo->pApplicationInfo->apiVersion;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700179 } else {
Sam Walls53bf7652020-04-21 17:35:15 +0100180 instance_api_version = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700181 }
Camden5b184be2019-08-13 07:50:19 -0600182}
183
184bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500185 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600186 bool skip = false;
187
188 // get API version of physical device passed when creating device.
189 VkPhysicalDeviceProperties physical_device_properties{};
190 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500191 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600192
193 // check api versions and warn if instance api Version is higher than version on device.
194 if (instance_api_version > device_api_version) {
Mark Lobodzinski60880782020-08-11 08:02:07 -0600195 std::string inst_api_name = StringAPIVersion(instance_api_version);
196 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600197
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700198 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
199 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
200 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600201 }
202
203 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
204 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800205 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700206 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
207 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600208 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700209 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], instance_api_version,
210 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Mark Lobodzinskia431b772020-11-10 08:12:13 -0700211 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i],
212 kVUID_BestPractices_CreateDevice_SpecialUseExtension);
Camden5b184be2019-08-13 07:50:19 -0600213 }
214
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600215 const auto bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
216 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700217 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
218 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600219 }
220
Szilard Papp7d2c7952020-06-22 14:38:13 +0100221 if ((VendorCheckEnabled(kBPVendorArm)) && (pCreateInfo->pEnabledFeatures != nullptr) &&
222 (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
223 skip |= LogPerformanceWarning(
224 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
225 "%s vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
226 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
227 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
228 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
229 VendorSpecificTag(kBPVendorArm));
230 }
231
Camden5b184be2019-08-13 07:50:19 -0600232 return skip;
233}
234
235bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500236 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600237 bool skip = false;
238
239 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700240 std::stringstream buffer_hex;
241 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600242
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700243 skip |= LogWarning(
244 device, kVUID_BestPractices_SharingModeExclusive,
245 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
246 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700247 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600248 }
249
250 return skip;
251}
252
253bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500254 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600255 bool skip = false;
256
257 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700258 std::stringstream image_hex;
259 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600260
261 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700262 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
263 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
264 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700265 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600266 }
267
Attilio Provenzano02859b22020-02-27 14:17:28 +0000268 if (VendorCheckEnabled(kBPVendorArm)) {
269 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
270 skip |= LogPerformanceWarning(
271 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
272 "%s vkCreateImage(): Trying to create an image with %u samples. "
273 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
274 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
275 }
276
277 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
278 skip |= LogPerformanceWarning(
279 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
280 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
281 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
282 "and do not need to be backed by physical storage. "
283 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
284 VendorSpecificTag(kBPVendorArm));
285 }
286 }
287
Camden5b184be2019-08-13 07:50:19 -0600288 return skip;
289}
290
291bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500292 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600293 bool skip = false;
294
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600295 const auto* bp_pd_state = GetPhysicalDeviceStateBP();
296 if (bp_pd_state) {
297 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
298 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
299 "vkCreateSwapchainKHR() called before getting surface capabilities from "
300 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
301 }
Camden83a9c372019-08-14 11:41:38 -0600302
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600303 if (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS) {
304 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
305 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
306 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
307 }
Camden83a9c372019-08-14 11:41:38 -0600308
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600309 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
310 skip |= LogWarning(
311 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
312 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
313 }
Camden83a9c372019-08-14 11:41:38 -0600314 }
315
Camden5b184be2019-08-13 07:50:19 -0600316 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700317 skip |=
318 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600319 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700320 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
321 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600322 }
323
Szilard Papp48a6da32020-06-10 14:41:59 +0100324 if (pCreateInfo->minImageCount == 2) {
325 skip |= LogPerformanceWarning(
326 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
327 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
328 ", which means double buffering is going "
329 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
330 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
331 "3 to use triple buffering to maximize performance in such cases.",
332 pCreateInfo->minImageCount);
333 }
334
Szilard Pappd5f0f812020-06-22 09:01:29 +0100335 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
336 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
337 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
338 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
339 "Presentation modes which are not FIFO will present the latest available frame and discard other "
340 "frame(s) if any.",
341 VendorSpecificTag(kBPVendorArm));
342 }
343
Camden5b184be2019-08-13 07:50:19 -0600344 return skip;
345}
346
347bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
348 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500349 const VkAllocationCallbacks* pAllocator,
350 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600351 bool skip = false;
352
353 for (uint32_t i = 0; i < swapchainCount; i++) {
354 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700355 skip |= LogWarning(
356 device, kVUID_BestPractices_SharingModeExclusive,
357 "Warning: A shared swapchain (index %" PRIu32
358 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
359 "queues (queueFamilyIndexCount of %" PRIu32 ").",
360 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600361 }
362 }
363
364 return skip;
365}
366
367bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500368 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600369 bool skip = false;
370
371 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
372 VkFormat format = pCreateInfo->pAttachments[i].format;
373 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
374 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
375 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700376 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
377 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
378 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
379 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
380 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600381 }
382 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700383 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
384 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
385 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
386 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
387 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600388 }
389 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000390
391 const auto& attachment = pCreateInfo->pAttachments[i];
392 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
393 bool access_requires_memory =
394 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
395
396 if (FormatHasStencil(format)) {
397 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
398 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
399 }
400
401 if (access_requires_memory) {
402 skip |= LogPerformanceWarning(
403 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
404 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
405 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
406 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
407 i, static_cast<uint32_t>(attachment.samples));
408 }
409 }
Camden5b184be2019-08-13 07:50:19 -0600410 }
411
412 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
413 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
414 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
415 }
416
417 return skip;
418}
419
Tony-LunarG767180f2020-04-23 14:03:59 -0600420bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
421 const VkImageView* image_views) const {
422 bool skip = false;
423
424 // Check for non-transient attachments that should be transient and vice versa
425 for (uint32_t i = 0; i < attachmentCount; ++i) {
426 auto& attachment = rpci->pAttachments[i];
427 bool attachment_should_be_transient =
428 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
429
430 if (FormatHasStencil(attachment.format)) {
431 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
432 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
433 }
434
435 auto view_state = GetImageViewState(image_views[i]);
436 if (view_state) {
437 auto& ivci = view_state->create_info;
438 auto& ici = GetImageState(ivci.image)->createInfo;
439
440 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
441
442 // The check for an image that should not be transient applies to all GPUs
443 if (!attachment_should_be_transient && image_is_transient) {
444 skip |= LogPerformanceWarning(
445 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
446 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
447 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
448 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
449 i);
450 }
451
452 bool supports_lazy = false;
453 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
454 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
455 supports_lazy = true;
456 }
457 }
458
459 // The check for an image that should be transient only applies to GPUs supporting
460 // lazily allocated memory
461 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
462 skip |= LogPerformanceWarning(
463 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
464 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
465 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
466 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
467 i);
468 }
469 }
470 }
471 return skip;
472}
473
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000474bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
475 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
476 bool skip = false;
477
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000478 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800479 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600480 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000481 }
482
483 return skip;
484}
485
Sam Wallse746d522020-03-16 21:20:23 +0000486bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
487 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
488 bool skip = false;
489 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
490
491 if (!skip) {
492 const auto& pool_handle = pAllocateInfo->descriptorPool;
493 auto iter = descriptor_pool_freed_count.find(pool_handle);
494 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
495 // this warning is specific to Arm
496 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
497 skip |= LogPerformanceWarning(
498 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
499 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
500 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
501 VendorSpecificTag(kBPVendorArm));
502 }
503 }
504
505 return skip;
506}
507
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600508void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
509 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000510 if (result == VK_SUCCESS) {
511 // find the free count for the pool we allocated into
512 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
513 if (iter != descriptor_pool_freed_count.end()) {
514 // we record successful allocations by subtracting the allocation count from the last recorded free count
515 const auto alloc_count = pAllocateInfo->descriptorSetCount;
516 // clamp the unsigned subtraction to the range [0, last_free_count]
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700517 if (iter->second > alloc_count) {
Sam Wallse746d522020-03-16 21:20:23 +0000518 iter->second -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700519 } else {
Sam Wallse746d522020-03-16 21:20:23 +0000520 iter->second = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700521 }
Sam Wallse746d522020-03-16 21:20:23 +0000522 }
523 }
524}
525
526void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
527 const VkDescriptorSet* pDescriptorSets, VkResult result) {
528 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
529 if (result == VK_SUCCESS) {
530 // we want to track frees because we're interested in suggesting re-use
531 auto iter = descriptor_pool_freed_count.find(descriptorPool);
532 if (iter == descriptor_pool_freed_count.end()) {
533 descriptor_pool_freed_count.insert(std::make_pair(descriptorPool, descriptorSetCount));
534 } else {
535 iter->second += descriptorSetCount;
536 }
537 }
538}
539
Camden5b184be2019-08-13 07:50:19 -0600540bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500541 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600542 bool skip = false;
543
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500544 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700545 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
546 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600547 }
548
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000549 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
550 skip |= LogPerformanceWarning(
551 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
552 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %llu. This is a very small allocation (current "
553 "threshold is %llu bytes). "
554 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
555 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
556 }
557
Camden83a9c372019-08-14 11:41:38 -0600558 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
559
560 return skip;
561}
562
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600563void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
564 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
565 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700566 if (result != VK_SUCCESS) {
567 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
568 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800569 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700570 static std::vector<VkResult> success_codes = {};
571 ValidateReturnCodes("vkReleaseFullScreenExclusiveModeEXT", result, error_codes, success_codes);
572 return;
573 }
574 num_mem_objects++;
575}
Camden Stocker9738af92019-10-16 13:54:03 -0700576
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600577void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
578 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700579 auto error = std::find(error_codes.begin(), error_codes.end(), result);
580 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000581 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
582 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
583
584 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
585 if (common_failure != common_failure_codes.end()) {
586 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
587 } else {
588 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
589 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700590 return;
591 }
592 auto success = std::find(success_codes.begin(), success_codes.end(), result);
593 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600594 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
595 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500596 }
597}
598
Jeff Bolz5c801d12019-10-09 10:38:45 -0500599bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
600 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700601 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600602 bool skip = false;
603
Camden Stocker9738af92019-10-16 13:54:03 -0700604 const DEVICE_MEMORY_STATE* mem_info = ValidationStateTracker::GetDevMemState(memory);
Camden83a9c372019-08-14 11:41:38 -0600605
606 for (auto& obj : mem_info->obj_bindings) {
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600607 LogObjectList objlist(device);
608 objlist.add(obj);
609 objlist.add(mem_info->mem);
610 skip |= LogWarning(objlist, layer_name.c_str(), "VK Object %s still has a reference to mem obj %s.",
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700611 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem).c_str());
Camden83a9c372019-08-14 11:41:38 -0600612 }
613
Camden5b184be2019-08-13 07:50:19 -0600614 return skip;
615}
616
617void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700618 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600619 if (memory != VK_NULL_HANDLE) {
620 num_mem_objects--;
621 }
622}
623
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000624bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600625 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500626 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600627
sfricke-samsunge2441192019-11-06 14:07:57 -0800628 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700629 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
630 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
631 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600632 }
633
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000634 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
635
636 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
637 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
638 skip |= LogPerformanceWarning(
639 device, kVUID_BestPractices_SmallDedicatedAllocation,
640 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
641 "The required size of the allocation is %llu, but smaller buffers like this should be sub-allocated from "
642 "larger memory blocks. (Current threshold is %llu bytes.)",
643 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
644 }
645
Camden Stockerb603cc82019-09-03 10:09:02 -0600646 return skip;
647}
648
649bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500650 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600651 bool skip = false;
652 const char* api_name = "BindBufferMemory()";
653
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000654 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600655
656 return skip;
657}
658
659bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500660 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600661 char api_name[64];
662 bool skip = false;
663
664 for (uint32_t i = 0; i < bindInfoCount; i++) {
665 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000666 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600667 }
668
669 return skip;
670}
Camden Stockerb603cc82019-09-03 10:09:02 -0600671
672bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500673 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600674 char api_name[64];
675 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600676
Camden Stocker8b798ab2019-09-03 10:33:28 -0600677 for (uint32_t i = 0; i < bindInfoCount; i++) {
678 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000679 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600680 }
681
682 return skip;
683}
684
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000685bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600686 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500687 const IMAGE_STATE* image_state = GetImageState(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600688
sfricke-samsung71bc6572020-04-29 15:49:43 -0700689 if (image_state->disjoint == false) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700690 if (!image_state->memory_requirements_checked && !image_state->external_memory_handle) {
691 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
692 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
693 api_name, report_data->FormatHandle(image).c_str());
694 }
695 } else {
696 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
697 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600698 }
699
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000700 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
701
702 if (mem_state->alloc_info.allocationSize == image_state->requirements.size &&
703 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
704 skip |= LogPerformanceWarning(
705 device, kVUID_BestPractices_SmallDedicatedAllocation,
706 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
707 "The required size of the allocation is %llu, but smaller images like this should be sub-allocated from "
708 "larger memory blocks. (Current threshold is %llu bytes.)",
709 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
710 }
711
712 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
713 // make sure this type is actually used.
714 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
715 // (i.e.most tile - based renderers)
716 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
717 bool supports_lazy = false;
718 uint32_t suggested_type = 0;
719
720 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
721 if ((1u << i) & image_state->requirements.memoryTypeBits) {
722 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
723 supports_lazy = true;
724 suggested_type = i;
725 break;
726 }
727 }
728 }
729
730 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
731
732 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
733 skip |= LogPerformanceWarning(
734 device, kVUID_BestPractices_NonLazyTransientImage,
735 "%s: Attempting to bind memory type % u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
736 "but this memory type is not LAZILY_ALLOCATED_BIT. You should use memory type %u here instead to save "
737 "%llu bytes of physical memory.",
738 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements.size);
739 }
740 }
741
Camden Stocker8b798ab2019-09-03 10:33:28 -0600742 return skip;
743}
744
745bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500746 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600747 bool skip = false;
748 const char* api_name = "vkBindImageMemory()";
749
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000750 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600751
752 return skip;
753}
754
755bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500756 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600757 char api_name[64];
758 bool skip = false;
759
760 for (uint32_t i = 0; i < bindInfoCount; i++) {
761 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700762 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600763 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
764 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600765 }
766
767 return skip;
768}
769
770bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500771 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600772 char api_name[64];
773 bool skip = false;
774
775 for (uint32_t i = 0; i < bindInfoCount; i++) {
776 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000777 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600778 }
779
780 return skip;
781}
Camden83a9c372019-08-14 11:41:38 -0600782
Attilio Provenzano02859b22020-02-27 14:17:28 +0000783static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
784 switch (format) {
785 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
786 case VK_FORMAT_R16_SFLOAT:
787 case VK_FORMAT_R16G16_SFLOAT:
788 case VK_FORMAT_R16G16B16_SFLOAT:
789 case VK_FORMAT_R16G16B16A16_SFLOAT:
790 case VK_FORMAT_R32_SFLOAT:
791 case VK_FORMAT_R32G32_SFLOAT:
792 case VK_FORMAT_R32G32B32_SFLOAT:
793 case VK_FORMAT_R32G32B32A32_SFLOAT:
794 return false;
795
796 default:
797 return true;
798 }
799}
800
801bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
802 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
803 bool skip = false;
804
805 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700806 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000807
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700808 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
809 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
810 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000811 return skip;
812 }
813
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700814 auto rp_state = GetRenderPassState(create_info->renderPass);
815 auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000816
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700817 for (uint32_t j = 0; j < create_info->pColorBlendState->attachmentCount; j++) {
818 auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000819 uint32_t att = subpass.pColorAttachments[j].attachment;
820
821 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
822 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
823 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
824 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
825 "color attachment #%u makes use "
826 "of a format which cannot be blended at full throughput when using MSAA.",
827 VendorSpecificTag(kBPVendorArm), i, j);
828 }
829 }
830 }
831 }
832
833 return skip;
834}
835
Camden5b184be2019-08-13 07:50:19 -0600836bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
837 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600838 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500839 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600840 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
841 pAllocator, pPipelines, cgpl_state_data);
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600842 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600843
844 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700845 skip |= LogPerformanceWarning(
846 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
847 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
848 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600849 }
850
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000851 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700852 auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000853
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600854 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700855 auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600856 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700857 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
858 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600859 count++;
860 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000861 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600862 if (count > kMaxInstancedVertexBuffers) {
863 skip |= LogPerformanceWarning(
864 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
865 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
866 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
867 count, kMaxInstancedVertexBuffers);
868 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000869 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000870
Szilard Pappaaf2da32020-06-22 10:37:35 +0100871 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
872 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
873 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f)) {
874 skip |= VendorCheckEnabled(kBPVendorArm) &&
875 LogPerformanceWarning(
876 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
877 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
878 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
879 "efficiency during rasterization. Consider disabling depthBias or increasing either "
880 "depthBiasConstantFactor or depthBiasSlopeFactor.",
881 VendorSpecificTag(kBPVendorArm));
882 }
883
Attilio Provenzano02859b22020-02-27 14:17:28 +0000884 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000885 }
886
Camden5b184be2019-08-13 07:50:19 -0600887 return skip;
888}
889
Sam Walls0961ec02020-03-31 16:39:15 +0100890void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
891 const VkGraphicsPipelineCreateInfo* pCreateInfos,
892 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
893 VkResult result, void* cgpl_state_data) {
894 for (size_t i = 0; i < count; i++) {
895 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
896 const VkPipeline pipeline_handle = pPipelines[i];
897
898 // record depth stencil state and color blend states for depth pre-pass tracking purposes
899 auto gp_cis = graphicsPipelineCIs.find(pipeline_handle);
900
901 // add the tracking state if it doesn't exist
902 if (gp_cis == graphicsPipelineCIs.end()) {
903 auto result = graphicsPipelineCIs.emplace(std::make_pair(pipeline_handle, GraphicsPipelineCIs{}));
904
905 if (!result.second) continue;
906
907 gp_cis = result.first;
908 }
909
Tony-LunarG412b1b72020-07-15 10:30:13 -0600910 gp_cis->second.colorBlendStateCI =
911 cgpl_state->pCreateInfos[i].pColorBlendState
912 ? new safe_VkPipelineColorBlendStateCreateInfo(cgpl_state->pCreateInfos[i].pColorBlendState)
913 : nullptr;
914 gp_cis->second.depthStencilStateCI =
915 cgpl_state->pCreateInfos[i].pDepthStencilState
916 ? new safe_VkPipelineDepthStencilStateCreateInfo(cgpl_state->pCreateInfos[i].pDepthStencilState)
917 : nullptr;
Sam Walls0961ec02020-03-31 16:39:15 +0100918 }
919}
920
Camden5b184be2019-08-13 07:50:19 -0600921bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
922 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600923 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500924 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600925 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
926 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600927
928 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700929 skip |= LogPerformanceWarning(
930 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
931 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
932 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600933 }
934
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100935 if (VendorCheckEnabled(kBPVendorArm)) {
936 for (size_t i = 0; i < createInfoCount; i++) {
937 skip |= ValidateCreateComputePipelineArm(pCreateInfos[i]);
938 }
939 }
940
941 return skip;
942}
943
944bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
945 bool skip = false;
946 auto* module = GetShaderModuleState(createInfo.stage.module);
947
948 uint32_t x = 1, y = 1, z = 1;
949 FindLocalSize(module, x, y, z);
950
951 uint32_t thread_count = x * y * z;
952
953 // Generate a priori warnings about work group sizes.
954 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
955 skip |= LogPerformanceWarning(
956 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
957 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
958 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
959 "groups with less than %u threads, especially when using barrier() or shared memory.",
960 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
961 }
962
963 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
964 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
965 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
966 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
967 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
968 "%u, %u) is not aligned to %u "
969 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
970 "leave threads idle on the shader "
971 "core.",
972 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
973 kThreadGroupDispatchCountAlignmentArm);
974 }
975
976 // Generate warnings about work group sizes based on active resources.
977 auto entrypoint = FindEntrypoint(module, createInfo.stage.pName, createInfo.stage.stage);
978 if (entrypoint == module->end()) return false;
979
980 bool has_writeable_descriptors = false;
locke-lunarg63e4daf2020-08-17 17:53:25 -0600981 bool has_atomic_descriptors = false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100982 auto accessible_ids = MarkAccessibleIds(module, entrypoint);
locke-lunarg63e4daf2020-08-17 17:53:25 -0600983 auto descriptor_uses =
984 CollectInterfaceByDescriptorSlot(module, accessible_ids, &has_writeable_descriptors, &has_atomic_descriptors);
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100985
986 unsigned dimensions = 0;
987 if (x > 1) dimensions++;
988 if (y > 1) dimensions++;
989 if (z > 1) dimensions++;
990 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
991 dimensions = std::max(dimensions, 1u);
992
993 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
994 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
995 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
996 bool accesses_2d = false;
997 for (const auto& usage : descriptor_uses) {
998 auto dim = GetShaderResourceDimensionality(module, usage.second);
999 if (dim < 0) continue;
1000 auto spvdim = spv::Dim(dim);
1001 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1002 }
1003
1004 if (accesses_2d && dimensions < 2) {
1005 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1006 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1007 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1008 "exhibiting poor spatial locality with respect to one or more shader resources.",
1009 VendorSpecificTag(kBPVendorArm), x, y, z);
1010 }
1011
Camden5b184be2019-08-13 07:50:19 -06001012 return skip;
1013}
1014
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001015bool BestPractices::CheckPipelineStageFlags(std::string api_name, const VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001016 bool skip = false;
1017
1018 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001019 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1020 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001021 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001022 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1023 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001024 }
1025
1026 return skip;
1027}
1028
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001029void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001030 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1031 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1032 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1033 LogPerformanceWarning(
1034 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1035 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1036 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1037 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1038 "convenient opportunity.",
1039 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1040 }
1041 }
1042}
1043
Jeff Bolz5c801d12019-10-09 10:38:45 -05001044bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1045 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001046 bool skip = false;
1047
1048 for (uint32_t submit = 0; submit < submitCount; submit++) {
1049 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1050 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1051 }
1052 }
1053
1054 return skip;
1055}
1056
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001057bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1058 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1059 bool skip = false;
1060
1061 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1062 skip |= LogPerformanceWarning(
1063 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1064 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1065 "pool instead.");
1066 }
1067
1068 return skip;
1069}
1070
1071bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1072 const VkCommandBufferBeginInfo* pBeginInfo) const {
1073 bool skip = false;
1074
1075 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1076 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1077 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1078 }
1079
Attilio Provenzano02859b22020-02-27 14:17:28 +00001080 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT)) {
1081 skip |= VendorCheckEnabled(kBPVendorArm) &&
1082 LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
1083 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1084 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1085 VendorSpecificTag(kBPVendorArm));
1086 }
1087
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001088 return skip;
1089}
1090
Jeff Bolz5c801d12019-10-09 10:38:45 -05001091bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001092 bool skip = false;
1093
1094 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1095
1096 return skip;
1097}
1098
Jeff Bolz5c801d12019-10-09 10:38:45 -05001099bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1100 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001101 bool skip = false;
1102
1103 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1104
1105 return skip;
1106}
1107
1108bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1109 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1110 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1111 uint32_t bufferMemoryBarrierCount,
1112 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1113 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001114 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001115 bool skip = false;
1116
1117 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1118 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1119
1120 return skip;
1121}
1122
1123bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1124 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1125 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1126 uint32_t bufferMemoryBarrierCount,
1127 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1128 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001129 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001130 bool skip = false;
1131
1132 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1133 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1134
1135 return skip;
1136}
1137
1138bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001139 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001140 bool skip = false;
1141
1142 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", pipelineStage);
1143
1144 return skip;
1145}
1146
Sam Walls0961ec02020-03-31 16:39:15 +01001147void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1148 VkPipeline pipeline) {
1149 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1150
1151 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1152 // check for depth/blend state tracking
1153 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1154 if (gp_cis != graphicsPipelineCIs.end()) {
1155 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1156 if (prepass_state == cbDepthPrePassStates.end()) {
1157 auto result = cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1158
1159 if (!result.second) return;
1160
1161 prepass_state = result.first;
1162 }
1163
1164 const auto* blend_state = gp_cis->second.colorBlendStateCI;
1165 const auto* stencil_state = gp_cis->second.depthStencilStateCI;
1166
1167 if (blend_state) {
1168 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
1169 prepass_state->second.depthOnly = true;
1170 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1171 if (blend_state->pAttachments[i].colorWriteMask != 0) {
1172 prepass_state->second.depthOnly = false;
1173 }
1174 }
1175 }
1176
1177 // check for depth value usage
1178 prepass_state->second.depthEqualComparison = false;
1179
1180 if (stencil_state && stencil_state->depthTestEnable) {
1181 switch (stencil_state->depthCompareOp) {
1182 case VK_COMPARE_OP_EQUAL:
1183 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1184 case VK_COMPARE_OP_LESS_OR_EQUAL:
1185 prepass_state->second.depthEqualComparison = true;
1186 break;
1187 default:
1188 break;
1189 }
1190 }
1191 } else {
1192 // reset depth pre-pass tracking
1193 cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1194 }
1195 }
1196}
1197
Attilio Provenzano02859b22020-02-27 14:17:28 +00001198static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1199 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001200 auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001201
1202 // If an attachment is ever used as a color attachment,
1203 // resolve attachment or depth stencil attachment,
1204 // it needs to exist on tile at some point.
1205
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001206 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1207 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001208 }
1209
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001210 if (subpass_info.pResolveAttachments) {
1211 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1212 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1213 }
1214 }
1215
1216 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001217 }
1218
1219 return false;
1220}
1221
1222bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1223 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1224 bool skip = false;
1225
1226 if (!pRenderPassBegin) {
1227 return skip;
1228 }
1229
1230 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1231 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001232 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001233 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001234 if (rpabi) {
1235 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1236 }
1237 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001238 // Check if any attachments have LOAD operation on them
1239 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1240 auto& attachment = rp_state->createInfo.pAttachments[att];
1241
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001242 bool attachment_has_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001243 if (!FormatHasStencil(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001244 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001245 }
1246
1247 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001248 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001249 }
1250
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001251 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001252
1253 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001254 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1255 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001256 }
1257
1258 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001259 if (attachment_needs_readback) {
Attilio Provenzano02859b22020-02-27 14:17:28 +00001260 skip |= VendorCheckEnabled(kBPVendorArm) &&
1261 LogPerformanceWarning(
1262 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1263 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1264 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
1265 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
1266 VendorSpecificTag(kBPVendorArm), att,
1267 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1268 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1269 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
1270 }
1271 }
1272 }
1273
1274 return skip;
1275}
1276
1277bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1278 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001279 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1280 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001281 return skip;
1282}
1283
1284bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1285 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001286 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001287 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1288 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001289 return skip;
1290}
1291
1292bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001293 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001294 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1295 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001296 return skip;
1297}
1298
Sam Walls0961ec02020-03-31 16:39:15 +01001299void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1300 const VkRenderPassBeginInfo* pRenderPassBegin) {
1301 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1302
1303 // add the tracking state if it doesn't exist
1304 if (prepass_state == cbDepthPrePassStates.end()) {
1305 auto result = cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1306
1307 if (!result.second) return;
1308
1309 prepass_state = result.first;
1310 }
1311
1312 // reset the renderpass state
1313 prepass_state->second = {};
1314
1315 const auto* cb_state = GetCBState(commandBuffer);
locke-lunargaecf2152020-05-12 17:15:41 -06001316 const auto* rp_state = cb_state->activeRenderPass.get();
Sam Walls0961ec02020-03-31 16:39:15 +01001317
1318 // track depth / color attachment usage within the renderpass
1319 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1320 // record if depth/color attachments are in use for this renderpass
1321 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) prepass_state->second.depthAttachment = true;
1322
1323 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) prepass_state->second.colorAttachment = true;
1324 }
1325}
1326
1327void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1328 VkSubpassContents contents) {
1329 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1330 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1331}
1332
1333void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1334 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1335 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1336 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1337}
1338
1339void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1340 const VkRenderPassBeginInfo* pRenderPassBegin,
1341 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1342 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1343 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1344}
1345
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001346// Generic function to handle validation for all CmdDraw* type functions
1347bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1348 bool skip = false;
1349 const CMD_BUFFER_STATE* cb_state = GetCBState(cmd_buffer);
1350 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001351 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1352 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001353 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001354
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001355 // Verify vertex binding
1356 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1357 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001358 skip |= LogPerformanceWarning(cb_state->commandBuffer, kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
1359 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
1360 report_data->FormatHandle(cb_state->commandBuffer).c_str(),
1361 report_data->FormatHandle(pipeline_state->pipeline).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001362 }
1363 }
1364 }
1365 return skip;
1366}
1367
Sam Walls0961ec02020-03-31 16:39:15 +01001368void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1369 if (VendorCheckEnabled(kBPVendorArm)) {
1370 RecordCmdDrawTypeArm(cmd_buffer, draw_count, caller);
1371 }
1372}
1373
1374void BestPractices::RecordCmdDrawTypeArm(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1375 auto prepass_state = cbDepthPrePassStates.find(cmd_buffer);
1376 if (prepass_state != cbDepthPrePassStates.end() && draw_count >= kDepthPrePassMinDrawCountArm) {
1377 if (prepass_state->second.depthOnly) prepass_state->second.numDrawCallsDepthOnly++;
1378
1379 if (prepass_state->second.depthEqualComparison) prepass_state->second.numDrawCallsDepthEqualCompare++;
1380 }
1381}
1382
Camden5b184be2019-08-13 07:50:19 -06001383bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001384 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001385 bool skip = false;
1386
1387 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001388 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1389 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001390 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001391 }
1392
1393 return skip;
1394}
1395
Sam Walls0961ec02020-03-31 16:39:15 +01001396void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1397 uint32_t firstVertex, uint32_t firstInstance) {
1398 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
1399 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
1400}
1401
Camden5b184be2019-08-13 07:50:19 -06001402bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001403 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001404 bool skip = false;
1405
1406 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001407 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1408 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001409 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001410 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1411
Attilio Provenzano02859b22020-02-27 14:17:28 +00001412 // Check if we reached the limit for small indexed draw calls.
1413 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1414 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1415 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
1416 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1)) {
1417 skip |= VendorCheckEnabled(kBPVendorArm) &&
1418 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
1419 "The command buffer contains many small indexed drawcalls "
1420 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1421 "You can try batching drawcalls or instancing when applicable.",
1422 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1423 }
1424
Sam Walls8e77e4f2020-03-16 20:47:40 +00001425 if (VendorCheckEnabled(kBPVendorArm)) {
1426 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1427 }
1428
1429 return skip;
1430}
1431
1432bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1433 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1434 bool skip = false;
1435
1436 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1437 const auto* cmd_state = GetCBState(commandBuffer);
1438 if (cmd_state == nullptr) return skip;
1439
locke-lunarg1ae57d62020-11-18 10:49:19 -07001440 const auto* ib_state = cmd_state->index_buffer_binding.buffer_state.get();
1441 if (ib_state == nullptr || cmd_state->index_buffer_binding.buffer_state->destroyed) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001442
1443 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
1444 const auto& ib_mem_state = *ib_state->binding.mem_state;
1445 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1446 const void* ib_mem = ib_mem_state.p_driver_data;
1447 bool primitive_restart_enable = false;
1448
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001449 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1450 const auto& pipeline_binding_iter = cmd_state->lastBound[lv_bind_point];
1451 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001452
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001453 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001454 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001455 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00001456
1457 // 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 -06001458 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00001459 uint32_t scan_stride;
1460 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1461 scan_stride = sizeof(uint8_t);
1462 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1463 scan_stride = sizeof(uint16_t);
1464 } else {
1465 scan_stride = sizeof(uint32_t);
1466 }
1467
1468 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1469 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1470
1471 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1472 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1473 // irrespective of whether or not they're part of the draw call.
1474
1475 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1476 uint32_t min_index = ~0u;
1477 // start with maximum as 0 and adjust to indices in the buffer
1478 uint32_t max_index = 0u;
1479
1480 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
1481 // for the given index buffer
1482 uint32_t vertex_shade_count = 0;
1483
1484 PostTransformLRUCacheModel post_transform_cache;
1485
1486 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
1487 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
1488 // target architecture.
1489 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
1490 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
1491 post_transform_cache.resize(32);
1492
1493 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1494 uint32_t scan_index;
1495 uint32_t primitive_restart_value;
1496 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1497 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1498 primitive_restart_value = 0xFF;
1499 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1500 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1501 primitive_restart_value = 0xFFFF;
1502 } else {
1503 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1504 primitive_restart_value = 0xFFFFFFFF;
1505 }
1506
1507 max_index = std::max(max_index, scan_index);
1508 min_index = std::min(min_index, scan_index);
1509
1510 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
1511 bool in_cache = post_transform_cache.query_cache(scan_index);
1512 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
1513 if (!in_cache) vertex_shade_count++;
1514 }
1515 }
1516
1517 // 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 +01001518 // 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
1519 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001520
1521 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07001522 skip |=
1523 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1524 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
1525 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
1526 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
1527 "maximum would be loaded, and possibly shaded, whether or not they are used.",
1528 VendorSpecificTag(kBPVendorArm),
1529 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001530 return skip;
1531 }
1532
1533 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
1534 // 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 +01001535 const size_t refs_per_bucket = 64;
1536 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
1537
1538 const uint32_t n_indices = max_index - min_index + 1;
1539 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
1540 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
1541
1542 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
1543 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00001544
1545 // To avoid using too much memory, we run over the indices again.
1546 // Knowing the size from the last scan allows us to record index usage with bitsets
1547 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1548 uint32_t scan_index;
1549 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1550 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1551 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1552 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1553 } else {
1554 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1555 }
1556 // keep track of the set of all indices used to reference vertices in the draw call
1557 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01001558 size_t bitset_bucket_index = index_offset / refs_per_bucket;
1559 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001560 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
1561 }
1562
1563 uint32_t vertex_reference_count = 0;
1564 for (const auto& bitset : vertex_reference_buckets) {
1565 vertex_reference_count += static_cast<uint32_t>(bitset.count());
1566 }
1567
1568 // 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 -07001569 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001570 // 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 -07001571 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001572
1573 if (utilization < 0.5f) {
1574 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1575 "%s The indices which were specified for the draw call only utilise approximately "
1576 "%.02f%% of the bound vertex buffer.",
1577 VendorSpecificTag(kBPVendorArm), utilization);
1578 }
1579
1580 if (cache_hit_rate <= 0.5f) {
1581 skip |=
1582 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
1583 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
1584 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
1585 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
1586 "recently shaded vertices.",
1587 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
1588 }
1589 }
1590
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001591 return skip;
1592}
1593
Attilio Provenzano02859b22020-02-27 14:17:28 +00001594void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1595 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1596 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
1597 firstInstance);
1598
1599 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1600 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
1601 cmd_state->small_indexed_draw_call_count++;
1602 }
1603}
1604
Sam Walls0961ec02020-03-31 16:39:15 +01001605void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1606 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1607 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1608 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
1609}
1610
sfricke-samsung681ab7b2020-10-29 01:53:35 -07001611bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1612 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
1613 uint32_t maxDrawCount, uint32_t stride) const {
1614 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
1615
1616 return skip;
1617}
1618
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001619bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
1620 VkDeviceSize offset, VkBuffer countBuffer,
1621 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
1622 uint32_t stride) const {
1623 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06001624
1625 return skip;
1626}
1627
1628bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001629 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001630 bool skip = false;
1631
1632 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001633 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1634 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001635 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001636 }
1637
1638 return skip;
1639}
1640
Sam Walls0961ec02020-03-31 16:39:15 +01001641void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1642 uint32_t count, uint32_t stride) {
1643 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
1644 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
1645}
1646
Camden5b184be2019-08-13 07:50:19 -06001647bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001648 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001649 bool skip = false;
1650
1651 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001652 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1653 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001654 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001655 }
1656
1657 return skip;
1658}
1659
Sam Walls0961ec02020-03-31 16:39:15 +01001660void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1661 uint32_t count, uint32_t stride) {
1662 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
1663 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
1664}
1665
Camden5b184be2019-08-13 07:50:19 -06001666bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001667 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06001668 bool skip = false;
1669
1670 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001671 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
1672 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
1673 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
1674 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06001675 }
1676
1677 return skip;
1678}
Camden83a9c372019-08-14 11:41:38 -06001679
Sam Walls0961ec02020-03-31 16:39:15 +01001680bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
1681 bool skip = false;
1682
1683 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
1684
1685 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1686
1687 if (prepass_state == cbDepthPrePassStates.end()) return skip;
1688
1689 bool uses_depth = (prepass_state->second.depthAttachment || prepass_state->second.colorAttachment) &&
1690 prepass_state->second.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
1691 prepass_state->second.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
1692 if (uses_depth) {
1693 skip |= LogPerformanceWarning(
1694 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
1695 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
1696 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
1697 "case, using depth pre-passes for hidden surface removal may worsen performance.",
1698 VendorSpecificTag(kBPVendorArm));
1699 }
1700
1701 return skip;
1702}
1703
Camden Stocker9c051442019-11-06 14:28:43 -08001704bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
1705 const char* api_name) const {
1706 bool skip = false;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001707 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08001708
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001709 if (bp_pd_state) {
1710 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
1711 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
1712 "Potential problem with calling %s() without first retrieving properties from "
1713 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
1714 api_name);
1715 }
Camden Stocker9c051442019-11-06 14:28:43 -08001716 }
1717
1718 return skip;
1719}
1720
Camden83a9c372019-08-14 11:41:38 -06001721bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001722 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06001723 bool skip = false;
1724
Camden Stocker9c051442019-11-06 14:28:43 -08001725 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06001726
Camden Stocker9c051442019-11-06 14:28:43 -08001727 return skip;
1728}
1729
1730bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
1731 uint32_t planeIndex,
1732 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
1733 bool skip = false;
1734
1735 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
1736
1737 return skip;
1738}
1739
1740bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
1741 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
1742 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
1743 bool skip = false;
1744
1745 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06001746
1747 return skip;
1748}
Camden05de2d42019-08-19 10:23:56 -06001749
1750bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001751 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06001752 bool skip = false;
1753
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001754 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
Camden05de2d42019-08-19 10:23:56 -06001755
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001756 if ((swapchain_state_itr != swapchain_bp_state_map.cend()) && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06001757 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001758 if (swapchain_state_itr->second.vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001759 skip |=
1760 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
1761 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
1762 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06001763 }
1764 }
1765
1766 return skip;
1767}
1768
1769// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001770bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
1771 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07001772 const CALL_STATE call_state,
1773 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06001774 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07001775 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
1776 if (UNCALLED == call_state) {
1777 skip |= LogWarning(
1778 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
1779 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
1780 "recommended "
1781 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
1782 caller_name, caller_name);
1783 // Then verify that pCount that is passed in on second call matches what was returned
1784 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
1785 skip |= LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
1786 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
1787 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
1788 ". It is recommended to instead receive all the properties by calling %s with "
1789 "pQueueFamilyPropertyCount that was "
1790 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
1791 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
1792 caller_name);
Camden05de2d42019-08-19 10:23:56 -06001793 }
1794
1795 return skip;
1796}
1797
Jeff Bolz5c801d12019-10-09 10:38:45 -05001798bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
1799 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06001800 bool skip = false;
1801
1802 for (uint32_t i = 0; i < bindInfoCount; i++) {
sourav parmarcd5fb182020-07-17 12:58:44 -07001803 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureStateNV(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06001804 if (!as_state->memory_requirements_checked) {
1805 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
1806 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
1807 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001808 skip |= LogWarning(
1809 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06001810 "vkBindAccelerationStructureMemoryNV(): "
1811 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
1812 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
1813 }
1814 }
1815
1816 return skip;
1817}
1818
Camden05de2d42019-08-19 10:23:56 -06001819bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
1820 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001821 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001822 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1823 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07001824 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
1825 if (pQueueFamilyProperties && bp_pd_state) {
1826 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
1827 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
1828 "vkGetPhysicalDeviceQueueFamilyProperties()");
1829 }
1830 return false;
Camden05de2d42019-08-19 10:23:56 -06001831}
1832
Mike Schuchardt2df08912020-12-15 16:28:09 -08001833bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
1834 uint32_t* pQueueFamilyPropertyCount,
1835 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001836 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1837 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07001838 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
1839 if (pQueueFamilyProperties && bp_pd_state) {
1840 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
1841 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
1842 "vkGetPhysicalDeviceQueueFamilyProperties2()");
1843 }
1844 return false;
Camden05de2d42019-08-19 10:23:56 -06001845}
1846
Jeff Bolz5c801d12019-10-09 10:38:45 -05001847bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08001848 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001849 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1850 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07001851 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
1852 if (pQueueFamilyProperties && bp_pd_state) {
1853 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
1854 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
1855 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
1856 }
1857 return false;
Camden05de2d42019-08-19 10:23:56 -06001858}
1859
1860bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
1861 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001862 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06001863 if (!pSurfaceFormats) return false;
1864 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001865 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
1866 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06001867 bool skip = false;
1868 if (call_state == UNCALLED) {
1869 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
1870 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001871 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
1872 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
1873 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06001874 } else {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001875 auto prev_format_count = static_cast<uint32_t>(physical_device_state->surface_formats.size());
Peter Chene191bd72019-09-16 13:04:37 -04001876 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001877 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
1878 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
1879 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
1880 "when pSurfaceFormatCount was NULL.",
1881 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06001882 }
1883 }
1884 return skip;
1885}
Camden Stocker23cc47d2019-09-03 14:53:57 -06001886
1887bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001888 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001889 bool skip = false;
1890
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001891 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
1892 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06001893 // Store sparse binding image_state and after binding is complete make sure that any requiring metadata have it bound
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001894 std::unordered_set<const IMAGE_STATE*> sparse_images;
1895 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
1896 // in RecordQueueBindSparse.
1897 std::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06001898 // 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 -07001899 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
1900 const auto& image_bind = bind_info.pImageBinds[i];
Camden Stocker23cc47d2019-09-03 14:53:57 -06001901 auto image_state = GetImageState(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001902 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001903 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001904 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06001905 sparse_images.insert(image_state);
1906 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1907 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1908 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001909 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1910 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1911 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1912 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001913 }
1914 }
1915 if (!image_state->memory_requirements_checked) {
1916 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001917 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1918 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1919 "vkGetImageMemoryRequirements() to retrieve requirements.",
1920 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001921 }
1922 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001923 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
1924 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
1925 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
1926 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001927 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001928 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06001929 sparse_images.insert(image_state);
1930 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1931 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1932 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001933 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1934 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1935 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1936 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001937 }
1938 }
1939 if (!image_state->memory_requirements_checked) {
1940 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001941 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1942 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1943 "vkGetImageMemoryRequirements() to retrieve requirements.",
1944 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001945 }
1946 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1947 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001948 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06001949 }
1950 }
1951 }
1952 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001953 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
1954 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001955 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001956 skip |= LogWarning(sparse_image_state->image, kVUID_Core_MemTrack_InvalidState,
1957 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
1958 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
1959 report_data->FormatHandle(sparse_image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001960 }
1961 }
1962 }
1963
1964 return skip;
1965}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001966
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001967void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
1968 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001969 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001970 return;
1971 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001972
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001973 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
1974 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
1975 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
1976 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
1977 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
1978 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001979 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001980 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001981 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1982 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
1983 image_state->sparse_metadata_bound = true;
1984 }
1985 }
1986 }
1987 }
1988}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001989
1990bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06001991 const VkClearAttachment* pAttachments, uint32_t rectCount,
1992 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001993 bool skip = false;
1994 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
1995 if (!cb_node) return skip;
1996
Camden Stockerf55721f2019-09-09 11:04:49 -06001997 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001998 if (!cb_node->hasDrawCmd && (cb_node->activeRenderPassBeginInfo.renderArea.extent.width == pRects[0].rect.extent.width) &&
1999 (cb_node->activeRenderPassBeginInfo.renderArea.extent.height == pRects[0].rect.extent.height)) {
2000 // There are times where app needs to use ClearAttachments (generally when reusing a buffer inside of a render pass)
2001 // This warning should be made more specific. It'd be best to avoid triggering this test if it's a use that must call
2002 // CmdClearAttachments.
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07002003 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
2004 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds. It is recommended you "
2005 "use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
2006 report_data->FormatHandle(commandBuffer).c_str());
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002007 }
2008
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002009 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
2010 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06002011 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002012 if (rp) {
2013 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
2014
2015 for (uint32_t i = 0; i < attachmentCount; i++) {
2016 auto& attachment = pAttachments[i];
2017 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
2018 uint32_t color_attachment = attachment.colorAttachment;
2019 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
2020
2021 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2022 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2023 skip |= LogPerformanceWarning(
2024 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2025 "vkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
2026 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2027 "it is more efficient.",
2028 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
2029 }
2030 }
2031 }
2032
2033 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
2034 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2035
2036 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2037 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2038 skip |= LogPerformanceWarning(
2039 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2040 "vkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
2041 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2042 "it is more efficient.",
2043 report_data->FormatHandle(commandBuffer).c_str());
2044 }
2045 }
2046 }
2047
2048 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
2049 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2050
2051 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2052 if (rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2053 skip |= LogPerformanceWarning(
2054 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2055 "vkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
2056 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2057 "it is more efficient.",
2058 report_data->FormatHandle(commandBuffer).c_str());
2059 }
2060 }
2061 }
2062 }
2063 }
2064
Camden Stockerf55721f2019-09-09 11:04:49 -06002065 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002066}
Attilio Provenzano02859b22020-02-27 14:17:28 +00002067
2068bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2069 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2070 const VkImageResolve* pRegions) const {
2071 bool skip = false;
2072
2073 skip |= VendorCheckEnabled(kBPVendorArm) &&
2074 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
2075 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
2076 "This is a very slow and extremely bandwidth intensive path. "
2077 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2078 VendorSpecificTag(kBPVendorArm));
2079
2080 return skip;
2081}
2082
Jeff Leger178b1e52020-10-05 12:22:23 -04002083bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2084 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
2085 bool skip = false;
2086
2087 skip |= VendorCheckEnabled(kBPVendorArm) &&
2088 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
2089 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
2090 "This is a very slow and extremely bandwidth intensive path. "
2091 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2092 VendorSpecificTag(kBPVendorArm));
2093
2094 return skip;
2095}
2096
Attilio Provenzano02859b22020-02-27 14:17:28 +00002097bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
2098 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
2099 bool skip = false;
2100
2101 if (VendorCheckEnabled(kBPVendorArm)) {
2102 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
2103 skip |= LogPerformanceWarning(
2104 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
2105 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
2106 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
2107 "image) are actually used. If you need different wrapping modes, disregard this warning.",
2108 VendorSpecificTag(kBPVendorArm));
2109 }
2110
2111 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
2112 skip |= LogPerformanceWarning(
2113 device, kVUID_BestPractices_CreateSampler_LodClamping,
2114 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
2115 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
2116 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
2117 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
2118 }
2119
2120 if (pCreateInfo->mipLodBias != 0.0f) {
2121 skip |=
2122 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
2123 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
2124 "descriptors being created and may cause reduced performance.",
2125 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
2126 }
2127
2128 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2129 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2130 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
2131 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
2132 skip |= LogPerformanceWarning(
2133 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
2134 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
2135 "This will lead to less efficient descriptors being created and may cause reduced performance. "
2136 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
2137 VendorSpecificTag(kBPVendorArm));
2138 }
2139
2140 if (pCreateInfo->unnormalizedCoordinates) {
2141 skip |= LogPerformanceWarning(
2142 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
2143 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
2144 "descriptors being created and may cause reduced performance.",
2145 VendorSpecificTag(kBPVendorArm));
2146 }
2147
2148 if (pCreateInfo->anisotropyEnable) {
2149 skip |= LogPerformanceWarning(
2150 device, kVUID_BestPractices_CreateSampler_Anisotropy,
2151 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
2152 "and may cause reduced performance.",
2153 VendorSpecificTag(kBPVendorArm));
2154 }
2155 }
2156
2157 return skip;
2158}
Sam Walls8e77e4f2020-03-16 20:47:40 +00002159
2160void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
2161
2162bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
2163 // look for a cache hit
2164 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
2165 if (hit != _entries.end()) {
2166 // mark the cache hit as being most recently used
2167 hit->age = iteration++;
2168 return true;
2169 }
2170
2171 // if there's no cache hit, we need to model the entry being inserted into the cache
2172 CacheEntry new_entry = {value, iteration};
2173 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
2174 // if there is still space left in the cache, use the next available slot
2175 *(_entries.begin() + iteration) = new_entry;
2176 } else {
2177 // otherwise replace the least recently used cache entry
2178 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
2179 *lru = new_entry;
2180 }
2181 iteration++;
2182 return false;
2183}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002184
2185bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
2186 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
2187 const auto swapchain_data = GetSwapchainState(swapchain);
2188 bool skip = false;
2189 if (swapchain_data && swapchain_data->images.size() == 0) {
2190 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
2191 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
2192 "vkGetSwapchainImagesKHR after swapchain creation.");
2193 }
2194 return skip;
2195}
2196
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002197void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
2198 if (no_pointer) {
2199 if (UNCALLED == call_state) {
2200 call_state = QUERY_COUNT;
2201 }
2202 } else { // Save queue family properties
2203 call_state = QUERY_DETAILS;
2204 }
2205}
2206
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002207void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2208 uint32_t* pQueueFamilyPropertyCount,
2209 VkQueueFamilyProperties* pQueueFamilyProperties) {
2210 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
2211 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002212 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002213 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002214 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2215 nullptr == pQueueFamilyProperties);
2216 }
2217}
2218
2219void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2220 uint32_t* pQueueFamilyPropertyCount,
2221 VkQueueFamilyProperties2* pQueueFamilyProperties) {
2222 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
2223 pQueueFamilyProperties);
2224 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2225 if (bp_pd_state) {
2226 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2227 nullptr == pQueueFamilyProperties);
2228 }
2229}
2230
2231void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
2232 uint32_t* pQueueFamilyPropertyCount,
2233 VkQueueFamilyProperties2* pQueueFamilyProperties) {
2234 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
2235 pQueueFamilyProperties);
2236 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2237 if (bp_pd_state) {
2238 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2239 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002240 }
2241}
2242
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002243void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
2244 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002245 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2246 if (bp_pd_state) {
2247 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2248 }
2249}
2250
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002251void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
2252 VkPhysicalDeviceFeatures2* pFeatures) {
2253 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002254 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2255 if (bp_pd_state) {
2256 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2257 }
2258}
2259
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002260void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
2261 VkPhysicalDeviceFeatures2* pFeatures) {
2262 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002263 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2264 if (bp_pd_state) {
2265 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2266 }
2267}
2268
2269void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
2270 VkSurfaceKHR surface,
2271 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
2272 VkResult result) {
2273 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2274 if (bp_pd_state) {
2275 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2276 }
2277}
2278
2279void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
2280 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2281 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
2282 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2283 if (bp_pd_state) {
2284 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2285 }
2286}
2287
2288void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
2289 VkSurfaceKHR surface,
2290 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
2291 VkResult result) {
2292 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2293 if (bp_pd_state) {
2294 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2295 }
2296}
2297
2298void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
2299 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
2300 VkPresentModeKHR* pPresentModes, VkResult result) {
2301 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2302 if (bp_pd_data) {
2303 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
2304
2305 if (*pPresentModeCount) {
2306 if (call_state < QUERY_COUNT) {
2307 call_state = QUERY_COUNT;
2308 }
2309 }
2310 if (pPresentModes) {
2311 if (call_state < QUERY_DETAILS) {
2312 call_state = QUERY_DETAILS;
2313 }
2314 }
2315 }
2316}
2317
2318void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2319 uint32_t* pSurfaceFormatCount,
2320 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
2321 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2322 if (bp_pd_data) {
2323 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
2324
2325 if (*pSurfaceFormatCount) {
2326 if (call_state < QUERY_COUNT) {
2327 call_state = QUERY_COUNT;
2328 }
2329 }
2330 if (pSurfaceFormats) {
2331 if (call_state < QUERY_DETAILS) {
2332 call_state = QUERY_DETAILS;
2333 }
2334 }
2335 }
2336}
2337
2338void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
2339 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2340 uint32_t* pSurfaceFormatCount,
2341 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
2342 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2343 if (bp_pd_data) {
2344 if (*pSurfaceFormatCount) {
2345 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
2346 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
2347 }
2348 }
2349 if (pSurfaceFormats) {
2350 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
2351 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
2352 }
2353 }
2354 }
2355}
2356
2357void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
2358 uint32_t* pPropertyCount,
2359 VkDisplayPlanePropertiesKHR* pProperties,
2360 VkResult result) {
2361 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2362 if (bp_pd_data) {
2363 if (*pPropertyCount) {
2364 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
2365 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
2366 }
2367 }
2368 if (pProperties) {
2369 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
2370 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
2371 }
2372 }
2373 }
2374}
2375
2376void BestPractices::ManualPostCallRecordCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
2377 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain,
2378 VkResult result) {
2379 if (VK_SUCCESS == result) {
2380 swapchain_bp_state_map.emplace(*pSwapchain, SWAPCHAIN_STATE_BP{});
2381 }
2382}
2383
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002384void BestPractices::PostCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain,
2385 const VkAllocationCallbacks* pAllocator) {
2386 ValidationStateTracker::PostCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002387 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2388 if (swapchain_state_itr != swapchain_bp_state_map.cend()) {
2389 swapchain_bp_state_map.erase(swapchain_state_itr);
2390 }
2391}
2392
2393void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
2394 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
2395 VkResult result) {
2396 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2397 assert(swapchain_state_itr != swapchain_bp_state_map.cend());
2398 auto& swapchain_state = swapchain_state_itr->second;
2399 if (pSwapchainImages || *pSwapchainImageCount) {
2400 if (swapchain_state.vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
2401 swapchain_state.vkGetSwapchainImagesKHRState = QUERY_DETAILS;
2402 }
2403 }
2404}
2405
2406void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
2407 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
2408 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
2409 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
2410 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
2411 }
2412 }
2413}
2414
2415void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo*, const VkAllocationCallbacks*,
2416 VkDevice*, VkResult result) {
2417 if (VK_SUCCESS == result) {
2418 instance_device_bp_state = &phys_device_bp_state_map[gpu];
2419 }
2420}
2421
2422PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
2423 if (phys_device_bp_state_map.count(phys_device) > 0) {
2424 return &phys_device_bp_state_map.at(phys_device);
2425 } else {
2426 return nullptr;
2427 }
2428}
2429
2430const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
2431 if (phys_device_bp_state_map.count(phys_device) > 0) {
2432 return &phys_device_bp_state_map.at(phys_device);
2433 } else {
2434 return nullptr;
2435 }
2436}
2437
2438PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
2439 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2440 if (bp_state) {
2441 return bp_state;
2442 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2443 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2444 } else {
2445 return nullptr;
2446 }
2447}
2448
2449const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
2450 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2451 if (bp_state) {
2452 return bp_state;
2453 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2454 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2455 } else {
2456 return nullptr;
2457 }
2458}