blob: f41a048fae9e7412978c36602da6484456b02942 [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"
Camden5b184be2019-08-13 07:50:19 -060023
24#include <string>
25#include <iomanip>
Sam Walls8e77e4f2020-03-16 20:47:40 +000026#include <bitset>
Camden5b184be2019-08-13 07:50:19 -060027
28// get the API name is proper format
Jeff Bolz46c0ea02019-10-09 13:06:29 -050029std::string BestPractices::GetAPIVersionName(uint32_t version) const {
Camden5b184be2019-08-13 07:50:19 -060030 std::stringstream version_name;
31 uint32_t major = VK_VERSION_MAJOR(version);
32 uint32_t minor = VK_VERSION_MINOR(version);
33 uint32_t patch = VK_VERSION_PATCH(version);
34
35 version_name << major << "." << minor << "." << patch << " (0x" << std::setfill('0') << std::setw(8) << std::hex << version
36 << ")";
37
38 return version_name.str();
39}
40
Attilio Provenzano19d6a982020-02-27 12:41:41 +000041struct VendorSpecificInfo {
42 bool CHECK_ENABLED::*check;
43 std::string name;
44};
45
46const std::map<BPVendorFlagBits, VendorSpecificInfo> vendor_info = {
47 {kBPVendorArm, {&CHECK_ENABLED::vendor_specific_arm, "Arm"}},
48};
49
50bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
51 for (const auto& vendor : vendor_info) {
52 if (vendors & vendor.first && enabled.*(vendor.second.check)) {
53 return true;
54 }
55 }
56 return false;
57}
58
59const char* VendorSpecificTag(BPVendorFlags vendors) {
60 // Cache built vendor tags in a map
61 static std::unordered_map<BPVendorFlags, std::string> tag_map;
62
63 auto res = tag_map.find(vendors);
64 if (res == tag_map.end()) {
65 // Build the vendor tag string
66 std::stringstream vendor_tag;
67
68 vendor_tag << "[";
69 bool first_vendor = true;
70 for (const auto& vendor : vendor_info) {
71 if (vendors & vendor.first) {
72 if (!first_vendor) {
73 vendor_tag << ", ";
74 }
75 vendor_tag << vendor.second.name;
76 first_vendor = false;
77 }
78 }
79 vendor_tag << "]";
80
81 tag_map[vendors] = vendor_tag.str();
82 res = tag_map.find(vendors);
83 }
84
85 return res->second.c_str();
86}
87
Mark Lobodzinski6167e102020-02-24 17:03:55 -070088const char* DepReasonToString(ExtDeprecationReason reason) {
89 switch (reason) {
90 case kExtPromoted:
91 return "promoted to";
92 break;
93 case kExtObsoleted:
94 return "obsoleted by";
95 break;
96 case kExtDeprecated:
97 return "deprecated by";
98 break;
99 default:
100 return "";
101 break;
102 }
103}
104
105bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
106 const char* vuid) const {
107 bool skip = false;
108 auto dep_info_it = deprecated_extensions.find(extension_name);
109 if (dep_info_it != deprecated_extensions.end()) {
110 auto dep_info = dep_info_it->second;
111 if ((dep_info.target.compare("VK_VERSION_1_1") && (version >= VK_VERSION_1_1)) ||
112 (dep_info.target.compare("VK_VERSION_1_2") && (version >= VK_VERSION_1_2))) {
113 skip |=
114 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
115 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
116 } else if (!dep_info.target.find("VK_VERSION")) {
117 if (dep_info.target.length() == 0) {
118 skip |= LogWarning(instance, vuid,
119 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
120 "without replacement.",
121 api_name, extension_name);
122 } else {
123 skip |= LogWarning(instance, vuid,
124 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
125 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
126 }
127 }
128 }
129 return skip;
130}
131
Camden5b184be2019-08-13 07:50:19 -0600132bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500133 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600134 bool skip = false;
135
136 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
137 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800138 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700139 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
140 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600141 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700142 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i],
143 pCreateInfo->pApplicationInfo->apiVersion,
144 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Camden5b184be2019-08-13 07:50:19 -0600145 }
146
147 return skip;
148}
149
150void BestPractices::PreCallRecordCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
151 VkInstance* pInstance) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700152 ValidationStateTracker::PreCallRecordCreateInstance(pCreateInfo, pAllocator, pInstance);
Camden5b184be2019-08-13 07:50:19 -0600153 instance_api_version = pCreateInfo->pApplicationInfo->apiVersion;
154}
155
156bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500157 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600158 bool skip = false;
159
160 // get API version of physical device passed when creating device.
161 VkPhysicalDeviceProperties physical_device_properties{};
162 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500163 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600164
165 // check api versions and warn if instance api Version is higher than version on device.
166 if (instance_api_version > device_api_version) {
167 std::string inst_api_name = GetAPIVersionName(instance_api_version);
168 std::string dev_api_name = GetAPIVersionName(device_api_version);
169
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700170 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
171 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
172 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600173 }
174
175 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
176 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800177 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700178 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
179 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600180 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700181 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], instance_api_version,
182 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Camden5b184be2019-08-13 07:50:19 -0600183 }
184
Camden83a9c372019-08-14 11:41:38 -0600185 auto pd_state = GetPhysicalDeviceState(physicalDevice);
Corta48da1d2019-09-20 18:59:07 +0200186 if ((pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700187 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
188 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600189 }
190
Camden5b184be2019-08-13 07:50:19 -0600191 return skip;
192}
193
194bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500195 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600196 bool skip = false;
197
198 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
199 std::stringstream bufferHex;
200 bufferHex << "0x" << std::hex << HandleToUint64(pBuffer);
201
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700202 skip |= LogWarning(
203 device, kVUID_BestPractices_SharingModeExclusive,
204 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
205 "(queueFamilyIndexCount of %" PRIu32 ").",
206 bufferHex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600207 }
208
209 return skip;
210}
211
212bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500213 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600214 bool skip = false;
215
216 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
217 std::stringstream imageHex;
218 imageHex << "0x" << std::hex << HandleToUint64(pImage);
219
220 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700221 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
222 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
223 "(queueFamilyIndexCount of %" PRIu32 ").",
224 imageHex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600225 }
226
Attilio Provenzano02859b22020-02-27 14:17:28 +0000227 if (VendorCheckEnabled(kBPVendorArm)) {
228 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
229 skip |= LogPerformanceWarning(
230 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
231 "%s vkCreateImage(): Trying to create an image with %u samples. "
232 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
233 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
234 }
235
236 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
237 skip |= LogPerformanceWarning(
238 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
239 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
240 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
241 "and do not need to be backed by physical storage. "
242 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
243 VendorSpecificTag(kBPVendorArm));
244 }
245 }
246
Camden5b184be2019-08-13 07:50:19 -0600247 return skip;
248}
249
250bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500251 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600252 bool skip = false;
253
Camden83a9c372019-08-14 11:41:38 -0600254 auto physical_device_state = GetPhysicalDeviceState();
255
256 if (physical_device_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700257 skip |= LogWarning(
258 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
Camden83a9c372019-08-14 11:41:38 -0600259 "vkCreateSwapchainKHR() called before getting surface capabilities from vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
260 }
261
262 if (physical_device_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700263 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
264 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
265 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
Camden83a9c372019-08-14 11:41:38 -0600266 }
267
268 if (physical_device_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700269 skip |= LogWarning(
270 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
271 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
Camden83a9c372019-08-14 11:41:38 -0600272 }
273
Camden5b184be2019-08-13 07:50:19 -0600274 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700275 skip |=
276 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
277 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCULSIVE while "
278 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
279 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600280 }
281
282 return skip;
283}
284
285bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
286 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500287 const VkAllocationCallbacks* pAllocator,
288 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600289 bool skip = false;
290
291 for (uint32_t i = 0; i < swapchainCount; i++) {
292 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700293 skip |= LogWarning(
294 device, kVUID_BestPractices_SharingModeExclusive,
295 "Warning: A shared swapchain (index %" PRIu32
296 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
297 "queues (queueFamilyIndexCount of %" PRIu32 ").",
298 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600299 }
300 }
301
302 return skip;
303}
304
305bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500306 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600307 bool skip = false;
308
309 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
310 VkFormat format = pCreateInfo->pAttachments[i].format;
311 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
312 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
313 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700314 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
315 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
316 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
317 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
318 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600319 }
320 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700321 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
322 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
323 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
324 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
325 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600326 }
327 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000328
329 const auto& attachment = pCreateInfo->pAttachments[i];
330 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
331 bool access_requires_memory =
332 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
333
334 if (FormatHasStencil(format)) {
335 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
336 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
337 }
338
339 if (access_requires_memory) {
340 skip |= LogPerformanceWarning(
341 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
342 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
343 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
344 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
345 i, static_cast<uint32_t>(attachment.samples));
346 }
347 }
Camden5b184be2019-08-13 07:50:19 -0600348 }
349
350 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
351 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
352 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
353 }
354
355 return skip;
356}
357
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000358bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
359 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
360 bool skip = false;
361
362 // Check for non-transient attachments that should be transient and vice versa
363 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
364 if (rp_state) {
365 const VkRenderPassCreateInfo2* rpci = rp_state->createInfo.ptr();
366 const VkImageView* image_views = pCreateInfo->pAttachments;
367
368 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
369 auto& attachment = rpci->pAttachments[i];
370 bool attachment_should_be_transient =
371 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
372
373 if (FormatHasStencil(attachment.format)) {
374 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
375 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
376 }
377
378 auto view_state = GetImageViewState(image_views[i]);
379 if (view_state) {
380 auto& ivci = view_state->create_info;
381 auto& ici = GetImageState(ivci.image)->createInfo;
382
383 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
384
385 // The check for an image that should not be transient applies to all GPUs
386 if (!attachment_should_be_transient && image_is_transient) {
387 skip |= LogPerformanceWarning(
388 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
389 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
390 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
391 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
392 i);
393 }
394
395 bool supports_lazy = false;
396 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
397 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
398 supports_lazy = true;
399 }
400 }
401
402 // The check for an image that should be transient only applies to GPUs supporting
403 // lazily allocated memory
404 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
405 skip |= LogPerformanceWarning(
406 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
407 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
408 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
409 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
410 i);
411 }
412 }
413 }
414 }
415
416 return skip;
417}
418
Camden5b184be2019-08-13 07:50:19 -0600419bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500420 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600421 bool skip = false;
422
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500423 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700424 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
425 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600426 }
427
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000428 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
429 skip |= LogPerformanceWarning(
430 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
431 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %llu. This is a very small allocation (current "
432 "threshold is %llu bytes). "
433 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
434 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
435 }
436
Camden83a9c372019-08-14 11:41:38 -0600437 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
438
439 return skip;
440}
441
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500442void BestPractices::PostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
443 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
444 VkResult result) {
Camden Stocker9738af92019-10-16 13:54:03 -0700445 ValidationStateTracker::PostCallRecordAllocateMemory(device, pAllocateInfo, pAllocator, pMemory, result);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700446 if (result != VK_SUCCESS) {
447 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
448 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
449 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR};
450 static std::vector<VkResult> success_codes = {};
451 ValidateReturnCodes("vkReleaseFullScreenExclusiveModeEXT", result, error_codes, success_codes);
452 return;
453 }
454 num_mem_objects++;
455}
Camden Stocker9738af92019-10-16 13:54:03 -0700456
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700457void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& success_codes,
458 const std::vector<VkResult>& error_codes) const {
459 auto error = std::find(error_codes.begin(), error_codes.end(), result);
460 if (error != error_codes.end()) {
461 LogWarning(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
462 return;
463 }
464 auto success = std::find(success_codes.begin(), success_codes.end(), result);
465 if (success != success_codes.end()) {
466 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned non-success return code %s.", api_name,
467 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500468 }
469}
470
Jeff Bolz5c801d12019-10-09 10:38:45 -0500471bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
472 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700473 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600474 bool skip = false;
475
Camden Stocker9738af92019-10-16 13:54:03 -0700476 const DEVICE_MEMORY_STATE* mem_info = ValidationStateTracker::GetDevMemState(memory);
Camden83a9c372019-08-14 11:41:38 -0600477
478 for (auto& obj : mem_info->obj_bindings) {
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600479 LogObjectList objlist(device);
480 objlist.add(obj);
481 objlist.add(mem_info->mem);
482 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 -0700483 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem).c_str());
Camden83a9c372019-08-14 11:41:38 -0600484 }
485
Camden5b184be2019-08-13 07:50:19 -0600486 return skip;
487}
488
489void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700490 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600491 if (memory != VK_NULL_HANDLE) {
492 num_mem_objects--;
493 }
494}
495
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000496bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600497 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500498 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600499
sfricke-samsunge2441192019-11-06 14:07:57 -0800500 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700501 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
502 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
503 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600504 }
505
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000506 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
507
508 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
509 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
510 skip |= LogPerformanceWarning(
511 device, kVUID_BestPractices_SmallDedicatedAllocation,
512 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
513 "The required size of the allocation is %llu, but smaller buffers like this should be sub-allocated from "
514 "larger memory blocks. (Current threshold is %llu bytes.)",
515 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
516 }
517
Camden Stockerb603cc82019-09-03 10:09:02 -0600518 return skip;
519}
520
521bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500522 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600523 bool skip = false;
524 const char* api_name = "BindBufferMemory()";
525
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000526 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600527
528 return skip;
529}
530
531bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500532 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600533 char api_name[64];
534 bool skip = false;
535
536 for (uint32_t i = 0; i < bindInfoCount; i++) {
537 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000538 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600539 }
540
541 return skip;
542}
Camden Stockerb603cc82019-09-03 10:09:02 -0600543
544bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500545 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600546 char api_name[64];
547 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600548
Camden Stocker8b798ab2019-09-03 10:33:28 -0600549 for (uint32_t i = 0; i < bindInfoCount; i++) {
550 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000551 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600552 }
553
554 return skip;
555}
556
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000557bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600558 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500559 const IMAGE_STATE* image_state = GetImageState(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600560
sfricke-samsunge2441192019-11-06 14:07:57 -0800561 if (!image_state->memory_requirements_checked && !image_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700562 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
563 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
564 api_name, report_data->FormatHandle(image).c_str());
Camden Stocker8b798ab2019-09-03 10:33:28 -0600565 }
566
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000567 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
568
569 if (mem_state->alloc_info.allocationSize == image_state->requirements.size &&
570 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
571 skip |= LogPerformanceWarning(
572 device, kVUID_BestPractices_SmallDedicatedAllocation,
573 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
574 "The required size of the allocation is %llu, but smaller images like this should be sub-allocated from "
575 "larger memory blocks. (Current threshold is %llu bytes.)",
576 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
577 }
578
579 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
580 // make sure this type is actually used.
581 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
582 // (i.e.most tile - based renderers)
583 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
584 bool supports_lazy = false;
585 uint32_t suggested_type = 0;
586
587 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
588 if ((1u << i) & image_state->requirements.memoryTypeBits) {
589 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
590 supports_lazy = true;
591 suggested_type = i;
592 break;
593 }
594 }
595 }
596
597 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
598
599 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
600 skip |= LogPerformanceWarning(
601 device, kVUID_BestPractices_NonLazyTransientImage,
602 "%s: Attempting to bind memory type % u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
603 "but this memory type is not LAZILY_ALLOCATED_BIT. You should use memory type %u here instead to save "
604 "%llu bytes of physical memory.",
605 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements.size);
606 }
607 }
608
Camden Stocker8b798ab2019-09-03 10:33:28 -0600609 return skip;
610}
611
612bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500613 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600614 bool skip = false;
615 const char* api_name = "vkBindImageMemory()";
616
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000617 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600618
619 return skip;
620}
621
622bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500623 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600624 char api_name[64];
625 bool skip = false;
626
627 for (uint32_t i = 0; i < bindInfoCount; i++) {
628 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000629 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600630 }
631
632 return skip;
633}
634
635bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500636 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600637 char api_name[64];
638 bool skip = false;
639
640 for (uint32_t i = 0; i < bindInfoCount; i++) {
641 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000642 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600643 }
644
645 return skip;
646}
Camden83a9c372019-08-14 11:41:38 -0600647
Attilio Provenzano02859b22020-02-27 14:17:28 +0000648static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
649 switch (format) {
650 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
651 case VK_FORMAT_R16_SFLOAT:
652 case VK_FORMAT_R16G16_SFLOAT:
653 case VK_FORMAT_R16G16B16_SFLOAT:
654 case VK_FORMAT_R16G16B16A16_SFLOAT:
655 case VK_FORMAT_R32_SFLOAT:
656 case VK_FORMAT_R32G32_SFLOAT:
657 case VK_FORMAT_R32G32B32_SFLOAT:
658 case VK_FORMAT_R32G32B32A32_SFLOAT:
659 return false;
660
661 default:
662 return true;
663 }
664}
665
666bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
667 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
668 bool skip = false;
669
670 for (uint32_t i = 0; i < createInfoCount; i++) {
671 auto pCreateInfo = &pCreateInfos[i];
672
673 if (!pCreateInfo->pColorBlendState || !pCreateInfo->pMultisampleState ||
674 pCreateInfo->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
675 pCreateInfo->pMultisampleState->sampleShadingEnable) {
676 return skip;
677 }
678
679 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
680 auto& subpass = rp_state->createInfo.pSubpasses[pCreateInfo->subpass];
681
682 for (uint32_t j = 0; j < pCreateInfo->pColorBlendState->attachmentCount; j++) {
683 auto& blend_att = pCreateInfo->pColorBlendState->pAttachments[j];
684 uint32_t att = subpass.pColorAttachments[j].attachment;
685
686 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
687 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
688 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
689 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
690 "color attachment #%u makes use "
691 "of a format which cannot be blended at full throughput when using MSAA.",
692 VendorSpecificTag(kBPVendorArm), i, j);
693 }
694 }
695 }
696 }
697
698 return skip;
699}
700
Camden5b184be2019-08-13 07:50:19 -0600701bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
702 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600703 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500704 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600705 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
706 pAllocator, pPipelines, cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600707
708 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700709 skip |= LogPerformanceWarning(
710 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
711 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
712 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600713 }
714
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000715 for (uint32_t i = 0; i < createInfoCount; i++) {
716 auto& createInfo = pCreateInfos[i];
717
718 auto& vertexInput = *createInfo.pVertexInputState;
719 uint32_t count = 0;
720 for (uint32_t j = 0; j < vertexInput.vertexBindingDescriptionCount; j++) {
721 if (vertexInput.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
722 count++;
723 }
724 }
725
726 if (count > kMaxInstancedVertexBuffers) {
727 skip |= LogPerformanceWarning(
728 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
729 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
730 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
731 count, kMaxInstancedVertexBuffers);
732 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000733
734 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000735 }
736
Camden5b184be2019-08-13 07:50:19 -0600737 return skip;
738}
739
740bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
741 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600742 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500743 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600744 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
745 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600746
747 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700748 skip |= LogPerformanceWarning(
749 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
750 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
751 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600752 }
753
754 return skip;
755}
756
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500757bool BestPractices::CheckPipelineStageFlags(std::string api_name, const VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -0600758 bool skip = false;
759
760 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700761 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
762 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600763 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700764 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
765 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600766 }
767
768 return skip;
769}
770
Mark Lobodzinski9b133c12020-03-10 10:42:56 -0600771void BestPractices::PostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
772 ValidationStateTracker::PostCallRecordQueuePresentKHR(queue, pPresentInfo, result);
773 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
774 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
775 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
776 LogPerformanceWarning(
777 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
778 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
779 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
780 "targets. Applications should query updated surface information and recreate their swapchain at the next "
781 "convenient opportunity.",
782 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
783 }
784 }
785}
786
Jeff Bolz5c801d12019-10-09 10:38:45 -0500787bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
788 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -0600789 bool skip = false;
790
791 for (uint32_t submit = 0; submit < submitCount; submit++) {
792 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
793 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
794 }
795 }
796
797 return skip;
798}
799
Attilio Provenzano746e43e2020-02-27 11:23:50 +0000800bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
801 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
802 bool skip = false;
803
804 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
805 skip |= LogPerformanceWarning(
806 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
807 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
808 "pool instead.");
809 }
810
811 return skip;
812}
813
814bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
815 const VkCommandBufferBeginInfo* pBeginInfo) const {
816 bool skip = false;
817
818 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
819 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
820 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
821 }
822
Attilio Provenzano02859b22020-02-27 14:17:28 +0000823 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT)) {
824 skip |= VendorCheckEnabled(kBPVendorArm) &&
825 LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
826 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
827 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
828 VendorSpecificTag(kBPVendorArm));
829 }
830
Attilio Provenzano746e43e2020-02-27 11:23:50 +0000831 return skip;
832}
833
Jeff Bolz5c801d12019-10-09 10:38:45 -0500834bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -0600835 bool skip = false;
836
837 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
838
839 return skip;
840}
841
Jeff Bolz5c801d12019-10-09 10:38:45 -0500842bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
843 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -0600844 bool skip = false;
845
846 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
847
848 return skip;
849}
850
851bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
852 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
853 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
854 uint32_t bufferMemoryBarrierCount,
855 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
856 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500857 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -0600858 bool skip = false;
859
860 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
861 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
862
863 return skip;
864}
865
866bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
867 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
868 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
869 uint32_t bufferMemoryBarrierCount,
870 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
871 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500872 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -0600873 bool skip = false;
874
875 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
876 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
877
878 return skip;
879}
880
881bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500882 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -0600883 bool skip = false;
884
885 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", pipelineStage);
886
887 return skip;
888}
889
Attilio Provenzano02859b22020-02-27 14:17:28 +0000890static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
891 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
892 auto& subpassInfo = createInfo.pSubpasses[subpass];
893
894 // If an attachment is ever used as a color attachment,
895 // resolve attachment or depth stencil attachment,
896 // it needs to exist on tile at some point.
897
898 for (uint32_t i = 0; i < subpassInfo.colorAttachmentCount; i++)
899 if (subpassInfo.pColorAttachments[i].attachment == attachment) return true;
900
901 if (subpassInfo.pResolveAttachments) {
902 for (uint32_t i = 0; i < subpassInfo.colorAttachmentCount; i++)
903 if (subpassInfo.pResolveAttachments[i].attachment == attachment) return true;
904 }
905
906 if (subpassInfo.pDepthStencilAttachment && subpassInfo.pDepthStencilAttachment->attachment == attachment) return true;
907 }
908
909 return false;
910}
911
912bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
913 const VkRenderPassBeginInfo* pRenderPassBegin) const {
914 bool skip = false;
915
916 if (!pRenderPassBegin) {
917 return skip;
918 }
919
920 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
921 if (rp_state) {
922 // Check if any attachments have LOAD operation on them
923 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
924 auto& attachment = rp_state->createInfo.pAttachments[att];
925
926 bool attachmentHasReadback = false;
927 if (!FormatHasStencil(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
928 attachmentHasReadback = true;
929 }
930
931 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
932 attachmentHasReadback = true;
933 }
934
935 bool attachmentNeedsReadback = false;
936
937 // Check if the attachment is actually used in any subpass on-tile
938 if (attachmentHasReadback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
939 attachmentNeedsReadback = true;
940 }
941
942 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
943 if (attachmentNeedsReadback) {
944 skip |= VendorCheckEnabled(kBPVendorArm) &&
945 LogPerformanceWarning(
946 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
947 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
948 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
949 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
950 VendorSpecificTag(kBPVendorArm), att,
951 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
952 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
953 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
954 }
955 }
956 }
957
958 return skip;
959}
960
961bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
962 VkSubpassContents contents) const {
963 bool skip = ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
964 return skip;
965}
966
967bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
968 const VkRenderPassBeginInfo* pRenderPassBegin,
969 const VkSubpassBeginInfoKHR* pSubpassBeginInfo) const {
970 bool skip = ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
971 return skip;
972}
973
974bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
975 const VkSubpassBeginInfoKHR* pSubpassBeginInfo) const {
976 bool skip = ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
977 return skip;
978}
979
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -0700980// Generic function to handle validation for all CmdDraw* type functions
981bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
982 bool skip = false;
983 const CMD_BUFFER_STATE* cb_state = GetCBState(cmd_buffer);
984 if (cb_state) {
985 const auto last_bound_it = cb_state->lastBound.find(VK_PIPELINE_BIND_POINT_GRAPHICS);
986 const PIPELINE_STATE* pipeline_state = nullptr;
987 if (last_bound_it != cb_state->lastBound.cend()) {
988 pipeline_state = last_bound_it->second.pipeline_state;
989 }
990 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
991 // Verify vertex binding
992 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
993 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700994 skip |= LogPerformanceWarning(cb_state->commandBuffer, kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
995 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
996 report_data->FormatHandle(cb_state->commandBuffer).c_str(),
997 report_data->FormatHandle(pipeline_state->pipeline).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -0700998 }
999 }
1000 }
1001 return skip;
1002}
1003
Camden5b184be2019-08-13 07:50:19 -06001004bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001005 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001006 bool skip = false;
1007
1008 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001009 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1010 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001011 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001012 }
1013
1014 return skip;
1015}
1016
1017bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001018 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001019 bool skip = false;
1020
1021 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001022 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1023 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001024 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001025 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1026
Attilio Provenzano02859b22020-02-27 14:17:28 +00001027 // Check if we reached the limit for small indexed draw calls.
1028 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1029 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1030 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
1031 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1)) {
1032 skip |= VendorCheckEnabled(kBPVendorArm) &&
1033 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
1034 "The command buffer contains many small indexed drawcalls "
1035 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1036 "You can try batching drawcalls or instancing when applicable.",
1037 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1038 }
1039
Sam Walls8e77e4f2020-03-16 20:47:40 +00001040 if (VendorCheckEnabled(kBPVendorArm)) {
1041 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1042 }
1043
1044 return skip;
1045}
1046
1047bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1048 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1049 bool skip = false;
1050
1051 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1052 const auto* cmd_state = GetCBState(commandBuffer);
1053 if (cmd_state == nullptr) return skip;
1054
1055 const auto* ib_state = GetBufferState(cmd_state->index_buffer_binding.buffer);
1056 if (ib_state == nullptr) return skip;
1057
1058 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
1059 const auto& ib_mem_state = *ib_state->binding.mem_state;
1060 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1061 const void* ib_mem = ib_mem_state.p_driver_data;
1062 bool primitive_restart_enable = false;
1063
1064 const auto& pipeline_binding_iter = cmd_state->lastBound.find(VK_PIPELINE_BIND_POINT_GRAPHICS);
1065
1066 if (pipeline_binding_iter != cmd_state->lastBound.end()) {
1067 const auto* pipeline_state = pipeline_binding_iter->second.pipeline_state;
1068 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr)
1069 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
1070 }
1071
1072 // no point checking index buffer if the memory is nonexistant/unmapped, or if there is no graphics pipeline bound to this CB
1073 if (ib_mem && pipeline_binding_iter != cmd_state->lastBound.end()) {
1074 uint32_t scan_stride;
1075 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1076 scan_stride = sizeof(uint8_t);
1077 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1078 scan_stride = sizeof(uint16_t);
1079 } else {
1080 scan_stride = sizeof(uint32_t);
1081 }
1082
1083 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1084 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1085
1086 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1087 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1088 // irrespective of whether or not they're part of the draw call.
1089
1090 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1091 uint32_t min_index = ~0u;
1092 // start with maximum as 0 and adjust to indices in the buffer
1093 uint32_t max_index = 0u;
1094
1095 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
1096 // for the given index buffer
1097 uint32_t vertex_shade_count = 0;
1098
1099 PostTransformLRUCacheModel post_transform_cache;
1100
1101 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
1102 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
1103 // target architecture.
1104 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
1105 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
1106 post_transform_cache.resize(32);
1107
1108 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1109 uint32_t scan_index;
1110 uint32_t primitive_restart_value;
1111 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1112 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1113 primitive_restart_value = 0xFF;
1114 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1115 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1116 primitive_restart_value = 0xFFFF;
1117 } else {
1118 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1119 primitive_restart_value = 0xFFFFFFFF;
1120 }
1121
1122 max_index = std::max(max_index, scan_index);
1123 min_index = std::min(min_index, scan_index);
1124
1125 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
1126 bool in_cache = post_transform_cache.query_cache(scan_index);
1127 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
1128 if (!in_cache) vertex_shade_count++;
1129 }
1130 }
1131
1132 // if the max and min values were not set, then we either have no indices, or all primitive restarts, exit...
1133 if (max_index < min_index) return skip;
1134
1135 if (max_index - min_index >= indexCount) {
1136 skip |= LogPerformanceWarning(
1137 device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1138 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
1139 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
1140 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
1141 "maximum would be loaded, and possibly shaded, whether or not they are used.",
1142 VendorSpecificTag(kBPVendorArm), (static_cast<float>(indexCount) / (max_index - min_index)) * 100.0f);
1143 return skip;
1144 }
1145
1146 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
1147 // each bit of the n-th bucket contains the inclusion information for indices (n*n_buckets) to ((n+1)*n_buckets)
1148 const size_t n_buckets = 64;
1149 std::vector<std::bitset<n_buckets>> vertex_reference_buckets;
1150 vertex_reference_buckets.resize((max_index - min_index + 1) / n_buckets);
1151
1152 // To avoid using too much memory, we run over the indices again.
1153 // Knowing the size from the last scan allows us to record index usage with bitsets
1154 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1155 uint32_t scan_index;
1156 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1157 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1158 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1159 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1160 } else {
1161 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1162 }
1163 // keep track of the set of all indices used to reference vertices in the draw call
1164 size_t index_offset = scan_index - min_index;
1165 size_t bitset_bucket_index = index_offset / n_buckets;
1166 uint64_t used_indices = 1ull << ((index_offset % n_buckets) & 0xFFFFFFFFu);
1167 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
1168 }
1169
1170 uint32_t vertex_reference_count = 0;
1171 for (const auto& bitset : vertex_reference_buckets) {
1172 vertex_reference_count += static_cast<uint32_t>(bitset.count());
1173 }
1174
1175 // low index buffer utilization implies that: of the vertices available to the draw call, not all are utilized
1176 float utilization = static_cast<float>(vertex_reference_count) / (max_index - min_index + 1);
1177 // low hit rate (high miss rate) implies the order of indices in the draw call may be possible to improve
1178 float cache_hit_rate = static_cast<float>(vertex_reference_count) / vertex_shade_count;
1179
1180 if (utilization < 0.5f) {
1181 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1182 "%s The indices which were specified for the draw call only utilise approximately "
1183 "%.02f%% of the bound vertex buffer.",
1184 VendorSpecificTag(kBPVendorArm), utilization);
1185 }
1186
1187 if (cache_hit_rate <= 0.5f) {
1188 skip |=
1189 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
1190 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
1191 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
1192 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
1193 "recently shaded vertices.",
1194 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
1195 }
1196 }
1197
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001198 return skip;
1199}
1200
Attilio Provenzano02859b22020-02-27 14:17:28 +00001201void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1202 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1203 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
1204 firstInstance);
1205
1206 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1207 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
1208 cmd_state->small_indexed_draw_call_count++;
1209 }
1210}
1211
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001212bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
1213 VkDeviceSize offset, VkBuffer countBuffer,
1214 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
1215 uint32_t stride) const {
1216 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06001217
1218 return skip;
1219}
1220
1221bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001222 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001223 bool skip = false;
1224
1225 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001226 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1227 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001228 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001229 }
1230
1231 return skip;
1232}
1233
1234bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001235 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001236 bool skip = false;
1237
1238 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001239 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1240 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001241 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001242 }
1243
1244 return skip;
1245}
1246
1247bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001248 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06001249 bool skip = false;
1250
1251 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001252 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
1253 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
1254 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
1255 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06001256 }
1257
1258 return skip;
1259}
Camden83a9c372019-08-14 11:41:38 -06001260
Camden Stocker9c051442019-11-06 14:28:43 -08001261bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
1262 const char* api_name) const {
1263 bool skip = false;
1264 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1265
1266 if (physical_device_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001267 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
1268 "Potential problem with calling %s() without first retrieving properties from "
1269 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
1270 api_name);
Camden Stocker9c051442019-11-06 14:28:43 -08001271 }
1272
1273 return skip;
1274}
1275
Camden83a9c372019-08-14 11:41:38 -06001276bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001277 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06001278 bool skip = false;
1279
Camden Stocker9c051442019-11-06 14:28:43 -08001280 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06001281
Camden Stocker9c051442019-11-06 14:28:43 -08001282 return skip;
1283}
1284
1285bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
1286 uint32_t planeIndex,
1287 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
1288 bool skip = false;
1289
1290 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
1291
1292 return skip;
1293}
1294
1295bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
1296 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
1297 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
1298 bool skip = false;
1299
1300 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06001301
1302 return skip;
1303}
Camden05de2d42019-08-19 10:23:56 -06001304
1305bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001306 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06001307 bool skip = false;
1308
1309 auto swapchain_state = GetSwapchainState(swapchain);
1310
1311 if (swapchain_state && pSwapchainImages) {
1312 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
1313 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001314 skip |=
1315 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
1316 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
1317 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06001318 }
1319 }
1320
1321 return skip;
1322}
1323
1324// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001325bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
1326 uint32_t requested_queue_family_property_count,
1327 bool qfp_null, const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06001328 bool skip = false;
1329 if (!qfp_null) {
1330 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
1331 if (UNCALLED == pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001332 skip |= LogWarning(
1333 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
Camden05de2d42019-08-19 10:23:56 -06001334 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is recommended "
1335 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
1336 caller_name, caller_name);
1337 // Then verify that pCount that is passed in on second call matches what was returned
1338 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001339 skip |= LogWarning(
1340 pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
Camden05de2d42019-08-19 10:23:56 -06001341 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
1342 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
1343 ". It is recommended to instead receive all the properties by calling %s with pQueueFamilyPropertyCount that was "
1344 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
1345 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name, caller_name);
1346 }
1347 }
1348
1349 return skip;
1350}
1351
Jeff Bolz5c801d12019-10-09 10:38:45 -05001352bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
1353 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06001354 bool skip = false;
1355
1356 for (uint32_t i = 0; i < bindInfoCount; i++) {
1357 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureState(pBindInfos[i].accelerationStructure);
1358 if (!as_state->memory_requirements_checked) {
1359 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
1360 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
1361 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001362 skip |= LogWarning(
1363 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06001364 "vkBindAccelerationStructureMemoryNV(): "
1365 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
1366 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
1367 }
1368 }
1369
1370 return skip;
1371}
1372
Camden05de2d42019-08-19 10:23:56 -06001373bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
1374 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001375 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001376 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1377 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001378 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001379 (nullptr == pQueueFamilyProperties),
1380 "vkGetPhysicalDeviceQueueFamilyProperties()");
1381}
1382
Jeff Bolz5c801d12019-10-09 10:38:45 -05001383bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(
1384 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount,
1385 VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001386 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1387 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001388 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001389 (nullptr == pQueueFamilyProperties),
1390 "vkGetPhysicalDeviceQueueFamilyProperties2()");
1391}
1392
Jeff Bolz5c801d12019-10-09 10:38:45 -05001393bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
1394 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount,
1395 VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001396 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1397 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001398 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001399 (nullptr == pQueueFamilyProperties),
1400 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
1401}
1402
1403bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
1404 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001405 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06001406 if (!pSurfaceFormats) return false;
1407 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1408 const auto& call_state = physical_device_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
1409 bool skip = false;
1410 if (call_state == UNCALLED) {
1411 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
1412 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001413 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
1414 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
1415 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06001416 } else {
1417 auto prev_format_count = (uint32_t)physical_device_state->surface_formats.size();
Peter Chene191bd72019-09-16 13:04:37 -04001418 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001419 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
1420 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
1421 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
1422 "when pSurfaceFormatCount was NULL.",
1423 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06001424 }
1425 }
1426 return skip;
1427}
Camden Stocker23cc47d2019-09-03 14:53:57 -06001428
1429bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001430 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001431 bool skip = false;
1432
1433 for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; bindIdx++) {
1434 const VkBindSparseInfo& bindInfo = pBindInfo[bindIdx];
1435 // 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 -05001436 std::unordered_set<const IMAGE_STATE*> sparse_images;
1437 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
1438 // in RecordQueueBindSparse.
1439 std::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06001440 // If we're binding sparse image memory make sure reqs were queried and note if metadata is required and bound
1441 for (uint32_t i = 0; i < bindInfo.imageBindCount; ++i) {
1442 const auto& image_bind = bindInfo.pImageBinds[i];
1443 auto image_state = GetImageState(image_bind.image);
1444 if (!image_state)
1445 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1446 sparse_images.insert(image_state);
1447 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1448 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1449 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001450 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1451 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1452 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1453 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001454 }
1455 }
1456 if (!image_state->memory_requirements_checked) {
1457 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001458 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1459 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1460 "vkGetImageMemoryRequirements() to retrieve requirements.",
1461 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001462 }
1463 }
1464 for (uint32_t i = 0; i < bindInfo.imageOpaqueBindCount; ++i) {
1465 const auto& image_opaque_bind = bindInfo.pImageOpaqueBinds[i];
1466 auto image_state = GetImageState(bindInfo.pImageOpaqueBinds[i].image);
1467 if (!image_state)
1468 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1469 sparse_images.insert(image_state);
1470 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1471 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1472 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001473 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1474 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1475 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1476 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001477 }
1478 }
1479 if (!image_state->memory_requirements_checked) {
1480 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001481 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1482 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1483 "vkGetImageMemoryRequirements() to retrieve requirements.",
1484 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001485 }
1486 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1487 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001488 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06001489 }
1490 }
1491 }
1492 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001493 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
1494 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001495 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001496 skip |= LogWarning(sparse_image_state->image, kVUID_Core_MemTrack_InvalidState,
1497 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
1498 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
1499 report_data->FormatHandle(sparse_image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001500 }
1501 }
1502 }
1503
1504 return skip;
1505}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001506
1507void BestPractices::PostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
1508 VkFence fence, VkResult result) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -07001509 ValidationStateTracker::PostCallRecordQueueBindSparse(queue, bindInfoCount, pBindInfo, fence, result);
1510
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001511 if (result != VK_SUCCESS) {
1512 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
1513 VK_ERROR_DEVICE_LOST};
1514 static std::vector<VkResult> success_codes = {};
1515 ValidateReturnCodes("vkReleaseFullScreenExclusiveModeEXT", result, error_codes, success_codes);
1516 return;
1517 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001518
1519 for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; bindIdx++) {
1520 const VkBindSparseInfo& bindInfo = pBindInfo[bindIdx];
1521 for (uint32_t i = 0; i < bindInfo.imageOpaqueBindCount; ++i) {
1522 const auto& image_opaque_bind = bindInfo.pImageOpaqueBinds[i];
1523 auto image_state = GetImageState(bindInfo.pImageOpaqueBinds[i].image);
1524 if (!image_state)
1525 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1526 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1527 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
1528 image_state->sparse_metadata_bound = true;
1529 }
1530 }
1531 }
1532 }
1533}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001534
1535bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06001536 const VkClearAttachment* pAttachments, uint32_t rectCount,
1537 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001538 bool skip = false;
1539 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
1540 if (!cb_node) return skip;
1541
Camden Stockerf55721f2019-09-09 11:04:49 -06001542 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001543 if (!cb_node->hasDrawCmd && (cb_node->activeRenderPassBeginInfo.renderArea.extent.width == pRects[0].rect.extent.width) &&
1544 (cb_node->activeRenderPassBeginInfo.renderArea.extent.height == pRects[0].rect.extent.height)) {
1545 // There are times where app needs to use ClearAttachments (generally when reusing a buffer inside of a render pass)
1546 // This warning should be made more specific. It'd be best to avoid triggering this test if it's a use that must call
1547 // CmdClearAttachments.
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001548 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
1549 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds. It is recommended you "
1550 "use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
1551 report_data->FormatHandle(commandBuffer).c_str());
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001552 }
1553
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001554 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
1555 // as it can be more efficient to just use LOAD_OP_CLEAR
1556 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass;
1557 if (rp) {
1558 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
1559
1560 for (uint32_t i = 0; i < attachmentCount; i++) {
1561 auto& attachment = pAttachments[i];
1562 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
1563 uint32_t color_attachment = attachment.colorAttachment;
1564 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
1565
1566 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
1567 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1568 skip |= LogPerformanceWarning(
1569 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
1570 "vkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
1571 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
1572 "it is more efficient.",
1573 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
1574 }
1575 }
1576 }
1577
1578 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
1579 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
1580
1581 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
1582 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1583 skip |= LogPerformanceWarning(
1584 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
1585 "vkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
1586 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
1587 "it is more efficient.",
1588 report_data->FormatHandle(commandBuffer).c_str());
1589 }
1590 }
1591 }
1592
1593 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
1594 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
1595
1596 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
1597 if (rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1598 skip |= LogPerformanceWarning(
1599 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
1600 "vkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
1601 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
1602 "it is more efficient.",
1603 report_data->FormatHandle(commandBuffer).c_str());
1604 }
1605 }
1606 }
1607 }
1608 }
1609
Camden Stockerf55721f2019-09-09 11:04:49 -06001610 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001611}
Attilio Provenzano02859b22020-02-27 14:17:28 +00001612
1613bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
1614 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
1615 const VkImageResolve* pRegions) const {
1616 bool skip = false;
1617
1618 skip |= VendorCheckEnabled(kBPVendorArm) &&
1619 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
1620 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
1621 "This is a very slow and extremely bandwidth intensive path. "
1622 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
1623 VendorSpecificTag(kBPVendorArm));
1624
1625 return skip;
1626}
1627
1628bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
1629 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
1630 bool skip = false;
1631
1632 if (VendorCheckEnabled(kBPVendorArm)) {
1633 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
1634 skip |= LogPerformanceWarning(
1635 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
1636 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
1637 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
1638 "image) are actually used. If you need different wrapping modes, disregard this warning.",
1639 VendorSpecificTag(kBPVendorArm));
1640 }
1641
1642 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
1643 skip |= LogPerformanceWarning(
1644 device, kVUID_BestPractices_CreateSampler_LodClamping,
1645 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
1646 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
1647 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
1648 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
1649 }
1650
1651 if (pCreateInfo->mipLodBias != 0.0f) {
1652 skip |=
1653 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
1654 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
1655 "descriptors being created and may cause reduced performance.",
1656 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
1657 }
1658
1659 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
1660 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
1661 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
1662 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
1663 skip |= LogPerformanceWarning(
1664 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
1665 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
1666 "This will lead to less efficient descriptors being created and may cause reduced performance. "
1667 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
1668 VendorSpecificTag(kBPVendorArm));
1669 }
1670
1671 if (pCreateInfo->unnormalizedCoordinates) {
1672 skip |= LogPerformanceWarning(
1673 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
1674 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
1675 "descriptors being created and may cause reduced performance.",
1676 VendorSpecificTag(kBPVendorArm));
1677 }
1678
1679 if (pCreateInfo->anisotropyEnable) {
1680 skip |= LogPerformanceWarning(
1681 device, kVUID_BestPractices_CreateSampler_Anisotropy,
1682 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
1683 "and may cause reduced performance.",
1684 VendorSpecificTag(kBPVendorArm));
1685 }
1686 }
1687
1688 return skip;
1689}
Sam Walls8e77e4f2020-03-16 20:47:40 +00001690
1691void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
1692
1693bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
1694 // look for a cache hit
1695 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
1696 if (hit != _entries.end()) {
1697 // mark the cache hit as being most recently used
1698 hit->age = iteration++;
1699 return true;
1700 }
1701
1702 // if there's no cache hit, we need to model the entry being inserted into the cache
1703 CacheEntry new_entry = {value, iteration};
1704 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
1705 // if there is still space left in the cache, use the next available slot
1706 *(_entries.begin() + iteration) = new_entry;
1707 } else {
1708 // otherwise replace the least recently used cache entry
1709 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
1710 *lru = new_entry;
1711 }
1712 iteration++;
1713 return false;
1714}