blob: 93d2cea00e53a544e4d3ac41938a7219711b6f31 [file] [log] [blame]
Gareth Webbdc6549a2021-06-16 03:52:24 +01001/* Copyright (c) 2015-2021 The Khronos Group Inc.
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002 * Copyright (c) 2015-2021 Valve Corporation
3 * Copyright (c) 2015-2021 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,
63 std::shared_ptr<COMMAND_POOL_STATE>& pool) {
64 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,
68 std::shared_ptr<COMMAND_POOL_STATE>& pool)
69 : 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)) ||
133 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700134 skip |=
135 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
136 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600137 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700138 if (dep_info.target.length() == 0) {
139 skip |= LogWarning(instance, vuid,
140 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
141 "without replacement.",
142 api_name, extension_name);
143 } else {
144 skip |= LogWarning(instance, vuid,
145 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
146 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
147 }
148 }
149 }
150 return skip;
151}
152
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200153bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const SpecialUseVUIDs& special_use_vuids) const
154{
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700155 bool skip = false;
156 auto dep_info_it = special_use_extensions.find(extension_name);
157
158 if (dep_info_it != special_use_extensions.end()) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200159 const char* const format = "%s(): Attempting to enable extension %s, but this extension is intended to support %s "
160 "and it is strongly recommended that it be otherwise avoided.";
161 auto& special_uses = dep_info_it->second;
162
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700163 if (special_uses.find("cadsupport") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200164 skip |= LogWarning(instance, special_use_vuids.cadsupport, format, api_name, extension_name,
165 "specialized functionality used by CAD/CAM applications");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700166 }
167 if (special_uses.find("d3demulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200168 skip |= LogWarning(instance, special_use_vuids.d3demulation, format, api_name, extension_name,
169 "D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700170 }
171 if (special_uses.find("devtools") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200172 skip |= LogWarning(instance, special_use_vuids.devtools, format, api_name, extension_name,
173 "developer tools such as capture-replay libraries");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700174 }
175 if (special_uses.find("debugging") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200176 skip |= LogWarning(instance, special_use_vuids.debugging, format, api_name, extension_name,
177 "use by applications when debugging");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700178 }
179 if (special_uses.find("glemulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200180 skip |= LogWarning(instance, special_use_vuids.glemulation, format, api_name, extension_name,
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700181 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200182 "specific to those APIs");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700183 }
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700184 }
185 return skip;
186}
187
Nadav Gevaf0808442021-05-21 13:51:25 -0400188void BestPractices::InitDeviceValidationObject(bool add_obj, ValidationObject* inst_obj, ValidationObject* dev_obj) {
189 if (add_obj) {
190 ValidationStateTracker::InitDeviceValidationObject(add_obj, inst_obj, dev_obj);
191 }
192}
193
194
Camden5b184be2019-08-13 07:50:19 -0600195bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500196 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600197 bool skip = false;
198
199 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
200 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800201 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700202 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
203 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600204 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600205 uint32_t specified_version =
206 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
207 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700208 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200209 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseInstanceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600210 }
211
212 return skip;
213}
214
215void BestPractices::PreCallRecordCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
216 VkInstance* pInstance) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700217 ValidationStateTracker::PreCallRecordCreateInstance(pCreateInfo, pAllocator, pInstance);
Sam Walls53bf7652020-04-21 17:35:15 +0100218
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700219 if (pCreateInfo != nullptr && pCreateInfo->pApplicationInfo != nullptr) {
Sam Walls53bf7652020-04-21 17:35:15 +0100220 instance_api_version = pCreateInfo->pApplicationInfo->apiVersion;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700221 } else {
Sam Walls53bf7652020-04-21 17:35:15 +0100222 instance_api_version = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700223 }
Camden5b184be2019-08-13 07:50:19 -0600224}
225
226bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500227 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600228 bool skip = false;
229
230 // get API version of physical device passed when creating device.
231 VkPhysicalDeviceProperties physical_device_properties{};
232 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500233 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600234
235 // check api versions and warn if instance api Version is higher than version on device.
236 if (instance_api_version > device_api_version) {
Mark Lobodzinski60880782020-08-11 08:02:07 -0600237 std::string inst_api_name = StringAPIVersion(instance_api_version);
238 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600239
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700240 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
241 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
242 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600243 }
244
245 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
246 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800247 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700248 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
249 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600250 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700251 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], instance_api_version,
252 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200253 skip |= ValidateSpecialUseExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseDeviceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600254 }
255
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600256 const auto bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
257 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700258 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
259 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600260 }
261
Nadav Gevaf0808442021-05-21 13:51:25 -0400262 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorAMD)) && (pCreateInfo->pEnabledFeatures != nullptr) &&
Szilard Papp7d2c7952020-06-22 14:38:13 +0100263 (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
264 skip |= LogPerformanceWarning(
265 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
Nadav Gevaf0808442021-05-21 13:51:25 -0400266 "%s %s vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
Szilard Papp7d2c7952020-06-22 14:38:13 +0100267 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
268 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
269 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
Nadav Gevaf0808442021-05-21 13:51:25 -0400270 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorAMD));
Szilard Papp7d2c7952020-06-22 14:38:13 +0100271 }
272
Camden5b184be2019-08-13 07:50:19 -0600273 return skip;
274}
275
276bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500277 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600278 bool skip = false;
279
280 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700281 std::stringstream buffer_hex;
282 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600283
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700284 skip |= LogWarning(
285 device, kVUID_BestPractices_SharingModeExclusive,
286 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
287 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700288 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600289 }
290
291 return skip;
292}
293
294bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500295 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600296 bool skip = false;
297
298 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700299 std::stringstream image_hex;
300 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600301
302 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700303 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
304 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
305 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700306 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600307 }
308
Attilio Provenzano02859b22020-02-27 14:17:28 +0000309 if (VendorCheckEnabled(kBPVendorArm)) {
310 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
311 skip |= LogPerformanceWarning(
312 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
313 "%s vkCreateImage(): Trying to create an image with %u samples. "
314 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
315 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
316 }
317
318 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
319 skip |= LogPerformanceWarning(
320 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
321 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
322 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
323 "and do not need to be backed by physical storage. "
324 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
325 VendorSpecificTag(kBPVendorArm));
326 }
327 }
328
Nadav Gevaf0808442021-05-21 13:51:25 -0400329 if (VendorCheckEnabled(kBPVendorAMD)) {
330 std::stringstream image_hex;
331 image_hex << "0x" << std::hex << HandleToUint64(pImage);
332
333 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
334 (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT)) {
335 skip |= LogPerformanceWarning(device,
336 kVUID_BestPractices_vkImage_AvoidConcurrentRenderTargets,
337 "%s Performance warning: image (%s) is created as a render target with VK_SHARING_MODE_CONCURRENT. "
338 "Using a SHARING_MODE_CONCURRENT "
339 "is not recommended with color and depth targets",
340 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
341 }
342
343 if ((pCreateInfo->usage &
344 (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
345 (pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
346 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseMutableRenderTargets,
347 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT. "
348 "Using a MUTABLE_FORMAT is not recommended with color, depth, and storage targets",
349 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
350 }
351
352 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
353 (pCreateInfo->usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
354 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseStorageRenderTargets,
355 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_USAGE_STORAGE_BIT. Using a "
356 "VK_IMAGE_USAGE_STORAGE_BIT is not recommended with color and depth targets",
357 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
358 }
359 }
360
Camden5b184be2019-08-13 07:50:19 -0600361 return skip;
362}
363
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100364void BestPractices::PreCallRecordDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
365 ValidationStateTracker::PreCallRecordDestroyImage(device, image, pAllocator);
366 ReleaseImageUsageState(image);
367}
368
Hans-Kristian Arntzen92664eb2021-03-29 12:19:48 +0200369void BestPractices::PreCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain, const VkAllocationCallbacks* pAllocator) {
Tony-LunarG299187b2021-05-28 09:29:12 -0600370 if (VK_NULL_HANDLE != swapchain) {
371 SWAPCHAIN_NODE* chain = GetSwapchainState(swapchain);
372 for (auto& image : chain->images) {
373 if (image.image_state) {
374 ReleaseImageUsageState(image.image_state->image());
375 }
376 }
Hans-Kristian Arntzen92664eb2021-03-29 12:19:48 +0200377 }
378 ValidationStateTracker::PreCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
379}
380
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100381IMAGE_STATE_BP* BestPractices::GetImageUsageState(VkImage vk_image) {
382 auto itr = imageUsageMap.find(vk_image);
383 if (itr != imageUsageMap.end()) {
384 return &itr->second;
385 } else {
386 auto& state = imageUsageMap[vk_image];
Nadav Gevaf0808442021-05-21 13:51:25 -0400387 IMAGE_STATE* image = Get<IMAGE_STATE>(vk_image);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100388 state.image = image;
389 state.usages.resize(image->createInfo.arrayLayers);
390 for (auto& mips : state.usages) {
391 mips.resize(image->createInfo.mipLevels, IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED);
392 }
393 return &state;
394 }
395}
396
397void BestPractices::ReleaseImageUsageState(VkImage image) {
398 auto itr = imageUsageMap.find(image);
399 if (itr != imageUsageMap.end()) {
400 imageUsageMap.erase(itr);
401 }
402}
403
Camden5b184be2019-08-13 07:50:19 -0600404bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500405 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600406 bool skip = false;
407
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600408 const auto* bp_pd_state = GetPhysicalDeviceStateBP();
409 if (bp_pd_state) {
410 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
411 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
412 "vkCreateSwapchainKHR() called before getting surface capabilities from "
413 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
414 }
Camden83a9c372019-08-14 11:41:38 -0600415
Shannon McPherson73e58c82021-03-05 17:14:26 -0700416 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
417 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600418 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
419 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
420 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
421 }
Camden83a9c372019-08-14 11:41:38 -0600422
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600423 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
424 skip |= LogWarning(
425 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
426 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
427 }
Camden83a9c372019-08-14 11:41:38 -0600428 }
429
Camden5b184be2019-08-13 07:50:19 -0600430 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700431 skip |=
432 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600433 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700434 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
435 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600436 }
437
Szilard Papp48a6da32020-06-10 14:41:59 +0100438 if (pCreateInfo->minImageCount == 2) {
439 skip |= LogPerformanceWarning(
440 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
441 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
442 ", which means double buffering is going "
443 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
444 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
445 "3 to use triple buffering to maximize performance in such cases.",
446 pCreateInfo->minImageCount);
447 }
448
Szilard Pappd5f0f812020-06-22 09:01:29 +0100449 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
450 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
451 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
452 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
453 "Presentation modes which are not FIFO will present the latest available frame and discard other "
454 "frame(s) if any.",
455 VendorSpecificTag(kBPVendorArm));
456 }
457
Camden5b184be2019-08-13 07:50:19 -0600458 return skip;
459}
460
461bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
462 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500463 const VkAllocationCallbacks* pAllocator,
464 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600465 bool skip = false;
466
467 for (uint32_t i = 0; i < swapchainCount; i++) {
468 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700469 skip |= LogWarning(
470 device, kVUID_BestPractices_SharingModeExclusive,
471 "Warning: A shared swapchain (index %" PRIu32
472 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
473 "queues (queueFamilyIndexCount of %" PRIu32 ").",
474 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600475 }
476 }
477
478 return skip;
479}
480
481bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500482 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600483 bool skip = false;
484
485 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
486 VkFormat format = pCreateInfo->pAttachments[i].format;
487 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
488 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
489 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700490 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
491 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
492 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
493 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
494 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600495 }
496 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700497 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
498 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
499 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
500 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
501 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600502 }
503 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000504
505 const auto& attachment = pCreateInfo->pAttachments[i];
506 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
507 bool access_requires_memory =
508 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
509
510 if (FormatHasStencil(format)) {
511 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
512 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
513 }
514
515 if (access_requires_memory) {
516 skip |= LogPerformanceWarning(
517 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
518 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
519 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
520 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
521 i, static_cast<uint32_t>(attachment.samples));
522 }
523 }
Camden5b184be2019-08-13 07:50:19 -0600524 }
525
526 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
527 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
528 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
529 }
530
531 return skip;
532}
533
Tony-LunarG767180f2020-04-23 14:03:59 -0600534bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
535 const VkImageView* image_views) const {
536 bool skip = false;
537
538 // Check for non-transient attachments that should be transient and vice versa
539 for (uint32_t i = 0; i < attachmentCount; ++i) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200540 const auto& attachment = rpci->pAttachments[i];
Tony-LunarG767180f2020-04-23 14:03:59 -0600541 bool attachment_should_be_transient =
542 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
543
544 if (FormatHasStencil(attachment.format)) {
545 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
546 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
547 }
548
549 auto view_state = GetImageViewState(image_views[i]);
550 if (view_state) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200551 const auto& ivci = view_state->create_info;
Nadav Gevaf0808442021-05-21 13:51:25 -0400552 const auto& ici = Get<IMAGE_STATE>(ivci.image)->createInfo;
Tony-LunarG767180f2020-04-23 14:03:59 -0600553
554 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
555
556 // The check for an image that should not be transient applies to all GPUs
557 if (!attachment_should_be_transient && image_is_transient) {
558 skip |= LogPerformanceWarning(
559 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
560 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
561 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
562 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
563 i);
564 }
565
566 bool supports_lazy = false;
567 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
568 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
569 supports_lazy = true;
570 }
571 }
572
573 // The check for an image that should be transient only applies to GPUs supporting
574 // lazily allocated memory
575 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
576 skip |= LogPerformanceWarning(
577 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
578 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
579 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
580 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
581 i);
582 }
583 }
584 }
585 return skip;
586}
587
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000588bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
589 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
590 bool skip = false;
591
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000592 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800593 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600594 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000595 }
596
597 return skip;
598}
599
Sam Wallse746d522020-03-16 21:20:23 +0000600bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
601 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
602 bool skip = false;
603 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
604
605 if (!skip) {
606 const auto& pool_handle = pAllocateInfo->descriptorPool;
607 auto iter = descriptor_pool_freed_count.find(pool_handle);
608 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
609 // this warning is specific to Arm
610 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
611 skip |= LogPerformanceWarning(
612 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
613 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
614 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
615 VendorSpecificTag(kBPVendorArm));
616 }
617 }
618
619 return skip;
620}
621
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600622void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
623 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000624 if (result == VK_SUCCESS) {
625 // find the free count for the pool we allocated into
626 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
627 if (iter != descriptor_pool_freed_count.end()) {
628 // we record successful allocations by subtracting the allocation count from the last recorded free count
629 const auto alloc_count = pAllocateInfo->descriptorSetCount;
630 // clamp the unsigned subtraction to the range [0, last_free_count]
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700631 if (iter->second > alloc_count) {
Sam Wallse746d522020-03-16 21:20:23 +0000632 iter->second -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700633 } else {
Sam Wallse746d522020-03-16 21:20:23 +0000634 iter->second = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700635 }
Sam Wallse746d522020-03-16 21:20:23 +0000636 }
637 }
638}
639
640void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
641 const VkDescriptorSet* pDescriptorSets, VkResult result) {
642 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
643 if (result == VK_SUCCESS) {
644 // we want to track frees because we're interested in suggesting re-use
645 auto iter = descriptor_pool_freed_count.find(descriptorPool);
646 if (iter == descriptor_pool_freed_count.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700647 descriptor_pool_freed_count.emplace(descriptorPool, descriptorSetCount);
Sam Wallse746d522020-03-16 21:20:23 +0000648 } else {
649 iter->second += descriptorSetCount;
650 }
651 }
652}
653
Camden5b184be2019-08-13 07:50:19 -0600654bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500655 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600656 bool skip = false;
657
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500658 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700659 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
660 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600661 }
662
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000663 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
664 skip |= LogPerformanceWarning(
665 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600666 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
667 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000668 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
669 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
670 }
671
Camden83a9c372019-08-14 11:41:38 -0600672 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
673
674 return skip;
675}
676
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600677void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
678 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
679 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700680 if (result != VK_SUCCESS) {
681 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
682 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800683 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700684 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600685 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700686 return;
687 }
688 num_mem_objects++;
689}
Camden Stocker9738af92019-10-16 13:54:03 -0700690
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600691void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
692 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700693 auto error = std::find(error_codes.begin(), error_codes.end(), result);
694 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000695 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
696 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
697
698 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
699 if (common_failure != common_failure_codes.end()) {
700 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
701 } else {
702 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
703 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700704 return;
705 }
706 auto success = std::find(success_codes.begin(), success_codes.end(), result);
707 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600708 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
709 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500710 }
711}
712
Jeff Bolz5c801d12019-10-09 10:38:45 -0500713bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
714 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700715 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600716 bool skip = false;
717
Camden Stocker9738af92019-10-16 13:54:03 -0700718 const DEVICE_MEMORY_STATE* mem_info = ValidationStateTracker::GetDevMemState(memory);
Camden83a9c372019-08-14 11:41:38 -0600719
Jeremy Gebben5570abe2021-05-16 18:35:13 -0600720 for (const auto& node: mem_info->ObjectBindings()) {
721 const auto& obj = node->Handle();
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600722 LogObjectList objlist(device);
723 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600724 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600725 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 -0600726 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600727 }
728
Camden5b184be2019-08-13 07:50:19 -0600729 return skip;
730}
731
732void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700733 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600734 if (memory != VK_NULL_HANDLE) {
735 num_mem_objects--;
736 }
737}
738
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000739bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600740 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500741 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600742
sfricke-samsunge2441192019-11-06 14:07:57 -0800743 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700744 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
745 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
746 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600747 }
748
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000749 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
750
751 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
752 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
753 skip |= LogPerformanceWarning(
754 device, kVUID_BestPractices_SmallDedicatedAllocation,
755 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600756 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
757 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000758 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
759 }
760
Camden Stockerb603cc82019-09-03 10:09:02 -0600761 return skip;
762}
763
764bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500765 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600766 bool skip = false;
767 const char* api_name = "BindBufferMemory()";
768
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000769 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600770
771 return skip;
772}
773
774bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500775 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600776 char api_name[64];
777 bool skip = false;
778
779 for (uint32_t i = 0; i < bindInfoCount; i++) {
780 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000781 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600782 }
783
784 return skip;
785}
Camden Stockerb603cc82019-09-03 10:09:02 -0600786
787bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500788 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600789 char api_name[64];
790 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600791
Camden Stocker8b798ab2019-09-03 10:33:28 -0600792 for (uint32_t i = 0; i < bindInfoCount; i++) {
793 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000794 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600795 }
796
797 return skip;
798}
799
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000800bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600801 bool skip = false;
Nadav Gevaf0808442021-05-21 13:51:25 -0400802 const IMAGE_STATE* image_state = Get<IMAGE_STATE>(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600803
sfricke-samsung71bc6572020-04-29 15:49:43 -0700804 if (image_state->disjoint == false) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600805 if (!image_state->memory_requirements_checked[0] && !image_state->external_memory_handle) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700806 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
807 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
808 api_name, report_data->FormatHandle(image).c_str());
809 }
810 } else {
811 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
812 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600813 }
814
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000815 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
816
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600817 if (mem_state->alloc_info.allocationSize == image_state->requirements[0].size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000818 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
819 skip |= LogPerformanceWarning(
820 device, kVUID_BestPractices_SmallDedicatedAllocation,
821 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600822 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
823 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000824 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
825 }
826
827 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
828 // make sure this type is actually used.
829 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
830 // (i.e.most tile - based renderers)
831 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
832 bool supports_lazy = false;
833 uint32_t suggested_type = 0;
834
835 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600836 if ((1u << i) & image_state->requirements[0].memoryTypeBits) {
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000837 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
838 supports_lazy = true;
839 suggested_type = i;
840 break;
841 }
842 }
843 }
844
845 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
846
847 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
848 skip |= LogPerformanceWarning(
849 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600850 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000851 "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 -0600852 "%" PRIu64 " bytes of physical memory.",
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600853 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements[0].size);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000854 }
855 }
856
Camden Stocker8b798ab2019-09-03 10:33:28 -0600857 return skip;
858}
859
860bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500861 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600862 bool skip = false;
863 const char* api_name = "vkBindImageMemory()";
864
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000865 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600866
867 return skip;
868}
869
870bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500871 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600872 char api_name[64];
873 bool skip = false;
874
875 for (uint32_t i = 0; i < bindInfoCount; i++) {
876 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700877 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600878 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
879 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600880 }
881
882 return skip;
883}
884
885bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500886 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600887 char api_name[64];
888 bool skip = false;
889
890 for (uint32_t i = 0; i < bindInfoCount; i++) {
891 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000892 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600893 }
894
895 return skip;
896}
Camden83a9c372019-08-14 11:41:38 -0600897
Attilio Provenzano02859b22020-02-27 14:17:28 +0000898static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
899 switch (format) {
900 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
901 case VK_FORMAT_R16_SFLOAT:
902 case VK_FORMAT_R16G16_SFLOAT:
903 case VK_FORMAT_R16G16B16_SFLOAT:
904 case VK_FORMAT_R16G16B16A16_SFLOAT:
905 case VK_FORMAT_R32_SFLOAT:
906 case VK_FORMAT_R32G32_SFLOAT:
907 case VK_FORMAT_R32G32B32_SFLOAT:
908 case VK_FORMAT_R32G32B32A32_SFLOAT:
909 return false;
910
911 default:
912 return true;
913 }
914}
915
916bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
917 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
918 bool skip = false;
919
920 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700921 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000922
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700923 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
924 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
925 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000926 return skip;
927 }
928
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700929 auto rp_state = GetRenderPassState(create_info->renderPass);
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200930 const auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000931
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +0200932 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
933 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info->pColorBlendState->attachmentCount);
934
935 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200936 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000937 uint32_t att = subpass.pColorAttachments[j].attachment;
938
939 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
940 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
941 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
942 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
943 "color attachment #%u makes use "
944 "of a format which cannot be blended at full throughput when using MSAA.",
945 VendorSpecificTag(kBPVendorArm), i, j);
946 }
947 }
948 }
949 }
950
951 return skip;
952}
953
Nadav Gevaf0808442021-05-21 13:51:25 -0400954void BestPractices::ManualPostCallRecordCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
955 const VkComputePipelineCreateInfo* pCreateInfos,
956 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
957 VkResult result, void* pipe_state) {
958 // AMD best practice
959 pipeline_cache = pipelineCache;
960}
961
Camden5b184be2019-08-13 07:50:19 -0600962bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
963 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600964 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500965 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600966 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
967 pAllocator, pPipelines, cgpl_state_data);
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600968 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600969
970 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700971 skip |= LogPerformanceWarning(
972 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
973 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
974 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600975 }
976
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000977 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200978 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000979
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600980 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200981 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600982 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700983 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
984 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600985 count++;
986 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000987 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600988 if (count > kMaxInstancedVertexBuffers) {
989 skip |= LogPerformanceWarning(
990 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
991 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
992 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
993 count, kMaxInstancedVertexBuffers);
994 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000995 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000996
Szilard Pappaaf2da32020-06-22 10:37:35 +0100997 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
998 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +0200999 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
1000 VendorCheckEnabled(kBPVendorArm)) {
1001 skip |= LogPerformanceWarning(
1002 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
1003 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
1004 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
1005 "efficiency during rasterization. Consider disabling depthBias or increasing either "
1006 "depthBiasConstantFactor or depthBiasSlopeFactor.",
1007 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +01001008 }
1009
Attilio Provenzano02859b22020-02-27 14:17:28 +00001010 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001011 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001012 if (VendorCheckEnabled(kBPVendorAMD)) {
1013 if (pipelineCache && pipeline_cache && pipelineCache != pipeline_cache) {
1014 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultiplePipelineCaches,
1015 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
1016 "improve cache hit rate", VendorSpecificTag(kBPVendorAMD));
1017 }
1018
1019 if (num_pso > kMaxRecommendedNumberOfPSOAMD) {
1020 skip |=
1021 LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_TooManyPipelines,
1022 "%s Performance warning: Too many pipelines created, consider consolidation",
1023 VendorSpecificTag(kBPVendorAMD));
1024 }
1025
1026 if (pCreateInfos->pInputAssemblyState->primitiveRestartEnable) {
1027 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_AvoidPrimitiveRestart,
1028 "%s Performance warning: Use of primitive restart is not recommended",
1029 VendorSpecificTag(kBPVendorAMD));
1030 }
1031
1032 // TODO: this might be too aggressive of a check
1033 if (pCreateInfos->pDynamicState && pCreateInfos->pDynamicState->dynamicStateCount > kDynamicStatesWarningLimitAMD) {
1034 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MinimizeNumDynamicStates,
1035 "%s Performance warning: Dynamic States usage incurs a performance cost. Ensure that they are truly needed",
1036 VendorSpecificTag(kBPVendorAMD));
1037 }
1038 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001039
Camden5b184be2019-08-13 07:50:19 -06001040 return skip;
1041}
1042
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001043void BestPractices::PreCallRecordDestroyPipeline(VkDevice device, VkPipeline pipeline, const VkAllocationCallbacks *pAllocator)
1044{
1045 auto itr = graphicsPipelineCIs.find(pipeline);
1046 if (itr != graphicsPipelineCIs.end()) {
1047 graphicsPipelineCIs.erase(itr);
1048 }
1049 ValidationStateTracker::PreCallRecordDestroyPipeline(device, pipeline, pAllocator);
1050}
1051
Sam Walls0961ec02020-03-31 16:39:15 +01001052void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
1053 const VkGraphicsPipelineCreateInfo* pCreateInfos,
1054 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
1055 VkResult result, void* cgpl_state_data) {
1056 for (size_t i = 0; i < count; i++) {
1057 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
1058 const VkPipeline pipeline_handle = pPipelines[i];
1059
1060 // record depth stencil state and color blend states for depth pre-pass tracking purposes
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001061 GraphicsPipelineCIs& cis = graphicsPipelineCIs[pipeline_handle];
Sam Walls0961ec02020-03-31 16:39:15 +01001062
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +02001063 auto& create_info = cgpl_state->pCreateInfos[i];
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +02001064
Jeremy Gebben396d06a2021-08-12 11:03:04 -06001065 if (create_info.pColorBlendState) {
1066 cis.colorBlendStateCI.emplace(create_info.pColorBlendState);
1067 }
1068
1069 if (create_info.pDepthStencilState) {
1070 cis.depthStencilStateCI.emplace(create_info.pDepthStencilState);
1071 }
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +02001072
1073 // Record which frame buffer attachments we should consider to be accessed when a draw call is performed.
1074 RENDER_PASS_STATE* rp = GetRenderPassState(create_info.renderPass);
1075 auto& subpass = rp->createInfo.pSubpasses[create_info.subpass];
1076 cis.accessFramebufferAttachments.clear();
1077
1078 if (cis.colorBlendStateCI) {
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +02001079 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
1080 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, cis.colorBlendStateCI->attachmentCount);
1081 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +02001082 if (cis.colorBlendStateCI->pAttachments[j].colorWriteMask != 0) {
1083 uint32_t attachment = subpass.pColorAttachments[j].attachment;
1084 if (attachment != VK_ATTACHMENT_UNUSED) {
1085 cis.accessFramebufferAttachments.push_back({ attachment, VK_IMAGE_ASPECT_COLOR_BIT });
1086 }
1087 }
1088 }
1089 }
1090
1091 if (cis.depthStencilStateCI && (cis.depthStencilStateCI->depthTestEnable ||
1092 cis.depthStencilStateCI->depthBoundsTestEnable ||
1093 cis.depthStencilStateCI->stencilTestEnable)) {
1094 uint32_t attachment = subpass.pDepthStencilAttachment ?
1095 subpass.pDepthStencilAttachment->attachment :
1096 VK_ATTACHMENT_UNUSED;
1097 if (attachment != VK_ATTACHMENT_UNUSED) {
1098 VkImageAspectFlags aspects = 0;
1099 if (cis.depthStencilStateCI->depthTestEnable || cis.depthStencilStateCI->depthBoundsTestEnable) {
1100 aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1101 }
1102 if (cis.depthStencilStateCI->stencilTestEnable) {
1103 aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1104 }
1105 cis.accessFramebufferAttachments.push_back({ attachment, aspects });
1106 }
1107 }
Sam Walls0961ec02020-03-31 16:39:15 +01001108 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001109
1110 // AMD best practice
1111 pipeline_cache = pipelineCache;
Sam Walls0961ec02020-03-31 16:39:15 +01001112}
1113
Camden5b184be2019-08-13 07:50:19 -06001114bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1115 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001116 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001117 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001118 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1119 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001120
1121 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001122 skip |= LogPerformanceWarning(
1123 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1124 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
1125 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001126 }
1127
Nadav Gevaf0808442021-05-21 13:51:25 -04001128 if (VendorCheckEnabled(kBPVendorAMD)) {
1129 if (pipelineCache && pipeline_cache && pipelineCache != pipeline_cache) {
1130 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1131 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
1132 "improve cache hit rate",
1133 VendorSpecificTag(kBPVendorAMD));
1134 }
1135 }
1136
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001137 if (VendorCheckEnabled(kBPVendorArm)) {
1138 for (size_t i = 0; i < createInfoCount; i++) {
1139 skip |= ValidateCreateComputePipelineArm(pCreateInfos[i]);
1140 }
1141 }
1142
1143 return skip;
1144}
1145
1146bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
1147 bool skip = false;
1148 auto* module = GetShaderModuleState(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001149 // Generate warnings about work group sizes based on active resources.
sfricke-samsung962cad92021-04-13 00:46:29 -07001150 auto entrypoint = module->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001151 if (entrypoint == module->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001152
1153 uint32_t x = 1, y = 1, z = 1;
sfricke-samsung962cad92021-04-13 00:46:29 -07001154 module->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001155
1156 uint32_t thread_count = x * y * z;
1157
1158 // Generate a priori warnings about work group sizes.
1159 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
1160 skip |= LogPerformanceWarning(
1161 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
1162 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1163 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1164 "groups with less than %u threads, especially when using barrier() or shared memory.",
1165 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1166 }
1167
1168 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1169 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1170 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1171 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1172 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1173 "%u, %u) is not aligned to %u "
1174 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1175 "leave threads idle on the shader "
1176 "core.",
1177 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1178 kThreadGroupDispatchCountAlignmentArm);
1179 }
1180
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001181 bool has_writeable_descriptors = false;
locke-lunarg63e4daf2020-08-17 17:53:25 -06001182 bool has_atomic_descriptors = false;
sfricke-samsung962cad92021-04-13 00:46:29 -07001183 auto accessible_ids = module->MarkAccessibleIds(entrypoint);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001184 auto descriptor_uses =
sfricke-samsung962cad92021-04-13 00:46:29 -07001185 module->CollectInterfaceByDescriptorSlot(accessible_ids, &has_writeable_descriptors, &has_atomic_descriptors);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001186
1187 unsigned dimensions = 0;
1188 if (x > 1) dimensions++;
1189 if (y > 1) dimensions++;
1190 if (z > 1) dimensions++;
1191 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1192 dimensions = std::max(dimensions, 1u);
1193
1194 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1195 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1196 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1197 bool accesses_2d = false;
1198 for (const auto& usage : descriptor_uses) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001199 auto dim = module->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001200 if (dim < 0) continue;
1201 auto spvdim = spv::Dim(dim);
1202 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1203 }
1204
1205 if (accesses_2d && dimensions < 2) {
1206 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1207 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1208 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1209 "exhibiting poor spatial locality with respect to one or more shader resources.",
1210 VendorSpecificTag(kBPVendorArm), x, y, z);
1211 }
1212
Camden5b184be2019-08-13 07:50:19 -06001213 return skip;
1214}
1215
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001216bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001217 bool skip = false;
1218
1219 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001220 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1221 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001222 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001223 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1224 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001225 }
1226
1227 return skip;
1228}
1229
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001230bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1231 bool skip = false;
1232
1233 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1234 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1235 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1236 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1237 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1238 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1239 }
1240
1241 return skip;
1242}
1243
1244bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1245 bool skip = false;
1246 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1247
1248 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1249 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1250
1251 return skip;
1252}
1253
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001254void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001255 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1256 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1257 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1258 LogPerformanceWarning(
1259 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1260 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1261 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1262 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1263 "convenient opportunity.",
1264 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1265 }
1266 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001267
1268 // AMD best practice
1269 // end-of-frame cleanup
1270 num_queue_submissions = 0;
1271 num_barriers_objects = 0;
1272 pipelines_used_in_frame.clear();
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001273}
1274
Jeff Bolz5c801d12019-10-09 10:38:45 -05001275bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1276 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001277 bool skip = false;
1278
1279 for (uint32_t submit = 0; submit < submitCount; submit++) {
1280 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1281 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1282 }
1283 }
1284
1285 return skip;
1286}
1287
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001288bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1289 VkFence fence) const {
1290 bool skip = false;
1291
1292 for (uint32_t submit = 0; submit < submitCount; submit++) {
1293 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1294 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1295 }
1296 }
1297
1298 return skip;
1299}
1300
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001301bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1302 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1303 bool skip = false;
1304
1305 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1306 skip |= LogPerformanceWarning(
1307 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1308 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1309 "pool instead.");
1310 }
1311
1312 return skip;
1313}
1314
1315bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1316 const VkCommandBufferBeginInfo* pBeginInfo) const {
1317 bool skip = false;
1318
1319 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1320 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1321 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1322 }
1323
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001324 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && VendorCheckEnabled(kBPVendorArm)) {
1325 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Attilio Provenzano02859b22020-02-27 14:17:28 +00001326 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1327 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1328 VendorSpecificTag(kBPVendorArm));
1329 }
1330
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001331 return skip;
1332}
1333
Jeff Bolz5c801d12019-10-09 10:38:45 -05001334bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001335 bool skip = false;
1336
1337 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1338
1339 return skip;
1340}
1341
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001342bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1343 const VkDependencyInfoKHR* pDependencyInfo) const {
1344 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1345}
1346
Jeff Bolz5c801d12019-10-09 10:38:45 -05001347bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1348 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001349 bool skip = false;
1350
1351 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1352
1353 return skip;
1354}
1355
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001356bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1357 VkPipelineStageFlags2KHR stageMask) const {
1358 bool skip = false;
1359
1360 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1361
1362 return skip;
1363}
1364
Camden5b184be2019-08-13 07:50:19 -06001365bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1366 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1367 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1368 uint32_t bufferMemoryBarrierCount,
1369 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1370 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001371 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001372 bool skip = false;
1373
1374 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1375 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1376
1377 return skip;
1378}
1379
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001380bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1381 const VkDependencyInfoKHR* pDependencyInfos) const {
1382 bool skip = false;
1383 for (uint32_t i = 0; i < eventCount; i++) {
1384 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1385 }
1386
1387 return skip;
1388}
1389
Camden5b184be2019-08-13 07:50:19 -06001390bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1391 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1392 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1393 uint32_t bufferMemoryBarrierCount,
1394 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1395 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001396 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001397 bool skip = false;
1398
1399 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1400 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1401
Nadav Gevaf0808442021-05-21 13:51:25 -04001402 if (VendorCheckEnabled(kBPVendorAMD)) {
1403 if (num_barriers_objects + imageMemoryBarrierCount + bufferMemoryBarrierCount > kMaxRecommendedBarriersSizeAMD) {
1404 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_highBarrierCount,
1405 "%s Performance warning: In this frame, %" PRIu32 " barriers were already submitted. Barriers have a high cost and can "
1406 "stall the GPU. "
1407 "Consider consolidating and re-organizing the frame to use fewer barriers.",
1408 VendorSpecificTag(kBPVendorAMD), num_barriers_objects);
1409 }
1410
1411 std::array<VkImageLayout, 3> read_layouts = {
1412 VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,
1413 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
1414 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1415 };
1416
1417 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
1418 // read to read barriers
1419 auto found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].oldLayout);
1420 bool old_is_read_layout = found != read_layouts.end();
1421 found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].newLayout);
1422 bool new_is_read_layout = found != read_layouts.end();
1423 if (old_is_read_layout && new_is_read_layout) {
1424 skip |= LogPerformanceWarning(device, kVUID_BestPractices_PipelineBarrier_readToReadBarrier,
1425 "%s Performance warning: Don't issue read-to-read barriers. Get the resource in the right state the first "
1426 "time you use it.",
1427 VendorSpecificTag(kBPVendorAMD));
1428 }
1429
1430 // general with no storage
1431 if (pImageMemoryBarriers[i].newLayout == VK_IMAGE_LAYOUT_GENERAL) {
1432 auto image_state = Get<IMAGE_STATE>(pImageMemoryBarriers[i].image);
1433 if (!(image_state->createInfo.usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
1434 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidGeneral,
1435 "%s Performance warning: VK_IMAGE_LAYOUT_GENERAL should only be used with "
1436 "VK_IMAGE_USAGE_STORAGE_BIT images.",
1437 VendorSpecificTag(kBPVendorAMD));
1438 }
1439 }
1440 }
1441 }
1442
Camden5b184be2019-08-13 07:50:19 -06001443 return skip;
1444}
1445
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001446bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1447 const VkDependencyInfoKHR* pDependencyInfo) const {
1448 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1449}
1450
Camden5b184be2019-08-13 07:50:19 -06001451bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001452 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001453 bool skip = false;
1454
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001455 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1456
1457 return skip;
1458}
1459
1460bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1461 VkQueryPool queryPool, uint32_t query) const {
1462 bool skip = false;
1463
1464 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001465
1466 return skip;
1467}
1468
Sam Walls0961ec02020-03-31 16:39:15 +01001469void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1470 VkPipeline pipeline) {
1471 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1472
Nadav Gevaf0808442021-05-21 13:51:25 -04001473 // AMD best practice
1474 pipelines_used_in_frame.emplace(pipeline);
1475
Sam Walls0961ec02020-03-31 16:39:15 +01001476 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1477 // check for depth/blend state tracking
1478 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1479 if (gp_cis != graphicsPipelineCIs.end()) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001480 auto* cb_node = GetCBState(commandBuffer);
1481 assert(cb_node);
1482 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01001483
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001484 render_pass_state.nextDrawTouchesAttachments = gp_cis->second.accessFramebufferAttachments;
1485 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001486
Jeremy Gebben396d06a2021-08-12 11:03:04 -06001487 const auto& blend_state = gp_cis->second.colorBlendStateCI;
1488 const auto& stencil_state = gp_cis->second.depthStencilStateCI;
Sam Walls0961ec02020-03-31 16:39:15 +01001489
1490 if (blend_state) {
1491 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001492 render_pass_state.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001493 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1494 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001495 render_pass_state.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001496 }
1497 }
1498 }
1499
1500 // check for depth value usage
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001501 render_pass_state.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001502
1503 if (stencil_state && stencil_state->depthTestEnable) {
1504 switch (stencil_state->depthCompareOp) {
1505 case VK_COMPARE_OP_EQUAL:
1506 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1507 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001508 render_pass_state.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001509 break;
1510 default:
1511 break;
1512 }
1513 }
Sam Walls0961ec02020-03-31 16:39:15 +01001514 }
1515 }
1516}
1517
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02001518static inline bool RenderPassUsesAttachmentAsResolve(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1519 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1520 const auto& subpass_info = createInfo.pSubpasses[subpass];
1521 if (subpass_info.pResolveAttachments) {
1522 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1523 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1524 }
1525 }
1526 }
1527
1528 return false;
1529}
1530
Attilio Provenzano02859b22020-02-27 14:17:28 +00001531static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1532 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001533 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001534
1535 // If an attachment is ever used as a color attachment,
1536 // resolve attachment or depth stencil attachment,
1537 // it needs to exist on tile at some point.
1538
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001539 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1540 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001541 }
1542
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001543 if (subpass_info.pResolveAttachments) {
1544 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1545 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1546 }
1547 }
1548
1549 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001550 }
1551
1552 return false;
1553}
1554
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001555static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1556 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1557 return false;
1558 }
1559
1560 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001561 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001562
1563 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1564 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1565 return true;
1566 }
1567 }
1568 }
1569
1570 return false;
1571}
1572
Attilio Provenzano02859b22020-02-27 14:17:28 +00001573bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1574 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1575 bool skip = false;
1576
1577 if (!pRenderPassBegin) {
1578 return skip;
1579 }
1580
Gareth Webbdc6549a2021-06-16 03:52:24 +01001581 if (pRenderPassBegin->renderArea.extent.width == 0 || pRenderPassBegin->renderArea.extent.height == 0) {
1582 skip |= LogWarning(device, kVUID_BestPractices_BeginRenderPass_ZeroSizeRenderArea,
1583 "This render pass has a zero-size render area. It cannot write to any attachments, "
1584 "and can only be used for side effects such as layout transitions.");
1585 }
1586
Attilio Provenzano02859b22020-02-27 14:17:28 +00001587 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1588 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001589 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001590 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001591 if (rpabi) {
1592 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1593 }
1594 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001595 // Check if any attachments have LOAD operation on them
1596 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001597 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001598
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001599 bool attachment_has_readback = false;
Hans-Kristian Arntzen4afb59b2021-06-18 12:41:36 +02001600 if (!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001601 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001602 }
1603
1604 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001605 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001606 }
1607
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001608 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001609
1610 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001611 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1612 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001613 }
1614
1615 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001616 if (attachment_needs_readback && VendorCheckEnabled(kBPVendorArm)) {
1617 skip |= LogPerformanceWarning(
1618 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1619 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1620 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
Nadav Gevaf0808442021-05-21 13:51:25 -04001621 "which will copy in total %u pixels (renderArea = "
1622 "{ %" PRId32 ", %" PRId32 ", %" PRIu32", %" PRIu32 " }) to the tile buffer.",
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001623 VendorSpecificTag(kBPVendorArm), att,
1624 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1625 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1626 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001627 }
1628 }
1629 }
1630
1631 return skip;
1632}
1633
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001634void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
1635 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001636 if (view) {
Jeremy Gebbenb4d17012021-07-08 13:18:15 -06001637 QueueValidateImage(funcs, function_name, GetImageUsageState(view->create_info.image), usage,
1638 view->normalized_subresource_range);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001639 }
1640}
1641
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001642void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1643 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001644 const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001645 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001646
1647 // If we're viewing a 3D slice, ignore base array layer.
1648 // The entire 3D subresource is accessed as one atomic unit.
1649 const uint32_t base_array_layer = image->createInfo.imageType == VK_IMAGE_TYPE_3D ? 0 : subresource_range.baseArrayLayer;
1650
1651 const uint32_t max_layers = image->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001652 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
1653 const uint32_t max_levels = image->createInfo.mipLevels - subresource_range.baseMipLevel;
1654 const uint32_t mip_levels = std::min(image->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001655
1656 for (uint32_t layer = 0; layer < array_layers; layer++) {
1657 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001658 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
1659 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001660 }
1661 }
1662}
1663
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001664void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1665 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001666 const VkImageSubresourceLayers& subresource_layers) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001667 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001668 const uint32_t max_layers = image->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
1669 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001670
1671 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001672 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001673 }
1674}
1675
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001676void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1677 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001678 uint32_t array_layer, uint32_t mip_level) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001679 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](const ValidationStateTracker*, const QUEUE_STATE*) -> bool {
1680 ValidateImageInQueue(function_name, state, usage, array_layer, mip_level);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001681 return false;
1682 });
1683}
1684
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001685void BestPractices::ValidateImageInQueueArm(const char* function_name, IMAGE_STATE* image,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001686 IMAGE_SUBRESOURCE_USAGE_BP last_usage,
1687 IMAGE_SUBRESOURCE_USAGE_BP usage,
1688 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001689 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001690 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 -06001691 !image->IsSwapchainImage()) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001692 LogPerformanceWarning(
1693 device, kVUID_BestPractices_RenderPass_RedundantStore,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001694 "%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 +02001695 "image was used, it was written to with STORE_OP_STORE. "
1696 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1697 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001698 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001699 } 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 +02001700 LogPerformanceWarning(
1701 device, kVUID_BestPractices_RenderPass_RedundantClear,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001702 "%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 +02001703 "image was used, it was written to with vkCmdClear*Image(). "
1704 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1705 "tile-based architectures."
1706 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001707 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001708 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
1709 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE ||
1710 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
1711 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE ||
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001712 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001713 const char *last_cmd = nullptr;
1714 const char *vuid = nullptr;
1715 const char *suggestion = nullptr;
1716
1717 switch (last_usage) {
1718 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
1719 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
1720 last_cmd = "vkCmdBlitImage";
1721 suggestion =
1722 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1723 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
1724 "which avoids the memory roundtrip.";
1725 break;
1726 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
1727 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
1728 last_cmd = "vkCmdClear*Image";
1729 suggestion =
1730 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1731 "tile-based architectures. "
1732 "Use LOAD_OP_CLEAR instead to clear the image for free.";
1733 break;
1734 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
1735 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
1736 last_cmd = "vkCmdCopy*Image";
1737 suggestion =
1738 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1739 "Rather than copying, just render the source image in a fragment shader in this render pass, "
1740 "which avoids the memory roundtrip.";
1741 break;
1742 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
1743 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
1744 last_cmd = "vkCmdResolveImage";
1745 suggestion =
1746 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
1747 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
1748 "which avoids the memory roundtrip.";
1749 break;
1750 default:
1751 break;
1752 }
1753
1754 LogPerformanceWarning(
1755 device, vuid,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001756 "%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 +01001757 "time image was used, it was written to with %s. %s",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001758 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level, last_cmd, suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001759 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001760}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001761
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001762void BestPractices::ValidateImageInQueue(const char* function_name, IMAGE_STATE_BP* state,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001763 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer,
1764 uint32_t mip_level) {
1765 IMAGE_STATE* image = state->image;
1766 IMAGE_SUBRESOURCE_USAGE_BP last_usage = state->usages[array_layer][mip_level];
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001767 state->usages[array_layer][mip_level] = usage;
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001768 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001769 ValidateImageInQueueArm(function_name, image, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001770 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001771}
1772
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001773void BestPractices::AddDeferredQueueOperations(CMD_BUFFER_STATE_BP* cb) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001774 cb->queue_submit_functions.insert(cb->queue_submit_functions.end(),
Hans-Kristian Arntzenf44df192021-06-14 11:42:08 +02001775 cb->queue_submit_functions_after_render_pass.begin(),
1776 cb->queue_submit_functions_after_render_pass.end());
1777 cb->queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001778}
1779
1780void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
1781 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001782 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001783}
1784
1785void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
1786 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001787 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001788}
1789
1790void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
1791 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001792 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001793}
1794
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001795void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer,
1796 const VkRenderPassBeginInfo* pRenderPassBegin,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001797 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001798 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001799 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1800}
1801
1802void BestPractices::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer,
1803 const VkRenderPassBeginInfo* pRenderPassBegin,
1804 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1805 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1806 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1807}
1808
1809void BestPractices::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1810 const VkRenderPassBeginInfo* pRenderPassBegin,
1811 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1812 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1813 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1814}
1815
1816void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001817
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001818 if (!pRenderPassBegin) {
1819 return;
1820 }
1821
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001822 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001823
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001824 auto* rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001825 if (rp_state) {
1826 // Check load ops
1827 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001828 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001829
1830 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
1831 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1832 continue;
1833 }
1834
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001835 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001836
1837 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
1838 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001839 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001840 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
1841 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001842 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001843 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001844 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001845 }
1846
1847 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001848 IMAGE_VIEW_STATE* image_view = nullptr;
1849
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001850 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001851 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1852 if (rpabi) {
1853 image_view = GetImageViewState(rpabi->pAttachments[att]);
1854 }
1855 } else {
1856 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1857 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001858
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001859 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view, usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001860 }
1861
1862 // Check store ops
1863 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001864 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001865
1866 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1867 continue;
1868 }
1869
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001870 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001871
1872 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
1873 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001874 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001875 }
1876
1877 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001878
1879 IMAGE_VIEW_STATE* image_view = nullptr;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001880 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001881 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1882 if (rpabi) {
1883 image_view = GetImageViewState(rpabi->pAttachments[att]);
1884 }
1885 } else {
1886 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1887 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001888
Hans-Kristian Arntzenf44df192021-06-14 11:42:08 +02001889 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view, usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001890 }
1891 }
1892}
1893
Attilio Provenzano02859b22020-02-27 14:17:28 +00001894bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1895 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001896 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1897 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001898 return skip;
1899}
1900
1901bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1902 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001903 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001904 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1905 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001906 return skip;
1907}
1908
1909bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001910 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001911 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1912 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001913 return skip;
1914}
1915
Sam Walls0961ec02020-03-31 16:39:15 +01001916void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1917 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001918 // Reset the renderpass state
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001919 auto* cb = GetCBState(commandBuffer);
1920 cb->hasDrawCmd = false;
1921 assert(cb);
1922 auto& render_pass_state = cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02001923 render_pass_state.touchesAttachments.clear();
1924 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001925 render_pass_state.numDrawCallsDepthOnly = 0;
1926 render_pass_state.numDrawCallsDepthEqualCompare = 0;
1927 render_pass_state.colorAttachment = false;
1928 render_pass_state.depthAttachment = false;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001929 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001930 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01001931
Hans-Kristian Arntzena1a92cc2021-03-17 13:09:33 +01001932 const auto* rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01001933
1934 // track depth / color attachment usage within the renderpass
1935 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1936 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001937 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001938
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001939 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001940 }
1941}
1942
1943void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1944 VkSubpassContents contents) {
1945 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1946 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1947}
1948
1949void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1950 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1951 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1952 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1953}
1954
1955void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1956 const VkRenderPassBeginInfo* pRenderPassBegin,
1957 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1958 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1959 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1960}
1961
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001962// Generic function to handle validation for all CmdDraw* type functions
1963bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1964 bool skip = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001965 const auto* cb_state = GetCBState(cmd_buffer);
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001966 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001967 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1968 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001969 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001970
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001971 // Verify vertex binding
1972 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1973 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001974 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001975 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001976 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
1977 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001978 }
1979 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001980
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06001981 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001982 if (pipe) {
1983 const auto* rp_state = pipe->rp_state.get();
1984 if (rp_state) {
1985 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
1986 const auto& subpass = rp_state->createInfo.pSubpasses[i];
1987 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(
1988 pipe->graphicsPipelineCI.pDepthStencilState, subpass.pDepthStencilAttachment);
1989 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && pipe->graphicsPipelineCI.pRasterizationState &&
1990 pipe->graphicsPipelineCI.pRasterizationState->depthBiasEnable == VK_TRUE) {
1991 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
1992 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
1993 }
1994 }
1995 }
1996 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001997 }
1998 return skip;
1999}
2000
Sam Walls0961ec02020-03-31 16:39:15 +01002001void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002002 auto* cb_node = GetCBState(cmd_buffer);
2003 assert(cb_node);
2004 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01002005 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002006 RecordCmdDrawTypeArm(render_pass_state, draw_count, caller);
2007 }
2008
2009 if (render_pass_state.drawTouchAttachments) {
2010 for (auto& touch : render_pass_state.nextDrawTouchesAttachments) {
2011 RecordAttachmentAccess(render_pass_state, touch.framebufferAttachment, touch.aspects);
2012 }
2013 // No need to touch the same attachments over and over.
2014 render_pass_state.drawTouchAttachments = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002015 }
2016}
2017
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002018void BestPractices::RecordCmdDrawTypeArm(RenderPassState& render_pass_state, uint32_t draw_count, const char* caller) {
2019 if (draw_count >= kDepthPrePassMinDrawCountArm) {
2020 if (render_pass_state.depthOnly) render_pass_state.numDrawCallsDepthOnly++;
2021 if (render_pass_state.depthEqualComparison) render_pass_state.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01002022 }
2023}
2024
Camden5b184be2019-08-13 07:50:19 -06002025bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002026 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002027 bool skip = false;
2028
2029 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002030 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2031 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002032 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002033 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06002034
2035 return skip;
2036}
2037
Sam Walls0961ec02020-03-31 16:39:15 +01002038void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2039 uint32_t firstVertex, uint32_t firstInstance) {
2040 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
2041 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
2042}
2043
Camden5b184be2019-08-13 07:50:19 -06002044bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002045 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002046 bool skip = false;
2047
2048 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002049 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2050 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002051 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002052 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
2053
Attilio Provenzano02859b22020-02-27 14:17:28 +00002054 // Check if we reached the limit for small indexed draw calls.
2055 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002056 const auto* cmd_state = GetCBState(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002057 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002058 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
2059 VendorCheckEnabled(kBPVendorArm)) {
2060 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06002061 "%s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00002062 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
2063 "You can try batching drawcalls or instancing when applicable.",
2064 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
2065 }
2066
Sam Walls8e77e4f2020-03-16 20:47:40 +00002067 if (VendorCheckEnabled(kBPVendorArm)) {
2068 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2069 }
2070
2071 return skip;
2072}
2073
2074bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2075 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
2076 bool skip = false;
2077
2078 // check for sparse/underutilised index buffer, and post-transform cache thrashing
2079 const auto* cmd_state = GetCBState(commandBuffer);
2080 if (cmd_state == nullptr) return skip;
2081
locke-lunarg1ae57d62020-11-18 10:49:19 -07002082 const auto* ib_state = cmd_state->index_buffer_binding.buffer_state.get();
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002083 if (ib_state == nullptr || cmd_state->index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002084
2085 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002086 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00002087 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
2088 const void* ib_mem = ib_mem_state.p_driver_data;
2089 bool primitive_restart_enable = false;
2090
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002091 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
2092 const auto& pipeline_binding_iter = cmd_state->lastBound[lv_bind_point];
2093 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002094
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002095 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002096 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002097 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00002098
2099 // 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 -06002100 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00002101 uint32_t scan_stride;
2102 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2103 scan_stride = sizeof(uint8_t);
2104 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2105 scan_stride = sizeof(uint16_t);
2106 } else {
2107 scan_stride = sizeof(uint32_t);
2108 }
2109
2110 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
2111 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
2112
2113 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
2114 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
2115 // irrespective of whether or not they're part of the draw call.
2116
2117 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
2118 uint32_t min_index = ~0u;
2119 // start with maximum as 0 and adjust to indices in the buffer
2120 uint32_t max_index = 0u;
2121
2122 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
2123 // for the given index buffer
2124 uint32_t vertex_shade_count = 0;
2125
2126 PostTransformLRUCacheModel post_transform_cache;
2127
2128 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
2129 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
2130 // target architecture.
2131 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
2132 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
2133 post_transform_cache.resize(32);
2134
2135 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2136 uint32_t scan_index;
2137 uint32_t primitive_restart_value;
2138 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2139 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2140 primitive_restart_value = 0xFF;
2141 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2142 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2143 primitive_restart_value = 0xFFFF;
2144 } else {
2145 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2146 primitive_restart_value = 0xFFFFFFFF;
2147 }
2148
2149 max_index = std::max(max_index, scan_index);
2150 min_index = std::min(min_index, scan_index);
2151
2152 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
2153 bool in_cache = post_transform_cache.query_cache(scan_index);
2154 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
2155 if (!in_cache) vertex_shade_count++;
2156 }
2157 }
2158
2159 // 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 +01002160 // 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
2161 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002162
2163 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07002164 skip |=
2165 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2166 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
2167 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
2168 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
2169 "maximum would be loaded, and possibly shaded, whether or not they are used.",
2170 VendorSpecificTag(kBPVendorArm),
2171 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002172 return skip;
2173 }
2174
2175 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
2176 // 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 +01002177 const size_t refs_per_bucket = 64;
2178 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
2179
2180 const uint32_t n_indices = max_index - min_index + 1;
2181 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
2182 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
2183
2184 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
2185 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00002186
2187 // To avoid using too much memory, we run over the indices again.
2188 // Knowing the size from the last scan allows us to record index usage with bitsets
2189 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2190 uint32_t scan_index;
2191 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2192 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2193 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2194 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2195 } else {
2196 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2197 }
2198 // keep track of the set of all indices used to reference vertices in the draw call
2199 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01002200 size_t bitset_bucket_index = index_offset / refs_per_bucket;
2201 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002202 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
2203 }
2204
2205 uint32_t vertex_reference_count = 0;
2206 for (const auto& bitset : vertex_reference_buckets) {
2207 vertex_reference_count += static_cast<uint32_t>(bitset.count());
2208 }
2209
2210 // 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 -07002211 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002212 // 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 -07002213 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002214
2215 if (utilization < 0.5f) {
2216 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2217 "%s The indices which were specified for the draw call only utilise approximately "
2218 "%.02f%% of the bound vertex buffer.",
2219 VendorSpecificTag(kBPVendorArm), utilization);
2220 }
2221
2222 if (cache_hit_rate <= 0.5f) {
2223 skip |=
2224 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
2225 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
2226 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
2227 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
2228 "recently shaded vertices.",
2229 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
2230 }
2231 }
2232
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002233 return skip;
2234}
2235
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002236bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2237 const VkCommandBuffer* pCommandBuffers) const {
2238 bool skip = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002239 const auto* primary = GetCBState(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002240 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002241 const auto* secondary_cb = GetCBState(pCommandBuffers[i]);
2242 if (secondary_cb == nullptr) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002243 continue;
2244 }
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002245 const auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002246 for (auto& clear : secondary.earlyClearAttachments) {
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002247 if (ClearAttachmentsIsFullClear(primary, uint32_t(clear.rects.size()), clear.rects.data())) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002248 skip |= ValidateClearAttachment(commandBuffer, primary,
2249 clear.framebufferAttachment, clear.colorAttachment,
2250 clear.aspects, true);
2251 }
2252 }
2253 }
Nadav Gevaf0808442021-05-21 13:51:25 -04002254
2255 if (VendorCheckEnabled(kBPVendorAMD)) {
2256 if (commandBufferCount > 0) {
2257 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_AvoidSecondaryCmdBuffers,
2258 "%s Performance warning: Use of secondary command buffers is not recommended. ",
2259 VendorSpecificTag(kBPVendorAMD));
2260 }
2261 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002262 return skip;
2263}
2264
2265void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2266 const VkCommandBuffer* pCommandBuffers) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002267 auto* primary = GetCBState(commandBuffer);
2268 auto& primary_state = primary->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002269
2270 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002271 auto* secondary_cb = GetCBState(pCommandBuffers[i]);
2272 if (secondary_cb == nullptr) {
2273 continue;
2274 }
2275 auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002276
2277 for (auto& early_clear : secondary.earlyClearAttachments) {
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002278 if (ClearAttachmentsIsFullClear(primary, uint32_t(early_clear.rects.size()), early_clear.rects.data())) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002279 RecordAttachmentClearAttachments(primary, primary_state, early_clear.framebufferAttachment,
2280 early_clear.colorAttachment, early_clear.aspects,
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002281 uint32_t(early_clear.rects.size()), early_clear.rects.data());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002282 } else {
2283 RecordAttachmentAccess(primary_state, early_clear.framebufferAttachment,
2284 early_clear.aspects);
2285 }
2286 }
2287
2288 for (auto& touch : secondary.touchesAttachments) {
2289 RecordAttachmentAccess(primary_state, touch.framebufferAttachment,
2290 touch.aspects);
2291 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02002292
2293 primary_state.numDrawCallsDepthEqualCompare += secondary.numDrawCallsDepthEqualCompare;
2294 primary_state.numDrawCallsDepthOnly += secondary.numDrawCallsDepthOnly;
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002295
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002296 auto* second_state = GetCBState(pCommandBuffers[i]);
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002297 if (second_state->hasDrawCmd) {
2298 primary->hasDrawCmd = true;
2299 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002300 }
2301
2302 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2303}
2304
2305void BestPractices::RecordAttachmentAccess(RenderPassState& state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
2306 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
2307 auto itr = std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002308 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002309 return info.framebufferAttachment == fb_attachment;
2310 });
2311
2312 if (itr != state.touchesAttachments.end()) {
2313 itr->aspects |= aspects;
2314 } else {
2315 state.touchesAttachments.push_back({ fb_attachment, aspects });
2316 }
2317}
2318
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002319void BestPractices::RecordAttachmentClearAttachments(CMD_BUFFER_STATE_BP* cmd_state, RenderPassState& state, uint32_t fb_attachment,
2320 uint32_t color_attachment, VkImageAspectFlags aspects, uint32_t rectCount,
2321 const VkClearRect* pRects) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002322 // If we observe a full clear before any other access to a frame buffer attachment,
2323 // we have candidate for redundant clear attachments.
2324 auto itr = std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002325 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002326 return info.framebufferAttachment == fb_attachment;
2327 });
2328
2329 uint32_t new_aspects = aspects;
2330 if (itr != state.touchesAttachments.end()) {
2331 new_aspects = aspects & ~itr->aspects;
2332 itr->aspects |= aspects;
2333 } else {
2334 state.touchesAttachments.push_back({ fb_attachment, aspects });
2335 }
2336
2337 if (new_aspects == 0) {
2338 return;
2339 }
2340
2341 if (cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2342 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
2343 // CmdExecuteCommands.
2344 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
2345 std::vector<VkClearRect>{pRects, pRects + rectCount} });
2346 }
2347}
2348
2349void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
2350 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
2351 uint32_t rectCount, const VkClearRect* pRects) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002352 auto* cmd_state = GetCBState(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002353 RENDER_PASS_STATE* rp_state = cmd_state->activeRenderPass.get();
2354 FRAMEBUFFER_STATE* fb_state = cmd_state->activeFramebuffer.get();
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002355 RenderPassState& tracking_state = cmd_state->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002356 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
2357
2358 if (rectCount == 0 || !rp_state) {
2359 return;
2360 }
2361
2362 if (!is_secondary && !fb_state) {
2363 return;
2364 }
2365
2366 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
2367 bool full_clear = ClearAttachmentsIsFullClear(cmd_state, rectCount, pRects);
2368
2369 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
2370 for (uint32_t i = 0; i < attachmentCount; i++) {
2371 auto& attachment = pClearAttachments[i];
2372 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
2373 VkImageAspectFlags aspects = attachment.aspectMask;
2374
2375 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
2376 if (subpass.pDepthStencilAttachment) {
2377 fb_attachment = subpass.pDepthStencilAttachment->attachment;
2378 }
2379 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
2380 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
2381 }
2382
2383 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2384 if (full_clear) {
2385 RecordAttachmentClearAttachments(cmd_state, tracking_state,
2386 fb_attachment, attachment.colorAttachment, aspects,
2387 rectCount, pRects);
2388 } else {
2389 RecordAttachmentAccess(tracking_state, fb_attachment, aspects);
2390 }
2391 }
2392 }
2393
2394 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments,
2395 rectCount, pRects);
2396}
2397
Attilio Provenzano02859b22020-02-27 14:17:28 +00002398void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2399 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2400 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
2401 firstInstance);
2402
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002403 auto* cmd_state = GetCBState(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002404 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
2405 cmd_state->small_indexed_draw_call_count++;
2406 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002407
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002408 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00002409}
2410
Sam Walls0961ec02020-03-31 16:39:15 +01002411void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2412 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2413 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2414 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
2415}
2416
sfricke-samsung681ab7b2020-10-29 01:53:35 -07002417bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2418 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
2419 uint32_t maxDrawCount, uint32_t stride) const {
2420 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
2421
2422 return skip;
2423}
2424
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002425bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
2426 VkDeviceSize offset, VkBuffer countBuffer,
2427 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
2428 uint32_t stride) const {
2429 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06002430
2431 return skip;
2432}
2433
2434bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002435 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002436 bool skip = false;
2437
2438 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002439 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2440 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002441 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002442 }
2443
2444 return skip;
2445}
2446
Sam Walls0961ec02020-03-31 16:39:15 +01002447void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2448 uint32_t count, uint32_t stride) {
2449 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
2450 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
2451}
2452
Camden5b184be2019-08-13 07:50:19 -06002453bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002454 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002455 bool skip = false;
2456
2457 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002458 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2459 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002460 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002461 }
2462
2463 return skip;
2464}
2465
Sam Walls0961ec02020-03-31 16:39:15 +01002466void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2467 uint32_t count, uint32_t stride) {
2468 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
2469 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
2470}
2471
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002472void BestPractices::ValidateBoundDescriptorSets(VkCommandBuffer commandBuffer, const char* function_name) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002473 auto* cb_state = GetCBState(commandBuffer);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002474
2475 if (cb_state) {
2476 for (auto descriptor_set : cb_state->validated_descriptor_sets) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002477 const auto& layout = *descriptor_set->GetLayout();
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002478
2479 for (uint32_t index = 0; index < descriptor_set->GetBindingCount(); ++index) {
2480 // For bindless scenarios, we should not attempt to track descriptor set state.
2481 // It is highly uncertain which resources are actually bound.
2482 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
2483 VkDescriptorBindingFlags flags = layout.GetDescriptorBindingFlagsFromIndex(index);
2484 if (flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT |
2485 VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
2486 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
2487 continue;
2488 }
2489
2490 auto index_range = layout.GetGlobalIndexRangeFromIndex(index);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002491 for (uint32_t i = index_range.start; i < index_range.end; ++i) {
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002492 VkImageView image_view{VK_NULL_HANDLE};
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002493
2494 auto descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2495 switch (descriptor->GetClass()) {
2496 case cvdescriptorset::DescriptorClass::Image: {
2497 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
2498 image_view = image_descriptor->GetImageView();
2499 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002500 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002501 }
2502 case cvdescriptorset::DescriptorClass::ImageSampler: {
2503 if (const auto image_sampler_descriptor =
2504 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
2505 image_view = image_sampler_descriptor->GetImageView();
2506 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002507 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002508 }
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002509 default:
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002510 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002511 }
2512
2513 if (image_view) {
2514 IMAGE_VIEW_STATE* image_view_state = GetImageViewState(image_view);
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002515 QueueValidateImageView(cb_state->queue_submit_functions, function_name,
2516 image_view_state, IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002517 }
2518 }
2519 }
2520 }
2521 }
2522}
2523
2524void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2525 uint32_t firstVertex, uint32_t firstInstance) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002526 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002527}
2528
2529void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2530 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002531 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002532}
2533
2534void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2535 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002536 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002537}
2538
Camden5b184be2019-08-13 07:50:19 -06002539bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002540 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06002541 bool skip = false;
2542
2543 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002544 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
2545 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
2546 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
2547 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06002548 }
2549
2550 return skip;
2551}
Camden83a9c372019-08-14 11:41:38 -06002552
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002553bool BestPractices::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2554 bool skip = false;
2555 skip |= StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
2556 skip |= ValidateCmdEndRenderPass(commandBuffer);
2557 return skip;
2558}
2559
2560bool BestPractices::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2561 bool skip = false;
2562 skip |= StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
2563 skip |= ValidateCmdEndRenderPass(commandBuffer);
2564 return skip;
2565}
2566
Sam Walls0961ec02020-03-31 16:39:15 +01002567bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2568 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002569 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002570 skip |= ValidateCmdEndRenderPass(commandBuffer);
2571 return skip;
2572}
2573
2574bool BestPractices::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2575 bool skip = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002576 const auto* cmd = GetCBState(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01002577
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002578 if (cmd == nullptr) return skip;
2579 auto &render_pass_state = cmd->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01002580
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002581 bool uses_depth = (render_pass_state.depthAttachment || render_pass_state.colorAttachment) &&
2582 render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2583 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
Sam Walls0961ec02020-03-31 16:39:15 +01002584 if (uses_depth) {
2585 skip |= LogPerformanceWarning(
2586 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
2587 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
2588 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
2589 "case, using depth pre-passes for hidden surface removal may worsen performance.",
2590 VendorSpecificTag(kBPVendorArm));
2591 }
2592
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002593 RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2594
2595 if (VendorCheckEnabled(kBPVendorArm) && rp) {
2596
2597 // If we use an attachment on-tile, we should access it in some way. Otherwise,
2598 // it is redundant to have it be part of the render pass.
2599 // Only consider it redundant if it will actually consume bandwidth, i.e.
2600 // LOAD_OP_LOAD is used or STORE_OP_STORE. CLEAR -> DONT_CARE is benign,
2601 // as is using pure input attachments.
2602 // CLEAR -> STORE might be considered a "useful" thing to do, but
2603 // the optimal thing to do is to defer the clear until you're actually
2604 // going to render to the image.
2605
2606 uint32_t num_attachments = rp->createInfo.attachmentCount;
2607 for (uint32_t i = 0; i < num_attachments; i++) {
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02002608 if (!RenderPassUsesAttachmentOnTile(rp->createInfo, i) ||
2609 RenderPassUsesAttachmentAsResolve(rp->createInfo, i)) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002610 continue;
2611 }
2612
2613 auto& attachment = rp->createInfo.pAttachments[i];
2614
2615 VkImageAspectFlags bandwidth_aspects = 0;
2616
2617 if (!FormatIsStencilOnly(attachment.format) &&
2618 (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2619 attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2620 if (FormatHasDepth(attachment.format)) {
2621 bandwidth_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
2622 } else {
2623 bandwidth_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
2624 }
2625 }
2626
2627 if (FormatHasStencil(attachment.format) &&
2628 (attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2629 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2630 bandwidth_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
2631 }
2632
2633 if (!bandwidth_aspects) {
2634 continue;
2635 }
2636
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002637 auto itr = std::find_if(render_pass_state.touchesAttachments.begin(), render_pass_state.touchesAttachments.end(),
2638 [&](const AttachmentInfo& info) { return info.framebufferAttachment == i; });
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002639 uint32_t untouched_aspects = bandwidth_aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002640 if (itr != render_pass_state.touchesAttachments.end()) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002641 untouched_aspects &= ~itr->aspects;
2642 }
2643
2644 if (untouched_aspects) {
2645 skip |= LogPerformanceWarning(
2646 device, kVUID_BestPractices_EndRenderPass_RedundantAttachmentOnTile,
2647 "%s Render pass was ended, but attachment #%u (format: %u, untouched aspects 0x%x) "
2648 "was never accessed by a pipeline or clear command. "
2649 "On tile-based architectures, LOAD_OP_LOAD and STORE_OP_STORE consume bandwidth and should not be part of the render pass "
2650 "if the attachments are not intended to be accessed.",
2651 VendorSpecificTag(kBPVendorArm), i, attachment.format, untouched_aspects);
2652 }
2653 }
2654 }
2655
Sam Walls0961ec02020-03-31 16:39:15 +01002656 return skip;
2657}
2658
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002659void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002660 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002661}
2662
2663void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002664 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002665}
2666
Camden Stocker9c051442019-11-06 14:28:43 -08002667bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2668 const char* api_name) const {
2669 bool skip = false;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002670 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002671
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002672 if (bp_pd_state) {
2673 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2674 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2675 "Potential problem with calling %s() without first retrieving properties from "
2676 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2677 api_name);
2678 }
Camden Stocker9c051442019-11-06 14:28:43 -08002679 }
2680
2681 return skip;
2682}
2683
Camden83a9c372019-08-14 11:41:38 -06002684bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002685 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002686 bool skip = false;
2687
Camden Stocker9c051442019-11-06 14:28:43 -08002688 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002689
Camden Stocker9c051442019-11-06 14:28:43 -08002690 return skip;
2691}
2692
2693bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2694 uint32_t planeIndex,
2695 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2696 bool skip = false;
2697
2698 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2699
2700 return skip;
2701}
2702
2703bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2704 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2705 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2706 bool skip = false;
2707
2708 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002709
2710 return skip;
2711}
Camden05de2d42019-08-19 10:23:56 -06002712
2713bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002714 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002715 bool skip = false;
2716
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002717 const auto* swapchain_state = static_cast<SWAPCHAIN_STATE_BP*>(Get<SWAPCHAIN_NODE>(swapchain));
Camden05de2d42019-08-19 10:23:56 -06002718
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002719 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002720 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002721 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002722 skip |=
2723 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2724 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2725 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002726 }
Camden05de2d42019-08-19 10:23:56 -06002727
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002728 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
2729 skip |= LogWarning(
2730 device, kVUID_BestPractices_Swapchain_InvalidCount,
2731 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
Nadav Gevaf0808442021-05-21 13:51:25 -04002732 "value (%" PRId32 ") that is greater than the value (%" PRId32 ") that was returned when pSwapchainImages was NULL.",
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002733 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
2734 }
2735 }
2736
Camden05de2d42019-08-19 10:23:56 -06002737 return skip;
2738}
2739
2740// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002741bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
2742 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002743 const CALL_STATE call_state,
2744 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002745 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002746 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2747 if (UNCALLED == call_state) {
2748 skip |= LogWarning(
2749 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
2750 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2751 "recommended "
2752 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2753 caller_name, caller_name);
2754 // Then verify that pCount that is passed in on second call matches what was returned
2755 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
2756 skip |= LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
2757 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2758 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2759 ". It is recommended to instead receive all the properties by calling %s with "
2760 "pQueueFamilyPropertyCount that was "
2761 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
2762 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
2763 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002764 }
2765
2766 return skip;
2767}
2768
Jeff Bolz5c801d12019-10-09 10:38:45 -05002769bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2770 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002771 bool skip = false;
2772
2773 for (uint32_t i = 0; i < bindInfoCount; i++) {
sourav parmarcd5fb182020-07-17 12:58:44 -07002774 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureStateNV(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002775 if (!as_state->memory_requirements_checked) {
2776 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2777 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2778 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002779 skip |= LogWarning(
2780 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002781 "vkBindAccelerationStructureMemoryNV(): "
2782 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
2783 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
2784 }
2785 }
2786
2787 return skip;
2788}
2789
Camden05de2d42019-08-19 10:23:56 -06002790bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2791 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002792 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002793 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2794 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002795 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2796 if (pQueueFamilyProperties && bp_pd_state) {
2797 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2798 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2799 "vkGetPhysicalDeviceQueueFamilyProperties()");
2800 }
2801 return false;
Camden05de2d42019-08-19 10:23:56 -06002802}
2803
Mike Schuchardt2df08912020-12-15 16:28:09 -08002804bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2805 uint32_t* pQueueFamilyPropertyCount,
2806 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002807 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2808 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002809 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2810 if (pQueueFamilyProperties && bp_pd_state) {
2811 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2812 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2813 "vkGetPhysicalDeviceQueueFamilyProperties2()");
2814 }
2815 return false;
Camden05de2d42019-08-19 10:23:56 -06002816}
2817
Jeff Bolz5c801d12019-10-09 10:38:45 -05002818bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08002819 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002820 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2821 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002822 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2823 if (pQueueFamilyProperties && bp_pd_state) {
2824 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2825 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2826 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
2827 }
2828 return false;
Camden05de2d42019-08-19 10:23:56 -06002829}
2830
2831bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2832 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002833 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06002834 if (!pSurfaceFormats) return false;
2835 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002836 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2837 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06002838 bool skip = false;
2839 if (call_state == UNCALLED) {
2840 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
2841 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002842 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
2843 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
2844 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06002845 } else {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002846 auto prev_format_count = static_cast<uint32_t>(physical_device_state->surface_formats.size());
Peter Chene191bd72019-09-16 13:04:37 -04002847 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002848 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
2849 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
2850 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
2851 "when pSurfaceFormatCount was NULL.",
2852 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06002853 }
2854 }
2855 return skip;
2856}
Camden Stocker23cc47d2019-09-03 14:53:57 -06002857
2858bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002859 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002860 bool skip = false;
2861
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002862 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2863 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002864 // 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 -07002865 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002866 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
2867 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002868 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06002869 // 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 -07002870 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
2871 const auto& image_bind = bind_info.pImageBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04002872 auto image_state = Get<IMAGE_STATE>(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002873 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002874 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002875 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002876 sparse_images.insert(image_state);
2877 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2878 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2879 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002880 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002881 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2882 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002883 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002884 }
2885 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002886 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002887 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002888 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002889 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2890 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002891 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002892 }
2893 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002894 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2895 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04002896 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002897 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002898 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002899 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002900 sparse_images.insert(image_state);
2901 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2902 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2903 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002904 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002905 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2906 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002907 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002908 }
2909 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002910 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002911 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002912 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002913 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2914 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002915 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002916 }
2917 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2918 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002919 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06002920 }
2921 }
2922 }
2923 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002924 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
2925 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002926 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002927 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002928 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
2929 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002930 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002931 }
2932 }
2933 }
2934
2935 return skip;
2936}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002937
Mark Lobodzinski84101d72020-04-24 09:43:48 -06002938void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
2939 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002940 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002941 return;
2942 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002943
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002944 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2945 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
2946 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2947 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04002948 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002949 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002950 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002951 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002952 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2953 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
2954 image_state->sparse_metadata_bound = true;
2955 }
2956 }
2957 }
2958 }
2959}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002960
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002961bool BestPractices::ClearAttachmentsIsFullClear(const CMD_BUFFER_STATE_BP* cmd, uint32_t rectCount,
2962 const VkClearRect* pRects) const {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002963 if (cmd->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2964 // We don't know the accurate render area in a secondary,
2965 // so assume we clear the entire frame buffer.
2966 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
2967 return true;
2968 }
2969
2970 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
2971 for (uint32_t i = 0; i < rectCount; i++) {
2972 auto& rect = pRects[i];
2973 auto& render_area = cmd->activeRenderPassBeginInfo.renderArea;
2974 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
2975 return true;
2976 }
2977 }
2978
2979 return false;
2980}
2981
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002982bool BestPractices::ValidateClearAttachment(VkCommandBuffer commandBuffer, const CMD_BUFFER_STATE_BP* cmd, uint32_t fb_attachment,
2983 uint32_t color_attachment, VkImageAspectFlags aspects, bool secondary) const {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002984 const RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2985 bool skip = false;
2986
2987 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
2988 return skip;
2989 }
2990
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002991 const auto& rp_state = cmd->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002992
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002993 auto attachment_itr = std::find_if(rp_state.touchesAttachments.begin(), rp_state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002994 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002995 return info.framebufferAttachment == fb_attachment;
2996 });
2997
2998 // Only report aspects which haven't been touched yet.
2999 VkImageAspectFlags new_aspects = aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003000 if (attachment_itr != rp_state.touchesAttachments.end()) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003001 new_aspects &= ~attachment_itr->aspects;
3002 }
3003
3004 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
3005 if (!cmd->hasDrawCmd) {
3006 skip |= LogPerformanceWarning(
3007 commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
Hans-Kristian Arntzen4ddd6182021-06-18 12:16:33 +02003008 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds in current render pass. It is recommended you "
3009 "use RenderPass LOAD_OP_CLEAR on attachments instead.",
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003010 report_data->FormatHandle(commandBuffer).c_str());
3011 }
3012
3013 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
3014 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3015 skip |= LogPerformanceWarning(
3016 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3017 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
3018 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3019 "it is more efficient.",
3020 secondary ? "vkCmdExecuteCommands(): " : "",
3021 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
3022 }
3023
3024 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
3025 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3026 skip |= LogPerformanceWarning(
3027 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3028 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
3029 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3030 "it is more efficient.",
3031 secondary ? "vkCmdExecuteCommands(): " : "",
3032 report_data->FormatHandle(commandBuffer).c_str());
3033 }
3034
3035 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
3036 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3037 skip |= LogPerformanceWarning(
3038 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3039 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
3040 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3041 "it is more efficient.",
3042 secondary ? "vkCmdExecuteCommands(): " : "",
3043 report_data->FormatHandle(commandBuffer).c_str());
3044 }
3045
3046 return skip;
3047}
3048
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003049bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06003050 const VkClearAttachment* pAttachments, uint32_t rectCount,
3051 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003052 bool skip = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003053 const auto* cb_node = GetCBState(commandBuffer);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003054 if (!cb_node) return skip;
3055
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003056 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
3057 // Defer checks to ExecuteCommands.
3058 return skip;
3059 }
3060
3061 // Only care about full clears, partial clears might have legitimate uses.
3062 if (!ClearAttachmentsIsFullClear(cb_node, rectCount, pRects)) {
3063 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003064 }
3065
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003066 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
3067 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06003068 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003069 if (rp) {
3070 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
3071
3072 for (uint32_t i = 0; i < attachmentCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003073 const auto& attachment = pAttachments[i];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003074
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003075 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
3076 uint32_t color_attachment = attachment.colorAttachment;
3077 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003078 skip |= ValidateClearAttachment(commandBuffer, cb_node,
3079 fb_attachment, color_attachment,
3080 attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003081 }
3082
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003083 if (subpass.pDepthStencilAttachment &&
3084 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003085 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003086 skip |= ValidateClearAttachment(commandBuffer, cb_node,
3087 fb_attachment, VK_ATTACHMENT_UNUSED,
3088 attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003089 }
3090 }
3091 }
3092
Nadav Gevaf0808442021-05-21 13:51:25 -04003093 if (VendorCheckEnabled(kBPVendorAMD)) {
3094 for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; attachment_idx++) {
3095 if (pAttachments[attachment_idx].aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) {
3096 bool black_check = false;
3097 black_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 0.0f;
3098 black_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 0.0f;
3099 black_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 0.0f;
3100 black_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3101 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3102
3103 bool white_check = false;
3104 white_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 1.0f;
3105 white_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 1.0f;
3106 white_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 1.0f;
3107 white_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3108 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3109
3110 if (black_check && white_check) {
3111 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3112 "%s Performance warning: vkCmdClearAttachments() clear value for color attachment %" PRId32 " is not a fast clear value."
3113 "Consider changing to one of the following:"
3114 "RGBA(0, 0, 0, 0) "
3115 "RGBA(0, 0, 0, 1) "
3116 "RGBA(1, 1, 1, 0) "
3117 "RGBA(1, 1, 1, 1)",
3118 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3119 }
3120 } else {
3121 if ((pAttachments[attachment_idx].clearValue.depthStencil.depth != 0 &&
3122 pAttachments[attachment_idx].clearValue.depthStencil.depth != 1) &&
3123 pAttachments[attachment_idx].clearValue.depthStencil.stencil != 0) {
3124 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3125 "%s Performance warning: vkCmdClearAttachments() clear value for depth/stencil "
3126 "attachment %" PRId32 " is not a fast clear value."
3127 "Consider changing to one of the following:"
3128 "D=0.0f, S=0"
3129 "D=1.0f, S=0",
3130 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3131 }
3132 }
3133 }
3134 }
3135
Camden Stockerf55721f2019-09-09 11:04:49 -06003136 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003137}
Attilio Provenzano02859b22020-02-27 14:17:28 +00003138
3139bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3140 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3141 const VkImageResolve* pRegions) const {
3142 bool skip = false;
3143
3144 skip |= VendorCheckEnabled(kBPVendorArm) &&
3145 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
3146 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
3147 "This is a very slow and extremely bandwidth intensive path. "
3148 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3149 VendorSpecificTag(kBPVendorArm));
3150
3151 return skip;
3152}
3153
Jeff Leger178b1e52020-10-05 12:22:23 -04003154bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3155 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
3156 bool skip = false;
3157
3158 skip |= VendorCheckEnabled(kBPVendorArm) &&
3159 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
3160 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
3161 "This is a very slow and extremely bandwidth intensive path. "
3162 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3163 VendorSpecificTag(kBPVendorArm));
3164
3165 return skip;
3166}
3167
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003168void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3169 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3170 const VkImageResolve* pRegions) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003171 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003172 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003173 auto* src = GetImageUsageState(srcImage);
3174 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003175
3176 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003177 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
3178 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003179 }
3180}
3181
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003182void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3183 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003184 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003185 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003186 auto* src = GetImageUsageState(pResolveImageInfo->srcImage);
3187 auto* dst = GetImageUsageState(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003188 uint32_t regionCount = pResolveImageInfo->regionCount;
3189
3190 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003191 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
3192 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003193 }
3194}
3195
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003196void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3197 const VkClearColorValue* pColor, uint32_t rangeCount,
3198 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003199 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003200 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003201 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003202
3203 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003204 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003205 }
3206}
3207
3208void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3209 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3210 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003211 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003212 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003213 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003214
3215 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003216 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003217 }
3218}
3219
3220void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3221 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3222 const VkImageCopy* pRegions) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003223 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003224 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003225 auto* src = GetImageUsageState(srcImage);
3226 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003227
3228 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003229 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
3230 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003231 }
3232}
3233
3234void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3235 VkImageLayout dstImageLayout, uint32_t regionCount,
3236 const VkBufferImageCopy* pRegions) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003237 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003238 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003239 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003240
3241 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003242 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003243 }
3244}
3245
3246void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3247 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003248 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003249 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003250 auto* src = GetImageUsageState(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003251
3252 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003253 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003254 }
3255}
3256
3257void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3258 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3259 const VkImageBlit* pRegions, VkFilter filter) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003260 auto* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003261 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003262 auto* src = GetImageUsageState(srcImage);
3263 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003264
3265 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003266 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
3267 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003268 }
3269}
3270
Attilio Provenzano02859b22020-02-27 14:17:28 +00003271bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
3272 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
3273 bool skip = false;
3274
3275 if (VendorCheckEnabled(kBPVendorArm)) {
3276 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
3277 skip |= LogPerformanceWarning(
3278 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
3279 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
3280 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
3281 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06003282 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003283 }
3284
3285 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
3286 skip |= LogPerformanceWarning(
3287 device, kVUID_BestPractices_CreateSampler_LodClamping,
3288 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
3289 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
3290 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
3291 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
3292 }
3293
3294 if (pCreateInfo->mipLodBias != 0.0f) {
3295 skip |=
3296 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
3297 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
3298 "descriptors being created and may cause reduced performance.",
3299 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
3300 }
3301
3302 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3303 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3304 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
3305 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
3306 skip |= LogPerformanceWarning(
3307 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
3308 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
3309 "This will lead to less efficient descriptors being created and may cause reduced performance. "
3310 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
3311 VendorSpecificTag(kBPVendorArm));
3312 }
3313
3314 if (pCreateInfo->unnormalizedCoordinates) {
3315 skip |= LogPerformanceWarning(
3316 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
3317 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
3318 "descriptors being created and may cause reduced performance.",
3319 VendorSpecificTag(kBPVendorArm));
3320 }
3321
3322 if (pCreateInfo->anisotropyEnable) {
3323 skip |= LogPerformanceWarning(
3324 device, kVUID_BestPractices_CreateSampler_Anisotropy,
3325 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
3326 "and may cause reduced performance.",
3327 VendorSpecificTag(kBPVendorArm));
3328 }
3329 }
3330
3331 return skip;
3332}
Sam Walls8e77e4f2020-03-16 20:47:40 +00003333
Nadav Gevaf0808442021-05-21 13:51:25 -04003334void BestPractices::PreCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
3335 const VkGraphicsPipelineCreateInfo* pCreateInfos,
3336 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
3337 void* cgpl_state) {
3338 ValidationStateTracker::PreCallRecordCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator,
3339 pPipelines);
3340 // AMD best practice
3341 num_pso += createInfoCount;
3342}
3343
3344bool BestPractices::PreCallValidateUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount,
3345 const VkWriteDescriptorSet* pDescriptorWrites, uint32_t descriptorCopyCount,
3346 const VkCopyDescriptorSet* pDescriptorCopies) const {
3347 bool skip = false;
3348 if (VendorCheckEnabled(kBPVendorAMD)) {
3349 if (descriptorCopyCount > 0) {
3350 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_AvoidCopyingDescriptors,
3351 "%s Performance warning: copying descriptor sets is not recommended",
3352 VendorSpecificTag(kBPVendorAMD));
3353 }
3354 }
3355
3356 return skip;
3357}
3358
3359bool BestPractices::PreCallValidateCreateDescriptorUpdateTemplate(VkDevice device,
3360 const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
3361 const VkAllocationCallbacks* pAllocator,
3362 VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate) const {
3363 bool skip = false;
3364 if (VendorCheckEnabled(kBPVendorAMD)) {
3365 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_PreferNonTemplate,
3366 "%s Performance warning: using DescriptorSetWithTemplate is not recommended. Prefer using "
3367 "vkUpdateDescriptorSet instead",
3368 VendorSpecificTag(kBPVendorAMD));
3369 }
3370
3371 return skip;
3372}
3373
3374bool BestPractices::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3375 const VkClearColorValue* pColor, uint32_t rangeCount,
3376 const VkImageSubresourceRange* pRanges) const {
3377 bool skip = false;
3378 if (VendorCheckEnabled(kBPVendorAMD)) {
3379 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_ClearImage,
3380 "%s Performance warning: using vkCmdClearColorImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3381 "vkCmdClearAttachments instead",
3382 VendorSpecificTag(kBPVendorAMD));
3383 }
3384
3385 return skip;
3386}
3387
3388bool BestPractices::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
3389 VkImageLayout imageLayout,
3390 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3391 const VkImageSubresourceRange* pRanges) const {
3392 bool skip = false;
3393 if (VendorCheckEnabled(kBPVendorAMD)) {
3394 skip |= LogPerformanceWarning(
3395 device, kVUID_BestPractices_ClearAttachment_ClearImage,
3396 "%s Performance warning: using vkCmdClearDepthStencilImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3397 "vkCmdClearAttachments instead",
3398 VendorSpecificTag(kBPVendorAMD));
3399 }
3400
3401 return skip;
3402}
3403
3404bool BestPractices::PreCallValidateCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo* pCreateInfo,
3405 const VkAllocationCallbacks* pAllocator,
3406 VkPipelineLayout* pPipelineLayout) const {
3407 bool skip = false;
3408 if (VendorCheckEnabled(kBPVendorAMD)) {
3409 // Descriptor sets cost 1 DWORD each.
3410 // Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF.
3411 // Dynamic buffers cost 4 DWORDs each when robust buffer access is ON.
3412 // Push constants cost 1 DWORD per 4 bytes in the Push constant range.
3413 uint32_t pipeline_size = pCreateInfo->setLayoutCount; // in DWORDS
3414 for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; i++) {
3415 std::shared_ptr<const cvdescriptorset::DescriptorSetLayout> descriptor_set_layout_state =
3416 GetDescriptorSetLayoutShared(pCreateInfo->pSetLayouts[i]);
3417 pipeline_size += descriptor_set_layout_state->GetDynamicDescriptorCount() * (robust_buffer_access ? 4 : 2);
3418 }
3419
3420 for (uint32_t i = 0; i < pCreateInfo->pushConstantRangeCount; i++) {
3421 pipeline_size += pCreateInfo->pPushConstantRanges[i].size / 4;
3422 }
3423
3424 if (pipeline_size > kPipelineLayoutSizeWarningLimitAMD) {
3425 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelinesLayout_KeepLayoutSmall,
3426 "%s Performance warning: pipeline layout size is too large. Prefer smaller pipeline layouts."
3427 "Descriptor sets cost 1 DWORD each. "
3428 "Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF. "
3429 "Dynamic buffers cost 4 DWORDs each when robust buffer access is ON. "
3430 "Push constants cost 1 DWORD per 4 bytes in the Push constant range. ",
3431 VendorSpecificTag(kBPVendorAMD));
3432 }
3433 }
3434
3435 return skip;
3436}
3437
3438bool BestPractices::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3439 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3440 const VkImageCopy* pRegions) const {
3441 bool skip = false;
3442 std::stringstream src_image_hex;
3443 std::stringstream dst_image_hex;
3444 src_image_hex << "0x" << std::hex << HandleToUint64(srcImage);
3445 dst_image_hex << "0x" << std::hex << HandleToUint64(dstImage);
3446
3447 if (VendorCheckEnabled(kBPVendorAMD)) {
3448 const IMAGE_STATE* src_state = Get<IMAGE_STATE>(srcImage);
3449 const IMAGE_STATE* dst_state = Get<IMAGE_STATE>(dstImage);
3450
3451 if (src_state && dst_state) {
3452 VkImageTiling src_Tiling = src_state->createInfo.tiling;
3453 VkImageTiling dst_Tiling = dst_state->createInfo.tiling;
3454 if (src_Tiling != dst_Tiling && (src_Tiling == VK_IMAGE_TILING_LINEAR || dst_Tiling == VK_IMAGE_TILING_LINEAR)) {
3455 skip |=
3456 LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidImageToImageCopy,
3457 "%s Performance warning: image %s and image %s have differing tilings. Use buffer to "
3458 "image (vkCmdCopyImageToBuffer) "
3459 "and image to buffer (vkCmdCopyBufferToImage) copies instead of image to image "
3460 "copies when converting between linear and optimal images",
3461 VendorSpecificTag(kBPVendorAMD), src_image_hex.str().c_str(), dst_image_hex.str().c_str());
3462 }
3463 }
3464 }
3465
3466 return skip;
3467}
3468
3469bool BestPractices::PreCallValidateCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
3470 VkPipeline pipeline) const {
3471 bool skip = false;
3472
3473 if (VendorCheckEnabled(kBPVendorAMD)) {
3474 if (pipelines_used_in_frame.find(pipeline) != pipelines_used_in_frame.end()) {
3475 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Pipeline_SortAndBind,
3476 "%s Performance warning: Pipeline %s was bound twice in the frame. Keep pipeline state changes to a minimum,"
3477 "for example, by sorting draw calls by pipeline.",
3478 VendorSpecificTag(kBPVendorAMD), report_data->FormatHandle(pipeline).c_str());
3479 }
3480 }
3481
3482 return skip;
3483}
3484
3485void BestPractices::ManualPostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
3486 VkFence fence, VkResult result) {
3487 // AMD best practice
3488 num_queue_submissions += submitCount;
3489}
3490
3491bool BestPractices::PreCallValidateQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) const {
3492 bool skip = false;
3493
3494 if (VendorCheckEnabled(kBPVendorAMD)) {
3495 if (num_queue_submissions > kNumberOfSubmissionWarningLimitAMD) {
3496 skip |= LogPerformanceWarning(
3497 device, kVUID_BestPractices_Submission_ReduceNumberOfSubmissions,
3498 "%s Performance warning: command buffers submitted %" PRId32 " times this frame. Submitting command buffers has a CPU "
3499 "and GPU overhead. Submit fewer times to incur less overhead.",
3500 VendorSpecificTag(kBPVendorAMD), num_queue_submissions);
3501 }
3502 }
3503
3504 return skip;
3505}
3506
3507void BestPractices::PostCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3508 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3509 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
3510 uint32_t bufferMemoryBarrierCount,
3511 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
3512 uint32_t imageMemoryBarrierCount,
3513 const VkImageMemoryBarrier* pImageMemoryBarriers) {
3514 num_barriers_objects += memoryBarrierCount;
3515 num_barriers_objects += imageMemoryBarrierCount;
3516 num_barriers_objects += bufferMemoryBarrierCount;
3517}
3518
3519void BestPractices::ManualPostCallRecordCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
3520 const VkAllocationCallbacks* pAllocator, VkFence* pFence, VkResult result) {
3521 // AMD best practice
3522 if (result == VK_SUCCESS) {
3523 num_fence_objects++;
3524 }
3525}
3526
3527void BestPractices::ManualPostCallRecordCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
3528 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore,
3529 VkResult result) {
3530 // AMD best practice
3531 if (result == VK_SUCCESS) {
3532 num_semaphore_objects++;
3533 }
3534}
3535
3536bool BestPractices::PreCallValidateCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
3537 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore) const {
3538 bool skip = false;
3539 if (VendorCheckEnabled(kBPVendorAMD)) {
3540 if (num_semaphore_objects > kMaxRecommendedSemaphoreObjectsSizeAMD) {
3541 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfSemaphores,
3542 "%s Performance warning: High number of vkSemaphore objects created."
3543 "Minimize the amount of queue synchronization that is used. "
3544 "Semaphores and fences have overhead. Each fence has a CPU and GPU cost with it.",
3545 VendorSpecificTag(kBPVendorAMD));
3546 }
3547 }
3548
3549 return skip;
3550}
3551
3552bool BestPractices::PreCallValidateCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
3553 const VkAllocationCallbacks* pAllocator, VkFence* pFence) const {
3554 bool skip = false;
3555 if (VendorCheckEnabled(kBPVendorAMD)) {
3556 if (num_fence_objects > kMaxRecommendedFenceObjectsSizeAMD) {
3557 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfFences,
3558 "%s Performance warning: High number of VkFence objects created."
3559 "Minimize the amount of CPU-GPU synchronization that is used. "
3560 "Semaphores and fences have overhead.Each fence has a CPU and GPU cost with it.",
3561 VendorSpecificTag(kBPVendorAMD));
3562 }
3563 }
3564
3565 return skip;
3566}
3567
Sam Walls8e77e4f2020-03-16 20:47:40 +00003568void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
3569
3570bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
3571 // look for a cache hit
3572 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
3573 if (hit != _entries.end()) {
3574 // mark the cache hit as being most recently used
3575 hit->age = iteration++;
3576 return true;
3577 }
3578
3579 // if there's no cache hit, we need to model the entry being inserted into the cache
3580 CacheEntry new_entry = {value, iteration};
3581 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
3582 // if there is still space left in the cache, use the next available slot
3583 *(_entries.begin() + iteration) = new_entry;
3584 } else {
3585 // otherwise replace the least recently used cache entry
3586 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
3587 *lru = new_entry;
3588 }
3589 iteration++;
3590 return false;
3591}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003592
3593bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
3594 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
3595 const auto swapchain_data = GetSwapchainState(swapchain);
3596 bool skip = false;
3597 if (swapchain_data && swapchain_data->images.size() == 0) {
3598 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
3599 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
3600 "vkGetSwapchainImagesKHR after swapchain creation.");
3601 }
3602 return skip;
3603}
3604
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003605void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
3606 if (no_pointer) {
3607 if (UNCALLED == call_state) {
3608 call_state = QUERY_COUNT;
3609 }
3610 } else { // Save queue family properties
3611 call_state = QUERY_DETAILS;
3612 }
3613}
3614
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003615void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
3616 uint32_t* pQueueFamilyPropertyCount,
3617 VkQueueFamilyProperties* pQueueFamilyProperties) {
3618 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
3619 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003620 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003621 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003622 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
3623 nullptr == pQueueFamilyProperties);
3624 }
3625}
3626
3627void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
3628 uint32_t* pQueueFamilyPropertyCount,
3629 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3630 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
3631 pQueueFamilyProperties);
3632 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3633 if (bp_pd_state) {
3634 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
3635 nullptr == pQueueFamilyProperties);
3636 }
3637}
3638
3639void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
3640 uint32_t* pQueueFamilyPropertyCount,
3641 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3642 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
3643 pQueueFamilyProperties);
3644 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3645 if (bp_pd_state) {
3646 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
3647 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003648 }
3649}
3650
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003651void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
3652 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003653 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3654 if (bp_pd_state) {
3655 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3656 }
3657}
3658
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003659void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
3660 VkPhysicalDeviceFeatures2* pFeatures) {
3661 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003662 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3663 if (bp_pd_state) {
3664 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3665 }
3666}
3667
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003668void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
3669 VkPhysicalDeviceFeatures2* pFeatures) {
3670 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003671 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3672 if (bp_pd_state) {
3673 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3674 }
3675}
3676
3677void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
3678 VkSurfaceKHR surface,
3679 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
3680 VkResult result) {
3681 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3682 if (bp_pd_state) {
3683 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3684 }
3685}
3686
3687void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
3688 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3689 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
3690 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3691 if (bp_pd_state) {
3692 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3693 }
3694}
3695
3696void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
3697 VkSurfaceKHR surface,
3698 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
3699 VkResult result) {
3700 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3701 if (bp_pd_state) {
3702 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3703 }
3704}
3705
3706void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
3707 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
3708 VkPresentModeKHR* pPresentModes, VkResult result) {
3709 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3710 if (bp_pd_data) {
3711 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
3712
3713 if (*pPresentModeCount) {
3714 if (call_state < QUERY_COUNT) {
3715 call_state = QUERY_COUNT;
3716 }
3717 }
3718 if (pPresentModes) {
3719 if (call_state < QUERY_DETAILS) {
3720 call_state = QUERY_DETAILS;
3721 }
3722 }
3723 }
3724}
3725
3726void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
3727 uint32_t* pSurfaceFormatCount,
3728 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
3729 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3730 if (bp_pd_data) {
3731 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
3732
3733 if (*pSurfaceFormatCount) {
3734 if (call_state < QUERY_COUNT) {
3735 call_state = QUERY_COUNT;
3736 }
3737 }
3738 if (pSurfaceFormats) {
3739 if (call_state < QUERY_DETAILS) {
3740 call_state = QUERY_DETAILS;
3741 }
3742 }
3743 }
3744}
3745
3746void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
3747 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3748 uint32_t* pSurfaceFormatCount,
3749 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
3750 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3751 if (bp_pd_data) {
3752 if (*pSurfaceFormatCount) {
3753 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
3754 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
3755 }
3756 }
3757 if (pSurfaceFormats) {
3758 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
3759 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
3760 }
3761 }
3762 }
3763}
3764
3765void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
3766 uint32_t* pPropertyCount,
3767 VkDisplayPlanePropertiesKHR* pProperties,
3768 VkResult result) {
3769 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3770 if (bp_pd_data) {
3771 if (*pPropertyCount) {
3772 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
3773 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
3774 }
3775 }
3776 if (pProperties) {
3777 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
3778 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
3779 }
3780 }
3781 }
3782}
3783
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003784void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
3785 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
3786 VkResult result) {
Nathaniel Cesario39152e62021-07-02 13:04:16 -06003787 auto* swapchain_state = static_cast<SWAPCHAIN_STATE_BP*>(Get<SWAPCHAIN_NODE>(swapchain));
3788 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
3789 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
3790 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003791 }
3792 }
3793}
3794
3795void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
3796 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
3797 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
3798 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
3799 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
3800 }
3801 }
3802}
3803
Nadav Gevaf0808442021-05-21 13:51:25 -04003804void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo* pCreateInfo,
3805 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice, VkResult result) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003806 if (VK_SUCCESS == result) {
3807 instance_device_bp_state = &phys_device_bp_state_map[gpu];
Nadav Gevaf0808442021-05-21 13:51:25 -04003808
3809 if ((pCreateInfo->pEnabledFeatures != nullptr) && (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
3810 robust_buffer_access = true;
3811 }
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003812 }
Nadav Gevaf0808442021-05-21 13:51:25 -04003813
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003814}
3815
3816PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
3817 if (phys_device_bp_state_map.count(phys_device) > 0) {
3818 return &phys_device_bp_state_map.at(phys_device);
3819 } else {
3820 return nullptr;
3821 }
3822}
3823
3824const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
3825 if (phys_device_bp_state_map.count(phys_device) > 0) {
3826 return &phys_device_bp_state_map.at(phys_device);
3827 } else {
3828 return nullptr;
3829 }
3830}
3831
3832PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
3833 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
3834 if (bp_state) {
3835 return bp_state;
3836 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
3837 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
3838 } else {
3839 return nullptr;
3840 }
3841}
3842
3843const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
3844 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
3845 if (bp_state) {
3846 return bp_state;
3847 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
3848 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
3849 } else {
3850 return nullptr;
3851 }
3852}
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003853
3854void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
3855 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
3856
3857 QUEUE_STATE* queue_state = GetQueueState(queue);
3858 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003859 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003860 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003861 auto* cb = GetCBState(submit_info.pCommandBuffers[cb_index]);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003862 for (auto &func : cb->queue_submit_functions) {
3863 func(this, queue_state);
3864 }
3865 }
3866 }
3867}