blob: a8e5775670bed056d3ea4c2fe860cb226a8832b4 [file] [log] [blame]
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -07001/* Copyright (c) 2015-2020 The Khronos Group Inc.
2 * Copyright (c) 2015-2020 Valve Corporation
3 * Copyright (c) 2015-2020 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
34const std::map<BPVendorFlagBits, VendorSpecificInfo> vendor_info = {
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 {
39 for (const auto& vendor : vendor_info) {
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;
58 for (const auto& vendor : vendor_info) {
59 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);
Camden5b184be2019-08-13 07:50:19 -0600166 }
167
168 return skip;
169}
170
171void BestPractices::PreCallRecordCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
172 VkInstance* pInstance) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700173 ValidationStateTracker::PreCallRecordCreateInstance(pCreateInfo, pAllocator, pInstance);
Sam Walls53bf7652020-04-21 17:35:15 +0100174
175 if (pCreateInfo != nullptr && pCreateInfo->pApplicationInfo != nullptr)
176 instance_api_version = pCreateInfo->pApplicationInfo->apiVersion;
177 else
178 instance_api_version = 0;
Camden5b184be2019-08-13 07:50:19 -0600179}
180
181bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500182 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600183 bool skip = false;
184
185 // get API version of physical device passed when creating device.
186 VkPhysicalDeviceProperties physical_device_properties{};
187 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500188 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600189
190 // check api versions and warn if instance api Version is higher than version on device.
191 if (instance_api_version > device_api_version) {
Mark Lobodzinski60880782020-08-11 08:02:07 -0600192 std::string inst_api_name = StringAPIVersion(instance_api_version);
193 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600194
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700195 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
196 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
197 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600198 }
199
200 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
201 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800202 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700203 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
204 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600205 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700206 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], instance_api_version,
207 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Camden5b184be2019-08-13 07:50:19 -0600208 }
209
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600210 const auto bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
211 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700212 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
213 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600214 }
215
Szilard Papp7d2c7952020-06-22 14:38:13 +0100216 if ((VendorCheckEnabled(kBPVendorArm)) && (pCreateInfo->pEnabledFeatures != nullptr) &&
217 (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
218 skip |= LogPerformanceWarning(
219 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
220 "%s vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
221 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
222 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
223 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
224 VendorSpecificTag(kBPVendorArm));
225 }
226
Camden5b184be2019-08-13 07:50:19 -0600227 return skip;
228}
229
230bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500231 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600232 bool skip = false;
233
234 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
235 std::stringstream bufferHex;
236 bufferHex << "0x" << std::hex << HandleToUint64(pBuffer);
237
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700238 skip |= LogWarning(
239 device, kVUID_BestPractices_SharingModeExclusive,
240 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
241 "(queueFamilyIndexCount of %" PRIu32 ").",
242 bufferHex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600243 }
244
245 return skip;
246}
247
248bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500249 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600250 bool skip = false;
251
252 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
253 std::stringstream imageHex;
254 imageHex << "0x" << std::hex << HandleToUint64(pImage);
255
256 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700257 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
258 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
259 "(queueFamilyIndexCount of %" PRIu32 ").",
260 imageHex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600261 }
262
Attilio Provenzano02859b22020-02-27 14:17:28 +0000263 if (VendorCheckEnabled(kBPVendorArm)) {
264 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
265 skip |= LogPerformanceWarning(
266 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
267 "%s vkCreateImage(): Trying to create an image with %u samples. "
268 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
269 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
270 }
271
272 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
273 skip |= LogPerformanceWarning(
274 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
275 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
276 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
277 "and do not need to be backed by physical storage. "
278 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
279 VendorSpecificTag(kBPVendorArm));
280 }
281 }
282
Camden5b184be2019-08-13 07:50:19 -0600283 return skip;
284}
285
286bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500287 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600288 bool skip = false;
289
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600290 const auto* bp_pd_state = GetPhysicalDeviceStateBP();
291 if (bp_pd_state) {
292 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
293 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
294 "vkCreateSwapchainKHR() called before getting surface capabilities from "
295 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
296 }
Camden83a9c372019-08-14 11:41:38 -0600297
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600298 if (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS) {
299 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
300 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
301 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
302 }
Camden83a9c372019-08-14 11:41:38 -0600303
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600304 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
305 skip |= LogWarning(
306 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
307 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
308 }
Camden83a9c372019-08-14 11:41:38 -0600309 }
310
Camden5b184be2019-08-13 07:50:19 -0600311 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700312 skip |=
313 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600314 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700315 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
316 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600317 }
318
Szilard Papp48a6da32020-06-10 14:41:59 +0100319 if (pCreateInfo->minImageCount == 2) {
320 skip |= LogPerformanceWarning(
321 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
322 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
323 ", which means double buffering is going "
324 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
325 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
326 "3 to use triple buffering to maximize performance in such cases.",
327 pCreateInfo->minImageCount);
328 }
329
Szilard Pappd5f0f812020-06-22 09:01:29 +0100330 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
331 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
332 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
333 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
334 "Presentation modes which are not FIFO will present the latest available frame and discard other "
335 "frame(s) if any.",
336 VendorSpecificTag(kBPVendorArm));
337 }
338
Camden5b184be2019-08-13 07:50:19 -0600339 return skip;
340}
341
342bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
343 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500344 const VkAllocationCallbacks* pAllocator,
345 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600346 bool skip = false;
347
348 for (uint32_t i = 0; i < swapchainCount; i++) {
349 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700350 skip |= LogWarning(
351 device, kVUID_BestPractices_SharingModeExclusive,
352 "Warning: A shared swapchain (index %" PRIu32
353 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
354 "queues (queueFamilyIndexCount of %" PRIu32 ").",
355 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600356 }
357 }
358
359 return skip;
360}
361
362bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500363 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600364 bool skip = false;
365
366 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
367 VkFormat format = pCreateInfo->pAttachments[i].format;
368 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
369 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
370 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700371 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
372 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
373 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
374 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
375 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600376 }
377 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700378 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
379 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
380 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
381 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
382 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600383 }
384 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000385
386 const auto& attachment = pCreateInfo->pAttachments[i];
387 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
388 bool access_requires_memory =
389 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
390
391 if (FormatHasStencil(format)) {
392 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
393 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
394 }
395
396 if (access_requires_memory) {
397 skip |= LogPerformanceWarning(
398 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
399 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
400 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
401 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
402 i, static_cast<uint32_t>(attachment.samples));
403 }
404 }
Camden5b184be2019-08-13 07:50:19 -0600405 }
406
407 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
408 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
409 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
410 }
411
412 return skip;
413}
414
Tony-LunarG767180f2020-04-23 14:03:59 -0600415bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
416 const VkImageView* image_views) const {
417 bool skip = false;
418
419 // Check for non-transient attachments that should be transient and vice versa
420 for (uint32_t i = 0; i < attachmentCount; ++i) {
421 auto& attachment = rpci->pAttachments[i];
422 bool attachment_should_be_transient =
423 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
424
425 if (FormatHasStencil(attachment.format)) {
426 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
427 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
428 }
429
430 auto view_state = GetImageViewState(image_views[i]);
431 if (view_state) {
432 auto& ivci = view_state->create_info;
433 auto& ici = GetImageState(ivci.image)->createInfo;
434
435 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
436
437 // The check for an image that should not be transient applies to all GPUs
438 if (!attachment_should_be_transient && image_is_transient) {
439 skip |= LogPerformanceWarning(
440 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
441 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
442 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
443 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
444 i);
445 }
446
447 bool supports_lazy = false;
448 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
449 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
450 supports_lazy = true;
451 }
452 }
453
454 // The check for an image that should be transient only applies to GPUs supporting
455 // lazily allocated memory
456 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
457 skip |= LogPerformanceWarning(
458 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
459 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
460 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
461 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
462 i);
463 }
464 }
465 }
466 return skip;
467}
468
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000469bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
470 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
471 bool skip = false;
472
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000473 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
Tony-LunarG767180f2020-04-23 14:03:59 -0600474 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR)) {
475 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000476 }
477
478 return skip;
479}
480
Sam Wallse746d522020-03-16 21:20:23 +0000481bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
482 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
483 bool skip = false;
484 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
485
486 if (!skip) {
487 const auto& pool_handle = pAllocateInfo->descriptorPool;
488 auto iter = descriptor_pool_freed_count.find(pool_handle);
489 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
490 // this warning is specific to Arm
491 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
492 skip |= LogPerformanceWarning(
493 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
494 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
495 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
496 VendorSpecificTag(kBPVendorArm));
497 }
498 }
499
500 return skip;
501}
502
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600503void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
504 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000505 if (result == VK_SUCCESS) {
506 // find the free count for the pool we allocated into
507 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
508 if (iter != descriptor_pool_freed_count.end()) {
509 // we record successful allocations by subtracting the allocation count from the last recorded free count
510 const auto alloc_count = pAllocateInfo->descriptorSetCount;
511 // clamp the unsigned subtraction to the range [0, last_free_count]
512 if (iter->second > alloc_count)
513 iter->second -= alloc_count;
514 else
515 iter->second = 0;
516 }
517 }
518}
519
520void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
521 const VkDescriptorSet* pDescriptorSets, VkResult result) {
522 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
523 if (result == VK_SUCCESS) {
524 // we want to track frees because we're interested in suggesting re-use
525 auto iter = descriptor_pool_freed_count.find(descriptorPool);
526 if (iter == descriptor_pool_freed_count.end()) {
527 descriptor_pool_freed_count.insert(std::make_pair(descriptorPool, descriptorSetCount));
528 } else {
529 iter->second += descriptorSetCount;
530 }
531 }
532}
533
Camden5b184be2019-08-13 07:50:19 -0600534bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500535 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600536 bool skip = false;
537
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500538 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700539 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
540 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600541 }
542
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000543 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
544 skip |= LogPerformanceWarning(
545 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
546 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %llu. This is a very small allocation (current "
547 "threshold is %llu bytes). "
548 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
549 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
550 }
551
Camden83a9c372019-08-14 11:41:38 -0600552 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
553
554 return skip;
555}
556
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600557void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
558 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
559 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700560 if (result != VK_SUCCESS) {
561 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
562 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
563 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR};
564 static std::vector<VkResult> success_codes = {};
565 ValidateReturnCodes("vkReleaseFullScreenExclusiveModeEXT", result, error_codes, success_codes);
566 return;
567 }
568 num_mem_objects++;
569}
Camden Stocker9738af92019-10-16 13:54:03 -0700570
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600571void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
572 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700573 auto error = std::find(error_codes.begin(), error_codes.end(), result);
574 if (error != error_codes.end()) {
Mark Lobodzinski629defa2020-04-29 12:00:23 -0600575 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700576 return;
577 }
578 auto success = std::find(success_codes.begin(), success_codes.end(), result);
579 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600580 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
581 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500582 }
583}
584
Jeff Bolz5c801d12019-10-09 10:38:45 -0500585bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
586 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700587 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600588 bool skip = false;
589
Camden Stocker9738af92019-10-16 13:54:03 -0700590 const DEVICE_MEMORY_STATE* mem_info = ValidationStateTracker::GetDevMemState(memory);
Camden83a9c372019-08-14 11:41:38 -0600591
592 for (auto& obj : mem_info->obj_bindings) {
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600593 LogObjectList objlist(device);
594 objlist.add(obj);
595 objlist.add(mem_info->mem);
596 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 -0700597 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem).c_str());
Camden83a9c372019-08-14 11:41:38 -0600598 }
599
Camden5b184be2019-08-13 07:50:19 -0600600 return skip;
601}
602
603void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700604 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600605 if (memory != VK_NULL_HANDLE) {
606 num_mem_objects--;
607 }
608}
609
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000610bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600611 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500612 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600613
sfricke-samsunge2441192019-11-06 14:07:57 -0800614 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700615 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
616 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
617 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600618 }
619
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000620 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
621
622 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
623 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
624 skip |= LogPerformanceWarning(
625 device, kVUID_BestPractices_SmallDedicatedAllocation,
626 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
627 "The required size of the allocation is %llu, but smaller buffers like this should be sub-allocated from "
628 "larger memory blocks. (Current threshold is %llu bytes.)",
629 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
630 }
631
Camden Stockerb603cc82019-09-03 10:09:02 -0600632 return skip;
633}
634
635bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500636 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600637 bool skip = false;
638 const char* api_name = "BindBufferMemory()";
639
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000640 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600641
642 return skip;
643}
644
645bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500646 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600647 char api_name[64];
648 bool skip = false;
649
650 for (uint32_t i = 0; i < bindInfoCount; i++) {
651 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000652 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600653 }
654
655 return skip;
656}
Camden Stockerb603cc82019-09-03 10:09:02 -0600657
658bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500659 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600660 char api_name[64];
661 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600662
Camden Stocker8b798ab2019-09-03 10:33:28 -0600663 for (uint32_t i = 0; i < bindInfoCount; i++) {
664 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000665 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600666 }
667
668 return skip;
669}
670
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000671bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600672 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500673 const IMAGE_STATE* image_state = GetImageState(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600674
sfricke-samsung71bc6572020-04-29 15:49:43 -0700675 if (image_state->disjoint == false) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700676 if (!image_state->memory_requirements_checked && !image_state->external_memory_handle) {
677 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
678 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
679 api_name, report_data->FormatHandle(image).c_str());
680 }
681 } else {
682 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
683 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600684 }
685
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000686 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
687
688 if (mem_state->alloc_info.allocationSize == image_state->requirements.size &&
689 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
690 skip |= LogPerformanceWarning(
691 device, kVUID_BestPractices_SmallDedicatedAllocation,
692 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
693 "The required size of the allocation is %llu, but smaller images like this should be sub-allocated from "
694 "larger memory blocks. (Current threshold is %llu bytes.)",
695 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
696 }
697
698 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
699 // make sure this type is actually used.
700 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
701 // (i.e.most tile - based renderers)
702 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
703 bool supports_lazy = false;
704 uint32_t suggested_type = 0;
705
706 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
707 if ((1u << i) & image_state->requirements.memoryTypeBits) {
708 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
709 supports_lazy = true;
710 suggested_type = i;
711 break;
712 }
713 }
714 }
715
716 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
717
718 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
719 skip |= LogPerformanceWarning(
720 device, kVUID_BestPractices_NonLazyTransientImage,
721 "%s: Attempting to bind memory type % u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
722 "but this memory type is not LAZILY_ALLOCATED_BIT. You should use memory type %u here instead to save "
723 "%llu bytes of physical memory.",
724 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements.size);
725 }
726 }
727
Camden Stocker8b798ab2019-09-03 10:33:28 -0600728 return skip;
729}
730
731bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500732 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600733 bool skip = false;
734 const char* api_name = "vkBindImageMemory()";
735
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000736 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600737
738 return skip;
739}
740
741bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500742 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600743 char api_name[64];
744 bool skip = false;
745
746 for (uint32_t i = 0; i < bindInfoCount; i++) {
747 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Tony-LunarG5e60b852020-04-27 11:27:54 -0600748 if (!lvl_find_in_chain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
749 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
750 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600751 }
752
753 return skip;
754}
755
756bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500757 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600758 char api_name[64];
759 bool skip = false;
760
761 for (uint32_t i = 0; i < bindInfoCount; i++) {
762 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000763 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600764 }
765
766 return skip;
767}
Camden83a9c372019-08-14 11:41:38 -0600768
Attilio Provenzano02859b22020-02-27 14:17:28 +0000769static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
770 switch (format) {
771 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
772 case VK_FORMAT_R16_SFLOAT:
773 case VK_FORMAT_R16G16_SFLOAT:
774 case VK_FORMAT_R16G16B16_SFLOAT:
775 case VK_FORMAT_R16G16B16A16_SFLOAT:
776 case VK_FORMAT_R32_SFLOAT:
777 case VK_FORMAT_R32G32_SFLOAT:
778 case VK_FORMAT_R32G32B32_SFLOAT:
779 case VK_FORMAT_R32G32B32A32_SFLOAT:
780 return false;
781
782 default:
783 return true;
784 }
785}
786
787bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
788 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
789 bool skip = false;
790
791 for (uint32_t i = 0; i < createInfoCount; i++) {
792 auto pCreateInfo = &pCreateInfos[i];
793
794 if (!pCreateInfo->pColorBlendState || !pCreateInfo->pMultisampleState ||
795 pCreateInfo->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
796 pCreateInfo->pMultisampleState->sampleShadingEnable) {
797 return skip;
798 }
799
800 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
801 auto& subpass = rp_state->createInfo.pSubpasses[pCreateInfo->subpass];
802
803 for (uint32_t j = 0; j < pCreateInfo->pColorBlendState->attachmentCount; j++) {
804 auto& blend_att = pCreateInfo->pColorBlendState->pAttachments[j];
805 uint32_t att = subpass.pColorAttachments[j].attachment;
806
807 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
808 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
809 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
810 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
811 "color attachment #%u makes use "
812 "of a format which cannot be blended at full throughput when using MSAA.",
813 VendorSpecificTag(kBPVendorArm), i, j);
814 }
815 }
816 }
817 }
818
819 return skip;
820}
821
Camden5b184be2019-08-13 07:50:19 -0600822bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
823 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600824 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500825 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600826 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
827 pAllocator, pPipelines, cgpl_state_data);
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600828 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600829
830 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700831 skip |= LogPerformanceWarning(
832 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
833 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
834 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600835 }
836
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000837 for (uint32_t i = 0; i < createInfoCount; i++) {
838 auto& createInfo = pCreateInfos[i];
839
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600840 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
841 auto& vertexInput = *createInfo.pVertexInputState;
842 uint32_t count = 0;
843 for (uint32_t j = 0; j < vertexInput.vertexBindingDescriptionCount; j++) {
844 if (vertexInput.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
845 count++;
846 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000847 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600848 if (count > kMaxInstancedVertexBuffers) {
849 skip |= LogPerformanceWarning(
850 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
851 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
852 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
853 count, kMaxInstancedVertexBuffers);
854 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000855 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000856
Szilard Pappaaf2da32020-06-22 10:37:35 +0100857 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
858 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
859 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f)) {
860 skip |= VendorCheckEnabled(kBPVendorArm) &&
861 LogPerformanceWarning(
862 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
863 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
864 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
865 "efficiency during rasterization. Consider disabling depthBias or increasing either "
866 "depthBiasConstantFactor or depthBiasSlopeFactor.",
867 VendorSpecificTag(kBPVendorArm));
868 }
869
Attilio Provenzano02859b22020-02-27 14:17:28 +0000870 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000871 }
872
Camden5b184be2019-08-13 07:50:19 -0600873 return skip;
874}
875
Sam Walls0961ec02020-03-31 16:39:15 +0100876void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
877 const VkGraphicsPipelineCreateInfo* pCreateInfos,
878 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
879 VkResult result, void* cgpl_state_data) {
880 for (size_t i = 0; i < count; i++) {
881 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
882 const VkPipeline pipeline_handle = pPipelines[i];
883
884 // record depth stencil state and color blend states for depth pre-pass tracking purposes
885 auto gp_cis = graphicsPipelineCIs.find(pipeline_handle);
886
887 // add the tracking state if it doesn't exist
888 if (gp_cis == graphicsPipelineCIs.end()) {
889 auto result = graphicsPipelineCIs.emplace(std::make_pair(pipeline_handle, GraphicsPipelineCIs{}));
890
891 if (!result.second) continue;
892
893 gp_cis = result.first;
894 }
895
Tony-LunarG412b1b72020-07-15 10:30:13 -0600896 gp_cis->second.colorBlendStateCI =
897 cgpl_state->pCreateInfos[i].pColorBlendState
898 ? new safe_VkPipelineColorBlendStateCreateInfo(cgpl_state->pCreateInfos[i].pColorBlendState)
899 : nullptr;
900 gp_cis->second.depthStencilStateCI =
901 cgpl_state->pCreateInfos[i].pDepthStencilState
902 ? new safe_VkPipelineDepthStencilStateCreateInfo(cgpl_state->pCreateInfos[i].pDepthStencilState)
903 : nullptr;
Sam Walls0961ec02020-03-31 16:39:15 +0100904 }
905}
906
Camden5b184be2019-08-13 07:50:19 -0600907bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
908 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600909 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500910 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600911 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
912 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600913
914 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700915 skip |= LogPerformanceWarning(
916 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
917 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
918 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600919 }
920
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100921 if (VendorCheckEnabled(kBPVendorArm)) {
922 for (size_t i = 0; i < createInfoCount; i++) {
923 skip |= ValidateCreateComputePipelineArm(pCreateInfos[i]);
924 }
925 }
926
927 return skip;
928}
929
930bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
931 bool skip = false;
932 auto* module = GetShaderModuleState(createInfo.stage.module);
933
934 uint32_t x = 1, y = 1, z = 1;
935 FindLocalSize(module, x, y, z);
936
937 uint32_t thread_count = x * y * z;
938
939 // Generate a priori warnings about work group sizes.
940 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
941 skip |= LogPerformanceWarning(
942 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
943 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
944 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
945 "groups with less than %u threads, especially when using barrier() or shared memory.",
946 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
947 }
948
949 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
950 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
951 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
952 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
953 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
954 "%u, %u) is not aligned to %u "
955 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
956 "leave threads idle on the shader "
957 "core.",
958 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
959 kThreadGroupDispatchCountAlignmentArm);
960 }
961
962 // Generate warnings about work group sizes based on active resources.
963 auto entrypoint = FindEntrypoint(module, createInfo.stage.pName, createInfo.stage.stage);
964 if (entrypoint == module->end()) return false;
965
966 bool has_writeable_descriptors = false;
locke-lunarg63e4daf2020-08-17 17:53:25 -0600967 bool has_atomic_descriptors = false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100968 auto accessible_ids = MarkAccessibleIds(module, entrypoint);
locke-lunarg63e4daf2020-08-17 17:53:25 -0600969 auto descriptor_uses =
970 CollectInterfaceByDescriptorSlot(module, accessible_ids, &has_writeable_descriptors, &has_atomic_descriptors);
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100971
972 unsigned dimensions = 0;
973 if (x > 1) dimensions++;
974 if (y > 1) dimensions++;
975 if (z > 1) dimensions++;
976 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
977 dimensions = std::max(dimensions, 1u);
978
979 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
980 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
981 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
982 bool accesses_2d = false;
983 for (const auto& usage : descriptor_uses) {
984 auto dim = GetShaderResourceDimensionality(module, usage.second);
985 if (dim < 0) continue;
986 auto spvdim = spv::Dim(dim);
987 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
988 }
989
990 if (accesses_2d && dimensions < 2) {
991 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
992 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
993 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
994 "exhibiting poor spatial locality with respect to one or more shader resources.",
995 VendorSpecificTag(kBPVendorArm), x, y, z);
996 }
997
Camden5b184be2019-08-13 07:50:19 -0600998 return skip;
999}
1000
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001001bool BestPractices::CheckPipelineStageFlags(std::string api_name, const VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001002 bool skip = false;
1003
1004 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001005 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1006 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001007 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001008 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1009 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001010 }
1011
1012 return skip;
1013}
1014
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001015void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001016 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1017 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1018 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1019 LogPerformanceWarning(
1020 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1021 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1022 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1023 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1024 "convenient opportunity.",
1025 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1026 }
1027 }
1028}
1029
Jeff Bolz5c801d12019-10-09 10:38:45 -05001030bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1031 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001032 bool skip = false;
1033
1034 for (uint32_t submit = 0; submit < submitCount; submit++) {
1035 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1036 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1037 }
1038 }
1039
1040 return skip;
1041}
1042
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001043bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1044 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1045 bool skip = false;
1046
1047 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1048 skip |= LogPerformanceWarning(
1049 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1050 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1051 "pool instead.");
1052 }
1053
1054 return skip;
1055}
1056
1057bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1058 const VkCommandBufferBeginInfo* pBeginInfo) const {
1059 bool skip = false;
1060
1061 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1062 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1063 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1064 }
1065
Attilio Provenzano02859b22020-02-27 14:17:28 +00001066 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT)) {
1067 skip |= VendorCheckEnabled(kBPVendorArm) &&
1068 LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
1069 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1070 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1071 VendorSpecificTag(kBPVendorArm));
1072 }
1073
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001074 return skip;
1075}
1076
Jeff Bolz5c801d12019-10-09 10:38:45 -05001077bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001078 bool skip = false;
1079
1080 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1081
1082 return skip;
1083}
1084
Jeff Bolz5c801d12019-10-09 10:38:45 -05001085bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1086 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001087 bool skip = false;
1088
1089 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1090
1091 return skip;
1092}
1093
1094bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1095 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1096 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1097 uint32_t bufferMemoryBarrierCount,
1098 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1099 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001100 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001101 bool skip = false;
1102
1103 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1104 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1105
1106 return skip;
1107}
1108
1109bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1110 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1111 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1112 uint32_t bufferMemoryBarrierCount,
1113 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1114 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001115 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001116 bool skip = false;
1117
1118 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1119 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1120
1121 return skip;
1122}
1123
1124bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001125 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001126 bool skip = false;
1127
1128 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", pipelineStage);
1129
1130 return skip;
1131}
1132
Sam Walls0961ec02020-03-31 16:39:15 +01001133void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1134 VkPipeline pipeline) {
1135 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1136
1137 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1138 // check for depth/blend state tracking
1139 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1140 if (gp_cis != graphicsPipelineCIs.end()) {
1141 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1142 if (prepass_state == cbDepthPrePassStates.end()) {
1143 auto result = cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1144
1145 if (!result.second) return;
1146
1147 prepass_state = result.first;
1148 }
1149
1150 const auto* blend_state = gp_cis->second.colorBlendStateCI;
1151 const auto* stencil_state = gp_cis->second.depthStencilStateCI;
1152
1153 if (blend_state) {
1154 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
1155 prepass_state->second.depthOnly = true;
1156 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1157 if (blend_state->pAttachments[i].colorWriteMask != 0) {
1158 prepass_state->second.depthOnly = false;
1159 }
1160 }
1161 }
1162
1163 // check for depth value usage
1164 prepass_state->second.depthEqualComparison = false;
1165
1166 if (stencil_state && stencil_state->depthTestEnable) {
1167 switch (stencil_state->depthCompareOp) {
1168 case VK_COMPARE_OP_EQUAL:
1169 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1170 case VK_COMPARE_OP_LESS_OR_EQUAL:
1171 prepass_state->second.depthEqualComparison = true;
1172 break;
1173 default:
1174 break;
1175 }
1176 }
1177 } else {
1178 // reset depth pre-pass tracking
1179 cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1180 }
1181 }
1182}
1183
Attilio Provenzano02859b22020-02-27 14:17:28 +00001184static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1185 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1186 auto& subpassInfo = createInfo.pSubpasses[subpass];
1187
1188 // If an attachment is ever used as a color attachment,
1189 // resolve attachment or depth stencil attachment,
1190 // it needs to exist on tile at some point.
1191
1192 for (uint32_t i = 0; i < subpassInfo.colorAttachmentCount; i++)
1193 if (subpassInfo.pColorAttachments[i].attachment == attachment) return true;
1194
1195 if (subpassInfo.pResolveAttachments) {
1196 for (uint32_t i = 0; i < subpassInfo.colorAttachmentCount; i++)
1197 if (subpassInfo.pResolveAttachments[i].attachment == attachment) return true;
1198 }
1199
1200 if (subpassInfo.pDepthStencilAttachment && subpassInfo.pDepthStencilAttachment->attachment == attachment) return true;
1201 }
1202
1203 return false;
1204}
1205
1206bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1207 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1208 bool skip = false;
1209
1210 if (!pRenderPassBegin) {
1211 return skip;
1212 }
1213
1214 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1215 if (rp_state) {
Tony-LunarG767180f2020-04-23 14:03:59 -06001216 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR) {
1217 const VkRenderPassAttachmentBeginInfo* rpabi =
1218 lvl_find_in_chain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1219 if (rpabi) {
1220 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1221 }
1222 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001223 // Check if any attachments have LOAD operation on them
1224 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1225 auto& attachment = rp_state->createInfo.pAttachments[att];
1226
1227 bool attachmentHasReadback = false;
1228 if (!FormatHasStencil(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1229 attachmentHasReadback = true;
1230 }
1231
1232 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1233 attachmentHasReadback = true;
1234 }
1235
1236 bool attachmentNeedsReadback = false;
1237
1238 // Check if the attachment is actually used in any subpass on-tile
1239 if (attachmentHasReadback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1240 attachmentNeedsReadback = true;
1241 }
1242
1243 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
1244 if (attachmentNeedsReadback) {
1245 skip |= VendorCheckEnabled(kBPVendorArm) &&
1246 LogPerformanceWarning(
1247 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1248 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1249 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
1250 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
1251 VendorSpecificTag(kBPVendorArm), att,
1252 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1253 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1254 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
1255 }
1256 }
1257 }
1258
1259 return skip;
1260}
1261
1262bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1263 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001264 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1265 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001266 return skip;
1267}
1268
1269bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1270 const VkRenderPassBeginInfo* pRenderPassBegin,
1271 const VkSubpassBeginInfoKHR* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001272 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1273 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001274 return skip;
1275}
1276
1277bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1278 const VkSubpassBeginInfoKHR* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001279 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1280 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001281 return skip;
1282}
1283
Sam Walls0961ec02020-03-31 16:39:15 +01001284void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1285 const VkRenderPassBeginInfo* pRenderPassBegin) {
1286 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1287
1288 // add the tracking state if it doesn't exist
1289 if (prepass_state == cbDepthPrePassStates.end()) {
1290 auto result = cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1291
1292 if (!result.second) return;
1293
1294 prepass_state = result.first;
1295 }
1296
1297 // reset the renderpass state
1298 prepass_state->second = {};
1299
1300 const auto* cb_state = GetCBState(commandBuffer);
locke-lunargaecf2152020-05-12 17:15:41 -06001301 const auto* rp_state = cb_state->activeRenderPass.get();
Sam Walls0961ec02020-03-31 16:39:15 +01001302
1303 // track depth / color attachment usage within the renderpass
1304 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1305 // record if depth/color attachments are in use for this renderpass
1306 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) prepass_state->second.depthAttachment = true;
1307
1308 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) prepass_state->second.colorAttachment = true;
1309 }
1310}
1311
1312void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1313 VkSubpassContents contents) {
1314 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1315 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1316}
1317
1318void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1319 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1320 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1321 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1322}
1323
1324void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1325 const VkRenderPassBeginInfo* pRenderPassBegin,
1326 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1327 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1328 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1329}
1330
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001331// Generic function to handle validation for all CmdDraw* type functions
1332bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1333 bool skip = false;
1334 const CMD_BUFFER_STATE* cb_state = GetCBState(cmd_buffer);
1335 if (cb_state) {
1336 const auto last_bound_it = cb_state->lastBound.find(VK_PIPELINE_BIND_POINT_GRAPHICS);
1337 const PIPELINE_STATE* pipeline_state = nullptr;
1338 if (last_bound_it != cb_state->lastBound.cend()) {
1339 pipeline_state = last_bound_it->second.pipeline_state;
1340 }
1341 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
1342 // Verify vertex binding
1343 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1344 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001345 skip |= LogPerformanceWarning(cb_state->commandBuffer, kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
1346 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
1347 report_data->FormatHandle(cb_state->commandBuffer).c_str(),
1348 report_data->FormatHandle(pipeline_state->pipeline).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001349 }
1350 }
1351 }
1352 return skip;
1353}
1354
Sam Walls0961ec02020-03-31 16:39:15 +01001355void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1356 if (VendorCheckEnabled(kBPVendorArm)) {
1357 RecordCmdDrawTypeArm(cmd_buffer, draw_count, caller);
1358 }
1359}
1360
1361void BestPractices::RecordCmdDrawTypeArm(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1362 auto prepass_state = cbDepthPrePassStates.find(cmd_buffer);
1363 if (prepass_state != cbDepthPrePassStates.end() && draw_count >= kDepthPrePassMinDrawCountArm) {
1364 if (prepass_state->second.depthOnly) prepass_state->second.numDrawCallsDepthOnly++;
1365
1366 if (prepass_state->second.depthEqualComparison) prepass_state->second.numDrawCallsDepthEqualCompare++;
1367 }
1368}
1369
Camden5b184be2019-08-13 07:50:19 -06001370bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001371 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001372 bool skip = false;
1373
1374 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001375 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1376 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001377 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001378 }
1379
1380 return skip;
1381}
1382
Sam Walls0961ec02020-03-31 16:39:15 +01001383void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1384 uint32_t firstVertex, uint32_t firstInstance) {
1385 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
1386 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
1387}
1388
Camden5b184be2019-08-13 07:50:19 -06001389bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001390 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001391 bool skip = false;
1392
1393 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001394 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1395 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001396 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001397 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1398
Attilio Provenzano02859b22020-02-27 14:17:28 +00001399 // Check if we reached the limit for small indexed draw calls.
1400 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1401 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1402 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
1403 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1)) {
1404 skip |= VendorCheckEnabled(kBPVendorArm) &&
1405 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
1406 "The command buffer contains many small indexed drawcalls "
1407 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1408 "You can try batching drawcalls or instancing when applicable.",
1409 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1410 }
1411
Sam Walls8e77e4f2020-03-16 20:47:40 +00001412 if (VendorCheckEnabled(kBPVendorArm)) {
1413 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1414 }
1415
1416 return skip;
1417}
1418
1419bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1420 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1421 bool skip = false;
1422
1423 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1424 const auto* cmd_state = GetCBState(commandBuffer);
1425 if (cmd_state == nullptr) return skip;
1426
1427 const auto* ib_state = GetBufferState(cmd_state->index_buffer_binding.buffer);
1428 if (ib_state == nullptr) return skip;
1429
1430 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
1431 const auto& ib_mem_state = *ib_state->binding.mem_state;
1432 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1433 const void* ib_mem = ib_mem_state.p_driver_data;
1434 bool primitive_restart_enable = false;
1435
1436 const auto& pipeline_binding_iter = cmd_state->lastBound.find(VK_PIPELINE_BIND_POINT_GRAPHICS);
1437
1438 if (pipeline_binding_iter != cmd_state->lastBound.end()) {
1439 const auto* pipeline_state = pipeline_binding_iter->second.pipeline_state;
1440 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr)
1441 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
1442 }
1443
1444 // no point checking index buffer if the memory is nonexistant/unmapped, or if there is no graphics pipeline bound to this CB
1445 if (ib_mem && pipeline_binding_iter != cmd_state->lastBound.end()) {
1446 uint32_t scan_stride;
1447 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1448 scan_stride = sizeof(uint8_t);
1449 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1450 scan_stride = sizeof(uint16_t);
1451 } else {
1452 scan_stride = sizeof(uint32_t);
1453 }
1454
1455 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1456 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1457
1458 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1459 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1460 // irrespective of whether or not they're part of the draw call.
1461
1462 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1463 uint32_t min_index = ~0u;
1464 // start with maximum as 0 and adjust to indices in the buffer
1465 uint32_t max_index = 0u;
1466
1467 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
1468 // for the given index buffer
1469 uint32_t vertex_shade_count = 0;
1470
1471 PostTransformLRUCacheModel post_transform_cache;
1472
1473 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
1474 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
1475 // target architecture.
1476 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
1477 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
1478 post_transform_cache.resize(32);
1479
1480 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1481 uint32_t scan_index;
1482 uint32_t primitive_restart_value;
1483 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1484 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1485 primitive_restart_value = 0xFF;
1486 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1487 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1488 primitive_restart_value = 0xFFFF;
1489 } else {
1490 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1491 primitive_restart_value = 0xFFFFFFFF;
1492 }
1493
1494 max_index = std::max(max_index, scan_index);
1495 min_index = std::min(min_index, scan_index);
1496
1497 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
1498 bool in_cache = post_transform_cache.query_cache(scan_index);
1499 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
1500 if (!in_cache) vertex_shade_count++;
1501 }
1502 }
1503
1504 // 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 +01001505 // 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
1506 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001507
1508 if (max_index - min_index >= indexCount) {
1509 skip |= LogPerformanceWarning(
1510 device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1511 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
1512 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
1513 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
1514 "maximum would be loaded, and possibly shaded, whether or not they are used.",
1515 VendorSpecificTag(kBPVendorArm), (static_cast<float>(indexCount) / (max_index - min_index)) * 100.0f);
1516 return skip;
1517 }
1518
1519 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
1520 // 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 +01001521 const size_t refs_per_bucket = 64;
1522 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
1523
1524 const uint32_t n_indices = max_index - min_index + 1;
1525 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
1526 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
1527
1528 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
1529 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00001530
1531 // To avoid using too much memory, we run over the indices again.
1532 // Knowing the size from the last scan allows us to record index usage with bitsets
1533 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1534 uint32_t scan_index;
1535 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1536 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1537 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1538 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1539 } else {
1540 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1541 }
1542 // keep track of the set of all indices used to reference vertices in the draw call
1543 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01001544 size_t bitset_bucket_index = index_offset / refs_per_bucket;
1545 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001546 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
1547 }
1548
1549 uint32_t vertex_reference_count = 0;
1550 for (const auto& bitset : vertex_reference_buckets) {
1551 vertex_reference_count += static_cast<uint32_t>(bitset.count());
1552 }
1553
1554 // low index buffer utilization implies that: of the vertices available to the draw call, not all are utilized
1555 float utilization = static_cast<float>(vertex_reference_count) / (max_index - min_index + 1);
1556 // low hit rate (high miss rate) implies the order of indices in the draw call may be possible to improve
1557 float cache_hit_rate = static_cast<float>(vertex_reference_count) / vertex_shade_count;
1558
1559 if (utilization < 0.5f) {
1560 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1561 "%s The indices which were specified for the draw call only utilise approximately "
1562 "%.02f%% of the bound vertex buffer.",
1563 VendorSpecificTag(kBPVendorArm), utilization);
1564 }
1565
1566 if (cache_hit_rate <= 0.5f) {
1567 skip |=
1568 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
1569 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
1570 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
1571 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
1572 "recently shaded vertices.",
1573 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
1574 }
1575 }
1576
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001577 return skip;
1578}
1579
Attilio Provenzano02859b22020-02-27 14:17:28 +00001580void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1581 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1582 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
1583 firstInstance);
1584
1585 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1586 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
1587 cmd_state->small_indexed_draw_call_count++;
1588 }
1589}
1590
Sam Walls0961ec02020-03-31 16:39:15 +01001591void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1592 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1593 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1594 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
1595}
1596
sfricke-samsung681ab7b2020-10-29 01:53:35 -07001597bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1598 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
1599 uint32_t maxDrawCount, uint32_t stride) const {
1600 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
1601
1602 return skip;
1603}
1604
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001605bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
1606 VkDeviceSize offset, VkBuffer countBuffer,
1607 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
1608 uint32_t stride) const {
1609 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06001610
1611 return skip;
1612}
1613
1614bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001615 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001616 bool skip = false;
1617
1618 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001619 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1620 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001621 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001622 }
1623
1624 return skip;
1625}
1626
Sam Walls0961ec02020-03-31 16:39:15 +01001627void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1628 uint32_t count, uint32_t stride) {
1629 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
1630 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
1631}
1632
Camden5b184be2019-08-13 07:50:19 -06001633bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001634 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001635 bool skip = false;
1636
1637 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001638 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1639 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001640 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001641 }
1642
1643 return skip;
1644}
1645
Sam Walls0961ec02020-03-31 16:39:15 +01001646void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1647 uint32_t count, uint32_t stride) {
1648 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
1649 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
1650}
1651
Camden5b184be2019-08-13 07:50:19 -06001652bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001653 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06001654 bool skip = false;
1655
1656 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001657 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
1658 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
1659 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
1660 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06001661 }
1662
1663 return skip;
1664}
Camden83a9c372019-08-14 11:41:38 -06001665
Sam Walls0961ec02020-03-31 16:39:15 +01001666bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
1667 bool skip = false;
1668
1669 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
1670
1671 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1672
1673 if (prepass_state == cbDepthPrePassStates.end()) return skip;
1674
1675 bool uses_depth = (prepass_state->second.depthAttachment || prepass_state->second.colorAttachment) &&
1676 prepass_state->second.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
1677 prepass_state->second.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
1678 if (uses_depth) {
1679 skip |= LogPerformanceWarning(
1680 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
1681 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
1682 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
1683 "case, using depth pre-passes for hidden surface removal may worsen performance.",
1684 VendorSpecificTag(kBPVendorArm));
1685 }
1686
1687 return skip;
1688}
1689
Camden Stocker9c051442019-11-06 14:28:43 -08001690bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
1691 const char* api_name) const {
1692 bool skip = false;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001693 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08001694
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001695 if (bp_pd_state) {
1696 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
1697 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
1698 "Potential problem with calling %s() without first retrieving properties from "
1699 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
1700 api_name);
1701 }
Camden Stocker9c051442019-11-06 14:28:43 -08001702 }
1703
1704 return skip;
1705}
1706
Camden83a9c372019-08-14 11:41:38 -06001707bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001708 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06001709 bool skip = false;
1710
Camden Stocker9c051442019-11-06 14:28:43 -08001711 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06001712
Camden Stocker9c051442019-11-06 14:28:43 -08001713 return skip;
1714}
1715
1716bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
1717 uint32_t planeIndex,
1718 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
1719 bool skip = false;
1720
1721 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
1722
1723 return skip;
1724}
1725
1726bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
1727 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
1728 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
1729 bool skip = false;
1730
1731 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06001732
1733 return skip;
1734}
Camden05de2d42019-08-19 10:23:56 -06001735
1736bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001737 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06001738 bool skip = false;
1739
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001740 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
Camden05de2d42019-08-19 10:23:56 -06001741
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001742 if ((swapchain_state_itr != swapchain_bp_state_map.cend()) && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06001743 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001744 if (swapchain_state_itr->second.vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001745 skip |=
1746 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
1747 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
1748 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06001749 }
1750 }
1751
1752 return skip;
1753}
1754
1755// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001756bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
1757 uint32_t requested_queue_family_property_count,
1758 bool qfp_null, const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06001759 bool skip = false;
1760 if (!qfp_null) {
1761 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001762 const auto* bp_pd_state = GetPhysicalDeviceStateBP(pd_state->phys_device);
1763 if (bp_pd_state) {
1764 if (UNCALLED == bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState) {
1765 skip |= LogWarning(
1766 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
1767 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
1768 "recommended "
1769 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
1770 caller_name, caller_name);
1771 // Then verify that pCount that is passed in on second call matches what was returned
1772 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
1773 skip |=
1774 LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
1775 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
1776 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
1777 ". It is recommended to instead receive all the properties by calling %s with "
1778 "pQueueFamilyPropertyCount that was "
1779 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
1780 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
1781 caller_name);
1782 }
Camden05de2d42019-08-19 10:23:56 -06001783 }
1784 }
1785
1786 return skip;
1787}
1788
Jeff Bolz5c801d12019-10-09 10:38:45 -05001789bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
1790 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06001791 bool skip = false;
1792
1793 for (uint32_t i = 0; i < bindInfoCount; i++) {
1794 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureState(pBindInfos[i].accelerationStructure);
1795 if (!as_state->memory_requirements_checked) {
1796 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
1797 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
1798 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001799 skip |= LogWarning(
1800 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06001801 "vkBindAccelerationStructureMemoryNV(): "
1802 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
1803 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
1804 }
1805 }
1806
1807 return skip;
1808}
1809
Camden05de2d42019-08-19 10:23:56 -06001810bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
1811 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001812 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001813 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1814 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001815 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001816 (nullptr == pQueueFamilyProperties),
1817 "vkGetPhysicalDeviceQueueFamilyProperties()");
1818}
1819
Jeff Bolz5c801d12019-10-09 10:38:45 -05001820bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(
1821 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount,
1822 VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001823 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1824 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001825 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001826 (nullptr == pQueueFamilyProperties),
1827 "vkGetPhysicalDeviceQueueFamilyProperties2()");
1828}
1829
Jeff Bolz5c801d12019-10-09 10:38:45 -05001830bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
1831 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount,
1832 VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001833 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1834 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001835 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001836 (nullptr == pQueueFamilyProperties),
1837 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
1838}
1839
1840bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
1841 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001842 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06001843 if (!pSurfaceFormats) return false;
1844 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001845 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
1846 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06001847 bool skip = false;
1848 if (call_state == UNCALLED) {
1849 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
1850 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001851 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
1852 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
1853 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06001854 } else {
1855 auto prev_format_count = (uint32_t)physical_device_state->surface_formats.size();
Peter Chene191bd72019-09-16 13:04:37 -04001856 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001857 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
1858 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
1859 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
1860 "when pSurfaceFormatCount was NULL.",
1861 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06001862 }
1863 }
1864 return skip;
1865}
Camden Stocker23cc47d2019-09-03 14:53:57 -06001866
1867bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001868 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001869 bool skip = false;
1870
1871 for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; bindIdx++) {
1872 const VkBindSparseInfo& bindInfo = pBindInfo[bindIdx];
1873 // 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 -05001874 std::unordered_set<const IMAGE_STATE*> sparse_images;
1875 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
1876 // in RecordQueueBindSparse.
1877 std::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06001878 // If we're binding sparse image memory make sure reqs were queried and note if metadata is required and bound
1879 for (uint32_t i = 0; i < bindInfo.imageBindCount; ++i) {
1880 const auto& image_bind = bindInfo.pImageBinds[i];
1881 auto image_state = GetImageState(image_bind.image);
1882 if (!image_state)
1883 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1884 sparse_images.insert(image_state);
1885 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1886 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1887 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001888 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1889 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1890 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1891 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001892 }
1893 }
1894 if (!image_state->memory_requirements_checked) {
1895 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001896 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1897 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1898 "vkGetImageMemoryRequirements() to retrieve requirements.",
1899 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001900 }
1901 }
1902 for (uint32_t i = 0; i < bindInfo.imageOpaqueBindCount; ++i) {
1903 const auto& image_opaque_bind = bindInfo.pImageOpaqueBinds[i];
1904 auto image_state = GetImageState(bindInfo.pImageOpaqueBinds[i].image);
1905 if (!image_state)
1906 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1907 sparse_images.insert(image_state);
1908 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1909 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1910 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001911 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1912 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1913 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1914 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001915 }
1916 }
1917 if (!image_state->memory_requirements_checked) {
1918 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001919 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1920 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1921 "vkGetImageMemoryRequirements() to retrieve requirements.",
1922 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001923 }
1924 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1925 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001926 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06001927 }
1928 }
1929 }
1930 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001931 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
1932 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001933 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001934 skip |= LogWarning(sparse_image_state->image, kVUID_Core_MemTrack_InvalidState,
1935 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
1936 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
1937 report_data->FormatHandle(sparse_image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001938 }
1939 }
1940 }
1941
1942 return skip;
1943}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001944
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001945void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
1946 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001947 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001948 return;
1949 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001950
1951 for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; bindIdx++) {
1952 const VkBindSparseInfo& bindInfo = pBindInfo[bindIdx];
1953 for (uint32_t i = 0; i < bindInfo.imageOpaqueBindCount; ++i) {
1954 const auto& image_opaque_bind = bindInfo.pImageOpaqueBinds[i];
1955 auto image_state = GetImageState(bindInfo.pImageOpaqueBinds[i].image);
1956 if (!image_state)
1957 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1958 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1959 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
1960 image_state->sparse_metadata_bound = true;
1961 }
1962 }
1963 }
1964 }
1965}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001966
1967bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06001968 const VkClearAttachment* pAttachments, uint32_t rectCount,
1969 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001970 bool skip = false;
1971 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
1972 if (!cb_node) return skip;
1973
Camden Stockerf55721f2019-09-09 11:04:49 -06001974 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001975 if (!cb_node->hasDrawCmd && (cb_node->activeRenderPassBeginInfo.renderArea.extent.width == pRects[0].rect.extent.width) &&
1976 (cb_node->activeRenderPassBeginInfo.renderArea.extent.height == pRects[0].rect.extent.height)) {
1977 // There are times where app needs to use ClearAttachments (generally when reusing a buffer inside of a render pass)
1978 // This warning should be made more specific. It'd be best to avoid triggering this test if it's a use that must call
1979 // CmdClearAttachments.
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001980 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
1981 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds. It is recommended you "
1982 "use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
1983 report_data->FormatHandle(commandBuffer).c_str());
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001984 }
1985
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001986 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
1987 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06001988 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001989 if (rp) {
1990 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
1991
1992 for (uint32_t i = 0; i < attachmentCount; i++) {
1993 auto& attachment = pAttachments[i];
1994 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
1995 uint32_t color_attachment = attachment.colorAttachment;
1996 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
1997
1998 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
1999 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2000 skip |= LogPerformanceWarning(
2001 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2002 "vkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
2003 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2004 "it is more efficient.",
2005 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
2006 }
2007 }
2008 }
2009
2010 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
2011 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2012
2013 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2014 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2015 skip |= LogPerformanceWarning(
2016 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2017 "vkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
2018 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2019 "it is more efficient.",
2020 report_data->FormatHandle(commandBuffer).c_str());
2021 }
2022 }
2023 }
2024
2025 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
2026 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2027
2028 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2029 if (rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2030 skip |= LogPerformanceWarning(
2031 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2032 "vkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
2033 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2034 "it is more efficient.",
2035 report_data->FormatHandle(commandBuffer).c_str());
2036 }
2037 }
2038 }
2039 }
2040 }
2041
Camden Stockerf55721f2019-09-09 11:04:49 -06002042 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002043}
Attilio Provenzano02859b22020-02-27 14:17:28 +00002044
2045bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2046 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2047 const VkImageResolve* pRegions) const {
2048 bool skip = false;
2049
2050 skip |= VendorCheckEnabled(kBPVendorArm) &&
2051 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
2052 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
2053 "This is a very slow and extremely bandwidth intensive path. "
2054 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2055 VendorSpecificTag(kBPVendorArm));
2056
2057 return skip;
2058}
2059
Jeff Leger178b1e52020-10-05 12:22:23 -04002060bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2061 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
2062 bool skip = false;
2063
2064 skip |= VendorCheckEnabled(kBPVendorArm) &&
2065 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
2066 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
2067 "This is a very slow and extremely bandwidth intensive path. "
2068 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2069 VendorSpecificTag(kBPVendorArm));
2070
2071 return skip;
2072}
2073
Attilio Provenzano02859b22020-02-27 14:17:28 +00002074bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
2075 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
2076 bool skip = false;
2077
2078 if (VendorCheckEnabled(kBPVendorArm)) {
2079 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
2080 skip |= LogPerformanceWarning(
2081 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
2082 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
2083 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
2084 "image) are actually used. If you need different wrapping modes, disregard this warning.",
2085 VendorSpecificTag(kBPVendorArm));
2086 }
2087
2088 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
2089 skip |= LogPerformanceWarning(
2090 device, kVUID_BestPractices_CreateSampler_LodClamping,
2091 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
2092 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
2093 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
2094 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
2095 }
2096
2097 if (pCreateInfo->mipLodBias != 0.0f) {
2098 skip |=
2099 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
2100 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
2101 "descriptors being created and may cause reduced performance.",
2102 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
2103 }
2104
2105 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2106 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2107 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
2108 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
2109 skip |= LogPerformanceWarning(
2110 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
2111 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
2112 "This will lead to less efficient descriptors being created and may cause reduced performance. "
2113 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
2114 VendorSpecificTag(kBPVendorArm));
2115 }
2116
2117 if (pCreateInfo->unnormalizedCoordinates) {
2118 skip |= LogPerformanceWarning(
2119 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
2120 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
2121 "descriptors being created and may cause reduced performance.",
2122 VendorSpecificTag(kBPVendorArm));
2123 }
2124
2125 if (pCreateInfo->anisotropyEnable) {
2126 skip |= LogPerformanceWarning(
2127 device, kVUID_BestPractices_CreateSampler_Anisotropy,
2128 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
2129 "and may cause reduced performance.",
2130 VendorSpecificTag(kBPVendorArm));
2131 }
2132 }
2133
2134 return skip;
2135}
Sam Walls8e77e4f2020-03-16 20:47:40 +00002136
2137void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
2138
2139bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
2140 // look for a cache hit
2141 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
2142 if (hit != _entries.end()) {
2143 // mark the cache hit as being most recently used
2144 hit->age = iteration++;
2145 return true;
2146 }
2147
2148 // if there's no cache hit, we need to model the entry being inserted into the cache
2149 CacheEntry new_entry = {value, iteration};
2150 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
2151 // if there is still space left in the cache, use the next available slot
2152 *(_entries.begin() + iteration) = new_entry;
2153 } else {
2154 // otherwise replace the least recently used cache entry
2155 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
2156 *lru = new_entry;
2157 }
2158 iteration++;
2159 return false;
2160}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002161
2162bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
2163 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
2164 const auto swapchain_data = GetSwapchainState(swapchain);
2165 bool skip = false;
2166 if (swapchain_data && swapchain_data->images.size() == 0) {
2167 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
2168 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
2169 "vkGetSwapchainImagesKHR after swapchain creation.");
2170 }
2171 return skip;
2172}
2173
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002174void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2175 uint32_t* pQueueFamilyPropertyCount,
2176 VkQueueFamilyProperties* pQueueFamilyProperties) {
2177 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
2178 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002179 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002180 if (bp_pd_state) {
2181 if (!pQueueFamilyProperties) {
2182 if (UNCALLED == bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState)
2183 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState = QUERY_COUNT;
2184 } else { // Save queue family properties
2185 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState = QUERY_DETAILS;
2186 }
2187 }
2188}
2189
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002190void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
2191 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002192 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2193 if (bp_pd_state) {
2194 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2195 }
2196}
2197
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002198void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
2199 VkPhysicalDeviceFeatures2* pFeatures) {
2200 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002201 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2202 if (bp_pd_state) {
2203 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2204 }
2205}
2206
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002207void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
2208 VkPhysicalDeviceFeatures2* pFeatures) {
2209 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002210 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2211 if (bp_pd_state) {
2212 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2213 }
2214}
2215
2216void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
2217 VkSurfaceKHR surface,
2218 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
2219 VkResult result) {
2220 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2221 if (bp_pd_state) {
2222 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2223 }
2224}
2225
2226void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
2227 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2228 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
2229 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2230 if (bp_pd_state) {
2231 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2232 }
2233}
2234
2235void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
2236 VkSurfaceKHR surface,
2237 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
2238 VkResult result) {
2239 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2240 if (bp_pd_state) {
2241 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2242 }
2243}
2244
2245void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
2246 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
2247 VkPresentModeKHR* pPresentModes, VkResult result) {
2248 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2249 if (bp_pd_data) {
2250 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
2251
2252 if (*pPresentModeCount) {
2253 if (call_state < QUERY_COUNT) {
2254 call_state = QUERY_COUNT;
2255 }
2256 }
2257 if (pPresentModes) {
2258 if (call_state < QUERY_DETAILS) {
2259 call_state = QUERY_DETAILS;
2260 }
2261 }
2262 }
2263}
2264
2265void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2266 uint32_t* pSurfaceFormatCount,
2267 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
2268 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2269 if (bp_pd_data) {
2270 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
2271
2272 if (*pSurfaceFormatCount) {
2273 if (call_state < QUERY_COUNT) {
2274 call_state = QUERY_COUNT;
2275 }
2276 }
2277 if (pSurfaceFormats) {
2278 if (call_state < QUERY_DETAILS) {
2279 call_state = QUERY_DETAILS;
2280 }
2281 }
2282 }
2283}
2284
2285void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
2286 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2287 uint32_t* pSurfaceFormatCount,
2288 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
2289 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2290 if (bp_pd_data) {
2291 if (*pSurfaceFormatCount) {
2292 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
2293 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
2294 }
2295 }
2296 if (pSurfaceFormats) {
2297 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
2298 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
2299 }
2300 }
2301 }
2302}
2303
2304void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
2305 uint32_t* pPropertyCount,
2306 VkDisplayPlanePropertiesKHR* pProperties,
2307 VkResult result) {
2308 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2309 if (bp_pd_data) {
2310 if (*pPropertyCount) {
2311 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
2312 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
2313 }
2314 }
2315 if (pProperties) {
2316 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
2317 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
2318 }
2319 }
2320 }
2321}
2322
2323void BestPractices::ManualPostCallRecordCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
2324 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain,
2325 VkResult result) {
2326 if (VK_SUCCESS == result) {
2327 swapchain_bp_state_map.emplace(*pSwapchain, SWAPCHAIN_STATE_BP{});
2328 }
2329}
2330
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002331void BestPractices::PostCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain,
2332 const VkAllocationCallbacks* pAllocator) {
2333 ValidationStateTracker::PostCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002334 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2335 if (swapchain_state_itr != swapchain_bp_state_map.cend()) {
2336 swapchain_bp_state_map.erase(swapchain_state_itr);
2337 }
2338}
2339
2340void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
2341 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
2342 VkResult result) {
2343 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2344 assert(swapchain_state_itr != swapchain_bp_state_map.cend());
2345 auto& swapchain_state = swapchain_state_itr->second;
2346 if (pSwapchainImages || *pSwapchainImageCount) {
2347 if (swapchain_state.vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
2348 swapchain_state.vkGetSwapchainImagesKHRState = QUERY_DETAILS;
2349 }
2350 }
2351}
2352
2353void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
2354 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
2355 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
2356 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
2357 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
2358 }
2359 }
2360}
2361
2362void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo*, const VkAllocationCallbacks*,
2363 VkDevice*, VkResult result) {
2364 if (VK_SUCCESS == result) {
2365 instance_device_bp_state = &phys_device_bp_state_map[gpu];
2366 }
2367}
2368
2369PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
2370 if (phys_device_bp_state_map.count(phys_device) > 0) {
2371 return &phys_device_bp_state_map.at(phys_device);
2372 } else {
2373 return nullptr;
2374 }
2375}
2376
2377const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
2378 if (phys_device_bp_state_map.count(phys_device) > 0) {
2379 return &phys_device_bp_state_map.at(phys_device);
2380 } else {
2381 return nullptr;
2382 }
2383}
2384
2385PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
2386 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2387 if (bp_state) {
2388 return bp_state;
2389 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2390 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2391 } else {
2392 return nullptr;
2393 }
2394}
2395
2396const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
2397 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2398 if (bp_state) {
2399 return bp_state;
2400 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2401 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2402 } else {
2403 return nullptr;
2404 }
2405}