blob: 9954b4bccd31e16380ddbc5b2f808fd43040b589 [file] [log] [blame]
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -07001/* Copyright (c) 2015-2020 The Khronos Group Inc.
2 * Copyright (c) 2015-2020 Valve Corporation
3 * Copyright (c) 2015-2020 LunarG, Inc.
Camdeneaa86ea2019-07-26 11:00:09 -06004 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author: Camden Stocker <camden@lunarg.com>
18 */
19
Mark Lobodzinski57b8ae82020-02-20 16:37:14 -070020#include "best_practices_validation.h"
Camden5b184be2019-08-13 07:50:19 -060021#include "layer_chassis_dispatch.h"
Camden Stocker0a660ce2019-08-27 15:30:40 -060022#include "best_practices_error_enums.h"
Sam Wallsd7ab6db2020-06-19 20:41:54 +010023#include "shader_validation.h"
Camden5b184be2019-08-13 07:50:19 -060024
25#include <string>
26#include <iomanip>
Sam Walls8e77e4f2020-03-16 20:47:40 +000027#include <bitset>
Sam Wallsd7ab6db2020-06-19 20:41:54 +010028#include <memory>
Camden5b184be2019-08-13 07:50:19 -060029
30// get the API name is proper format
Jeff Bolz46c0ea02019-10-09 13:06:29 -050031std::string BestPractices::GetAPIVersionName(uint32_t version) const {
Camden5b184be2019-08-13 07:50:19 -060032 std::stringstream version_name;
33 uint32_t major = VK_VERSION_MAJOR(version);
34 uint32_t minor = VK_VERSION_MINOR(version);
35 uint32_t patch = VK_VERSION_PATCH(version);
36
37 version_name << major << "." << minor << "." << patch << " (0x" << std::setfill('0') << std::setw(8) << std::hex << version
38 << ")";
39
40 return version_name.str();
41}
42
Attilio Provenzano19d6a982020-02-27 12:41:41 +000043struct VendorSpecificInfo {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060044 EnableFlags vendor_id;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000045 std::string name;
46};
47
48const std::map<BPVendorFlagBits, VendorSpecificInfo> vendor_info = {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060049 {kBPVendorArm, {vendor_specific_arm, "Arm"}},
Attilio Provenzano19d6a982020-02-27 12:41:41 +000050};
51
52bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
53 for (const auto& vendor : vendor_info) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060054 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000055 return true;
56 }
57 }
58 return false;
59}
60
61const char* VendorSpecificTag(BPVendorFlags vendors) {
62 // Cache built vendor tags in a map
63 static std::unordered_map<BPVendorFlags, std::string> tag_map;
64
65 auto res = tag_map.find(vendors);
66 if (res == tag_map.end()) {
67 // Build the vendor tag string
68 std::stringstream vendor_tag;
69
70 vendor_tag << "[";
71 bool first_vendor = true;
72 for (const auto& vendor : vendor_info) {
73 if (vendors & vendor.first) {
74 if (!first_vendor) {
75 vendor_tag << ", ";
76 }
77 vendor_tag << vendor.second.name;
78 first_vendor = false;
79 }
80 }
81 vendor_tag << "]";
82
83 tag_map[vendors] = vendor_tag.str();
84 res = tag_map.find(vendors);
85 }
86
87 return res->second.c_str();
88}
89
Mark Lobodzinski6167e102020-02-24 17:03:55 -070090const char* DepReasonToString(ExtDeprecationReason reason) {
91 switch (reason) {
92 case kExtPromoted:
93 return "promoted to";
94 break;
95 case kExtObsoleted:
96 return "obsoleted by";
97 break;
98 case kExtDeprecated:
99 return "deprecated by";
100 break;
101 default:
102 return "";
103 break;
104 }
105}
106
107bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
108 const char* vuid) const {
109 bool skip = false;
110 auto dep_info_it = deprecated_extensions.find(extension_name);
111 if (dep_info_it != deprecated_extensions.end()) {
112 auto dep_info = dep_info_it->second;
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600113 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
114 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700115 skip |=
116 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
117 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600118 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700119 if (dep_info.target.length() == 0) {
120 skip |= LogWarning(instance, vuid,
121 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
122 "without replacement.",
123 api_name, extension_name);
124 } else {
125 skip |= LogWarning(instance, vuid,
126 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
127 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
128 }
129 }
130 }
131 return skip;
132}
133
Camden5b184be2019-08-13 07:50:19 -0600134bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500135 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600136 bool skip = false;
137
138 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
139 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800140 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700141 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
142 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600143 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600144 uint32_t specified_version =
145 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
146 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700147 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Camden5b184be2019-08-13 07:50:19 -0600148 }
149
150 return skip;
151}
152
153void BestPractices::PreCallRecordCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
154 VkInstance* pInstance) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700155 ValidationStateTracker::PreCallRecordCreateInstance(pCreateInfo, pAllocator, pInstance);
Sam Walls53bf7652020-04-21 17:35:15 +0100156
157 if (pCreateInfo != nullptr && pCreateInfo->pApplicationInfo != nullptr)
158 instance_api_version = pCreateInfo->pApplicationInfo->apiVersion;
159 else
160 instance_api_version = 0;
Camden5b184be2019-08-13 07:50:19 -0600161}
162
163bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500164 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600165 bool skip = false;
166
167 // get API version of physical device passed when creating device.
168 VkPhysicalDeviceProperties physical_device_properties{};
169 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500170 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600171
172 // check api versions and warn if instance api Version is higher than version on device.
173 if (instance_api_version > device_api_version) {
174 std::string inst_api_name = GetAPIVersionName(instance_api_version);
175 std::string dev_api_name = GetAPIVersionName(device_api_version);
176
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700177 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
178 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
179 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600180 }
181
182 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
183 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800184 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700185 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
186 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600187 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700188 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], instance_api_version,
189 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Camden5b184be2019-08-13 07:50:19 -0600190 }
191
Camden83a9c372019-08-14 11:41:38 -0600192 auto pd_state = GetPhysicalDeviceState(physicalDevice);
Corta48da1d2019-09-20 18:59:07 +0200193 if ((pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700194 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
195 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600196 }
197
Szilard Papp7d2c7952020-06-22 14:38:13 +0100198 if ((VendorCheckEnabled(kBPVendorArm)) && (pCreateInfo->pEnabledFeatures != nullptr) &&
199 (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
200 skip |= LogPerformanceWarning(
201 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
202 "%s vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
203 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
204 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
205 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
206 VendorSpecificTag(kBPVendorArm));
207 }
208
Camden5b184be2019-08-13 07:50:19 -0600209 return skip;
210}
211
212bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500213 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) 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 bufferHex;
218 bufferHex << "0x" << std::hex << HandleToUint64(pBuffer);
219
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700220 skip |= LogWarning(
221 device, kVUID_BestPractices_SharingModeExclusive,
222 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
223 "(queueFamilyIndexCount of %" PRIu32 ").",
224 bufferHex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600225 }
226
227 return skip;
228}
229
230bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500231 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600232 bool skip = false;
233
234 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
235 std::stringstream imageHex;
236 imageHex << "0x" << std::hex << HandleToUint64(pImage);
237
238 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700239 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
240 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
241 "(queueFamilyIndexCount of %" PRIu32 ").",
242 imageHex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600243 }
244
Attilio Provenzano02859b22020-02-27 14:17:28 +0000245 if (VendorCheckEnabled(kBPVendorArm)) {
246 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
247 skip |= LogPerformanceWarning(
248 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
249 "%s vkCreateImage(): Trying to create an image with %u samples. "
250 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
251 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
252 }
253
254 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
255 skip |= LogPerformanceWarning(
256 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
257 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
258 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
259 "and do not need to be backed by physical storage. "
260 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
261 VendorSpecificTag(kBPVendorArm));
262 }
263 }
264
Camden5b184be2019-08-13 07:50:19 -0600265 return skip;
266}
267
268bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500269 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600270 bool skip = false;
271
Camden83a9c372019-08-14 11:41:38 -0600272 auto physical_device_state = GetPhysicalDeviceState();
273
274 if (physical_device_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700275 skip |= LogWarning(
276 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
Camden83a9c372019-08-14 11:41:38 -0600277 "vkCreateSwapchainKHR() called before getting surface capabilities from vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
278 }
279
280 if (physical_device_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700281 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
282 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
283 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
Camden83a9c372019-08-14 11:41:38 -0600284 }
285
286 if (physical_device_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700287 skip |= LogWarning(
288 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
289 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
Camden83a9c372019-08-14 11:41:38 -0600290 }
291
Camden5b184be2019-08-13 07:50:19 -0600292 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700293 skip |=
294 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600295 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700296 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
297 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600298 }
299
Szilard Papp48a6da32020-06-10 14:41:59 +0100300 if (pCreateInfo->minImageCount == 2) {
301 skip |= LogPerformanceWarning(
302 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
303 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
304 ", which means double buffering is going "
305 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
306 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
307 "3 to use triple buffering to maximize performance in such cases.",
308 pCreateInfo->minImageCount);
309 }
310
Szilard Pappd5f0f812020-06-22 09:01:29 +0100311 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
312 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
313 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
314 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
315 "Presentation modes which are not FIFO will present the latest available frame and discard other "
316 "frame(s) if any.",
317 VendorSpecificTag(kBPVendorArm));
318 }
319
Camden5b184be2019-08-13 07:50:19 -0600320 return skip;
321}
322
323bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
324 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500325 const VkAllocationCallbacks* pAllocator,
326 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600327 bool skip = false;
328
329 for (uint32_t i = 0; i < swapchainCount; i++) {
330 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700331 skip |= LogWarning(
332 device, kVUID_BestPractices_SharingModeExclusive,
333 "Warning: A shared swapchain (index %" PRIu32
334 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
335 "queues (queueFamilyIndexCount of %" PRIu32 ").",
336 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600337 }
338 }
339
340 return skip;
341}
342
343bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500344 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600345 bool skip = false;
346
347 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
348 VkFormat format = pCreateInfo->pAttachments[i].format;
349 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
350 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
351 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700352 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
353 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
354 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
355 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
356 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600357 }
358 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700359 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
360 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
361 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
362 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
363 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600364 }
365 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000366
367 const auto& attachment = pCreateInfo->pAttachments[i];
368 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
369 bool access_requires_memory =
370 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
371
372 if (FormatHasStencil(format)) {
373 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
374 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
375 }
376
377 if (access_requires_memory) {
378 skip |= LogPerformanceWarning(
379 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
380 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
381 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
382 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
383 i, static_cast<uint32_t>(attachment.samples));
384 }
385 }
Camden5b184be2019-08-13 07:50:19 -0600386 }
387
388 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
389 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
390 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
391 }
392
393 return skip;
394}
395
Tony-LunarG767180f2020-04-23 14:03:59 -0600396bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
397 const VkImageView* image_views) const {
398 bool skip = false;
399
400 // Check for non-transient attachments that should be transient and vice versa
401 for (uint32_t i = 0; i < attachmentCount; ++i) {
402 auto& attachment = rpci->pAttachments[i];
403 bool attachment_should_be_transient =
404 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
405
406 if (FormatHasStencil(attachment.format)) {
407 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
408 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
409 }
410
411 auto view_state = GetImageViewState(image_views[i]);
412 if (view_state) {
413 auto& ivci = view_state->create_info;
414 auto& ici = GetImageState(ivci.image)->createInfo;
415
416 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
417
418 // The check for an image that should not be transient applies to all GPUs
419 if (!attachment_should_be_transient && image_is_transient) {
420 skip |= LogPerformanceWarning(
421 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
422 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
423 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
424 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
425 i);
426 }
427
428 bool supports_lazy = false;
429 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
430 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
431 supports_lazy = true;
432 }
433 }
434
435 // The check for an image that should be transient only applies to GPUs supporting
436 // lazily allocated memory
437 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
438 skip |= LogPerformanceWarning(
439 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
440 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
441 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
442 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
443 i);
444 }
445 }
446 }
447 return skip;
448}
449
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000450bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
451 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
452 bool skip = false;
453
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000454 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
Tony-LunarG767180f2020-04-23 14:03:59 -0600455 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR)) {
456 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000457 }
458
459 return skip;
460}
461
Sam Wallse746d522020-03-16 21:20:23 +0000462bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
463 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
464 bool skip = false;
465 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
466
467 if (!skip) {
468 const auto& pool_handle = pAllocateInfo->descriptorPool;
469 auto iter = descriptor_pool_freed_count.find(pool_handle);
470 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
471 // this warning is specific to Arm
472 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
473 skip |= LogPerformanceWarning(
474 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
475 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
476 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
477 VendorSpecificTag(kBPVendorArm));
478 }
479 }
480
481 return skip;
482}
483
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600484void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
485 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000486 if (result == VK_SUCCESS) {
487 // find the free count for the pool we allocated into
488 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
489 if (iter != descriptor_pool_freed_count.end()) {
490 // we record successful allocations by subtracting the allocation count from the last recorded free count
491 const auto alloc_count = pAllocateInfo->descriptorSetCount;
492 // clamp the unsigned subtraction to the range [0, last_free_count]
493 if (iter->second > alloc_count)
494 iter->second -= alloc_count;
495 else
496 iter->second = 0;
497 }
498 }
499}
500
501void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
502 const VkDescriptorSet* pDescriptorSets, VkResult result) {
503 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
504 if (result == VK_SUCCESS) {
505 // we want to track frees because we're interested in suggesting re-use
506 auto iter = descriptor_pool_freed_count.find(descriptorPool);
507 if (iter == descriptor_pool_freed_count.end()) {
508 descriptor_pool_freed_count.insert(std::make_pair(descriptorPool, descriptorSetCount));
509 } else {
510 iter->second += descriptorSetCount;
511 }
512 }
513}
514
Camden5b184be2019-08-13 07:50:19 -0600515bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500516 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600517 bool skip = false;
518
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500519 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700520 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
521 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600522 }
523
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000524 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
525 skip |= LogPerformanceWarning(
526 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
527 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %llu. This is a very small allocation (current "
528 "threshold is %llu bytes). "
529 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
530 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
531 }
532
Camden83a9c372019-08-14 11:41:38 -0600533 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
534
535 return skip;
536}
537
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600538void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
539 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
540 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700541 if (result != VK_SUCCESS) {
542 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
543 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
544 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR};
545 static std::vector<VkResult> success_codes = {};
546 ValidateReturnCodes("vkReleaseFullScreenExclusiveModeEXT", result, error_codes, success_codes);
547 return;
548 }
549 num_mem_objects++;
550}
Camden Stocker9738af92019-10-16 13:54:03 -0700551
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600552void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
553 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700554 auto error = std::find(error_codes.begin(), error_codes.end(), result);
555 if (error != error_codes.end()) {
Mark Lobodzinski629defa2020-04-29 12:00:23 -0600556 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700557 return;
558 }
559 auto success = std::find(success_codes.begin(), success_codes.end(), result);
560 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600561 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
562 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500563 }
564}
565
Jeff Bolz5c801d12019-10-09 10:38:45 -0500566bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
567 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700568 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600569 bool skip = false;
570
Camden Stocker9738af92019-10-16 13:54:03 -0700571 const DEVICE_MEMORY_STATE* mem_info = ValidationStateTracker::GetDevMemState(memory);
Camden83a9c372019-08-14 11:41:38 -0600572
573 for (auto& obj : mem_info->obj_bindings) {
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600574 LogObjectList objlist(device);
575 objlist.add(obj);
576 objlist.add(mem_info->mem);
577 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 -0700578 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem).c_str());
Camden83a9c372019-08-14 11:41:38 -0600579 }
580
Camden5b184be2019-08-13 07:50:19 -0600581 return skip;
582}
583
584void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700585 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600586 if (memory != VK_NULL_HANDLE) {
587 num_mem_objects--;
588 }
589}
590
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000591bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600592 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500593 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600594
sfricke-samsunge2441192019-11-06 14:07:57 -0800595 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700596 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
597 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
598 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600599 }
600
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000601 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
602
603 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
604 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
605 skip |= LogPerformanceWarning(
606 device, kVUID_BestPractices_SmallDedicatedAllocation,
607 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
608 "The required size of the allocation is %llu, but smaller buffers like this should be sub-allocated from "
609 "larger memory blocks. (Current threshold is %llu bytes.)",
610 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
611 }
612
Camden Stockerb603cc82019-09-03 10:09:02 -0600613 return skip;
614}
615
616bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500617 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600618 bool skip = false;
619 const char* api_name = "BindBufferMemory()";
620
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000621 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600622
623 return skip;
624}
625
626bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500627 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600628 char api_name[64];
629 bool skip = false;
630
631 for (uint32_t i = 0; i < bindInfoCount; i++) {
632 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000633 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600634 }
635
636 return skip;
637}
Camden Stockerb603cc82019-09-03 10:09:02 -0600638
639bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500640 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600641 char api_name[64];
642 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600643
Camden Stocker8b798ab2019-09-03 10:33:28 -0600644 for (uint32_t i = 0; i < bindInfoCount; i++) {
645 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000646 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600647 }
648
649 return skip;
650}
651
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000652bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600653 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500654 const IMAGE_STATE* image_state = GetImageState(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600655
sfricke-samsung71bc6572020-04-29 15:49:43 -0700656 if (image_state->disjoint == false) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700657 if (!image_state->memory_requirements_checked && !image_state->external_memory_handle) {
658 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
659 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
660 api_name, report_data->FormatHandle(image).c_str());
661 }
662 } else {
663 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
664 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600665 }
666
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000667 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
668
669 if (mem_state->alloc_info.allocationSize == image_state->requirements.size &&
670 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
671 skip |= LogPerformanceWarning(
672 device, kVUID_BestPractices_SmallDedicatedAllocation,
673 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
674 "The required size of the allocation is %llu, but smaller images like this should be sub-allocated from "
675 "larger memory blocks. (Current threshold is %llu bytes.)",
676 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
677 }
678
679 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
680 // make sure this type is actually used.
681 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
682 // (i.e.most tile - based renderers)
683 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
684 bool supports_lazy = false;
685 uint32_t suggested_type = 0;
686
687 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
688 if ((1u << i) & image_state->requirements.memoryTypeBits) {
689 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
690 supports_lazy = true;
691 suggested_type = i;
692 break;
693 }
694 }
695 }
696
697 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
698
699 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
700 skip |= LogPerformanceWarning(
701 device, kVUID_BestPractices_NonLazyTransientImage,
702 "%s: Attempting to bind memory type % u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
703 "but this memory type is not LAZILY_ALLOCATED_BIT. You should use memory type %u here instead to save "
704 "%llu bytes of physical memory.",
705 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements.size);
706 }
707 }
708
Camden Stocker8b798ab2019-09-03 10:33:28 -0600709 return skip;
710}
711
712bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500713 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600714 bool skip = false;
715 const char* api_name = "vkBindImageMemory()";
716
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000717 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600718
719 return skip;
720}
721
722bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500723 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600724 char api_name[64];
725 bool skip = false;
726
727 for (uint32_t i = 0; i < bindInfoCount; i++) {
728 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Tony-LunarG5e60b852020-04-27 11:27:54 -0600729 if (!lvl_find_in_chain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
730 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
731 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600732 }
733
734 return skip;
735}
736
737bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500738 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600739 char api_name[64];
740 bool skip = false;
741
742 for (uint32_t i = 0; i < bindInfoCount; i++) {
743 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000744 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600745 }
746
747 return skip;
748}
Camden83a9c372019-08-14 11:41:38 -0600749
Attilio Provenzano02859b22020-02-27 14:17:28 +0000750static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
751 switch (format) {
752 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
753 case VK_FORMAT_R16_SFLOAT:
754 case VK_FORMAT_R16G16_SFLOAT:
755 case VK_FORMAT_R16G16B16_SFLOAT:
756 case VK_FORMAT_R16G16B16A16_SFLOAT:
757 case VK_FORMAT_R32_SFLOAT:
758 case VK_FORMAT_R32G32_SFLOAT:
759 case VK_FORMAT_R32G32B32_SFLOAT:
760 case VK_FORMAT_R32G32B32A32_SFLOAT:
761 return false;
762
763 default:
764 return true;
765 }
766}
767
768bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
769 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
770 bool skip = false;
771
772 for (uint32_t i = 0; i < createInfoCount; i++) {
773 auto pCreateInfo = &pCreateInfos[i];
774
775 if (!pCreateInfo->pColorBlendState || !pCreateInfo->pMultisampleState ||
776 pCreateInfo->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
777 pCreateInfo->pMultisampleState->sampleShadingEnable) {
778 return skip;
779 }
780
781 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
782 auto& subpass = rp_state->createInfo.pSubpasses[pCreateInfo->subpass];
783
784 for (uint32_t j = 0; j < pCreateInfo->pColorBlendState->attachmentCount; j++) {
785 auto& blend_att = pCreateInfo->pColorBlendState->pAttachments[j];
786 uint32_t att = subpass.pColorAttachments[j].attachment;
787
788 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
789 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
790 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
791 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
792 "color attachment #%u makes use "
793 "of a format which cannot be blended at full throughput when using MSAA.",
794 VendorSpecificTag(kBPVendorArm), i, j);
795 }
796 }
797 }
798 }
799
800 return skip;
801}
802
Camden5b184be2019-08-13 07:50:19 -0600803bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
804 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600805 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500806 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600807 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
808 pAllocator, pPipelines, cgpl_state_data);
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600809 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600810
811 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700812 skip |= LogPerformanceWarning(
813 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
814 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
815 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600816 }
817
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000818 for (uint32_t i = 0; i < createInfoCount; i++) {
819 auto& createInfo = pCreateInfos[i];
820
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600821 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
822 auto& vertexInput = *createInfo.pVertexInputState;
823 uint32_t count = 0;
824 for (uint32_t j = 0; j < vertexInput.vertexBindingDescriptionCount; j++) {
825 if (vertexInput.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
826 count++;
827 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000828 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600829 if (count > kMaxInstancedVertexBuffers) {
830 skip |= LogPerformanceWarning(
831 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
832 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
833 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
834 count, kMaxInstancedVertexBuffers);
835 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000836 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000837
Szilard Pappaaf2da32020-06-22 10:37:35 +0100838 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
839 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
840 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f)) {
841 skip |= VendorCheckEnabled(kBPVendorArm) &&
842 LogPerformanceWarning(
843 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
844 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
845 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
846 "efficiency during rasterization. Consider disabling depthBias or increasing either "
847 "depthBiasConstantFactor or depthBiasSlopeFactor.",
848 VendorSpecificTag(kBPVendorArm));
849 }
850
Attilio Provenzano02859b22020-02-27 14:17:28 +0000851 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000852 }
853
Camden5b184be2019-08-13 07:50:19 -0600854 return skip;
855}
856
Sam Walls0961ec02020-03-31 16:39:15 +0100857void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
858 const VkGraphicsPipelineCreateInfo* pCreateInfos,
859 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
860 VkResult result, void* cgpl_state_data) {
861 for (size_t i = 0; i < count; i++) {
862 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
863 const VkPipeline pipeline_handle = pPipelines[i];
864
865 // record depth stencil state and color blend states for depth pre-pass tracking purposes
866 auto gp_cis = graphicsPipelineCIs.find(pipeline_handle);
867
868 // add the tracking state if it doesn't exist
869 if (gp_cis == graphicsPipelineCIs.end()) {
870 auto result = graphicsPipelineCIs.emplace(std::make_pair(pipeline_handle, GraphicsPipelineCIs{}));
871
872 if (!result.second) continue;
873
874 gp_cis = result.first;
875 }
876
Tony-LunarG412b1b72020-07-15 10:30:13 -0600877 gp_cis->second.colorBlendStateCI =
878 cgpl_state->pCreateInfos[i].pColorBlendState
879 ? new safe_VkPipelineColorBlendStateCreateInfo(cgpl_state->pCreateInfos[i].pColorBlendState)
880 : nullptr;
881 gp_cis->second.depthStencilStateCI =
882 cgpl_state->pCreateInfos[i].pDepthStencilState
883 ? new safe_VkPipelineDepthStencilStateCreateInfo(cgpl_state->pCreateInfos[i].pDepthStencilState)
884 : nullptr;
Sam Walls0961ec02020-03-31 16:39:15 +0100885 }
886}
887
Camden5b184be2019-08-13 07:50:19 -0600888bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
889 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600890 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500891 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600892 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
893 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600894
895 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700896 skip |= LogPerformanceWarning(
897 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
898 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
899 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600900 }
901
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100902 if (VendorCheckEnabled(kBPVendorArm)) {
903 for (size_t i = 0; i < createInfoCount; i++) {
904 skip |= ValidateCreateComputePipelineArm(pCreateInfos[i]);
905 }
906 }
907
908 return skip;
909}
910
911bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
912 bool skip = false;
913 auto* module = GetShaderModuleState(createInfo.stage.module);
914
915 uint32_t x = 1, y = 1, z = 1;
916 FindLocalSize(module, x, y, z);
917
918 uint32_t thread_count = x * y * z;
919
920 // Generate a priori warnings about work group sizes.
921 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
922 skip |= LogPerformanceWarning(
923 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
924 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
925 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
926 "groups with less than %u threads, especially when using barrier() or shared memory.",
927 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
928 }
929
930 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
931 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
932 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
933 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
934 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
935 "%u, %u) is not aligned to %u "
936 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
937 "leave threads idle on the shader "
938 "core.",
939 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
940 kThreadGroupDispatchCountAlignmentArm);
941 }
942
943 // Generate warnings about work group sizes based on active resources.
944 auto entrypoint = FindEntrypoint(module, createInfo.stage.pName, createInfo.stage.stage);
945 if (entrypoint == module->end()) return false;
946
947 bool has_writeable_descriptors = false;
948 auto accessible_ids = MarkAccessibleIds(module, entrypoint);
949 auto descriptor_uses = CollectInterfaceByDescriptorSlot(module, accessible_ids, &has_writeable_descriptors);
950
951 unsigned dimensions = 0;
952 if (x > 1) dimensions++;
953 if (y > 1) dimensions++;
954 if (z > 1) dimensions++;
955 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
956 dimensions = std::max(dimensions, 1u);
957
958 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
959 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
960 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
961 bool accesses_2d = false;
962 for (const auto& usage : descriptor_uses) {
963 auto dim = GetShaderResourceDimensionality(module, usage.second);
964 if (dim < 0) continue;
965 auto spvdim = spv::Dim(dim);
966 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
967 }
968
969 if (accesses_2d && dimensions < 2) {
970 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
971 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
972 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
973 "exhibiting poor spatial locality with respect to one or more shader resources.",
974 VendorSpecificTag(kBPVendorArm), x, y, z);
975 }
976
Camden5b184be2019-08-13 07:50:19 -0600977 return skip;
978}
979
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500980bool BestPractices::CheckPipelineStageFlags(std::string api_name, const VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -0600981 bool skip = false;
982
983 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700984 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
985 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600986 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700987 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
988 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600989 }
990
991 return skip;
992}
993
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600994void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -0600995 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
996 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
997 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
998 LogPerformanceWarning(
999 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1000 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1001 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1002 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1003 "convenient opportunity.",
1004 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1005 }
1006 }
1007}
1008
Jeff Bolz5c801d12019-10-09 10:38:45 -05001009bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1010 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001011 bool skip = false;
1012
1013 for (uint32_t submit = 0; submit < submitCount; submit++) {
1014 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1015 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1016 }
1017 }
1018
1019 return skip;
1020}
1021
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001022bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1023 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1024 bool skip = false;
1025
1026 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1027 skip |= LogPerformanceWarning(
1028 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1029 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1030 "pool instead.");
1031 }
1032
1033 return skip;
1034}
1035
1036bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1037 const VkCommandBufferBeginInfo* pBeginInfo) const {
1038 bool skip = false;
1039
1040 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1041 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1042 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1043 }
1044
Attilio Provenzano02859b22020-02-27 14:17:28 +00001045 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT)) {
1046 skip |= VendorCheckEnabled(kBPVendorArm) &&
1047 LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
1048 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1049 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1050 VendorSpecificTag(kBPVendorArm));
1051 }
1052
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001053 return skip;
1054}
1055
Jeff Bolz5c801d12019-10-09 10:38:45 -05001056bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001057 bool skip = false;
1058
1059 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1060
1061 return skip;
1062}
1063
Jeff Bolz5c801d12019-10-09 10:38:45 -05001064bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1065 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001066 bool skip = false;
1067
1068 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1069
1070 return skip;
1071}
1072
1073bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1074 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1075 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1076 uint32_t bufferMemoryBarrierCount,
1077 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1078 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001079 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001080 bool skip = false;
1081
1082 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1083 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1084
1085 return skip;
1086}
1087
1088bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1089 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1090 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1091 uint32_t bufferMemoryBarrierCount,
1092 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1093 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001094 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001095 bool skip = false;
1096
1097 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1098 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1099
1100 return skip;
1101}
1102
1103bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001104 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001105 bool skip = false;
1106
1107 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", pipelineStage);
1108
1109 return skip;
1110}
1111
Sam Walls0961ec02020-03-31 16:39:15 +01001112void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1113 VkPipeline pipeline) {
1114 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1115
1116 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1117 // check for depth/blend state tracking
1118 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1119 if (gp_cis != graphicsPipelineCIs.end()) {
1120 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1121 if (prepass_state == cbDepthPrePassStates.end()) {
1122 auto result = cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1123
1124 if (!result.second) return;
1125
1126 prepass_state = result.first;
1127 }
1128
1129 const auto* blend_state = gp_cis->second.colorBlendStateCI;
1130 const auto* stencil_state = gp_cis->second.depthStencilStateCI;
1131
1132 if (blend_state) {
1133 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
1134 prepass_state->second.depthOnly = true;
1135 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1136 if (blend_state->pAttachments[i].colorWriteMask != 0) {
1137 prepass_state->second.depthOnly = false;
1138 }
1139 }
1140 }
1141
1142 // check for depth value usage
1143 prepass_state->second.depthEqualComparison = false;
1144
1145 if (stencil_state && stencil_state->depthTestEnable) {
1146 switch (stencil_state->depthCompareOp) {
1147 case VK_COMPARE_OP_EQUAL:
1148 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1149 case VK_COMPARE_OP_LESS_OR_EQUAL:
1150 prepass_state->second.depthEqualComparison = true;
1151 break;
1152 default:
1153 break;
1154 }
1155 }
1156 } else {
1157 // reset depth pre-pass tracking
1158 cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1159 }
1160 }
1161}
1162
Attilio Provenzano02859b22020-02-27 14:17:28 +00001163static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1164 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1165 auto& subpassInfo = createInfo.pSubpasses[subpass];
1166
1167 // If an attachment is ever used as a color attachment,
1168 // resolve attachment or depth stencil attachment,
1169 // it needs to exist on tile at some point.
1170
1171 for (uint32_t i = 0; i < subpassInfo.colorAttachmentCount; i++)
1172 if (subpassInfo.pColorAttachments[i].attachment == attachment) return true;
1173
1174 if (subpassInfo.pResolveAttachments) {
1175 for (uint32_t i = 0; i < subpassInfo.colorAttachmentCount; i++)
1176 if (subpassInfo.pResolveAttachments[i].attachment == attachment) return true;
1177 }
1178
1179 if (subpassInfo.pDepthStencilAttachment && subpassInfo.pDepthStencilAttachment->attachment == attachment) return true;
1180 }
1181
1182 return false;
1183}
1184
1185bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1186 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1187 bool skip = false;
1188
1189 if (!pRenderPassBegin) {
1190 return skip;
1191 }
1192
1193 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1194 if (rp_state) {
Tony-LunarG767180f2020-04-23 14:03:59 -06001195 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR) {
1196 const VkRenderPassAttachmentBeginInfo* rpabi =
1197 lvl_find_in_chain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1198 if (rpabi) {
1199 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1200 }
1201 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001202 // Check if any attachments have LOAD operation on them
1203 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1204 auto& attachment = rp_state->createInfo.pAttachments[att];
1205
1206 bool attachmentHasReadback = false;
1207 if (!FormatHasStencil(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1208 attachmentHasReadback = true;
1209 }
1210
1211 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1212 attachmentHasReadback = true;
1213 }
1214
1215 bool attachmentNeedsReadback = false;
1216
1217 // Check if the attachment is actually used in any subpass on-tile
1218 if (attachmentHasReadback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1219 attachmentNeedsReadback = true;
1220 }
1221
1222 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
1223 if (attachmentNeedsReadback) {
1224 skip |= VendorCheckEnabled(kBPVendorArm) &&
1225 LogPerformanceWarning(
1226 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1227 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1228 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
1229 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
1230 VendorSpecificTag(kBPVendorArm), att,
1231 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1232 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1233 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
1234 }
1235 }
1236 }
1237
1238 return skip;
1239}
1240
1241bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1242 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001243 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1244 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001245 return skip;
1246}
1247
1248bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1249 const VkRenderPassBeginInfo* pRenderPassBegin,
1250 const VkSubpassBeginInfoKHR* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001251 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1252 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001253 return skip;
1254}
1255
1256bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1257 const VkSubpassBeginInfoKHR* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001258 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1259 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001260 return skip;
1261}
1262
Sam Walls0961ec02020-03-31 16:39:15 +01001263void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1264 const VkRenderPassBeginInfo* pRenderPassBegin) {
1265 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1266
1267 // add the tracking state if it doesn't exist
1268 if (prepass_state == cbDepthPrePassStates.end()) {
1269 auto result = cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1270
1271 if (!result.second) return;
1272
1273 prepass_state = result.first;
1274 }
1275
1276 // reset the renderpass state
1277 prepass_state->second = {};
1278
1279 const auto* cb_state = GetCBState(commandBuffer);
locke-lunargaecf2152020-05-12 17:15:41 -06001280 const auto* rp_state = cb_state->activeRenderPass.get();
Sam Walls0961ec02020-03-31 16:39:15 +01001281
1282 // track depth / color attachment usage within the renderpass
1283 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1284 // record if depth/color attachments are in use for this renderpass
1285 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) prepass_state->second.depthAttachment = true;
1286
1287 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) prepass_state->second.colorAttachment = true;
1288 }
1289}
1290
1291void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1292 VkSubpassContents contents) {
1293 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1294 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1295}
1296
1297void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1298 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1299 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1300 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1301}
1302
1303void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1304 const VkRenderPassBeginInfo* pRenderPassBegin,
1305 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1306 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1307 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1308}
1309
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001310// Generic function to handle validation for all CmdDraw* type functions
1311bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1312 bool skip = false;
1313 const CMD_BUFFER_STATE* cb_state = GetCBState(cmd_buffer);
1314 if (cb_state) {
1315 const auto last_bound_it = cb_state->lastBound.find(VK_PIPELINE_BIND_POINT_GRAPHICS);
1316 const PIPELINE_STATE* pipeline_state = nullptr;
1317 if (last_bound_it != cb_state->lastBound.cend()) {
1318 pipeline_state = last_bound_it->second.pipeline_state;
1319 }
1320 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
1321 // Verify vertex binding
1322 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1323 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001324 skip |= LogPerformanceWarning(cb_state->commandBuffer, kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
1325 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
1326 report_data->FormatHandle(cb_state->commandBuffer).c_str(),
1327 report_data->FormatHandle(pipeline_state->pipeline).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001328 }
1329 }
1330 }
1331 return skip;
1332}
1333
Sam Walls0961ec02020-03-31 16:39:15 +01001334void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1335 if (VendorCheckEnabled(kBPVendorArm)) {
1336 RecordCmdDrawTypeArm(cmd_buffer, draw_count, caller);
1337 }
1338}
1339
1340void BestPractices::RecordCmdDrawTypeArm(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1341 auto prepass_state = cbDepthPrePassStates.find(cmd_buffer);
1342 if (prepass_state != cbDepthPrePassStates.end() && draw_count >= kDepthPrePassMinDrawCountArm) {
1343 if (prepass_state->second.depthOnly) prepass_state->second.numDrawCallsDepthOnly++;
1344
1345 if (prepass_state->second.depthEqualComparison) prepass_state->second.numDrawCallsDepthEqualCompare++;
1346 }
1347}
1348
Camden5b184be2019-08-13 07:50:19 -06001349bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001350 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001351 bool skip = false;
1352
1353 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001354 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1355 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001356 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001357 }
1358
1359 return skip;
1360}
1361
Sam Walls0961ec02020-03-31 16:39:15 +01001362void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1363 uint32_t firstVertex, uint32_t firstInstance) {
1364 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
1365 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
1366}
1367
Camden5b184be2019-08-13 07:50:19 -06001368bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001369 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001370 bool skip = false;
1371
1372 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001373 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1374 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001375 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001376 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1377
Attilio Provenzano02859b22020-02-27 14:17:28 +00001378 // Check if we reached the limit for small indexed draw calls.
1379 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1380 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1381 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
1382 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1)) {
1383 skip |= VendorCheckEnabled(kBPVendorArm) &&
1384 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
1385 "The command buffer contains many small indexed drawcalls "
1386 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1387 "You can try batching drawcalls or instancing when applicable.",
1388 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1389 }
1390
Sam Walls8e77e4f2020-03-16 20:47:40 +00001391 if (VendorCheckEnabled(kBPVendorArm)) {
1392 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1393 }
1394
1395 return skip;
1396}
1397
1398bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1399 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1400 bool skip = false;
1401
1402 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1403 const auto* cmd_state = GetCBState(commandBuffer);
1404 if (cmd_state == nullptr) return skip;
1405
1406 const auto* ib_state = GetBufferState(cmd_state->index_buffer_binding.buffer);
1407 if (ib_state == nullptr) return skip;
1408
1409 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
1410 const auto& ib_mem_state = *ib_state->binding.mem_state;
1411 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1412 const void* ib_mem = ib_mem_state.p_driver_data;
1413 bool primitive_restart_enable = false;
1414
1415 const auto& pipeline_binding_iter = cmd_state->lastBound.find(VK_PIPELINE_BIND_POINT_GRAPHICS);
1416
1417 if (pipeline_binding_iter != cmd_state->lastBound.end()) {
1418 const auto* pipeline_state = pipeline_binding_iter->second.pipeline_state;
1419 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr)
1420 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
1421 }
1422
1423 // no point checking index buffer if the memory is nonexistant/unmapped, or if there is no graphics pipeline bound to this CB
1424 if (ib_mem && pipeline_binding_iter != cmd_state->lastBound.end()) {
1425 uint32_t scan_stride;
1426 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1427 scan_stride = sizeof(uint8_t);
1428 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1429 scan_stride = sizeof(uint16_t);
1430 } else {
1431 scan_stride = sizeof(uint32_t);
1432 }
1433
1434 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1435 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1436
1437 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1438 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1439 // irrespective of whether or not they're part of the draw call.
1440
1441 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1442 uint32_t min_index = ~0u;
1443 // start with maximum as 0 and adjust to indices in the buffer
1444 uint32_t max_index = 0u;
1445
1446 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
1447 // for the given index buffer
1448 uint32_t vertex_shade_count = 0;
1449
1450 PostTransformLRUCacheModel post_transform_cache;
1451
1452 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
1453 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
1454 // target architecture.
1455 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
1456 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
1457 post_transform_cache.resize(32);
1458
1459 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1460 uint32_t scan_index;
1461 uint32_t primitive_restart_value;
1462 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1463 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1464 primitive_restart_value = 0xFF;
1465 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1466 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1467 primitive_restart_value = 0xFFFF;
1468 } else {
1469 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1470 primitive_restart_value = 0xFFFFFFFF;
1471 }
1472
1473 max_index = std::max(max_index, scan_index);
1474 min_index = std::min(min_index, scan_index);
1475
1476 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
1477 bool in_cache = post_transform_cache.query_cache(scan_index);
1478 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
1479 if (!in_cache) vertex_shade_count++;
1480 }
1481 }
1482
1483 // if the max and min values were not set, then we either have no indices, or all primitive restarts, exit...
1484 if (max_index < min_index) return skip;
1485
1486 if (max_index - min_index >= indexCount) {
1487 skip |= LogPerformanceWarning(
1488 device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1489 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
1490 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
1491 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
1492 "maximum would be loaded, and possibly shaded, whether or not they are used.",
1493 VendorSpecificTag(kBPVendorArm), (static_cast<float>(indexCount) / (max_index - min_index)) * 100.0f);
1494 return skip;
1495 }
1496
1497 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
1498 // each bit of the n-th bucket contains the inclusion information for indices (n*n_buckets) to ((n+1)*n_buckets)
1499 const size_t n_buckets = 64;
1500 std::vector<std::bitset<n_buckets>> vertex_reference_buckets;
1501 vertex_reference_buckets.resize((max_index - min_index + 1) / n_buckets);
1502
1503 // To avoid using too much memory, we run over the indices again.
1504 // Knowing the size from the last scan allows us to record index usage with bitsets
1505 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1506 uint32_t scan_index;
1507 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1508 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1509 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1510 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1511 } else {
1512 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1513 }
1514 // keep track of the set of all indices used to reference vertices in the draw call
1515 size_t index_offset = scan_index - min_index;
1516 size_t bitset_bucket_index = index_offset / n_buckets;
1517 uint64_t used_indices = 1ull << ((index_offset % n_buckets) & 0xFFFFFFFFu);
1518 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
1519 }
1520
1521 uint32_t vertex_reference_count = 0;
1522 for (const auto& bitset : vertex_reference_buckets) {
1523 vertex_reference_count += static_cast<uint32_t>(bitset.count());
1524 }
1525
1526 // low index buffer utilization implies that: of the vertices available to the draw call, not all are utilized
1527 float utilization = static_cast<float>(vertex_reference_count) / (max_index - min_index + 1);
1528 // low hit rate (high miss rate) implies the order of indices in the draw call may be possible to improve
1529 float cache_hit_rate = static_cast<float>(vertex_reference_count) / vertex_shade_count;
1530
1531 if (utilization < 0.5f) {
1532 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1533 "%s The indices which were specified for the draw call only utilise approximately "
1534 "%.02f%% of the bound vertex buffer.",
1535 VendorSpecificTag(kBPVendorArm), utilization);
1536 }
1537
1538 if (cache_hit_rate <= 0.5f) {
1539 skip |=
1540 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
1541 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
1542 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
1543 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
1544 "recently shaded vertices.",
1545 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
1546 }
1547 }
1548
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001549 return skip;
1550}
1551
Attilio Provenzano02859b22020-02-27 14:17:28 +00001552void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1553 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1554 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
1555 firstInstance);
1556
1557 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1558 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
1559 cmd_state->small_indexed_draw_call_count++;
1560 }
1561}
1562
Sam Walls0961ec02020-03-31 16:39:15 +01001563void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1564 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1565 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1566 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
1567}
1568
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001569bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
1570 VkDeviceSize offset, VkBuffer countBuffer,
1571 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
1572 uint32_t stride) const {
1573 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06001574
1575 return skip;
1576}
1577
1578bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001579 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001580 bool skip = false;
1581
1582 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001583 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1584 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001585 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001586 }
1587
1588 return skip;
1589}
1590
Sam Walls0961ec02020-03-31 16:39:15 +01001591void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1592 uint32_t count, uint32_t stride) {
1593 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
1594 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
1595}
1596
Camden5b184be2019-08-13 07:50:19 -06001597bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001598 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001599 bool skip = false;
1600
1601 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001602 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1603 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001604 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001605 }
1606
1607 return skip;
1608}
1609
Sam Walls0961ec02020-03-31 16:39:15 +01001610void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1611 uint32_t count, uint32_t stride) {
1612 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
1613 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
1614}
1615
Camden5b184be2019-08-13 07:50:19 -06001616bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001617 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06001618 bool skip = false;
1619
1620 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001621 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
1622 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
1623 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
1624 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06001625 }
1626
1627 return skip;
1628}
Camden83a9c372019-08-14 11:41:38 -06001629
Sam Walls0961ec02020-03-31 16:39:15 +01001630bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
1631 bool skip = false;
1632
1633 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
1634
1635 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1636
1637 if (prepass_state == cbDepthPrePassStates.end()) return skip;
1638
1639 bool uses_depth = (prepass_state->second.depthAttachment || prepass_state->second.colorAttachment) &&
1640 prepass_state->second.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
1641 prepass_state->second.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
1642 if (uses_depth) {
1643 skip |= LogPerformanceWarning(
1644 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
1645 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
1646 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
1647 "case, using depth pre-passes for hidden surface removal may worsen performance.",
1648 VendorSpecificTag(kBPVendorArm));
1649 }
1650
1651 return skip;
1652}
1653
Camden Stocker9c051442019-11-06 14:28:43 -08001654bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
1655 const char* api_name) const {
1656 bool skip = false;
1657 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1658
1659 if (physical_device_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001660 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
1661 "Potential problem with calling %s() without first retrieving properties from "
1662 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
1663 api_name);
Camden Stocker9c051442019-11-06 14:28:43 -08001664 }
1665
1666 return skip;
1667}
1668
Camden83a9c372019-08-14 11:41:38 -06001669bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001670 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06001671 bool skip = false;
1672
Camden Stocker9c051442019-11-06 14:28:43 -08001673 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06001674
Camden Stocker9c051442019-11-06 14:28:43 -08001675 return skip;
1676}
1677
1678bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
1679 uint32_t planeIndex,
1680 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
1681 bool skip = false;
1682
1683 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
1684
1685 return skip;
1686}
1687
1688bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
1689 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
1690 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
1691 bool skip = false;
1692
1693 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06001694
1695 return skip;
1696}
Camden05de2d42019-08-19 10:23:56 -06001697
1698bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001699 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06001700 bool skip = false;
1701
1702 auto swapchain_state = GetSwapchainState(swapchain);
1703
1704 if (swapchain_state && pSwapchainImages) {
1705 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
1706 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001707 skip |=
1708 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
1709 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
1710 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06001711 }
1712 }
1713
1714 return skip;
1715}
1716
1717// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001718bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
1719 uint32_t requested_queue_family_property_count,
1720 bool qfp_null, const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06001721 bool skip = false;
1722 if (!qfp_null) {
1723 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
1724 if (UNCALLED == pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001725 skip |= LogWarning(
1726 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
Camden05de2d42019-08-19 10:23:56 -06001727 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is recommended "
1728 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
1729 caller_name, caller_name);
1730 // Then verify that pCount that is passed in on second call matches what was returned
1731 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001732 skip |= LogWarning(
1733 pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
Camden05de2d42019-08-19 10:23:56 -06001734 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
1735 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
1736 ". It is recommended to instead receive all the properties by calling %s with pQueueFamilyPropertyCount that was "
1737 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
1738 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name, caller_name);
1739 }
1740 }
1741
1742 return skip;
1743}
1744
Jeff Bolz5c801d12019-10-09 10:38:45 -05001745bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
1746 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06001747 bool skip = false;
1748
1749 for (uint32_t i = 0; i < bindInfoCount; i++) {
1750 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureState(pBindInfos[i].accelerationStructure);
1751 if (!as_state->memory_requirements_checked) {
1752 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
1753 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
1754 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001755 skip |= LogWarning(
1756 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06001757 "vkBindAccelerationStructureMemoryNV(): "
1758 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
1759 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
1760 }
1761 }
1762
1763 return skip;
1764}
1765
Camden05de2d42019-08-19 10:23:56 -06001766bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
1767 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001768 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001769 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1770 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001771 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001772 (nullptr == pQueueFamilyProperties),
1773 "vkGetPhysicalDeviceQueueFamilyProperties()");
1774}
1775
Jeff Bolz5c801d12019-10-09 10:38:45 -05001776bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(
1777 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount,
1778 VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001779 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1780 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001781 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001782 (nullptr == pQueueFamilyProperties),
1783 "vkGetPhysicalDeviceQueueFamilyProperties2()");
1784}
1785
Jeff Bolz5c801d12019-10-09 10:38:45 -05001786bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
1787 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount,
1788 VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001789 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1790 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001791 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001792 (nullptr == pQueueFamilyProperties),
1793 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
1794}
1795
1796bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
1797 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001798 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06001799 if (!pSurfaceFormats) return false;
1800 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1801 const auto& call_state = physical_device_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
1802 bool skip = false;
1803 if (call_state == UNCALLED) {
1804 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
1805 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001806 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
1807 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
1808 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06001809 } else {
1810 auto prev_format_count = (uint32_t)physical_device_state->surface_formats.size();
Peter Chene191bd72019-09-16 13:04:37 -04001811 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001812 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
1813 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
1814 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
1815 "when pSurfaceFormatCount was NULL.",
1816 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06001817 }
1818 }
1819 return skip;
1820}
Camden Stocker23cc47d2019-09-03 14:53:57 -06001821
1822bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001823 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001824 bool skip = false;
1825
1826 for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; bindIdx++) {
1827 const VkBindSparseInfo& bindInfo = pBindInfo[bindIdx];
1828 // 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 -05001829 std::unordered_set<const IMAGE_STATE*> sparse_images;
1830 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
1831 // in RecordQueueBindSparse.
1832 std::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06001833 // If we're binding sparse image memory make sure reqs were queried and note if metadata is required and bound
1834 for (uint32_t i = 0; i < bindInfo.imageBindCount; ++i) {
1835 const auto& image_bind = bindInfo.pImageBinds[i];
1836 auto image_state = GetImageState(image_bind.image);
1837 if (!image_state)
1838 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1839 sparse_images.insert(image_state);
1840 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1841 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1842 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001843 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1844 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1845 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1846 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001847 }
1848 }
1849 if (!image_state->memory_requirements_checked) {
1850 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001851 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1852 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1853 "vkGetImageMemoryRequirements() to retrieve requirements.",
1854 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001855 }
1856 }
1857 for (uint32_t i = 0; i < bindInfo.imageOpaqueBindCount; ++i) {
1858 const auto& image_opaque_bind = bindInfo.pImageOpaqueBinds[i];
1859 auto image_state = GetImageState(bindInfo.pImageOpaqueBinds[i].image);
1860 if (!image_state)
1861 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1862 sparse_images.insert(image_state);
1863 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1864 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1865 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001866 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1867 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1868 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1869 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001870 }
1871 }
1872 if (!image_state->memory_requirements_checked) {
1873 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001874 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1875 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1876 "vkGetImageMemoryRequirements() to retrieve requirements.",
1877 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001878 }
1879 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1880 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001881 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06001882 }
1883 }
1884 }
1885 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001886 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
1887 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001888 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001889 skip |= LogWarning(sparse_image_state->image, kVUID_Core_MemTrack_InvalidState,
1890 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
1891 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
1892 report_data->FormatHandle(sparse_image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001893 }
1894 }
1895 }
1896
1897 return skip;
1898}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001899
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001900void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
1901 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001902 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001903 return;
1904 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001905
1906 for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; bindIdx++) {
1907 const VkBindSparseInfo& bindInfo = pBindInfo[bindIdx];
1908 for (uint32_t i = 0; i < bindInfo.imageOpaqueBindCount; ++i) {
1909 const auto& image_opaque_bind = bindInfo.pImageOpaqueBinds[i];
1910 auto image_state = GetImageState(bindInfo.pImageOpaqueBinds[i].image);
1911 if (!image_state)
1912 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1913 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1914 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
1915 image_state->sparse_metadata_bound = true;
1916 }
1917 }
1918 }
1919 }
1920}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001921
1922bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06001923 const VkClearAttachment* pAttachments, uint32_t rectCount,
1924 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001925 bool skip = false;
1926 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
1927 if (!cb_node) return skip;
1928
Camden Stockerf55721f2019-09-09 11:04:49 -06001929 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001930 if (!cb_node->hasDrawCmd && (cb_node->activeRenderPassBeginInfo.renderArea.extent.width == pRects[0].rect.extent.width) &&
1931 (cb_node->activeRenderPassBeginInfo.renderArea.extent.height == pRects[0].rect.extent.height)) {
1932 // There are times where app needs to use ClearAttachments (generally when reusing a buffer inside of a render pass)
1933 // This warning should be made more specific. It'd be best to avoid triggering this test if it's a use that must call
1934 // CmdClearAttachments.
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001935 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
1936 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds. It is recommended you "
1937 "use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
1938 report_data->FormatHandle(commandBuffer).c_str());
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001939 }
1940
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001941 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
1942 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06001943 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001944 if (rp) {
1945 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
1946
1947 for (uint32_t i = 0; i < attachmentCount; i++) {
1948 auto& attachment = pAttachments[i];
1949 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
1950 uint32_t color_attachment = attachment.colorAttachment;
1951 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
1952
1953 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
1954 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1955 skip |= LogPerformanceWarning(
1956 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
1957 "vkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
1958 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
1959 "it is more efficient.",
1960 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
1961 }
1962 }
1963 }
1964
1965 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
1966 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
1967
1968 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
1969 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1970 skip |= LogPerformanceWarning(
1971 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
1972 "vkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
1973 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
1974 "it is more efficient.",
1975 report_data->FormatHandle(commandBuffer).c_str());
1976 }
1977 }
1978 }
1979
1980 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
1981 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
1982
1983 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
1984 if (rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1985 skip |= LogPerformanceWarning(
1986 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
1987 "vkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
1988 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
1989 "it is more efficient.",
1990 report_data->FormatHandle(commandBuffer).c_str());
1991 }
1992 }
1993 }
1994 }
1995 }
1996
Camden Stockerf55721f2019-09-09 11:04:49 -06001997 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001998}
Attilio Provenzano02859b22020-02-27 14:17:28 +00001999
2000bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2001 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2002 const VkImageResolve* pRegions) const {
2003 bool skip = false;
2004
2005 skip |= VendorCheckEnabled(kBPVendorArm) &&
2006 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
2007 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
2008 "This is a very slow and extremely bandwidth intensive path. "
2009 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2010 VendorSpecificTag(kBPVendorArm));
2011
2012 return skip;
2013}
2014
2015bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
2016 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
2017 bool skip = false;
2018
2019 if (VendorCheckEnabled(kBPVendorArm)) {
2020 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
2021 skip |= LogPerformanceWarning(
2022 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
2023 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
2024 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
2025 "image) are actually used. If you need different wrapping modes, disregard this warning.",
2026 VendorSpecificTag(kBPVendorArm));
2027 }
2028
2029 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
2030 skip |= LogPerformanceWarning(
2031 device, kVUID_BestPractices_CreateSampler_LodClamping,
2032 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
2033 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
2034 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
2035 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
2036 }
2037
2038 if (pCreateInfo->mipLodBias != 0.0f) {
2039 skip |=
2040 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
2041 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
2042 "descriptors being created and may cause reduced performance.",
2043 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
2044 }
2045
2046 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2047 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2048 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
2049 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
2050 skip |= LogPerformanceWarning(
2051 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
2052 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
2053 "This will lead to less efficient descriptors being created and may cause reduced performance. "
2054 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
2055 VendorSpecificTag(kBPVendorArm));
2056 }
2057
2058 if (pCreateInfo->unnormalizedCoordinates) {
2059 skip |= LogPerformanceWarning(
2060 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
2061 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
2062 "descriptors being created and may cause reduced performance.",
2063 VendorSpecificTag(kBPVendorArm));
2064 }
2065
2066 if (pCreateInfo->anisotropyEnable) {
2067 skip |= LogPerformanceWarning(
2068 device, kVUID_BestPractices_CreateSampler_Anisotropy,
2069 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
2070 "and may cause reduced performance.",
2071 VendorSpecificTag(kBPVendorArm));
2072 }
2073 }
2074
2075 return skip;
2076}
Sam Walls8e77e4f2020-03-16 20:47:40 +00002077
2078void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
2079
2080bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
2081 // look for a cache hit
2082 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
2083 if (hit != _entries.end()) {
2084 // mark the cache hit as being most recently used
2085 hit->age = iteration++;
2086 return true;
2087 }
2088
2089 // if there's no cache hit, we need to model the entry being inserted into the cache
2090 CacheEntry new_entry = {value, iteration};
2091 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
2092 // if there is still space left in the cache, use the next available slot
2093 *(_entries.begin() + iteration) = new_entry;
2094 } else {
2095 // otherwise replace the least recently used cache entry
2096 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
2097 *lru = new_entry;
2098 }
2099 iteration++;
2100 return false;
2101}