blob: 36b893a81ceb08eacb21da958b7c2f98b6f105c4 [file] [log] [blame]
Jeremy Gebben610d3a62022-01-01 12:53:17 -07001/* Copyright (c) 2015-2022 The Khronos Group Inc.
2 * Copyright (c) 2015-2022 Valve Corporation
3 * Copyright (c) 2015-2022 LunarG, Inc.
Nadav Geva41c12a22021-05-21 13:14:05 -04004 * Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
Camdeneaa86ea2019-07-26 11:00:09 -06005 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 * Author: Camden Stocker <camden@lunarg.com>
Nadav Geva41c12a22021-05-21 13:14:05 -040019 * Author: Nadav Geva <nadav.geva@amd.com>
Camdeneaa86ea2019-07-26 11:00:09 -060020 */
21
Mark Lobodzinski57b8ae82020-02-20 16:37:14 -070022#include "best_practices_validation.h"
Camden5b184be2019-08-13 07:50:19 -060023#include "layer_chassis_dispatch.h"
Camden Stocker0a660ce2019-08-27 15:30:40 -060024#include "best_practices_error_enums.h"
Sam Wallsd7ab6db2020-06-19 20:41:54 +010025#include "shader_validation.h"
Jeremy Gebbena3705f42021-01-19 16:47:43 -070026#include "sync_utils.h"
Jeremy Gebben159b3cc2021-06-03 09:09:03 -060027#include "cmd_buffer_state.h"
28#include "device_state.h"
29#include "render_pass_state.h"
Camden5b184be2019-08-13 07:50:19 -060030
31#include <string>
Sam Walls8e77e4f2020-03-16 20:47:40 +000032#include <bitset>
Sam Wallsd7ab6db2020-06-19 20:41:54 +010033#include <memory>
Camden5b184be2019-08-13 07:50:19 -060034
Attilio Provenzano19d6a982020-02-27 12:41:41 +000035struct VendorSpecificInfo {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060036 EnableFlags vendor_id;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000037 std::string name;
38};
39
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070040const std::map<BPVendorFlagBits, VendorSpecificInfo> kVendorInfo = {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060041 {kBPVendorArm, {vendor_specific_arm, "Arm"}},
Nadav Geva41c12a22021-05-21 13:14:05 -040042 {kBPVendorAMD, {vendor_specific_amd, "AMD"}},
Attilio Provenzano19d6a982020-02-27 12:41:41 +000043};
44
Hannes Harnisch607d1d92021-07-10 18:44:56 +020045const SpecialUseVUIDs kSpecialUseInstanceVUIDs {
46 kVUID_BestPractices_CreateInstance_SpecialUseExtension_CADSupport,
47 kVUID_BestPractices_CreateInstance_SpecialUseExtension_D3DEmulation,
48 kVUID_BestPractices_CreateInstance_SpecialUseExtension_DevTools,
49 kVUID_BestPractices_CreateInstance_SpecialUseExtension_Debugging,
50 kVUID_BestPractices_CreateInstance_SpecialUseExtension_GLEmulation,
51};
52
53const SpecialUseVUIDs kSpecialUseDeviceVUIDs {
54 kVUID_BestPractices_CreateDevice_SpecialUseExtension_CADSupport,
55 kVUID_BestPractices_CreateDevice_SpecialUseExtension_D3DEmulation,
56 kVUID_BestPractices_CreateDevice_SpecialUseExtension_DevTools,
57 kVUID_BestPractices_CreateDevice_SpecialUseExtension_Debugging,
58 kVUID_BestPractices_CreateDevice_SpecialUseExtension_GLEmulation,
59};
60
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060061std::shared_ptr<CMD_BUFFER_STATE> BestPractices::CreateCmdBufferState(VkCommandBuffer cb,
62 const VkCommandBufferAllocateInfo* pCreateInfo,
Jeremy Gebbencd7fa282021-10-27 10:25:32 -060063 const COMMAND_POOL_STATE* pool) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060064 return std::static_pointer_cast<CMD_BUFFER_STATE>(std::make_shared<CMD_BUFFER_STATE_BP>(this, cb, pCreateInfo, pool));
65}
66
67CMD_BUFFER_STATE_BP::CMD_BUFFER_STATE_BP(BestPractices* bp, VkCommandBuffer cb, const VkCommandBufferAllocateInfo* pCreateInfo,
Jeremy Gebbencd7fa282021-10-27 10:25:32 -060068 const COMMAND_POOL_STATE* pool)
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060069 : CMD_BUFFER_STATE(bp, cb, pCreateInfo, pool) {}
70
Attilio Provenzano19d6a982020-02-27 12:41:41 +000071bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070072 for (const auto& vendor : kVendorInfo) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060073 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000074 return true;
75 }
76 }
77 return false;
78}
79
80const char* VendorSpecificTag(BPVendorFlags vendors) {
81 // Cache built vendor tags in a map
Jeremy Gebbencbf22862021-03-03 12:01:22 -070082 static layer_data::unordered_map<BPVendorFlags, std::string> tag_map;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000083
84 auto res = tag_map.find(vendors);
85 if (res == tag_map.end()) {
86 // Build the vendor tag string
87 std::stringstream vendor_tag;
88
89 vendor_tag << "[";
90 bool first_vendor = true;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070091 for (const auto& vendor : kVendorInfo) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000092 if (vendors & vendor.first) {
93 if (!first_vendor) {
94 vendor_tag << ", ";
95 }
96 vendor_tag << vendor.second.name;
97 first_vendor = false;
98 }
99 }
100 vendor_tag << "]";
101
102 tag_map[vendors] = vendor_tag.str();
103 res = tag_map.find(vendors);
104 }
105
106 return res->second.c_str();
107}
108
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700109const char* DepReasonToString(ExtDeprecationReason reason) {
110 switch (reason) {
111 case kExtPromoted:
112 return "promoted to";
113 break;
114 case kExtObsoleted:
115 return "obsoleted by";
116 break;
117 case kExtDeprecated:
118 return "deprecated by";
119 break;
120 default:
121 return "";
122 break;
123 }
124}
125
126bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
127 const char* vuid) const {
128 bool skip = false;
129 auto dep_info_it = deprecated_extensions.find(extension_name);
130 if (dep_info_it != deprecated_extensions.end()) {
131 auto dep_info = dep_info_it->second;
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600132 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
Tony-LunarGc30b59f2022-02-15 11:02:36 -0700133 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2)) ||
134 ((dep_info.target.compare("VK_VERSION_1_3") == 0) && (version >= VK_API_VERSION_1_3))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700135 skip |=
136 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
137 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600138 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700139 if (dep_info.target.length() == 0) {
140 skip |= LogWarning(instance, vuid,
141 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
142 "without replacement.",
143 api_name, extension_name);
144 } else {
145 skip |= LogWarning(instance, vuid,
146 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
147 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
148 }
149 }
150 }
151 return skip;
152}
153
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200154bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const SpecialUseVUIDs& special_use_vuids) const
155{
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700156 bool skip = false;
157 auto dep_info_it = special_use_extensions.find(extension_name);
158
159 if (dep_info_it != special_use_extensions.end()) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200160 const char* const format = "%s(): Attempting to enable extension %s, but this extension is intended to support %s "
161 "and it is strongly recommended that it be otherwise avoided.";
162 auto& special_uses = dep_info_it->second;
sfricke-samsungef15e482022-01-26 11:32:49 -0800163
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700164 if (special_uses.find("cadsupport") != std::string::npos) {
sfricke-samsungef15e482022-01-26 11:32:49 -0800165 skip |= LogWarning(instance, special_use_vuids.cadsupport, format, api_name, extension_name,
166 "specialized functionality used by CAD/CAM applications");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700167 }
168 if (special_uses.find("d3demulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200169 skip |= LogWarning(instance, special_use_vuids.d3demulation, format, api_name, extension_name,
170 "D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700171 }
172 if (special_uses.find("devtools") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200173 skip |= LogWarning(instance, special_use_vuids.devtools, format, api_name, extension_name,
174 "developer tools such as capture-replay libraries");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700175 }
176 if (special_uses.find("debugging") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200177 skip |= LogWarning(instance, special_use_vuids.debugging, format, api_name, extension_name,
178 "use by applications when debugging");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700179 }
180 if (special_uses.find("glemulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200181 skip |= LogWarning(instance, special_use_vuids.glemulation, format, api_name, extension_name,
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700182 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200183 "specific to those APIs");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700184 }
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700185 }
186 return skip;
187}
188
Nadav Gevaf0808442021-05-21 13:51:25 -0400189void BestPractices::InitDeviceValidationObject(bool add_obj, ValidationObject* inst_obj, ValidationObject* dev_obj) {
190 if (add_obj) {
191 ValidationStateTracker::InitDeviceValidationObject(add_obj, inst_obj, dev_obj);
192 }
193}
194
195
Camden5b184be2019-08-13 07:50:19 -0600196bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500197 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600198 bool skip = false;
199
200 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
201 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800202 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700203 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
204 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600205 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600206 uint32_t specified_version =
207 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
208 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700209 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200210 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseInstanceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600211 }
212
213 return skip;
214}
215
Camden5b184be2019-08-13 07:50:19 -0600216bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500217 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600218 bool skip = false;
219
220 // get API version of physical device passed when creating device.
221 VkPhysicalDeviceProperties physical_device_properties{};
222 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500223 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600224
225 // check api versions and warn if instance api Version is higher than version on device.
Jeremy Gebben404f6ac2021-10-28 12:33:28 -0600226 if (api_version > device_api_version) {
227 std::string inst_api_name = StringAPIVersion(api_version);
Mark Lobodzinski60880782020-08-11 08:02:07 -0600228 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600229
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700230 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
231 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
232 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600233 }
234
235 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
236 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800237 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700238 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
239 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600240 }
Jeremy Gebben404f6ac2021-10-28 12:33:28 -0600241 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], api_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700242 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200243 skip |= ValidateSpecialUseExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseDeviceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600244 }
245
Jeremy Gebben78684b12022-02-23 17:31:56 -0700246 const auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600247 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700248 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
249 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600250 }
251
Nadav Gevaf0808442021-05-21 13:51:25 -0400252 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorAMD)) && (pCreateInfo->pEnabledFeatures != nullptr) &&
Szilard Papp7d2c7952020-06-22 14:38:13 +0100253 (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
254 skip |= LogPerformanceWarning(
255 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
Nadav Gevaf0808442021-05-21 13:51:25 -0400256 "%s %s vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
Szilard Papp7d2c7952020-06-22 14:38:13 +0100257 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
258 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
259 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
Nadav Gevaf0808442021-05-21 13:51:25 -0400260 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorAMD));
Szilard Papp7d2c7952020-06-22 14:38:13 +0100261 }
262
Camden5b184be2019-08-13 07:50:19 -0600263 return skip;
264}
265
266bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500267 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600268 bool skip = false;
269
270 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700271 std::stringstream buffer_hex;
272 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600273
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700274 skip |= LogWarning(
275 device, kVUID_BestPractices_SharingModeExclusive,
276 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
277 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700278 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600279 }
280
281 return skip;
282}
283
284bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500285 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600286 bool skip = false;
287
288 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700289 std::stringstream image_hex;
290 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600291
292 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700293 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
294 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
295 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700296 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600297 }
298
Attilio Provenzano02859b22020-02-27 14:17:28 +0000299 if (VendorCheckEnabled(kBPVendorArm)) {
300 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
301 skip |= LogPerformanceWarning(
302 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
303 "%s vkCreateImage(): Trying to create an image with %u samples. "
304 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
305 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
306 }
307
308 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
309 skip |= LogPerformanceWarning(
310 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
311 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
312 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
313 "and do not need to be backed by physical storage. "
314 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
315 VendorSpecificTag(kBPVendorArm));
316 }
317 }
318
Nadav Gevaf0808442021-05-21 13:51:25 -0400319 if (VendorCheckEnabled(kBPVendorAMD)) {
320 std::stringstream image_hex;
321 image_hex << "0x" << std::hex << HandleToUint64(pImage);
322
323 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
324 (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT)) {
325 skip |= LogPerformanceWarning(device,
326 kVUID_BestPractices_vkImage_AvoidConcurrentRenderTargets,
327 "%s Performance warning: image (%s) is created as a render target with VK_SHARING_MODE_CONCURRENT. "
328 "Using a SHARING_MODE_CONCURRENT "
329 "is not recommended with color and depth targets",
330 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
331 }
332
333 if ((pCreateInfo->usage &
334 (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
335 (pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
336 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseMutableRenderTargets,
337 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT. "
338 "Using a MUTABLE_FORMAT is not recommended with color, depth, and storage targets",
339 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
340 }
341
342 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
343 (pCreateInfo->usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
344 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseStorageRenderTargets,
345 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_USAGE_STORAGE_BIT. Using a "
346 "VK_IMAGE_USAGE_STORAGE_BIT is not recommended with color and depth targets",
347 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
348 }
349 }
350
Camden5b184be2019-08-13 07:50:19 -0600351 return skip;
352}
353
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100354void BestPractices::PreCallRecordDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
355 ValidationStateTracker::PreCallRecordDestroyImage(device, image, pAllocator);
356 ReleaseImageUsageState(image);
357}
358
Hans-Kristian Arntzen92664eb2021-03-29 12:19:48 +0200359void BestPractices::PreCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain, const VkAllocationCallbacks* pAllocator) {
Tony-LunarG299187b2021-05-28 09:29:12 -0600360 if (VK_NULL_HANDLE != swapchain) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600361 auto chain = Get<SWAPCHAIN_NODE>(swapchain);
Tony-LunarG299187b2021-05-28 09:29:12 -0600362 for (auto& image : chain->images) {
363 if (image.image_state) {
364 ReleaseImageUsageState(image.image_state->image());
365 }
366 }
Hans-Kristian Arntzen92664eb2021-03-29 12:19:48 +0200367 }
368 ValidationStateTracker::PreCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
369}
370
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100371IMAGE_STATE_BP* BestPractices::GetImageUsageState(VkImage vk_image) {
372 auto itr = imageUsageMap.find(vk_image);
373 if (itr != imageUsageMap.end()) {
374 return &itr->second;
375 } else {
376 auto& state = imageUsageMap[vk_image];
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600377 auto image = Get<IMAGE_STATE>(vk_image);
Jeremy Gebben9f537102021-10-05 16:37:12 -0600378 state.image = image.get();
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100379 state.usages.resize(image->createInfo.arrayLayers);
380 for (auto& mips : state.usages) {
381 mips.resize(image->createInfo.mipLevels, IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED);
382 }
383 return &state;
384 }
385}
386
387void BestPractices::ReleaseImageUsageState(VkImage image) {
388 auto itr = imageUsageMap.find(image);
389 if (itr != imageUsageMap.end()) {
390 imageUsageMap.erase(itr);
391 }
392}
393
Camden5b184be2019-08-13 07:50:19 -0600394bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500395 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600396 bool skip = false;
397
Jeremy Gebben383b9a32021-09-08 16:31:33 -0600398 const auto* bp_pd_state = GetPhysicalDeviceState();
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600399 if (bp_pd_state) {
400 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
401 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
402 "vkCreateSwapchainKHR() called before getting surface capabilities from "
403 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
404 }
Camden83a9c372019-08-14 11:41:38 -0600405
Shannon McPherson73e58c82021-03-05 17:14:26 -0700406 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
407 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600408 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
409 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
410 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
411 }
Camden83a9c372019-08-14 11:41:38 -0600412
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600413 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
414 skip |= LogWarning(
415 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
416 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
417 }
Camden83a9c372019-08-14 11:41:38 -0600418 }
419
Camden5b184be2019-08-13 07:50:19 -0600420 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700421 skip |=
422 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600423 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700424 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
425 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600426 }
427
Szilard Papp48a6da32020-06-10 14:41:59 +0100428 if (pCreateInfo->minImageCount == 2) {
429 skip |= LogPerformanceWarning(
430 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
431 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
432 ", which means double buffering is going "
433 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
434 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
435 "3 to use triple buffering to maximize performance in such cases.",
436 pCreateInfo->minImageCount);
437 }
438
Szilard Pappd5f0f812020-06-22 09:01:29 +0100439 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
440 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
441 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
442 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
443 "Presentation modes which are not FIFO will present the latest available frame and discard other "
444 "frame(s) if any.",
445 VendorSpecificTag(kBPVendorArm));
446 }
447
Camden5b184be2019-08-13 07:50:19 -0600448 return skip;
449}
450
451bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
452 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500453 const VkAllocationCallbacks* pAllocator,
454 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600455 bool skip = false;
456
457 for (uint32_t i = 0; i < swapchainCount; i++) {
458 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700459 skip |= LogWarning(
460 device, kVUID_BestPractices_SharingModeExclusive,
461 "Warning: A shared swapchain (index %" PRIu32
462 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
463 "queues (queueFamilyIndexCount of %" PRIu32 ").",
464 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600465 }
466 }
467
468 return skip;
469}
470
471bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500472 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600473 bool skip = false;
474
475 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
476 VkFormat format = pCreateInfo->pAttachments[i].format;
477 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
478 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
479 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700480 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
481 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
482 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
483 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
484 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600485 }
486 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700487 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
488 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
489 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
490 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
491 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600492 }
493 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000494
495 const auto& attachment = pCreateInfo->pAttachments[i];
496 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
497 bool access_requires_memory =
498 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
499
500 if (FormatHasStencil(format)) {
501 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
502 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
503 }
504
505 if (access_requires_memory) {
506 skip |= LogPerformanceWarning(
507 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
508 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
509 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
510 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
511 i, static_cast<uint32_t>(attachment.samples));
512 }
513 }
Camden5b184be2019-08-13 07:50:19 -0600514 }
515
516 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
517 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
518 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
519 }
520
521 return skip;
522}
523
Tony-LunarG767180f2020-04-23 14:03:59 -0600524bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
525 const VkImageView* image_views) const {
526 bool skip = false;
527
528 // Check for non-transient attachments that should be transient and vice versa
529 for (uint32_t i = 0; i < attachmentCount; ++i) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200530 const auto& attachment = rpci->pAttachments[i];
Tony-LunarG767180f2020-04-23 14:03:59 -0600531 bool attachment_should_be_transient =
532 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
533
534 if (FormatHasStencil(attachment.format)) {
535 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
536 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
537 }
538
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600539 auto view_state = Get<IMAGE_VIEW_STATE>(image_views[i]);
Tony-LunarG767180f2020-04-23 14:03:59 -0600540 if (view_state) {
Jeremy Gebben057f9d52021-11-05 14:12:31 -0600541 const auto& ici = view_state->image_state->createInfo;
Tony-LunarG767180f2020-04-23 14:03:59 -0600542
543 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
544
545 // The check for an image that should not be transient applies to all GPUs
546 if (!attachment_should_be_transient && image_is_transient) {
547 skip |= LogPerformanceWarning(
548 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
549 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
550 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
551 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
552 i);
553 }
554
555 bool supports_lazy = false;
556 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
557 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
558 supports_lazy = true;
559 }
560 }
561
562 // The check for an image that should be transient only applies to GPUs supporting
563 // lazily allocated memory
564 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
565 skip |= LogPerformanceWarning(
566 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
567 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
568 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
569 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
570 i);
571 }
572 }
573 }
574 return skip;
575}
576
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000577bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
578 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
579 bool skip = false;
580
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600581 auto rp_state = Get<RENDER_PASS_STATE>(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800582 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600583 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000584 }
585
586 return skip;
587}
588
Sam Wallse746d522020-03-16 21:20:23 +0000589bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
590 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
591 bool skip = false;
592 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
593
594 if (!skip) {
595 const auto& pool_handle = pAllocateInfo->descriptorPool;
596 auto iter = descriptor_pool_freed_count.find(pool_handle);
597 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
598 // this warning is specific to Arm
599 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
600 skip |= LogPerformanceWarning(
601 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
602 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
603 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
604 VendorSpecificTag(kBPVendorArm));
605 }
606 }
607
608 return skip;
609}
610
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600611void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
612 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000613 if (result == VK_SUCCESS) {
614 // find the free count for the pool we allocated into
615 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
616 if (iter != descriptor_pool_freed_count.end()) {
617 // we record successful allocations by subtracting the allocation count from the last recorded free count
618 const auto alloc_count = pAllocateInfo->descriptorSetCount;
619 // clamp the unsigned subtraction to the range [0, last_free_count]
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700620 if (iter->second > alloc_count) {
Sam Wallse746d522020-03-16 21:20:23 +0000621 iter->second -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700622 } else {
Sam Wallse746d522020-03-16 21:20:23 +0000623 iter->second = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700624 }
Sam Wallse746d522020-03-16 21:20:23 +0000625 }
626 }
627}
628
629void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
630 const VkDescriptorSet* pDescriptorSets, VkResult result) {
631 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
632 if (result == VK_SUCCESS) {
633 // we want to track frees because we're interested in suggesting re-use
634 auto iter = descriptor_pool_freed_count.find(descriptorPool);
635 if (iter == descriptor_pool_freed_count.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700636 descriptor_pool_freed_count.emplace(descriptorPool, descriptorSetCount);
Sam Wallse746d522020-03-16 21:20:23 +0000637 } else {
638 iter->second += descriptorSetCount;
639 }
640 }
641}
642
Camden5b184be2019-08-13 07:50:19 -0600643bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500644 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600645 bool skip = false;
646
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500647 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700648 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
649 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600650 }
651
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000652 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
653 skip |= LogPerformanceWarning(
654 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600655 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
656 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000657 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
658 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
659 }
660
Camden83a9c372019-08-14 11:41:38 -0600661 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
662
663 return skip;
664}
665
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600666void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
667 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
668 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700669 if (result != VK_SUCCESS) {
670 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
671 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800672 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700673 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600674 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700675 return;
676 }
677 num_mem_objects++;
678}
Camden Stocker9738af92019-10-16 13:54:03 -0700679
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600680void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
681 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700682 auto error = std::find(error_codes.begin(), error_codes.end(), result);
683 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000684 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
685 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
686
687 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
688 if (common_failure != common_failure_codes.end()) {
689 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
690 } else {
691 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
692 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700693 return;
694 }
695 auto success = std::find(success_codes.begin(), success_codes.end(), result);
696 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600697 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
698 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500699 }
700}
701
Jeff Bolz5c801d12019-10-09 10:38:45 -0500702bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
703 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700704 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600705 bool skip = false;
706
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700707 auto mem_info = Get<DEVICE_MEMORY_STATE>(memory);
Camden83a9c372019-08-14 11:41:38 -0600708
Jeremy Gebben610d3a62022-01-01 12:53:17 -0700709 for (const auto& item : mem_info->ObjectBindings()) {
710 const auto& obj = item.first;
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600711 LogObjectList objlist(device);
712 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600713 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600714 skip |= LogWarning(objlist, layer_name.c_str(), "VK Object %s still has a reference to mem obj %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600715 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600716 }
717
Camden5b184be2019-08-13 07:50:19 -0600718 return skip;
719}
720
721void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700722 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600723 if (memory != VK_NULL_HANDLE) {
724 num_mem_objects--;
725 }
726}
727
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000728bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600729 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700730 auto buffer_state = Get<BUFFER_STATE>(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600731
sfricke-samsunge2441192019-11-06 14:07:57 -0800732 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700733 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
734 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
735 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600736 }
737
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700738 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000739
AndreyVK_D3D0416a332021-11-02 23:22:28 +0300740 if (mem_state && mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000741 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
742 skip |= LogPerformanceWarning(
743 device, kVUID_BestPractices_SmallDedicatedAllocation,
744 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600745 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
746 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000747 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
748 }
749
Camden Stockerb603cc82019-09-03 10:09:02 -0600750 return skip;
751}
752
753bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500754 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600755 bool skip = false;
756 const char* api_name = "BindBufferMemory()";
757
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000758 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600759
760 return skip;
761}
762
763bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500764 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600765 char api_name[64];
766 bool skip = false;
767
768 for (uint32_t i = 0; i < bindInfoCount; i++) {
769 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000770 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600771 }
772
773 return skip;
774}
Camden Stockerb603cc82019-09-03 10:09:02 -0600775
776bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500777 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600778 char api_name[64];
779 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600780
Camden Stocker8b798ab2019-09-03 10:33:28 -0600781 for (uint32_t i = 0; i < bindInfoCount; i++) {
782 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000783 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600784 }
785
786 return skip;
787}
788
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000789bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600790 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700791 auto image_state = Get<IMAGE_STATE>(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600792
sfricke-samsung71bc6572020-04-29 15:49:43 -0700793 if (image_state->disjoint == false) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600794 if (!image_state->memory_requirements_checked[0] && !image_state->external_memory_handle) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700795 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
796 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
797 api_name, report_data->FormatHandle(image).c_str());
798 }
799 } else {
800 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
801 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600802 }
803
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700804 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000805
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600806 if (mem_state->alloc_info.allocationSize == image_state->requirements[0].size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000807 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
808 skip |= LogPerformanceWarning(
809 device, kVUID_BestPractices_SmallDedicatedAllocation,
810 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600811 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
812 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000813 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
814 }
815
816 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
817 // make sure this type is actually used.
818 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
819 // (i.e.most tile - based renderers)
820 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
821 bool supports_lazy = false;
822 uint32_t suggested_type = 0;
823
824 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600825 if ((1u << i) & image_state->requirements[0].memoryTypeBits) {
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000826 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
827 supports_lazy = true;
828 suggested_type = i;
829 break;
830 }
831 }
832 }
833
834 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
835
836 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
837 skip |= LogPerformanceWarning(
838 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600839 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000840 "but this memory type is not LAZILY_ALLOCATED_BIT. You should use memory type %u here instead to save "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600841 "%" PRIu64 " bytes of physical memory.",
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600842 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements[0].size);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000843 }
844 }
845
Camden Stocker8b798ab2019-09-03 10:33:28 -0600846 return skip;
847}
848
849bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500850 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600851 bool skip = false;
852 const char* api_name = "vkBindImageMemory()";
853
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000854 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600855
856 return skip;
857}
858
859bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500860 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600861 char api_name[64];
862 bool skip = false;
863
864 for (uint32_t i = 0; i < bindInfoCount; i++) {
865 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700866 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600867 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
868 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600869 }
870
871 return skip;
872}
873
874bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500875 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600876 char api_name[64];
877 bool skip = false;
878
879 for (uint32_t i = 0; i < bindInfoCount; i++) {
880 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000881 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600882 }
883
884 return skip;
885}
Camden83a9c372019-08-14 11:41:38 -0600886
Attilio Provenzano02859b22020-02-27 14:17:28 +0000887static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
888 switch (format) {
889 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
890 case VK_FORMAT_R16_SFLOAT:
891 case VK_FORMAT_R16G16_SFLOAT:
892 case VK_FORMAT_R16G16B16_SFLOAT:
893 case VK_FORMAT_R16G16B16A16_SFLOAT:
894 case VK_FORMAT_R32_SFLOAT:
895 case VK_FORMAT_R32G32_SFLOAT:
896 case VK_FORMAT_R32G32B32_SFLOAT:
897 case VK_FORMAT_R32G32B32A32_SFLOAT:
898 return false;
899
900 default:
901 return true;
902 }
903}
904
905bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
906 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
907 bool skip = false;
908
909 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700910 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000911
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700912 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
913 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
914 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000915 return skip;
916 }
917
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600918 auto rp_state = Get<RENDER_PASS_STATE>(create_info->renderPass);
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200919 const auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000920
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +0200921 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
922 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info->pColorBlendState->attachmentCount);
923
924 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200925 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000926 uint32_t att = subpass.pColorAttachments[j].attachment;
927
928 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
929 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
930 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
931 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
932 "color attachment #%u makes use "
933 "of a format which cannot be blended at full throughput when using MSAA.",
934 VendorSpecificTag(kBPVendorArm), i, j);
935 }
936 }
937 }
938 }
939
940 return skip;
941}
942
Nadav Gevaf0808442021-05-21 13:51:25 -0400943void BestPractices::ManualPostCallRecordCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
944 const VkComputePipelineCreateInfo* pCreateInfos,
945 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
946 VkResult result, void* pipe_state) {
947 // AMD best practice
948 pipeline_cache = pipelineCache;
949}
950
Camden5b184be2019-08-13 07:50:19 -0600951bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
952 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600953 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500954 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600955 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
956 pAllocator, pPipelines, cgpl_state_data);
ziga-lunarg08c81582022-03-08 17:33:45 +0100957 if (skip) {
958 return skip;
959 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600960 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600961
962 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700963 skip |= LogPerformanceWarning(
964 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
965 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
966 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600967 }
968
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000969 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200970 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000971
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600972 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200973 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600974 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700975 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
976 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600977 count++;
978 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000979 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600980 if (count > kMaxInstancedVertexBuffers) {
981 skip |= LogPerformanceWarning(
982 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
983 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
984 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
985 count, kMaxInstancedVertexBuffers);
986 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000987 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000988
Szilard Pappaaf2da32020-06-22 10:37:35 +0100989 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
990 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +0200991 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
992 VendorCheckEnabled(kBPVendorArm)) {
993 skip |= LogPerformanceWarning(
994 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
995 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
996 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
997 "efficiency during rasterization. Consider disabling depthBias or increasing either "
998 "depthBiasConstantFactor or depthBiasSlopeFactor.",
999 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +01001000 }
1001
Attilio Provenzano02859b22020-02-27 14:17:28 +00001002 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001003 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001004 if (VendorCheckEnabled(kBPVendorAMD)) {
1005 if (pipelineCache && pipeline_cache && pipelineCache != pipeline_cache) {
1006 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultiplePipelineCaches,
1007 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
1008 "improve cache hit rate", VendorSpecificTag(kBPVendorAMD));
1009 }
1010
1011 if (num_pso > kMaxRecommendedNumberOfPSOAMD) {
1012 skip |=
1013 LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_TooManyPipelines,
1014 "%s Performance warning: Too many pipelines created, consider consolidation",
1015 VendorSpecificTag(kBPVendorAMD));
1016 }
1017
Nathaniel Cesario1a7e1a92021-08-30 14:34:20 -06001018 if (pCreateInfos->pInputAssemblyState && pCreateInfos->pInputAssemblyState->primitiveRestartEnable) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001019 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_AvoidPrimitiveRestart,
1020 "%s Performance warning: Use of primitive restart is not recommended",
1021 VendorSpecificTag(kBPVendorAMD));
1022 }
1023
1024 // TODO: this might be too aggressive of a check
1025 if (pCreateInfos->pDynamicState && pCreateInfos->pDynamicState->dynamicStateCount > kDynamicStatesWarningLimitAMD) {
1026 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MinimizeNumDynamicStates,
1027 "%s Performance warning: Dynamic States usage incurs a performance cost. Ensure that they are truly needed",
1028 VendorSpecificTag(kBPVendorAMD));
1029 }
1030 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001031
Camden5b184be2019-08-13 07:50:19 -06001032 return skip;
1033}
1034
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001035void BestPractices::PreCallRecordDestroyPipeline(VkDevice device, VkPipeline pipeline, const VkAllocationCallbacks *pAllocator)
1036{
1037 auto itr = graphicsPipelineCIs.find(pipeline);
1038 if (itr != graphicsPipelineCIs.end()) {
1039 graphicsPipelineCIs.erase(itr);
1040 }
1041 ValidationStateTracker::PreCallRecordDestroyPipeline(device, pipeline, pAllocator);
1042}
1043
Sam Walls0961ec02020-03-31 16:39:15 +01001044void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
1045 const VkGraphicsPipelineCreateInfo* pCreateInfos,
1046 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
1047 VkResult result, void* cgpl_state_data) {
1048 for (size_t i = 0; i < count; i++) {
1049 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
1050 const VkPipeline pipeline_handle = pPipelines[i];
1051
1052 // record depth stencil state and color blend states for depth pre-pass tracking purposes
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001053 GraphicsPipelineCIs& cis = graphicsPipelineCIs[pipeline_handle];
Sam Walls0961ec02020-03-31 16:39:15 +01001054
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +02001055 auto& create_info = cgpl_state->pCreateInfos[i];
Andrej Redeky0d513072022-02-13 14:38:20 +01001056
1057 if (create_info.renderPass == VK_NULL_HANDLE) {
1058 // TODO: this is necessary to avoid crashing
1059 LogWarning(device, kVUID_BestPractices_DynamicRendering_NotSupported,
1060 "vkCreateGraphicsPipelines: pCreateInfos[%" PRIu32
1061 "].renderPass is VK_NULL_HANDLE, VK_KHR_dynamic_rendering is not supported.\n",
1062 static_cast<uint32_t>(i));
1063 continue;
1064 }
1065
Tony-LunarGf9b894b2022-02-08 15:01:37 -07001066 auto rp = Get<RENDER_PASS_STATE>(create_info.renderPass);
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +02001067
Jeremy Gebben396d06a2021-08-12 11:03:04 -06001068 if (create_info.pColorBlendState) {
Tony-LunarGf9b894b2022-02-08 15:01:37 -07001069 // pColorBlendState is ignored if the pipeline has rasterization disabled or if no color attachments are used
1070 bool uses_color_attachments = false;
1071 for (uint32_t j = 0; j < rp->createInfo.subpassCount; j++) {
1072 uses_color_attachments |= rp->UsesColorAttachment(j);
1073 }
1074 if (uses_color_attachments && !create_info.pRasterizationState->rasterizerDiscardEnable) {
1075 cis.colorBlendStateCI.emplace(create_info.pColorBlendState);
1076 }
Jeremy Gebben396d06a2021-08-12 11:03:04 -06001077 }
1078
1079 if (create_info.pDepthStencilState) {
Tony-LunarGf9b894b2022-02-08 15:01:37 -07001080 // pDepthStencilState is ignored if the pipeline has rasterization disabled or if no depth/stencil attachment is used
1081 bool uses_depth_stencil = false;
1082 for (uint32_t j = 0; j < rp->createInfo.subpassCount; j++) {
1083 uses_depth_stencil |= rp->UsesDepthStencilAttachment(j);
1084 }
1085 if (uses_depth_stencil && !create_info.pRasterizationState->rasterizerDiscardEnable) {
1086 cis.depthStencilStateCI.emplace(create_info.pDepthStencilState);
1087 }
Jeremy Gebben396d06a2021-08-12 11:03:04 -06001088 }
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +02001089 // Record which frame buffer attachments we should consider to be accessed when a draw call is performed.
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +02001090 auto& subpass = rp->createInfo.pSubpasses[create_info.subpass];
1091 cis.accessFramebufferAttachments.clear();
1092
1093 if (cis.colorBlendStateCI) {
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +02001094 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
1095 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, cis.colorBlendStateCI->attachmentCount);
1096 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +02001097 if (cis.colorBlendStateCI->pAttachments[j].colorWriteMask != 0) {
1098 uint32_t attachment = subpass.pColorAttachments[j].attachment;
1099 if (attachment != VK_ATTACHMENT_UNUSED) {
1100 cis.accessFramebufferAttachments.push_back({ attachment, VK_IMAGE_ASPECT_COLOR_BIT });
1101 }
1102 }
1103 }
1104 }
1105
1106 if (cis.depthStencilStateCI && (cis.depthStencilStateCI->depthTestEnable ||
1107 cis.depthStencilStateCI->depthBoundsTestEnable ||
1108 cis.depthStencilStateCI->stencilTestEnable)) {
1109 uint32_t attachment = subpass.pDepthStencilAttachment ?
1110 subpass.pDepthStencilAttachment->attachment :
1111 VK_ATTACHMENT_UNUSED;
1112 if (attachment != VK_ATTACHMENT_UNUSED) {
1113 VkImageAspectFlags aspects = 0;
1114 if (cis.depthStencilStateCI->depthTestEnable || cis.depthStencilStateCI->depthBoundsTestEnable) {
1115 aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1116 }
1117 if (cis.depthStencilStateCI->stencilTestEnable) {
1118 aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1119 }
1120 cis.accessFramebufferAttachments.push_back({ attachment, aspects });
1121 }
1122 }
Sam Walls0961ec02020-03-31 16:39:15 +01001123 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001124
1125 // AMD best practice
1126 pipeline_cache = pipelineCache;
Sam Walls0961ec02020-03-31 16:39:15 +01001127}
1128
Camden5b184be2019-08-13 07:50:19 -06001129bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1130 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001131 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001132 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001133 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1134 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001135
1136 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001137 skip |= LogPerformanceWarning(
1138 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1139 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
1140 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001141 }
1142
Nadav Gevaf0808442021-05-21 13:51:25 -04001143 if (VendorCheckEnabled(kBPVendorAMD)) {
1144 if (pipelineCache && pipeline_cache && pipelineCache != pipeline_cache) {
1145 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1146 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
1147 "improve cache hit rate",
1148 VendorSpecificTag(kBPVendorAMD));
1149 }
1150 }
1151
sfricke-samsung86d055a2022-02-11 14:43:50 -08001152 for (uint32_t i = 0; i < createInfoCount; i++) {
1153 const VkComputePipelineCreateInfo& createInfo = pCreateInfos[i];
1154 if (VendorCheckEnabled(kBPVendorArm)) {
1155 skip |= ValidateCreateComputePipelineArm(createInfo);
1156 }
1157
1158 if (IsExtEnabled(device_extensions.vk_khr_maintenance4)) {
1159 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
1160 for (const auto& builtin : module_state->static_data_.builtin_decoration_list) {
1161 if (builtin.builtin == spv::BuiltInWorkgroupSize) {
1162 skip |= LogWarning(device, kVUID_BestPractices_SpirvDeprecated_WorkgroupSize,
1163 "vkCreateComputePipelines(): pCreateInfos[ %" PRIu32
1164 "] is using the Workgroup built-in which SPIR-V 1.6 deprecated. The VK_KHR_maintenance4 "
1165 "extension exposes a new LocalSizeId execution mode that should be used instead.",
1166 i);
1167 }
1168 }
1169 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001170 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001171
1172 return skip;
1173}
1174
1175bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
1176 bool skip = false;
sfricke-samsungef15e482022-01-26 11:32:49 -08001177 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001178 // Generate warnings about work group sizes based on active resources.
sfricke-samsungef15e482022-01-26 11:32:49 -08001179 auto entrypoint = module_state->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
1180 if (entrypoint == module_state->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001181
1182 uint32_t x = 1, y = 1, z = 1;
sfricke-samsungef15e482022-01-26 11:32:49 -08001183 module_state->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001184
1185 uint32_t thread_count = x * y * z;
1186
1187 // Generate a priori warnings about work group sizes.
1188 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
1189 skip |= LogPerformanceWarning(
1190 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
1191 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1192 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1193 "groups with less than %u threads, especially when using barrier() or shared memory.",
1194 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1195 }
1196
1197 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1198 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1199 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1200 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1201 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1202 "%u, %u) is not aligned to %u "
1203 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1204 "leave threads idle on the shader "
1205 "core.",
1206 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1207 kThreadGroupDispatchCountAlignmentArm);
1208 }
1209
sfricke-samsungef15e482022-01-26 11:32:49 -08001210 auto accessible_ids = module_state->MarkAccessibleIds(entrypoint);
1211 auto descriptor_uses = module_state->CollectInterfaceByDescriptorSlot(accessible_ids);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001212
1213 unsigned dimensions = 0;
1214 if (x > 1) dimensions++;
1215 if (y > 1) dimensions++;
1216 if (z > 1) dimensions++;
1217 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1218 dimensions = std::max(dimensions, 1u);
1219
1220 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1221 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1222 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1223 bool accesses_2d = false;
1224 for (const auto& usage : descriptor_uses) {
sfricke-samsungef15e482022-01-26 11:32:49 -08001225 auto dim = module_state->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001226 if (dim < 0) continue;
1227 auto spvdim = spv::Dim(dim);
1228 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1229 }
1230
1231 if (accesses_2d && dimensions < 2) {
1232 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1233 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1234 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1235 "exhibiting poor spatial locality with respect to one or more shader resources.",
1236 VendorSpecificTag(kBPVendorArm), x, y, z);
1237 }
1238
Camden5b184be2019-08-13 07:50:19 -06001239 return skip;
1240}
1241
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001242bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001243 bool skip = false;
1244
1245 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001246 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1247 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001248 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001249 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1250 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001251 }
1252
1253 return skip;
1254}
1255
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001256bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1257 bool skip = false;
1258
1259 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1260 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1261 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1262 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1263 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1264 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1265 }
1266
1267 return skip;
1268}
1269
1270bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1271 bool skip = false;
1272 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1273
1274 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1275 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1276
1277 return skip;
1278}
1279
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001280void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001281 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1282 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1283 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1284 LogPerformanceWarning(
1285 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1286 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1287 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1288 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1289 "convenient opportunity.",
1290 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1291 }
1292 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001293
1294 // AMD best practice
1295 // end-of-frame cleanup
1296 num_queue_submissions = 0;
1297 num_barriers_objects = 0;
1298 pipelines_used_in_frame.clear();
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001299}
1300
Jeff Bolz5c801d12019-10-09 10:38:45 -05001301bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1302 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001303 bool skip = false;
1304
1305 for (uint32_t submit = 0; submit < submitCount; submit++) {
1306 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1307 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1308 }
1309 }
1310
1311 return skip;
1312}
1313
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001314bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1315 VkFence fence) const {
1316 bool skip = false;
1317
1318 for (uint32_t submit = 0; submit < submitCount; submit++) {
1319 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1320 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1321 }
1322 }
1323
1324 return skip;
1325}
1326
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001327bool BestPractices::PreCallValidateQueueSubmit2(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2* pSubmits,
1328 VkFence fence) const {
1329 bool skip = false;
1330
1331 for (uint32_t submit = 0; submit < submitCount; submit++) {
1332 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1333 skip |= CheckPipelineStageFlags("vkQueueSubmit2", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1334 }
1335 }
1336
1337 return skip;
1338}
1339
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001340bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1341 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1342 bool skip = false;
1343
1344 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1345 skip |= LogPerformanceWarning(
1346 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1347 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1348 "pool instead.");
1349 }
1350
1351 return skip;
1352}
1353
1354bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1355 const VkCommandBufferBeginInfo* pBeginInfo) const {
1356 bool skip = false;
1357
1358 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1359 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1360 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1361 }
1362
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001363 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && VendorCheckEnabled(kBPVendorArm)) {
1364 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Attilio Provenzano02859b22020-02-27 14:17:28 +00001365 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1366 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1367 VendorSpecificTag(kBPVendorArm));
1368 }
1369
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001370 return skip;
1371}
1372
Jeff Bolz5c801d12019-10-09 10:38:45 -05001373bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001374 bool skip = false;
1375
1376 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1377
1378 return skip;
1379}
1380
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001381bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1382 const VkDependencyInfoKHR* pDependencyInfo) const {
1383 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1384}
1385
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001386bool BestPractices::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1387 const VkDependencyInfo* pDependencyInfo) const {
1388 return CheckDependencyInfo("vkCmdSetEvent2", *pDependencyInfo);
1389}
1390
Jeff Bolz5c801d12019-10-09 10:38:45 -05001391bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1392 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001393 bool skip = false;
1394
1395 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1396
1397 return skip;
1398}
1399
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001400bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1401 VkPipelineStageFlags2KHR stageMask) const {
1402 bool skip = false;
1403
1404 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1405
1406 return skip;
1407}
1408
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001409bool BestPractices::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1410 VkPipelineStageFlags2 stageMask) const {
1411 bool skip = false;
1412
1413 skip |= CheckPipelineStageFlags("vkCmdResetEvent2", stageMask);
1414
1415 return skip;
1416}
1417
Camden5b184be2019-08-13 07:50:19 -06001418bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1419 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1420 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1421 uint32_t bufferMemoryBarrierCount,
1422 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1423 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001424 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001425 bool skip = false;
1426
1427 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1428 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1429
1430 return skip;
1431}
1432
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001433bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1434 const VkDependencyInfoKHR* pDependencyInfos) const {
1435 bool skip = false;
1436 for (uint32_t i = 0; i < eventCount; i++) {
1437 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1438 }
1439
1440 return skip;
1441}
1442
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001443bool BestPractices::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1444 const VkDependencyInfo* pDependencyInfos) const {
1445 bool skip = false;
1446 for (uint32_t i = 0; i < eventCount; i++) {
1447 skip = CheckDependencyInfo("vkCmdWaitEvents2", pDependencyInfos[i]);
1448 }
1449
1450 return skip;
1451}
1452
Camden5b184be2019-08-13 07:50:19 -06001453bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1454 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1455 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1456 uint32_t bufferMemoryBarrierCount,
1457 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1458 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001459 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001460 bool skip = false;
1461
1462 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1463 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1464
Nadav Gevaf0808442021-05-21 13:51:25 -04001465 if (VendorCheckEnabled(kBPVendorAMD)) {
1466 if (num_barriers_objects + imageMemoryBarrierCount + bufferMemoryBarrierCount > kMaxRecommendedBarriersSizeAMD) {
1467 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_highBarrierCount,
1468 "%s Performance warning: In this frame, %" PRIu32 " barriers were already submitted. Barriers have a high cost and can "
1469 "stall the GPU. "
1470 "Consider consolidating and re-organizing the frame to use fewer barriers.",
1471 VendorSpecificTag(kBPVendorAMD), num_barriers_objects);
1472 }
1473
1474 std::array<VkImageLayout, 3> read_layouts = {
1475 VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,
1476 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
1477 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1478 };
1479
1480 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
1481 // read to read barriers
1482 auto found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].oldLayout);
1483 bool old_is_read_layout = found != read_layouts.end();
1484 found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].newLayout);
1485 bool new_is_read_layout = found != read_layouts.end();
1486 if (old_is_read_layout && new_is_read_layout) {
1487 skip |= LogPerformanceWarning(device, kVUID_BestPractices_PipelineBarrier_readToReadBarrier,
1488 "%s Performance warning: Don't issue read-to-read barriers. Get the resource in the right state the first "
1489 "time you use it.",
1490 VendorSpecificTag(kBPVendorAMD));
1491 }
1492
1493 // general with no storage
1494 if (pImageMemoryBarriers[i].newLayout == VK_IMAGE_LAYOUT_GENERAL) {
1495 auto image_state = Get<IMAGE_STATE>(pImageMemoryBarriers[i].image);
1496 if (!(image_state->createInfo.usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
1497 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidGeneral,
1498 "%s Performance warning: VK_IMAGE_LAYOUT_GENERAL should only be used with "
1499 "VK_IMAGE_USAGE_STORAGE_BIT images.",
1500 VendorSpecificTag(kBPVendorAMD));
1501 }
1502 }
1503 }
1504 }
1505
Camden5b184be2019-08-13 07:50:19 -06001506 return skip;
1507}
1508
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001509bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1510 const VkDependencyInfoKHR* pDependencyInfo) const {
1511 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1512}
1513
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001514bool BestPractices::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
1515 const VkDependencyInfo* pDependencyInfo) const {
1516 return CheckDependencyInfo("vkCmdPipelineBarrier2", *pDependencyInfo);
1517}
1518
Camden5b184be2019-08-13 07:50:19 -06001519bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001520 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001521 bool skip = false;
1522
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001523 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1524
1525 return skip;
1526}
1527
1528bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1529 VkQueryPool queryPool, uint32_t query) const {
1530 bool skip = false;
1531
1532 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001533
1534 return skip;
1535}
1536
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001537bool BestPractices::PreCallValidateCmdWriteTimestamp2(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 pipelineStage,
1538 VkQueryPool queryPool, uint32_t query) const {
1539 bool skip = false;
1540
1541 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2", pipelineStage);
1542
1543 return skip;
1544}
1545
Sam Walls0961ec02020-03-31 16:39:15 +01001546void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1547 VkPipeline pipeline) {
1548 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1549
Nadav Gevaf0808442021-05-21 13:51:25 -04001550 // AMD best practice
1551 pipelines_used_in_frame.emplace(pipeline);
1552
Sam Walls0961ec02020-03-31 16:39:15 +01001553 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1554 // check for depth/blend state tracking
1555 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1556 if (gp_cis != graphicsPipelineCIs.end()) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07001557 auto cb_node = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001558 assert(cb_node);
1559 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01001560
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001561 render_pass_state.nextDrawTouchesAttachments = gp_cis->second.accessFramebufferAttachments;
1562 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001563
Jeremy Gebben396d06a2021-08-12 11:03:04 -06001564 const auto& blend_state = gp_cis->second.colorBlendStateCI;
1565 const auto& stencil_state = gp_cis->second.depthStencilStateCI;
Sam Walls0961ec02020-03-31 16:39:15 +01001566
1567 if (blend_state) {
1568 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001569 render_pass_state.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001570 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1571 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001572 render_pass_state.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001573 }
1574 }
1575 }
1576
1577 // check for depth value usage
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001578 render_pass_state.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001579
1580 if (stencil_state && stencil_state->depthTestEnable) {
1581 switch (stencil_state->depthCompareOp) {
1582 case VK_COMPARE_OP_EQUAL:
1583 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1584 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001585 render_pass_state.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001586 break;
1587 default:
1588 break;
1589 }
1590 }
Sam Walls0961ec02020-03-31 16:39:15 +01001591 }
1592 }
1593}
1594
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02001595static inline bool RenderPassUsesAttachmentAsResolve(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1596 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1597 const auto& subpass_info = createInfo.pSubpasses[subpass];
1598 if (subpass_info.pResolveAttachments) {
1599 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1600 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1601 }
1602 }
1603 }
1604
1605 return false;
1606}
1607
Attilio Provenzano02859b22020-02-27 14:17:28 +00001608static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1609 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001610 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001611
1612 // If an attachment is ever used as a color attachment,
1613 // resolve attachment or depth stencil attachment,
1614 // it needs to exist on tile at some point.
1615
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001616 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1617 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001618 }
1619
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001620 if (subpass_info.pResolveAttachments) {
1621 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1622 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1623 }
1624 }
1625
1626 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001627 }
1628
1629 return false;
1630}
1631
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001632static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1633 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1634 return false;
1635 }
1636
1637 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001638 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001639
1640 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1641 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1642 return true;
1643 }
1644 }
1645 }
1646
1647 return false;
1648}
1649
Attilio Provenzano02859b22020-02-27 14:17:28 +00001650bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1651 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1652 bool skip = false;
1653
1654 if (!pRenderPassBegin) {
1655 return skip;
1656 }
1657
Gareth Webbdc6549a2021-06-16 03:52:24 +01001658 if (pRenderPassBegin->renderArea.extent.width == 0 || pRenderPassBegin->renderArea.extent.height == 0) {
1659 skip |= LogWarning(device, kVUID_BestPractices_BeginRenderPass_ZeroSizeRenderArea,
1660 "This render pass has a zero-size render area. It cannot write to any attachments, "
1661 "and can only be used for side effects such as layout transitions.");
1662 }
1663
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001664 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001665 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001666 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001667 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001668 if (rpabi) {
1669 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1670 }
1671 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001672 // Check if any attachments have LOAD operation on them
1673 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001674 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001675
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001676 bool attachment_has_readback = false;
Hans-Kristian Arntzen4afb59b2021-06-18 12:41:36 +02001677 if (!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001678 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001679 }
1680
1681 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001682 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001683 }
1684
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001685 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001686
1687 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001688 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1689 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001690 }
1691
1692 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001693 if (attachment_needs_readback && VendorCheckEnabled(kBPVendorArm)) {
1694 skip |= LogPerformanceWarning(
1695 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1696 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1697 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
Nadav Gevaf0808442021-05-21 13:51:25 -04001698 "which will copy in total %u pixels (renderArea = "
1699 "{ %" PRId32 ", %" PRId32 ", %" PRIu32", %" PRIu32 " }) to the tile buffer.",
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001700 VendorSpecificTag(kBPVendorArm), att,
1701 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1702 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1703 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001704 }
1705 }
1706 }
1707
1708 return skip;
1709}
1710
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001711void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
1712 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001713 if (view) {
Jeremy Gebbenb4d17012021-07-08 13:18:15 -06001714 QueueValidateImage(funcs, function_name, GetImageUsageState(view->create_info.image), usage,
1715 view->normalized_subresource_range);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001716 }
1717}
1718
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001719void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1720 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001721 const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001722 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001723
1724 // If we're viewing a 3D slice, ignore base array layer.
1725 // The entire 3D subresource is accessed as one atomic unit.
1726 const uint32_t base_array_layer = image->createInfo.imageType == VK_IMAGE_TYPE_3D ? 0 : subresource_range.baseArrayLayer;
1727
1728 const uint32_t max_layers = image->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001729 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
1730 const uint32_t max_levels = image->createInfo.mipLevels - subresource_range.baseMipLevel;
1731 const uint32_t mip_levels = std::min(image->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001732
1733 for (uint32_t layer = 0; layer < array_layers; layer++) {
1734 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001735 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
1736 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001737 }
1738 }
1739}
1740
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001741void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1742 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001743 const VkImageSubresourceLayers& subresource_layers) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001744 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001745 const uint32_t max_layers = image->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
1746 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001747
1748 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001749 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001750 }
1751}
1752
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001753void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1754 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001755 uint32_t array_layer, uint32_t mip_level) {
Jeremy Gebben7fd238f2022-03-04 10:32:24 -07001756 if (VendorCheckEnabled(kBPVendorArm)) {
1757 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](
1758 const ValidationStateTracker&, const QUEUE_STATE&, const CMD_BUFFER_STATE&) -> bool {
1759 ValidateImageInQueue(function_name, state, usage, array_layer, mip_level);
1760 return false;
1761 });
1762 }
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001763}
1764
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001765void BestPractices::ValidateImageInQueueArm(const char* function_name, IMAGE_STATE* image,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001766 IMAGE_SUBRESOURCE_USAGE_BP last_usage,
1767 IMAGE_SUBRESOURCE_USAGE_BP usage,
1768 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001769 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001770 if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED && last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED &&
Jeremy Gebben82e11d52021-07-26 09:19:37 -06001771 !image->IsSwapchainImage()) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001772 LogPerformanceWarning(
1773 device, kVUID_BestPractices_RenderPass_RedundantStore,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001774 "%s: %s Subresource (arrayLayer: %u, mipLevel: %u) of image was cleared as part of LOAD_OP_CLEAR, but last time "
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001775 "image was used, it was written to with STORE_OP_STORE. "
1776 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1777 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001778 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001779 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED && last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001780 LogPerformanceWarning(
1781 device, kVUID_BestPractices_RenderPass_RedundantClear,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001782 "%s: %s Subresource (arrayLayer: %u, mipLevel: %u) of image was cleared as part of LOAD_OP_CLEAR, but last time "
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001783 "image was used, it was written to with vkCmdClear*Image(). "
1784 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1785 "tile-based architectures."
1786 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001787 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001788 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
1789 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE ||
1790 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
1791 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE ||
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001792 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001793 const char *last_cmd = nullptr;
1794 const char *vuid = nullptr;
1795 const char *suggestion = nullptr;
1796
1797 switch (last_usage) {
1798 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
1799 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
1800 last_cmd = "vkCmdBlitImage";
1801 suggestion =
1802 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1803 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
1804 "which avoids the memory roundtrip.";
1805 break;
1806 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
1807 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
1808 last_cmd = "vkCmdClear*Image";
1809 suggestion =
1810 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1811 "tile-based architectures. "
1812 "Use LOAD_OP_CLEAR instead to clear the image for free.";
1813 break;
1814 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
1815 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
1816 last_cmd = "vkCmdCopy*Image";
1817 suggestion =
1818 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1819 "Rather than copying, just render the source image in a fragment shader in this render pass, "
1820 "which avoids the memory roundtrip.";
1821 break;
1822 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
1823 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
1824 last_cmd = "vkCmdResolveImage";
1825 suggestion =
1826 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
1827 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
1828 "which avoids the memory roundtrip.";
1829 break;
1830 default:
1831 break;
1832 }
1833
1834 LogPerformanceWarning(
1835 device, vuid,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001836 "%s: %s Subresource (arrayLayer: %u, mipLevel: %u) of image was loaded to tile as part of LOAD_OP_LOAD, but last "
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001837 "time image was used, it was written to with %s. %s",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001838 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level, last_cmd, suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001839 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001840}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001841
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001842void BestPractices::ValidateImageInQueue(const char* function_name, IMAGE_STATE_BP* state,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001843 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer,
1844 uint32_t mip_level) {
1845 IMAGE_STATE* image = state->image;
1846 IMAGE_SUBRESOURCE_USAGE_BP last_usage = state->usages[array_layer][mip_level];
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001847 state->usages[array_layer][mip_level] = usage;
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001848 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001849 ValidateImageInQueueArm(function_name, image, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001850 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001851}
1852
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001853void BestPractices::AddDeferredQueueOperations(CMD_BUFFER_STATE_BP* cb) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001854 cb->queue_submit_functions.insert(cb->queue_submit_functions.end(),
Hans-Kristian Arntzenf44df192021-06-14 11:42:08 +02001855 cb->queue_submit_functions_after_render_pass.begin(),
1856 cb->queue_submit_functions_after_render_pass.end());
1857 cb->queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001858}
1859
1860void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
1861 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Jeremy Gebben78684b12022-02-23 17:31:56 -07001862 auto cb_node = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Jeremy Gebben9f537102021-10-05 16:37:12 -06001863 AddDeferredQueueOperations(cb_node.get());
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001864}
1865
1866void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
1867 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Jeremy Gebben78684b12022-02-23 17:31:56 -07001868 auto cb_node = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Jeremy Gebben9f537102021-10-05 16:37:12 -06001869 AddDeferredQueueOperations(cb_node.get());
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001870}
1871
1872void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
1873 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Jeremy Gebben78684b12022-02-23 17:31:56 -07001874 auto cb_node = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Jeremy Gebben9f537102021-10-05 16:37:12 -06001875 AddDeferredQueueOperations(cb_node.get());
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001876}
1877
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001878void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer,
1879 const VkRenderPassBeginInfo* pRenderPassBegin,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001880 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001881 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001882 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1883}
1884
1885void BestPractices::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer,
1886 const VkRenderPassBeginInfo* pRenderPassBegin,
1887 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1888 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1889 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1890}
1891
1892void BestPractices::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1893 const VkRenderPassBeginInfo* pRenderPassBegin,
1894 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1895 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1896 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1897}
1898
1899void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001900
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001901 if (!pRenderPassBegin) {
1902 return;
1903 }
1904
Jeremy Gebben78684b12022-02-23 17:31:56 -07001905 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001906
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001907 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001908 if (rp_state) {
1909 // Check load ops
1910 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001911 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001912
1913 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
1914 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1915 continue;
1916 }
1917
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001918 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001919
1920 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
1921 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001922 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001923 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
1924 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001925 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001926 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001927 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001928 }
1929
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001930 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Jeremy Gebben9f537102021-10-05 16:37:12 -06001931 std::shared_ptr<IMAGE_VIEW_STATE> image_view = nullptr;
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001932
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001933 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001934 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1935 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001936 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001937 }
1938 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001939 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001940 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001941
Jeremy Gebben9f537102021-10-05 16:37:12 -06001942 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001943 }
1944
1945 // Check store ops
1946 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001947 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001948
1949 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1950 continue;
1951 }
1952
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001953 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001954
1955 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
1956 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001957 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001958 }
1959
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001960 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001961
Jeremy Gebben9f537102021-10-05 16:37:12 -06001962 std::shared_ptr<IMAGE_VIEW_STATE> image_view;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001963 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001964 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1965 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001966 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001967 }
1968 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001969 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001970 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001971
Jeremy Gebben9f537102021-10-05 16:37:12 -06001972 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001973 }
1974 }
1975}
1976
Attilio Provenzano02859b22020-02-27 14:17:28 +00001977bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1978 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001979 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1980 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001981 return skip;
1982}
1983
1984bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1985 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001986 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001987 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1988 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001989 return skip;
1990}
1991
1992bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001993 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001994 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1995 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001996 return skip;
1997}
1998
Sam Walls0961ec02020-03-31 16:39:15 +01001999void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
2000 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002001 // Reset the renderpass state
Jeremy Gebben78684b12022-02-23 17:31:56 -07002002 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002003 cb->hasDrawCmd = false;
2004 assert(cb);
2005 auto& render_pass_state = cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002006 render_pass_state.touchesAttachments.clear();
2007 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002008 render_pass_state.numDrawCallsDepthOnly = 0;
2009 render_pass_state.numDrawCallsDepthEqualCompare = 0;
2010 render_pass_state.colorAttachment = false;
2011 render_pass_state.depthAttachment = false;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002012 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002013 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01002014
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002015 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01002016
2017 // track depth / color attachment usage within the renderpass
2018 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
2019 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002020 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002021
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002022 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002023 }
2024}
2025
2026void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2027 VkSubpassContents contents) {
2028 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
2029 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
2030}
2031
2032void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2033 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2034 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2035 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2036}
2037
2038void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2039 const VkRenderPassBeginInfo* pRenderPassBegin,
2040 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2041 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2042 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2043}
2044
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002045// Generic function to handle validation for all CmdDraw* type functions
2046bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
2047 bool skip = false;
Jeremy Gebben78684b12022-02-23 17:31:56 -07002048 const auto cb_state = Get<CMD_BUFFER_STATE_BP>(cmd_buffer);
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002049 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002050 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
2051 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002052 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002053
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002054 // Verify vertex binding
2055 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
2056 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002057 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07002058 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002059 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
2060 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002061 }
2062 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002063
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002064 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002065 if (pipe) {
2066 const auto* rp_state = pipe->rp_state.get();
2067 if (rp_state) {
2068 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
2069 const auto& subpass = rp_state->createInfo.pSubpasses[i];
Jeremy Gebben11af9792021-08-20 10:20:09 -06002070 const auto& create_info = pipe->create_info.graphics;
2071 const uint32_t depth_stencil_attachment =
2072 GetSubpassDepthStencilAttachmentIndex(create_info.pDepthStencilState, subpass.pDepthStencilAttachment);
2073 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && create_info.pRasterizationState &&
2074 create_info.pRasterizationState->depthBiasEnable == VK_TRUE) {
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002075 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
2076 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
2077 }
2078 }
2079 }
2080 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002081 }
2082 return skip;
2083}
2084
Sam Walls0961ec02020-03-31 16:39:15 +01002085void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07002086 auto cb_node = Get<CMD_BUFFER_STATE_BP>(cmd_buffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002087 assert(cb_node);
2088 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01002089 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002090 RecordCmdDrawTypeArm(render_pass_state, draw_count, caller);
2091 }
2092
2093 if (render_pass_state.drawTouchAttachments) {
2094 for (auto& touch : render_pass_state.nextDrawTouchesAttachments) {
2095 RecordAttachmentAccess(render_pass_state, touch.framebufferAttachment, touch.aspects);
2096 }
2097 // No need to touch the same attachments over and over.
2098 render_pass_state.drawTouchAttachments = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002099 }
2100}
2101
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002102void BestPractices::RecordCmdDrawTypeArm(RenderPassState& render_pass_state, uint32_t draw_count, const char* caller) {
2103 if (draw_count >= kDepthPrePassMinDrawCountArm) {
2104 if (render_pass_state.depthOnly) render_pass_state.numDrawCallsDepthOnly++;
2105 if (render_pass_state.depthEqualComparison) render_pass_state.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01002106 }
2107}
2108
Camden5b184be2019-08-13 07:50:19 -06002109bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002110 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002111 bool skip = false;
2112
2113 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002114 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2115 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002116 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002117 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06002118
2119 return skip;
2120}
2121
Sam Walls0961ec02020-03-31 16:39:15 +01002122void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2123 uint32_t firstVertex, uint32_t firstInstance) {
2124 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
2125 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
2126}
2127
Camden5b184be2019-08-13 07:50:19 -06002128bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002129 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002130 bool skip = false;
2131
2132 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002133 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2134 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002135 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002136 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
2137
Attilio Provenzano02859b22020-02-27 14:17:28 +00002138 // Check if we reached the limit for small indexed draw calls.
2139 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
Jeremy Gebben78684b12022-02-23 17:31:56 -07002140 const auto cmd_state = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002141 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002142 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
2143 VendorCheckEnabled(kBPVendorArm)) {
2144 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06002145 "%s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00002146 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
2147 "You can try batching drawcalls or instancing when applicable.",
2148 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
2149 }
2150
Sam Walls8e77e4f2020-03-16 20:47:40 +00002151 if (VendorCheckEnabled(kBPVendorArm)) {
2152 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2153 }
2154
2155 return skip;
2156}
2157
2158bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2159 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
2160 bool skip = false;
2161
2162 // check for sparse/underutilised index buffer, and post-transform cache thrashing
Jeremy Gebben78684b12022-02-23 17:31:56 -07002163 const auto cmd_state = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002164 if (cmd_state == nullptr) return skip;
2165
locke-lunarg1ae57d62020-11-18 10:49:19 -07002166 const auto* ib_state = cmd_state->index_buffer_binding.buffer_state.get();
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002167 if (ib_state == nullptr || cmd_state->index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002168
2169 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002170 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00002171 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
2172 const void* ib_mem = ib_mem_state.p_driver_data;
2173 bool primitive_restart_enable = false;
2174
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002175 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
2176 const auto& pipeline_binding_iter = cmd_state->lastBound[lv_bind_point];
2177 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002178
Jeremy Gebben11af9792021-08-20 10:20:09 -06002179 if (pipeline_state != nullptr && pipeline_state->create_info.graphics.pInputAssemblyState != nullptr) {
2180 primitive_restart_enable = pipeline_state->create_info.graphics.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002181 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00002182
2183 // no point checking index buffer if the memory is nonexistant/unmapped, or if there is no graphics pipeline bound to this CB
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002184 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00002185 uint32_t scan_stride;
2186 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2187 scan_stride = sizeof(uint8_t);
2188 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2189 scan_stride = sizeof(uint16_t);
2190 } else {
2191 scan_stride = sizeof(uint32_t);
2192 }
2193
2194 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
2195 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
2196
2197 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
2198 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
2199 // irrespective of whether or not they're part of the draw call.
2200
2201 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
2202 uint32_t min_index = ~0u;
2203 // start with maximum as 0 and adjust to indices in the buffer
2204 uint32_t max_index = 0u;
2205
2206 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
2207 // for the given index buffer
2208 uint32_t vertex_shade_count = 0;
2209
2210 PostTransformLRUCacheModel post_transform_cache;
2211
2212 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
2213 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
2214 // target architecture.
2215 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
2216 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
2217 post_transform_cache.resize(32);
2218
2219 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2220 uint32_t scan_index;
2221 uint32_t primitive_restart_value;
2222 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2223 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2224 primitive_restart_value = 0xFF;
2225 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2226 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2227 primitive_restart_value = 0xFFFF;
2228 } else {
2229 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2230 primitive_restart_value = 0xFFFFFFFF;
2231 }
2232
2233 max_index = std::max(max_index, scan_index);
2234 min_index = std::min(min_index, scan_index);
2235
2236 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
2237 bool in_cache = post_transform_cache.query_cache(scan_index);
2238 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
2239 if (!in_cache) vertex_shade_count++;
2240 }
2241 }
2242
2243 // if the max and min values were not set, then we either have no indices, or all primitive restarts, exit...
Sam Walls61b06892020-07-23 16:20:50 +01002244 // if the max and min are the same, then it implies all the indices are the same, then we don't need to do anything
2245 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002246
2247 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07002248 skip |=
2249 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2250 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
2251 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
2252 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
2253 "maximum would be loaded, and possibly shaded, whether or not they are used.",
2254 VendorSpecificTag(kBPVendorArm),
2255 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002256 return skip;
2257 }
2258
2259 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
2260 // each bit of the n-th bucket contains the inclusion information for indices (n*n_buckets) to ((n+1)*n_buckets)
Sam Walls61b06892020-07-23 16:20:50 +01002261 const size_t refs_per_bucket = 64;
2262 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
2263
2264 const uint32_t n_indices = max_index - min_index + 1;
2265 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
2266 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
2267
2268 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
2269 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00002270
2271 // To avoid using too much memory, we run over the indices again.
2272 // Knowing the size from the last scan allows us to record index usage with bitsets
2273 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2274 uint32_t scan_index;
2275 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2276 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2277 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2278 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2279 } else {
2280 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2281 }
2282 // keep track of the set of all indices used to reference vertices in the draw call
2283 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01002284 size_t bitset_bucket_index = index_offset / refs_per_bucket;
2285 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002286 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
2287 }
2288
2289 uint32_t vertex_reference_count = 0;
2290 for (const auto& bitset : vertex_reference_buckets) {
2291 vertex_reference_count += static_cast<uint32_t>(bitset.count());
2292 }
2293
2294 // low index buffer utilization implies that: of the vertices available to the draw call, not all are utilized
Mark Young0ec6b062020-11-19 15:32:17 -07002295 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002296 // low hit rate (high miss rate) implies the order of indices in the draw call may be possible to improve
Mark Young0ec6b062020-11-19 15:32:17 -07002297 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002298
2299 if (utilization < 0.5f) {
2300 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2301 "%s The indices which were specified for the draw call only utilise approximately "
2302 "%.02f%% of the bound vertex buffer.",
2303 VendorSpecificTag(kBPVendorArm), utilization);
2304 }
2305
2306 if (cache_hit_rate <= 0.5f) {
2307 skip |=
2308 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
2309 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
2310 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
2311 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
2312 "recently shaded vertices.",
2313 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
2314 }
2315 }
2316
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002317 return skip;
2318}
2319
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002320bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2321 const VkCommandBuffer* pCommandBuffers) const {
2322 bool skip = false;
Jeremy Gebben78684b12022-02-23 17:31:56 -07002323 const auto primary = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002324 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07002325 const auto secondary_cb = Get<CMD_BUFFER_STATE_BP>(pCommandBuffers[i]);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002326 if (secondary_cb == nullptr) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002327 continue;
2328 }
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002329 const auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002330 for (auto& clear : secondary.earlyClearAttachments) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002331 if (ClearAttachmentsIsFullClear(primary.get(), uint32_t(clear.rects.size()), clear.rects.data())) {
2332 skip |= ValidateClearAttachment(commandBuffer, primary.get(), clear.framebufferAttachment, clear.colorAttachment,
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002333 clear.aspects, true);
2334 }
2335 }
2336 }
Nadav Gevaf0808442021-05-21 13:51:25 -04002337
2338 if (VendorCheckEnabled(kBPVendorAMD)) {
2339 if (commandBufferCount > 0) {
2340 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_AvoidSecondaryCmdBuffers,
2341 "%s Performance warning: Use of secondary command buffers is not recommended. ",
2342 VendorSpecificTag(kBPVendorAMD));
2343 }
2344 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002345 return skip;
2346}
2347
2348void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2349 const VkCommandBuffer* pCommandBuffers) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07002350 auto primary = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002351 auto& primary_state = primary->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002352
2353 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07002354 auto secondary_cb = Get<CMD_BUFFER_STATE_BP>(pCommandBuffers[i]);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002355 if (secondary_cb == nullptr) {
2356 continue;
2357 }
2358 auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002359
2360 for (auto& early_clear : secondary.earlyClearAttachments) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002361 if (ClearAttachmentsIsFullClear(primary.get(), uint32_t(early_clear.rects.size()), early_clear.rects.data())) {
2362 RecordAttachmentClearAttachments(primary.get(), primary_state, early_clear.framebufferAttachment,
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002363 early_clear.colorAttachment, early_clear.aspects,
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002364 uint32_t(early_clear.rects.size()), early_clear.rects.data());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002365 } else {
2366 RecordAttachmentAccess(primary_state, early_clear.framebufferAttachment,
2367 early_clear.aspects);
2368 }
2369 }
2370
2371 for (auto& touch : secondary.touchesAttachments) {
2372 RecordAttachmentAccess(primary_state, touch.framebufferAttachment,
2373 touch.aspects);
2374 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02002375
2376 primary_state.numDrawCallsDepthEqualCompare += secondary.numDrawCallsDepthEqualCompare;
2377 primary_state.numDrawCallsDepthOnly += secondary.numDrawCallsDepthOnly;
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002378
Jeremy Gebben78684b12022-02-23 17:31:56 -07002379 auto second_state = Get<CMD_BUFFER_STATE_BP>(pCommandBuffers[i]);
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002380 if (second_state->hasDrawCmd) {
2381 primary->hasDrawCmd = true;
2382 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002383 }
2384
2385 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2386}
2387
2388void BestPractices::RecordAttachmentAccess(RenderPassState& state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
2389 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
2390 auto itr = std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002391 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002392 return info.framebufferAttachment == fb_attachment;
2393 });
2394
2395 if (itr != state.touchesAttachments.end()) {
2396 itr->aspects |= aspects;
2397 } else {
2398 state.touchesAttachments.push_back({ fb_attachment, aspects });
2399 }
2400}
2401
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002402void BestPractices::RecordAttachmentClearAttachments(CMD_BUFFER_STATE_BP* cmd_state, RenderPassState& state, uint32_t fb_attachment,
2403 uint32_t color_attachment, VkImageAspectFlags aspects, uint32_t rectCount,
2404 const VkClearRect* pRects) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002405 // If we observe a full clear before any other access to a frame buffer attachment,
2406 // we have candidate for redundant clear attachments.
2407 auto itr = std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002408 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002409 return info.framebufferAttachment == fb_attachment;
2410 });
2411
2412 uint32_t new_aspects = aspects;
2413 if (itr != state.touchesAttachments.end()) {
2414 new_aspects = aspects & ~itr->aspects;
2415 itr->aspects |= aspects;
2416 } else {
2417 state.touchesAttachments.push_back({ fb_attachment, aspects });
2418 }
2419
2420 if (new_aspects == 0) {
2421 return;
2422 }
2423
2424 if (cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2425 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
2426 // CmdExecuteCommands.
2427 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
2428 std::vector<VkClearRect>{pRects, pRects + rectCount} });
2429 }
2430}
2431
2432void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
2433 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
2434 uint32_t rectCount, const VkClearRect* pRects) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07002435 auto cmd_state = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002436 RENDER_PASS_STATE* rp_state = cmd_state->activeRenderPass.get();
2437 FRAMEBUFFER_STATE* fb_state = cmd_state->activeFramebuffer.get();
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002438 RenderPassState& tracking_state = cmd_state->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002439 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
2440
2441 if (rectCount == 0 || !rp_state) {
2442 return;
2443 }
2444
2445 if (!is_secondary && !fb_state) {
2446 return;
2447 }
2448
2449 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
Jeremy Gebben9f537102021-10-05 16:37:12 -06002450 bool full_clear = ClearAttachmentsIsFullClear(cmd_state.get(), rectCount, pRects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002451
2452 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
2453 for (uint32_t i = 0; i < attachmentCount; i++) {
2454 auto& attachment = pClearAttachments[i];
2455 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
2456 VkImageAspectFlags aspects = attachment.aspectMask;
2457
2458 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
2459 if (subpass.pDepthStencilAttachment) {
2460 fb_attachment = subpass.pDepthStencilAttachment->attachment;
2461 }
2462 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
2463 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
2464 }
2465
2466 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2467 if (full_clear) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002468 RecordAttachmentClearAttachments(cmd_state.get(), tracking_state, fb_attachment, attachment.colorAttachment,
2469 aspects, rectCount, pRects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002470 } else {
2471 RecordAttachmentAccess(tracking_state, fb_attachment, aspects);
2472 }
2473 }
2474 }
2475
2476 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments,
2477 rectCount, pRects);
2478}
2479
Attilio Provenzano02859b22020-02-27 14:17:28 +00002480void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2481 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2482 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
2483 firstInstance);
2484
Jeremy Gebben78684b12022-02-23 17:31:56 -07002485 auto cmd_state = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002486 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
2487 cmd_state->small_indexed_draw_call_count++;
2488 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002489
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002490 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00002491}
2492
Sam Walls0961ec02020-03-31 16:39:15 +01002493void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2494 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2495 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2496 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
2497}
2498
sfricke-samsung681ab7b2020-10-29 01:53:35 -07002499bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2500 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
2501 uint32_t maxDrawCount, uint32_t stride) const {
2502 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
2503
2504 return skip;
2505}
2506
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002507bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
2508 VkDeviceSize offset, VkBuffer countBuffer,
2509 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
2510 uint32_t stride) const {
2511 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06002512
2513 return skip;
2514}
2515
2516bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002517 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002518 bool skip = false;
2519
2520 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002521 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2522 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002523 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002524 }
2525
2526 return skip;
2527}
2528
Sam Walls0961ec02020-03-31 16:39:15 +01002529void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2530 uint32_t count, uint32_t stride) {
2531 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
2532 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
2533}
2534
Camden5b184be2019-08-13 07:50:19 -06002535bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002536 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002537 bool skip = false;
2538
2539 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002540 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2541 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002542 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002543 }
2544
2545 return skip;
2546}
2547
Sam Walls0961ec02020-03-31 16:39:15 +01002548void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2549 uint32_t count, uint32_t stride) {
2550 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
2551 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
2552}
2553
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002554void BestPractices::ValidateBoundDescriptorSets(VkCommandBuffer commandBuffer, const char* function_name) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07002555 auto cb_state = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002556
2557 if (cb_state) {
2558 for (auto descriptor_set : cb_state->validated_descriptor_sets) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002559 const auto& layout = *descriptor_set->GetLayout();
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002560
2561 for (uint32_t index = 0; index < descriptor_set->GetBindingCount(); ++index) {
2562 // For bindless scenarios, we should not attempt to track descriptor set state.
2563 // It is highly uncertain which resources are actually bound.
2564 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
2565 VkDescriptorBindingFlags flags = layout.GetDescriptorBindingFlagsFromIndex(index);
2566 if (flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT |
2567 VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
2568 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
2569 continue;
2570 }
2571
2572 auto index_range = layout.GetGlobalIndexRangeFromIndex(index);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002573 for (uint32_t i = index_range.start; i < index_range.end; ++i) {
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002574 VkImageView image_view{VK_NULL_HANDLE};
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002575
2576 auto descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2577 switch (descriptor->GetClass()) {
2578 case cvdescriptorset::DescriptorClass::Image: {
2579 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
2580 image_view = image_descriptor->GetImageView();
2581 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002582 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002583 }
2584 case cvdescriptorset::DescriptorClass::ImageSampler: {
2585 if (const auto image_sampler_descriptor =
2586 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
2587 image_view = image_sampler_descriptor->GetImageView();
2588 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002589 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002590 }
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002591 default:
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002592 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002593 }
2594
2595 if (image_view) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002596 auto image_view_state = Get<IMAGE_VIEW_STATE>(image_view);
Jeremy Gebben9f537102021-10-05 16:37:12 -06002597 QueueValidateImageView(cb_state->queue_submit_functions, function_name, image_view_state.get(),
2598 IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002599 }
2600 }
2601 }
2602 }
2603 }
2604}
2605
2606void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2607 uint32_t firstVertex, uint32_t firstInstance) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002608 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002609}
2610
2611void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2612 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002613 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002614}
2615
2616void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2617 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002618 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002619}
2620
Camden5b184be2019-08-13 07:50:19 -06002621bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002622 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06002623 bool skip = false;
2624
2625 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002626 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
2627 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
2628 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
2629 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06002630 }
2631
2632 return skip;
2633}
Camden83a9c372019-08-14 11:41:38 -06002634
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002635bool BestPractices::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2636 bool skip = false;
2637 skip |= StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
2638 skip |= ValidateCmdEndRenderPass(commandBuffer);
2639 return skip;
2640}
2641
2642bool BestPractices::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2643 bool skip = false;
2644 skip |= StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
2645 skip |= ValidateCmdEndRenderPass(commandBuffer);
2646 return skip;
2647}
2648
Sam Walls0961ec02020-03-31 16:39:15 +01002649bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2650 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002651 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002652 skip |= ValidateCmdEndRenderPass(commandBuffer);
2653 return skip;
2654}
2655
2656bool BestPractices::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2657 bool skip = false;
Jeremy Gebben78684b12022-02-23 17:31:56 -07002658 const auto cmd = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01002659
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002660 if (cmd == nullptr) return skip;
2661 auto &render_pass_state = cmd->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01002662
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002663 bool uses_depth = (render_pass_state.depthAttachment || render_pass_state.colorAttachment) &&
2664 render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2665 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
Sam Walls0961ec02020-03-31 16:39:15 +01002666 if (uses_depth) {
2667 skip |= LogPerformanceWarning(
2668 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
2669 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
2670 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
2671 "case, using depth pre-passes for hidden surface removal may worsen performance.",
2672 VendorSpecificTag(kBPVendorArm));
2673 }
2674
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002675 RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2676
2677 if (VendorCheckEnabled(kBPVendorArm) && rp) {
2678
2679 // If we use an attachment on-tile, we should access it in some way. Otherwise,
2680 // it is redundant to have it be part of the render pass.
2681 // Only consider it redundant if it will actually consume bandwidth, i.e.
2682 // LOAD_OP_LOAD is used or STORE_OP_STORE. CLEAR -> DONT_CARE is benign,
2683 // as is using pure input attachments.
2684 // CLEAR -> STORE might be considered a "useful" thing to do, but
2685 // the optimal thing to do is to defer the clear until you're actually
2686 // going to render to the image.
2687
2688 uint32_t num_attachments = rp->createInfo.attachmentCount;
2689 for (uint32_t i = 0; i < num_attachments; i++) {
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02002690 if (!RenderPassUsesAttachmentOnTile(rp->createInfo, i) ||
2691 RenderPassUsesAttachmentAsResolve(rp->createInfo, i)) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002692 continue;
2693 }
2694
2695 auto& attachment = rp->createInfo.pAttachments[i];
2696
2697 VkImageAspectFlags bandwidth_aspects = 0;
2698
2699 if (!FormatIsStencilOnly(attachment.format) &&
2700 (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2701 attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2702 if (FormatHasDepth(attachment.format)) {
2703 bandwidth_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
2704 } else {
2705 bandwidth_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
2706 }
2707 }
2708
2709 if (FormatHasStencil(attachment.format) &&
2710 (attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2711 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2712 bandwidth_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
2713 }
2714
2715 if (!bandwidth_aspects) {
2716 continue;
2717 }
2718
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002719 auto itr = std::find_if(render_pass_state.touchesAttachments.begin(), render_pass_state.touchesAttachments.end(),
2720 [&](const AttachmentInfo& info) { return info.framebufferAttachment == i; });
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002721 uint32_t untouched_aspects = bandwidth_aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002722 if (itr != render_pass_state.touchesAttachments.end()) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002723 untouched_aspects &= ~itr->aspects;
2724 }
2725
2726 if (untouched_aspects) {
2727 skip |= LogPerformanceWarning(
2728 device, kVUID_BestPractices_EndRenderPass_RedundantAttachmentOnTile,
2729 "%s Render pass was ended, but attachment #%u (format: %u, untouched aspects 0x%x) "
2730 "was never accessed by a pipeline or clear command. "
2731 "On tile-based architectures, LOAD_OP_LOAD and STORE_OP_STORE consume bandwidth and should not be part of the render pass "
2732 "if the attachments are not intended to be accessed.",
2733 VendorSpecificTag(kBPVendorArm), i, attachment.format, untouched_aspects);
2734 }
2735 }
2736 }
2737
Sam Walls0961ec02020-03-31 16:39:15 +01002738 return skip;
2739}
2740
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002741void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002742 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002743}
2744
2745void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002746 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002747}
2748
Camden Stocker9c051442019-11-06 14:28:43 -08002749bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2750 const char* api_name) const {
2751 bool skip = false;
Jeremy Gebben78684b12022-02-23 17:31:56 -07002752 const auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002753
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002754 if (bp_pd_state) {
2755 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2756 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2757 "Potential problem with calling %s() without first retrieving properties from "
2758 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2759 api_name);
2760 }
Camden Stocker9c051442019-11-06 14:28:43 -08002761 }
2762
2763 return skip;
2764}
2765
Camden83a9c372019-08-14 11:41:38 -06002766bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002767 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002768 bool skip = false;
2769
Camden Stocker9c051442019-11-06 14:28:43 -08002770 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002771
Camden Stocker9c051442019-11-06 14:28:43 -08002772 return skip;
2773}
2774
2775bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2776 uint32_t planeIndex,
2777 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2778 bool skip = false;
2779
2780 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2781
2782 return skip;
2783}
2784
2785bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2786 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2787 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2788 bool skip = false;
2789
2790 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002791
2792 return skip;
2793}
Camden05de2d42019-08-19 10:23:56 -06002794
2795bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002796 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002797 bool skip = false;
2798
Jeremy Gebben78684b12022-02-23 17:31:56 -07002799 auto swapchain_state = Get<SWAPCHAIN_STATE_BP>(swapchain);
Camden05de2d42019-08-19 10:23:56 -06002800
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002801 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002802 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002803 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002804 skip |=
2805 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2806 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2807 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002808 }
Camden05de2d42019-08-19 10:23:56 -06002809
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002810 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
2811 skip |= LogWarning(
2812 device, kVUID_BestPractices_Swapchain_InvalidCount,
2813 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
Nadav Gevaf0808442021-05-21 13:51:25 -04002814 "value (%" PRId32 ") that is greater than the value (%" PRId32 ") that was returned when pSwapchainImages was NULL.",
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002815 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
2816 }
2817 }
2818
Camden05de2d42019-08-19 10:23:56 -06002819 return skip;
2820}
2821
2822// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002823bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* bp_pd_state,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002824 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002825 const CALL_STATE call_state,
2826 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002827 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002828 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2829 if (UNCALLED == call_state) {
2830 skip |= LogWarning(
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002831 bp_pd_state->Handle(), kVUID_Core_DevLimit_MissingQueryCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002832 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2833 "recommended "
2834 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2835 caller_name, caller_name);
2836 // Then verify that pCount that is passed in on second call matches what was returned
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002837 } else if (bp_pd_state->queue_family_known_count != requested_queue_family_property_count) {
2838 skip |= LogWarning(bp_pd_state->Handle(), kVUID_Core_DevLimit_CountMismatch,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002839 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2840 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2841 ". It is recommended to instead receive all the properties by calling %s with "
2842 "pQueueFamilyPropertyCount that was "
2843 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002844 caller_name, requested_queue_family_property_count, bp_pd_state->queue_family_known_count, caller_name,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002845 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002846 }
2847
2848 return skip;
2849}
2850
Jeff Bolz5c801d12019-10-09 10:38:45 -05002851bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2852 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002853 bool skip = false;
2854
2855 for (uint32_t i = 0; i < bindInfoCount; i++) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002856 auto as_state = Get<ACCELERATION_STRUCTURE_STATE>(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002857 if (!as_state->memory_requirements_checked) {
2858 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2859 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2860 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002861 skip |= LogWarning(
2862 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002863 "vkBindAccelerationStructureMemoryNV(): "
2864 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
2865 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
2866 }
2867 }
2868
2869 return skip;
2870}
2871
Camden05de2d42019-08-19 10:23:56 -06002872bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2873 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002874 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Jeremy Gebben78684b12022-02-23 17:31:56 -07002875 const auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002876 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002877 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002878 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2879 "vkGetPhysicalDeviceQueueFamilyProperties()");
2880 }
2881 return false;
Camden05de2d42019-08-19 10:23:56 -06002882}
2883
Mike Schuchardt2df08912020-12-15 16:28:09 -08002884bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2885 uint32_t* pQueueFamilyPropertyCount,
2886 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben78684b12022-02-23 17:31:56 -07002887 const auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002888 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002889 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002890 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2891 "vkGetPhysicalDeviceQueueFamilyProperties2()");
2892 }
2893 return false;
Camden05de2d42019-08-19 10:23:56 -06002894}
2895
Jeff Bolz5c801d12019-10-09 10:38:45 -05002896bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08002897 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben78684b12022-02-23 17:31:56 -07002898 const auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002899 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002900 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002901 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2902 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
2903 }
2904 return false;
Camden05de2d42019-08-19 10:23:56 -06002905}
2906
2907bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2908 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002909 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06002910 if (!pSurfaceFormats) return false;
Jeremy Gebben78684b12022-02-23 17:31:56 -07002911 const auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002912 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06002913 bool skip = false;
2914 if (call_state == UNCALLED) {
2915 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
2916 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002917 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
2918 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
2919 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06002920 } else {
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06002921 if (*pSurfaceFormatCount > bp_pd_state->surface_formats_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002922 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
2923 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
2924 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
2925 "when pSurfaceFormatCount was NULL.",
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06002926 *pSurfaceFormatCount, bp_pd_state->surface_formats_count);
Camden05de2d42019-08-19 10:23:56 -06002927 }
2928 }
2929 return skip;
2930}
Camden Stocker23cc47d2019-09-03 14:53:57 -06002931
2932bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002933 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002934 bool skip = false;
2935
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002936 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2937 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002938 // Store sparse binding image_state and after binding is complete make sure that any requiring metadata have it bound
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002939 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002940 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
2941 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002942 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06002943 // If we're binding sparse image memory make sure reqs were queried and note if metadata is required and bound
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002944 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
2945 const auto& image_bind = bind_info.pImageBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04002946 auto image_state = Get<IMAGE_STATE>(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002947 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002948 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002949 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06002950 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002951 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2952 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2953 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002954 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002955 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2956 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002957 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002958 }
2959 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002960 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002961 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002962 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002963 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2964 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002965 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002966 }
2967 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002968 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2969 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04002970 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002971 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002972 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002973 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06002974 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002975 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2976 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2977 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002978 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002979 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2980 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002981 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002982 }
2983 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002984 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002985 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002986 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002987 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2988 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002989 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002990 }
2991 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2992 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002993 sparse_images_with_metadata.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002994 }
2995 }
2996 }
2997 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002998 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
2999 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003000 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003001 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003002 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
3003 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003004 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003005 }
3006 }
3007 }
3008
3009 return skip;
3010}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003011
Mark Lobodzinski84101d72020-04-24 09:43:48 -06003012void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
3013 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07003014 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07003015 return;
3016 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003017
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003018 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
3019 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
3020 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
3021 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04003022 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003023 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003024 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003025 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003026 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
3027 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
3028 image_state->sparse_metadata_bound = true;
3029 }
3030 }
3031 }
3032 }
3033}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003034
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003035bool BestPractices::ClearAttachmentsIsFullClear(const CMD_BUFFER_STATE_BP* cmd, uint32_t rectCount,
3036 const VkClearRect* pRects) const {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003037 if (cmd->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
3038 // We don't know the accurate render area in a secondary,
3039 // so assume we clear the entire frame buffer.
3040 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
3041 return true;
3042 }
3043
3044 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
3045 for (uint32_t i = 0; i < rectCount; i++) {
3046 auto& rect = pRects[i];
3047 auto& render_area = cmd->activeRenderPassBeginInfo.renderArea;
3048 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
3049 return true;
3050 }
3051 }
3052
3053 return false;
3054}
3055
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003056bool BestPractices::ValidateClearAttachment(VkCommandBuffer commandBuffer, const CMD_BUFFER_STATE_BP* cmd, uint32_t fb_attachment,
3057 uint32_t color_attachment, VkImageAspectFlags aspects, bool secondary) const {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003058 const RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
3059 bool skip = false;
3060
3061 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
3062 return skip;
3063 }
3064
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003065 const auto& rp_state = cmd->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003066
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003067 auto attachment_itr = std::find_if(rp_state.touchesAttachments.begin(), rp_state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02003068 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003069 return info.framebufferAttachment == fb_attachment;
3070 });
3071
3072 // Only report aspects which haven't been touched yet.
3073 VkImageAspectFlags new_aspects = aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003074 if (attachment_itr != rp_state.touchesAttachments.end()) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003075 new_aspects &= ~attachment_itr->aspects;
3076 }
3077
3078 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
3079 if (!cmd->hasDrawCmd) {
3080 skip |= LogPerformanceWarning(
3081 commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
Hans-Kristian Arntzen4ddd6182021-06-18 12:16:33 +02003082 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds in current render pass. It is recommended you "
3083 "use RenderPass LOAD_OP_CLEAR on attachments instead.",
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003084 report_data->FormatHandle(commandBuffer).c_str());
3085 }
3086
3087 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
3088 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3089 skip |= LogPerformanceWarning(
3090 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3091 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
3092 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3093 "it is more efficient.",
3094 secondary ? "vkCmdExecuteCommands(): " : "",
3095 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
3096 }
3097
3098 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
3099 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3100 skip |= LogPerformanceWarning(
3101 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3102 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
3103 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3104 "it is more efficient.",
3105 secondary ? "vkCmdExecuteCommands(): " : "",
3106 report_data->FormatHandle(commandBuffer).c_str());
3107 }
3108
3109 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
3110 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3111 skip |= LogPerformanceWarning(
3112 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3113 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
3114 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3115 "it is more efficient.",
3116 secondary ? "vkCmdExecuteCommands(): " : "",
3117 report_data->FormatHandle(commandBuffer).c_str());
3118 }
3119
3120 return skip;
3121}
3122
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003123bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06003124 const VkClearAttachment* pAttachments, uint32_t rectCount,
3125 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003126 bool skip = false;
Jeremy Gebben78684b12022-02-23 17:31:56 -07003127 const auto cb_node = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003128 if (!cb_node) return skip;
3129
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003130 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
3131 // Defer checks to ExecuteCommands.
3132 return skip;
3133 }
3134
3135 // Only care about full clears, partial clears might have legitimate uses.
Jeremy Gebben9f537102021-10-05 16:37:12 -06003136 if (!ClearAttachmentsIsFullClear(cb_node.get(), rectCount, pRects)) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003137 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003138 }
3139
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003140 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
3141 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06003142 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003143 if (rp) {
3144 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
3145
3146 for (uint32_t i = 0; i < attachmentCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003147 const auto& attachment = pAttachments[i];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003148
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003149 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
3150 uint32_t color_attachment = attachment.colorAttachment;
3151 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
Jeremy Gebben9f537102021-10-05 16:37:12 -06003152 skip |= ValidateClearAttachment(commandBuffer, cb_node.get(), fb_attachment, color_attachment,
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003153 attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003154 }
3155
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003156 if (subpass.pDepthStencilAttachment &&
3157 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003158 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
Jeremy Gebben9f537102021-10-05 16:37:12 -06003159 skip |= ValidateClearAttachment(commandBuffer, cb_node.get(), fb_attachment, VK_ATTACHMENT_UNUSED,
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003160 attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003161 }
3162 }
3163 }
3164
Nadav Gevaf0808442021-05-21 13:51:25 -04003165 if (VendorCheckEnabled(kBPVendorAMD)) {
3166 for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; attachment_idx++) {
3167 if (pAttachments[attachment_idx].aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) {
3168 bool black_check = false;
3169 black_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 0.0f;
3170 black_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 0.0f;
3171 black_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 0.0f;
3172 black_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3173 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3174
3175 bool white_check = false;
3176 white_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 1.0f;
3177 white_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 1.0f;
3178 white_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 1.0f;
3179 white_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3180 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3181
3182 if (black_check && white_check) {
3183 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3184 "%s Performance warning: vkCmdClearAttachments() clear value for color attachment %" PRId32 " is not a fast clear value."
3185 "Consider changing to one of the following:"
3186 "RGBA(0, 0, 0, 0) "
3187 "RGBA(0, 0, 0, 1) "
3188 "RGBA(1, 1, 1, 0) "
3189 "RGBA(1, 1, 1, 1)",
3190 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3191 }
3192 } else {
3193 if ((pAttachments[attachment_idx].clearValue.depthStencil.depth != 0 &&
3194 pAttachments[attachment_idx].clearValue.depthStencil.depth != 1) &&
3195 pAttachments[attachment_idx].clearValue.depthStencil.stencil != 0) {
3196 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3197 "%s Performance warning: vkCmdClearAttachments() clear value for depth/stencil "
3198 "attachment %" PRId32 " is not a fast clear value."
3199 "Consider changing to one of the following:"
3200 "D=0.0f, S=0"
3201 "D=1.0f, S=0",
3202 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3203 }
3204 }
3205 }
3206 }
3207
Camden Stockerf55721f2019-09-09 11:04:49 -06003208 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003209}
Attilio Provenzano02859b22020-02-27 14:17:28 +00003210
3211bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3212 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3213 const VkImageResolve* pRegions) const {
3214 bool skip = false;
3215
3216 skip |= VendorCheckEnabled(kBPVendorArm) &&
3217 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
3218 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
3219 "This is a very slow and extremely bandwidth intensive path. "
3220 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3221 VendorSpecificTag(kBPVendorArm));
3222
3223 return skip;
3224}
3225
Jeff Leger178b1e52020-10-05 12:22:23 -04003226bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3227 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
3228 bool skip = false;
3229
3230 skip |= VendorCheckEnabled(kBPVendorArm) &&
3231 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
3232 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
3233 "This is a very slow and extremely bandwidth intensive path. "
3234 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3235 VendorSpecificTag(kBPVendorArm));
3236
3237 return skip;
3238}
3239
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003240bool BestPractices::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
3241 const VkResolveImageInfo2* pResolveImageInfo) const {
3242 bool skip = false;
3243
3244 skip |= VendorCheckEnabled(kBPVendorArm) &&
3245 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2_ResolvingImage,
3246 "%s Attempting to use vkCmdResolveImage2 to resolve a multisampled image. "
3247 "This is a very slow and extremely bandwidth intensive path. "
3248 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3249 VendorSpecificTag(kBPVendorArm));
3250
3251 return skip;
3252}
3253
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003254void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3255 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3256 const VkImageResolve* pRegions) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003257 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003258 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003259 auto* src = GetImageUsageState(srcImage);
3260 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003261
3262 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003263 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
3264 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003265 }
3266}
3267
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003268void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3269 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003270 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003271 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003272 auto* src = GetImageUsageState(pResolveImageInfo->srcImage);
3273 auto* dst = GetImageUsageState(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003274 uint32_t regionCount = pResolveImageInfo->regionCount;
3275
3276 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003277 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
3278 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003279 }
3280}
3281
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003282void BestPractices::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer,
3283 const VkResolveImageInfo2* pResolveImageInfo) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003284 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003285 auto& funcs = cb->queue_submit_functions;
3286 auto* src = GetImageUsageState(pResolveImageInfo->srcImage);
3287 auto* dst = GetImageUsageState(pResolveImageInfo->dstImage);
3288 uint32_t regionCount = pResolveImageInfo->regionCount;
3289
3290 for (uint32_t i = 0; i < regionCount; i++) {
3291 QueueValidateImage(funcs, "vkCmdResolveImage2()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ,
3292 pResolveImageInfo->pRegions[i].srcSubresource);
3293 QueueValidateImage(funcs, "vkCmdResolveImage2()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE,
3294 pResolveImageInfo->pRegions[i].dstSubresource);
3295 }
3296}
3297
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003298void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3299 const VkClearColorValue* pColor, uint32_t rangeCount,
3300 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003301 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003302 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003303 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003304
3305 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003306 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003307 }
3308}
3309
3310void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3311 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3312 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003313 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003314 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003315 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003316
3317 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003318 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003319 }
3320}
3321
3322void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3323 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3324 const VkImageCopy* pRegions) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003325 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003326 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003327 auto* src = GetImageUsageState(srcImage);
3328 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003329
3330 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003331 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
3332 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003333 }
3334}
3335
3336void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3337 VkImageLayout dstImageLayout, uint32_t regionCount,
3338 const VkBufferImageCopy* pRegions) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003339 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003340 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003341 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003342
3343 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003344 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003345 }
3346}
3347
3348void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3349 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003350 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003351 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003352 auto* src = GetImageUsageState(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003353
3354 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003355 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003356 }
3357}
3358
3359void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3360 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3361 const VkImageBlit* pRegions, VkFilter filter) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003362 auto cb = Get<CMD_BUFFER_STATE_BP>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003363 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003364 auto* src = GetImageUsageState(srcImage);
3365 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003366
3367 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003368 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
3369 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003370 }
3371}
3372
Attilio Provenzano02859b22020-02-27 14:17:28 +00003373bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
3374 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
3375 bool skip = false;
3376
3377 if (VendorCheckEnabled(kBPVendorArm)) {
3378 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
3379 skip |= LogPerformanceWarning(
3380 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
3381 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
3382 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
3383 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06003384 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003385 }
3386
3387 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
3388 skip |= LogPerformanceWarning(
3389 device, kVUID_BestPractices_CreateSampler_LodClamping,
3390 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
3391 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
3392 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
3393 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
3394 }
3395
3396 if (pCreateInfo->mipLodBias != 0.0f) {
3397 skip |=
3398 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
3399 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
3400 "descriptors being created and may cause reduced performance.",
3401 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
3402 }
3403
3404 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3405 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3406 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
3407 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
3408 skip |= LogPerformanceWarning(
3409 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
3410 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
3411 "This will lead to less efficient descriptors being created and may cause reduced performance. "
3412 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
3413 VendorSpecificTag(kBPVendorArm));
3414 }
3415
3416 if (pCreateInfo->unnormalizedCoordinates) {
3417 skip |= LogPerformanceWarning(
3418 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
3419 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
3420 "descriptors being created and may cause reduced performance.",
3421 VendorSpecificTag(kBPVendorArm));
3422 }
3423
3424 if (pCreateInfo->anisotropyEnable) {
3425 skip |= LogPerformanceWarning(
3426 device, kVUID_BestPractices_CreateSampler_Anisotropy,
3427 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
3428 "and may cause reduced performance.",
3429 VendorSpecificTag(kBPVendorArm));
3430 }
3431 }
3432
3433 return skip;
3434}
Sam Walls8e77e4f2020-03-16 20:47:40 +00003435
Nadav Gevaf0808442021-05-21 13:51:25 -04003436void BestPractices::PreCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
3437 const VkGraphicsPipelineCreateInfo* pCreateInfos,
3438 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
3439 void* cgpl_state) {
3440 ValidationStateTracker::PreCallRecordCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator,
3441 pPipelines);
3442 // AMD best practice
3443 num_pso += createInfoCount;
3444}
3445
3446bool BestPractices::PreCallValidateUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount,
3447 const VkWriteDescriptorSet* pDescriptorWrites, uint32_t descriptorCopyCount,
3448 const VkCopyDescriptorSet* pDescriptorCopies) const {
3449 bool skip = false;
3450 if (VendorCheckEnabled(kBPVendorAMD)) {
3451 if (descriptorCopyCount > 0) {
3452 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_AvoidCopyingDescriptors,
3453 "%s Performance warning: copying descriptor sets is not recommended",
3454 VendorSpecificTag(kBPVendorAMD));
3455 }
3456 }
3457
3458 return skip;
3459}
3460
3461bool BestPractices::PreCallValidateCreateDescriptorUpdateTemplate(VkDevice device,
3462 const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
3463 const VkAllocationCallbacks* pAllocator,
3464 VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate) const {
3465 bool skip = false;
3466 if (VendorCheckEnabled(kBPVendorAMD)) {
3467 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_PreferNonTemplate,
3468 "%s Performance warning: using DescriptorSetWithTemplate is not recommended. Prefer using "
3469 "vkUpdateDescriptorSet instead",
3470 VendorSpecificTag(kBPVendorAMD));
3471 }
3472
3473 return skip;
3474}
3475
3476bool BestPractices::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3477 const VkClearColorValue* pColor, uint32_t rangeCount,
3478 const VkImageSubresourceRange* pRanges) const {
3479 bool skip = false;
3480 if (VendorCheckEnabled(kBPVendorAMD)) {
sfricke-samsungef15e482022-01-26 11:32:49 -08003481 skip |= LogPerformanceWarning(
3482 device, kVUID_BestPractices_ClearAttachment_ClearImage,
Nadav Gevaf0808442021-05-21 13:51:25 -04003483 "%s Performance warning: using vkCmdClearColorImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3484 "vkCmdClearAttachments instead",
3485 VendorSpecificTag(kBPVendorAMD));
3486 }
3487
3488 return skip;
3489}
3490
3491bool BestPractices::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
3492 VkImageLayout imageLayout,
3493 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3494 const VkImageSubresourceRange* pRanges) const {
3495 bool skip = false;
3496 if (VendorCheckEnabled(kBPVendorAMD)) {
3497 skip |= LogPerformanceWarning(
3498 device, kVUID_BestPractices_ClearAttachment_ClearImage,
3499 "%s Performance warning: using vkCmdClearDepthStencilImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3500 "vkCmdClearAttachments instead",
3501 VendorSpecificTag(kBPVendorAMD));
3502 }
3503
3504 return skip;
3505}
3506
3507bool BestPractices::PreCallValidateCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo* pCreateInfo,
3508 const VkAllocationCallbacks* pAllocator,
3509 VkPipelineLayout* pPipelineLayout) const {
3510 bool skip = false;
3511 if (VendorCheckEnabled(kBPVendorAMD)) {
3512 // Descriptor sets cost 1 DWORD each.
3513 // Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF.
3514 // Dynamic buffers cost 4 DWORDs each when robust buffer access is ON.
3515 // Push constants cost 1 DWORD per 4 bytes in the Push constant range.
3516 uint32_t pipeline_size = pCreateInfo->setLayoutCount; // in DWORDS
3517 for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; i++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06003518 auto descriptor_set_layout_state = Get<cvdescriptorset::DescriptorSetLayout>(pCreateInfo->pSetLayouts[i]);
Nadav Gevaf0808442021-05-21 13:51:25 -04003519 pipeline_size += descriptor_set_layout_state->GetDynamicDescriptorCount() * (robust_buffer_access ? 4 : 2);
3520 }
3521
3522 for (uint32_t i = 0; i < pCreateInfo->pushConstantRangeCount; i++) {
3523 pipeline_size += pCreateInfo->pPushConstantRanges[i].size / 4;
3524 }
3525
3526 if (pipeline_size > kPipelineLayoutSizeWarningLimitAMD) {
3527 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelinesLayout_KeepLayoutSmall,
3528 "%s Performance warning: pipeline layout size is too large. Prefer smaller pipeline layouts."
3529 "Descriptor sets cost 1 DWORD each. "
3530 "Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF. "
3531 "Dynamic buffers cost 4 DWORDs each when robust buffer access is ON. "
3532 "Push constants cost 1 DWORD per 4 bytes in the Push constant range. ",
3533 VendorSpecificTag(kBPVendorAMD));
3534 }
3535 }
3536
3537 return skip;
3538}
3539
3540bool BestPractices::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3541 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3542 const VkImageCopy* pRegions) const {
3543 bool skip = false;
3544 std::stringstream src_image_hex;
3545 std::stringstream dst_image_hex;
3546 src_image_hex << "0x" << std::hex << HandleToUint64(srcImage);
3547 dst_image_hex << "0x" << std::hex << HandleToUint64(dstImage);
3548
3549 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003550 auto src_state = Get<IMAGE_STATE>(srcImage);
3551 auto dst_state = Get<IMAGE_STATE>(dstImage);
Nadav Gevaf0808442021-05-21 13:51:25 -04003552
3553 if (src_state && dst_state) {
3554 VkImageTiling src_Tiling = src_state->createInfo.tiling;
3555 VkImageTiling dst_Tiling = dst_state->createInfo.tiling;
3556 if (src_Tiling != dst_Tiling && (src_Tiling == VK_IMAGE_TILING_LINEAR || dst_Tiling == VK_IMAGE_TILING_LINEAR)) {
3557 skip |=
3558 LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidImageToImageCopy,
3559 "%s Performance warning: image %s and image %s have differing tilings. Use buffer to "
3560 "image (vkCmdCopyImageToBuffer) "
3561 "and image to buffer (vkCmdCopyBufferToImage) copies instead of image to image "
3562 "copies when converting between linear and optimal images",
3563 VendorSpecificTag(kBPVendorAMD), src_image_hex.str().c_str(), dst_image_hex.str().c_str());
3564 }
3565 }
3566 }
3567
3568 return skip;
3569}
3570
3571bool BestPractices::PreCallValidateCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
3572 VkPipeline pipeline) const {
3573 bool skip = false;
3574
3575 if (VendorCheckEnabled(kBPVendorAMD)) {
3576 if (pipelines_used_in_frame.find(pipeline) != pipelines_used_in_frame.end()) {
3577 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Pipeline_SortAndBind,
3578 "%s Performance warning: Pipeline %s was bound twice in the frame. Keep pipeline state changes to a minimum,"
3579 "for example, by sorting draw calls by pipeline.",
3580 VendorSpecificTag(kBPVendorAMD), report_data->FormatHandle(pipeline).c_str());
3581 }
3582 }
3583
3584 return skip;
3585}
3586
3587void BestPractices::ManualPostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
3588 VkFence fence, VkResult result) {
3589 // AMD best practice
3590 num_queue_submissions += submitCount;
3591}
3592
3593bool BestPractices::PreCallValidateQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) const {
3594 bool skip = false;
3595
3596 if (VendorCheckEnabled(kBPVendorAMD)) {
3597 if (num_queue_submissions > kNumberOfSubmissionWarningLimitAMD) {
3598 skip |= LogPerformanceWarning(
3599 device, kVUID_BestPractices_Submission_ReduceNumberOfSubmissions,
3600 "%s Performance warning: command buffers submitted %" PRId32 " times this frame. Submitting command buffers has a CPU "
3601 "and GPU overhead. Submit fewer times to incur less overhead.",
3602 VendorSpecificTag(kBPVendorAMD), num_queue_submissions);
3603 }
3604 }
3605
3606 return skip;
3607}
3608
3609void BestPractices::PostCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3610 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3611 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
3612 uint32_t bufferMemoryBarrierCount,
3613 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
3614 uint32_t imageMemoryBarrierCount,
3615 const VkImageMemoryBarrier* pImageMemoryBarriers) {
3616 num_barriers_objects += memoryBarrierCount;
3617 num_barriers_objects += imageMemoryBarrierCount;
3618 num_barriers_objects += bufferMemoryBarrierCount;
3619}
3620
3621void BestPractices::ManualPostCallRecordCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
3622 const VkAllocationCallbacks* pAllocator, VkFence* pFence, VkResult result) {
3623 // AMD best practice
3624 if (result == VK_SUCCESS) {
3625 num_fence_objects++;
3626 }
3627}
3628
3629void BestPractices::ManualPostCallRecordCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
3630 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore,
3631 VkResult result) {
3632 // AMD best practice
3633 if (result == VK_SUCCESS) {
3634 num_semaphore_objects++;
3635 }
3636}
3637
3638bool BestPractices::PreCallValidateCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
3639 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore) const {
3640 bool skip = false;
3641 if (VendorCheckEnabled(kBPVendorAMD)) {
3642 if (num_semaphore_objects > kMaxRecommendedSemaphoreObjectsSizeAMD) {
3643 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfSemaphores,
3644 "%s Performance warning: High number of vkSemaphore objects created."
3645 "Minimize the amount of queue synchronization that is used. "
3646 "Semaphores and fences have overhead. Each fence has a CPU and GPU cost with it.",
3647 VendorSpecificTag(kBPVendorAMD));
3648 }
3649 }
3650
3651 return skip;
3652}
3653
3654bool BestPractices::PreCallValidateCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
3655 const VkAllocationCallbacks* pAllocator, VkFence* pFence) const {
3656 bool skip = false;
3657 if (VendorCheckEnabled(kBPVendorAMD)) {
3658 if (num_fence_objects > kMaxRecommendedFenceObjectsSizeAMD) {
3659 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfFences,
3660 "%s Performance warning: High number of VkFence objects created."
3661 "Minimize the amount of CPU-GPU synchronization that is used. "
3662 "Semaphores and fences have overhead.Each fence has a CPU and GPU cost with it.",
3663 VendorSpecificTag(kBPVendorAMD));
3664 }
3665 }
3666
3667 return skip;
3668}
3669
Sam Walls8e77e4f2020-03-16 20:47:40 +00003670void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
3671
3672bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
3673 // look for a cache hit
3674 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
3675 if (hit != _entries.end()) {
3676 // mark the cache hit as being most recently used
3677 hit->age = iteration++;
3678 return true;
3679 }
3680
3681 // if there's no cache hit, we need to model the entry being inserted into the cache
3682 CacheEntry new_entry = {value, iteration};
3683 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
3684 // if there is still space left in the cache, use the next available slot
3685 *(_entries.begin() + iteration) = new_entry;
3686 } else {
3687 // otherwise replace the least recently used cache entry
3688 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
3689 *lru = new_entry;
3690 }
3691 iteration++;
3692 return false;
3693}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003694
3695bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
3696 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003697 auto swapchain_data = Get<SWAPCHAIN_NODE>(swapchain);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003698 bool skip = false;
3699 if (swapchain_data && swapchain_data->images.size() == 0) {
3700 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
3701 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
3702 "vkGetSwapchainImagesKHR after swapchain creation.");
3703 }
3704 return skip;
3705}
3706
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003707void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
3708 if (no_pointer) {
3709 if (UNCALLED == call_state) {
3710 call_state = QUERY_COUNT;
3711 }
3712 } else { // Save queue family properties
3713 call_state = QUERY_DETAILS;
3714 }
3715}
3716
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003717void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
3718 uint32_t* pQueueFamilyPropertyCount,
3719 VkQueueFamilyProperties* pQueueFamilyProperties) {
3720 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
3721 pQueueFamilyProperties);
Jeremy Gebben78684b12022-02-23 17:31:56 -07003722 auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003723 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003724 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
3725 nullptr == pQueueFamilyProperties);
3726 }
3727}
3728
3729void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
3730 uint32_t* pQueueFamilyPropertyCount,
3731 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3732 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
3733 pQueueFamilyProperties);
Jeremy Gebben78684b12022-02-23 17:31:56 -07003734 auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003735 if (bp_pd_state) {
3736 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
3737 nullptr == pQueueFamilyProperties);
3738 }
3739}
3740
3741void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
3742 uint32_t* pQueueFamilyPropertyCount,
3743 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3744 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
3745 pQueueFamilyProperties);
Jeremy Gebben78684b12022-02-23 17:31:56 -07003746 auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003747 if (bp_pd_state) {
3748 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
3749 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003750 }
3751}
3752
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003753void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
3754 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Jeremy Gebben78684b12022-02-23 17:31:56 -07003755 auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003756 if (bp_pd_state) {
3757 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3758 }
3759}
3760
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003761void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
3762 VkPhysicalDeviceFeatures2* pFeatures) {
3763 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Jeremy Gebben78684b12022-02-23 17:31:56 -07003764 auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003765 if (bp_pd_state) {
3766 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3767 }
3768}
3769
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003770void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
3771 VkPhysicalDeviceFeatures2* pFeatures) {
3772 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Jeremy Gebben78684b12022-02-23 17:31:56 -07003773 auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003774 if (bp_pd_state) {
3775 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3776 }
3777}
3778
3779void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
3780 VkSurfaceKHR surface,
3781 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
3782 VkResult result) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003783 auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003784 if (bp_pd_state) {
3785 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3786 }
3787}
3788
3789void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
3790 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3791 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003792 auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003793 if (bp_pd_state) {
3794 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3795 }
3796}
3797
3798void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
3799 VkSurfaceKHR surface,
3800 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
3801 VkResult result) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003802 auto bp_pd_state = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003803 if (bp_pd_state) {
3804 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3805 }
3806}
3807
3808void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
3809 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
3810 VkPresentModeKHR* pPresentModes, VkResult result) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003811 auto bp_pd_data = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003812 if (bp_pd_data) {
3813 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
3814
3815 if (*pPresentModeCount) {
3816 if (call_state < QUERY_COUNT) {
3817 call_state = QUERY_COUNT;
3818 }
3819 }
3820 if (pPresentModes) {
3821 if (call_state < QUERY_DETAILS) {
3822 call_state = QUERY_DETAILS;
3823 }
3824 }
3825 }
3826}
3827
3828void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
3829 uint32_t* pSurfaceFormatCount,
3830 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003831 auto bp_pd_data = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003832 if (bp_pd_data) {
3833 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
3834
3835 if (*pSurfaceFormatCount) {
3836 if (call_state < QUERY_COUNT) {
3837 call_state = QUERY_COUNT;
3838 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003839 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003840 }
3841 if (pSurfaceFormats) {
3842 if (call_state < QUERY_DETAILS) {
3843 call_state = QUERY_DETAILS;
3844 }
3845 }
3846 }
3847}
3848
3849void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
3850 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3851 uint32_t* pSurfaceFormatCount,
3852 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003853 auto bp_pd_data = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003854 if (bp_pd_data) {
3855 if (*pSurfaceFormatCount) {
3856 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
3857 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
3858 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003859 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003860 }
3861 if (pSurfaceFormats) {
3862 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
3863 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
3864 }
3865 }
3866 }
3867}
3868
3869void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
3870 uint32_t* pPropertyCount,
3871 VkDisplayPlanePropertiesKHR* pProperties,
3872 VkResult result) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003873 auto bp_pd_data = Get<PHYSICAL_DEVICE_STATE_BP>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003874 if (bp_pd_data) {
3875 if (*pPropertyCount) {
3876 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
3877 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
3878 }
3879 }
3880 if (pProperties) {
3881 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
3882 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
3883 }
3884 }
3885 }
3886}
3887
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003888void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
3889 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
3890 VkResult result) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003891 auto swapchain_state = Get<SWAPCHAIN_STATE_BP>(swapchain);
Nathaniel Cesario39152e62021-07-02 13:04:16 -06003892 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
3893 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
3894 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003895 }
3896 }
3897}
3898
Nadav Gevaf0808442021-05-21 13:51:25 -04003899void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo* pCreateInfo,
3900 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice, VkResult result) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003901 if (VK_SUCCESS == result) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003902 if ((pCreateInfo->pEnabledFeatures != nullptr) && (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
3903 robust_buffer_access = true;
3904 }
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003905 }
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003906}
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003907
3908void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
3909 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
3910
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06003911 auto queue_state = Get<QUEUE_STATE>(queue);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003912 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003913 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003914 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
Jeremy Gebben78684b12022-02-23 17:31:56 -07003915 auto cb = Get<CMD_BUFFER_STATE_BP>(submit_info.pCommandBuffers[cb_index]);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003916 for (auto &func : cb->queue_submit_functions) {
Jeremy Gebbene5361dd2021-11-18 14:23:56 -07003917 func(*this, *queue_state, *cb);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003918 }
3919 }
3920 }
3921}