blob: 888f60bff634be43ce57635a70f273994f181633 [file] [log] [blame]
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -07001/* Copyright (c) 2015-2020 The Khronos Group Inc.
2 * Copyright (c) 2015-2020 Valve Corporation
3 * Copyright (c) 2015-2020 LunarG, Inc.
Camdeneaa86ea2019-07-26 11:00:09 -06004 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author: Camden Stocker <camden@lunarg.com>
18 */
19
Mark Lobodzinski57b8ae82020-02-20 16:37:14 -070020#include "best_practices_validation.h"
Camden5b184be2019-08-13 07:50:19 -060021#include "layer_chassis_dispatch.h"
Camden Stocker0a660ce2019-08-27 15:30:40 -060022#include "best_practices_error_enums.h"
Sam Wallsd7ab6db2020-06-19 20:41:54 +010023#include "shader_validation.h"
Camden5b184be2019-08-13 07:50:19 -060024
25#include <string>
Sam Walls8e77e4f2020-03-16 20:47:40 +000026#include <bitset>
Sam Wallsd7ab6db2020-06-19 20:41:54 +010027#include <memory>
Camden5b184be2019-08-13 07:50:19 -060028
Attilio Provenzano19d6a982020-02-27 12:41:41 +000029struct VendorSpecificInfo {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060030 EnableFlags vendor_id;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000031 std::string name;
32};
33
34const std::map<BPVendorFlagBits, VendorSpecificInfo> vendor_info = {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060035 {kBPVendorArm, {vendor_specific_arm, "Arm"}},
Attilio Provenzano19d6a982020-02-27 12:41:41 +000036};
37
38bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
39 for (const auto& vendor : vendor_info) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060040 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000041 return true;
42 }
43 }
44 return false;
45}
46
47const char* VendorSpecificTag(BPVendorFlags vendors) {
48 // Cache built vendor tags in a map
49 static std::unordered_map<BPVendorFlags, std::string> tag_map;
50
51 auto res = tag_map.find(vendors);
52 if (res == tag_map.end()) {
53 // Build the vendor tag string
54 std::stringstream vendor_tag;
55
56 vendor_tag << "[";
57 bool first_vendor = true;
58 for (const auto& vendor : vendor_info) {
59 if (vendors & vendor.first) {
60 if (!first_vendor) {
61 vendor_tag << ", ";
62 }
63 vendor_tag << vendor.second.name;
64 first_vendor = false;
65 }
66 }
67 vendor_tag << "]";
68
69 tag_map[vendors] = vendor_tag.str();
70 res = tag_map.find(vendors);
71 }
72
73 return res->second.c_str();
74}
75
Mark Lobodzinski6167e102020-02-24 17:03:55 -070076const char* DepReasonToString(ExtDeprecationReason reason) {
77 switch (reason) {
78 case kExtPromoted:
79 return "promoted to";
80 break;
81 case kExtObsoleted:
82 return "obsoleted by";
83 break;
84 case kExtDeprecated:
85 return "deprecated by";
86 break;
87 default:
88 return "";
89 break;
90 }
91}
92
93bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
94 const char* vuid) const {
95 bool skip = false;
96 auto dep_info_it = deprecated_extensions.find(extension_name);
97 if (dep_info_it != deprecated_extensions.end()) {
98 auto dep_info = dep_info_it->second;
Mark Lobodzinski6a149702020-05-14 12:21:34 -060099 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
100 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700101 skip |=
102 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
103 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600104 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700105 if (dep_info.target.length() == 0) {
106 skip |= LogWarning(instance, vuid,
107 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
108 "without replacement.",
109 api_name, extension_name);
110 } else {
111 skip |= LogWarning(instance, vuid,
112 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
113 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
114 }
115 }
116 }
117 return skip;
118}
119
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700120bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const char* vuid) const {
121 bool skip = false;
122 auto dep_info_it = special_use_extensions.find(extension_name);
123
124 if (dep_info_it != special_use_extensions.end()) {
125 auto special_uses = dep_info_it->second;
126 std::string message("is intended to support the following uses: ");
127 if (special_uses.find("cadsupport") != std::string::npos) {
128 message.append("specialized functionality used by CAD/CAM applications, ");
129 }
130 if (special_uses.find("d3demulation") != std::string::npos) {
131 message.append("D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D, ");
132 }
133 if (special_uses.find("devtools") != std::string::npos) {
134 message.append(" developer tools such as capture-replay libraries, ");
135 }
136 if (special_uses.find("debugging") != std::string::npos) {
137 message.append("use by applications when debugging, ");
138 }
139 if (special_uses.find("glemulation") != std::string::npos) {
140 message.append(
141 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
142 "specific to those APIs, ");
143 }
144 message.append("and it is strongly recommended that they be otherwise avoided");
145
146 skip |= LogWarning(instance, vuid, "%s(): Attempting to enable extension %s, but this extension %s.", api_name,
147 extension_name, message.c_str());
148 }
149 return skip;
150}
151
Camden5b184be2019-08-13 07:50:19 -0600152bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500153 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600154 bool skip = false;
155
156 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
157 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800158 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700159 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
160 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600161 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600162 uint32_t specified_version =
163 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
164 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700165 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Mark Lobodzinskia431b772020-11-10 08:12:13 -0700166 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i],
167 kVUID_BestPractices_CreateInstance_SpecialUseExtension);
Camden5b184be2019-08-13 07:50:19 -0600168 }
169
170 return skip;
171}
172
173void BestPractices::PreCallRecordCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
174 VkInstance* pInstance) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700175 ValidationStateTracker::PreCallRecordCreateInstance(pCreateInfo, pAllocator, pInstance);
Sam Walls53bf7652020-04-21 17:35:15 +0100176
177 if (pCreateInfo != nullptr && pCreateInfo->pApplicationInfo != nullptr)
178 instance_api_version = pCreateInfo->pApplicationInfo->apiVersion;
179 else
180 instance_api_version = 0;
Camden5b184be2019-08-13 07:50:19 -0600181}
182
183bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500184 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600185 bool skip = false;
186
187 // get API version of physical device passed when creating device.
188 VkPhysicalDeviceProperties physical_device_properties{};
189 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500190 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600191
192 // check api versions and warn if instance api Version is higher than version on device.
193 if (instance_api_version > device_api_version) {
Mark Lobodzinski60880782020-08-11 08:02:07 -0600194 std::string inst_api_name = StringAPIVersion(instance_api_version);
195 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600196
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700197 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
198 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
199 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600200 }
201
202 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
203 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800204 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700205 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
206 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600207 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700208 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], instance_api_version,
209 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Mark Lobodzinskia431b772020-11-10 08:12:13 -0700210 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i],
211 kVUID_BestPractices_CreateDevice_SpecialUseExtension);
Camden5b184be2019-08-13 07:50:19 -0600212 }
213
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600214 const auto bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
215 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700216 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
217 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600218 }
219
Szilard Papp7d2c7952020-06-22 14:38:13 +0100220 if ((VendorCheckEnabled(kBPVendorArm)) && (pCreateInfo->pEnabledFeatures != nullptr) &&
221 (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
222 skip |= LogPerformanceWarning(
223 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
224 "%s vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
225 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
226 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
227 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
228 VendorSpecificTag(kBPVendorArm));
229 }
230
Camden5b184be2019-08-13 07:50:19 -0600231 return skip;
232}
233
234bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500235 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600236 bool skip = false;
237
238 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
239 std::stringstream bufferHex;
240 bufferHex << "0x" << std::hex << HandleToUint64(pBuffer);
241
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700242 skip |= LogWarning(
243 device, kVUID_BestPractices_SharingModeExclusive,
244 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
245 "(queueFamilyIndexCount of %" PRIu32 ").",
246 bufferHex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600247 }
248
249 return skip;
250}
251
252bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500253 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600254 bool skip = false;
255
256 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
257 std::stringstream imageHex;
258 imageHex << "0x" << std::hex << HandleToUint64(pImage);
259
260 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700261 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
262 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
263 "(queueFamilyIndexCount of %" PRIu32 ").",
264 imageHex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600265 }
266
Attilio Provenzano02859b22020-02-27 14:17:28 +0000267 if (VendorCheckEnabled(kBPVendorArm)) {
268 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
269 skip |= LogPerformanceWarning(
270 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
271 "%s vkCreateImage(): Trying to create an image with %u samples. "
272 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
273 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
274 }
275
276 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
277 skip |= LogPerformanceWarning(
278 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
279 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
280 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
281 "and do not need to be backed by physical storage. "
282 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
283 VendorSpecificTag(kBPVendorArm));
284 }
285 }
286
Camden5b184be2019-08-13 07:50:19 -0600287 return skip;
288}
289
290bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500291 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600292 bool skip = false;
293
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600294 const auto* bp_pd_state = GetPhysicalDeviceStateBP();
295 if (bp_pd_state) {
296 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
297 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
298 "vkCreateSwapchainKHR() called before getting surface capabilities from "
299 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
300 }
Camden83a9c372019-08-14 11:41:38 -0600301
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600302 if (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS) {
303 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
304 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
305 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
306 }
Camden83a9c372019-08-14 11:41:38 -0600307
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600308 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
309 skip |= LogWarning(
310 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
311 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
312 }
Camden83a9c372019-08-14 11:41:38 -0600313 }
314
Camden5b184be2019-08-13 07:50:19 -0600315 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700316 skip |=
317 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600318 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700319 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
320 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600321 }
322
Szilard Papp48a6da32020-06-10 14:41:59 +0100323 if (pCreateInfo->minImageCount == 2) {
324 skip |= LogPerformanceWarning(
325 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
326 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
327 ", which means double buffering is going "
328 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
329 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
330 "3 to use triple buffering to maximize performance in such cases.",
331 pCreateInfo->minImageCount);
332 }
333
Szilard Pappd5f0f812020-06-22 09:01:29 +0100334 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
335 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
336 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
337 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
338 "Presentation modes which are not FIFO will present the latest available frame and discard other "
339 "frame(s) if any.",
340 VendorSpecificTag(kBPVendorArm));
341 }
342
Camden5b184be2019-08-13 07:50:19 -0600343 return skip;
344}
345
346bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
347 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500348 const VkAllocationCallbacks* pAllocator,
349 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600350 bool skip = false;
351
352 for (uint32_t i = 0; i < swapchainCount; i++) {
353 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700354 skip |= LogWarning(
355 device, kVUID_BestPractices_SharingModeExclusive,
356 "Warning: A shared swapchain (index %" PRIu32
357 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
358 "queues (queueFamilyIndexCount of %" PRIu32 ").",
359 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600360 }
361 }
362
363 return skip;
364}
365
366bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500367 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600368 bool skip = false;
369
370 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
371 VkFormat format = pCreateInfo->pAttachments[i].format;
372 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
373 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
374 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700375 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
376 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
377 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
378 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
379 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600380 }
381 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700382 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
383 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
384 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
385 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
386 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600387 }
388 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000389
390 const auto& attachment = pCreateInfo->pAttachments[i];
391 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
392 bool access_requires_memory =
393 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
394
395 if (FormatHasStencil(format)) {
396 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
397 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
398 }
399
400 if (access_requires_memory) {
401 skip |= LogPerformanceWarning(
402 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
403 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
404 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
405 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
406 i, static_cast<uint32_t>(attachment.samples));
407 }
408 }
Camden5b184be2019-08-13 07:50:19 -0600409 }
410
411 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
412 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
413 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
414 }
415
416 return skip;
417}
418
Tony-LunarG767180f2020-04-23 14:03:59 -0600419bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
420 const VkImageView* image_views) const {
421 bool skip = false;
422
423 // Check for non-transient attachments that should be transient and vice versa
424 for (uint32_t i = 0; i < attachmentCount; ++i) {
425 auto& attachment = rpci->pAttachments[i];
426 bool attachment_should_be_transient =
427 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
428
429 if (FormatHasStencil(attachment.format)) {
430 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
431 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
432 }
433
434 auto view_state = GetImageViewState(image_views[i]);
435 if (view_state) {
436 auto& ivci = view_state->create_info;
437 auto& ici = GetImageState(ivci.image)->createInfo;
438
439 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
440
441 // The check for an image that should not be transient applies to all GPUs
442 if (!attachment_should_be_transient && image_is_transient) {
443 skip |= LogPerformanceWarning(
444 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
445 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
446 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
447 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
448 i);
449 }
450
451 bool supports_lazy = false;
452 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
453 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
454 supports_lazy = true;
455 }
456 }
457
458 // The check for an image that should be transient only applies to GPUs supporting
459 // lazily allocated memory
460 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
461 skip |= LogPerformanceWarning(
462 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
463 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
464 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
465 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
466 i);
467 }
468 }
469 }
470 return skip;
471}
472
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000473bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
474 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
475 bool skip = false;
476
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000477 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
Tony-LunarG767180f2020-04-23 14:03:59 -0600478 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR)) {
479 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000480 }
481
482 return skip;
483}
484
Sam Wallse746d522020-03-16 21:20:23 +0000485bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
486 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
487 bool skip = false;
488 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
489
490 if (!skip) {
491 const auto& pool_handle = pAllocateInfo->descriptorPool;
492 auto iter = descriptor_pool_freed_count.find(pool_handle);
493 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
494 // this warning is specific to Arm
495 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
496 skip |= LogPerformanceWarning(
497 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
498 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
499 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
500 VendorSpecificTag(kBPVendorArm));
501 }
502 }
503
504 return skip;
505}
506
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600507void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
508 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000509 if (result == VK_SUCCESS) {
510 // find the free count for the pool we allocated into
511 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
512 if (iter != descriptor_pool_freed_count.end()) {
513 // we record successful allocations by subtracting the allocation count from the last recorded free count
514 const auto alloc_count = pAllocateInfo->descriptorSetCount;
515 // clamp the unsigned subtraction to the range [0, last_free_count]
516 if (iter->second > alloc_count)
517 iter->second -= alloc_count;
518 else
519 iter->second = 0;
520 }
521 }
522}
523
524void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
525 const VkDescriptorSet* pDescriptorSets, VkResult result) {
526 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
527 if (result == VK_SUCCESS) {
528 // we want to track frees because we're interested in suggesting re-use
529 auto iter = descriptor_pool_freed_count.find(descriptorPool);
530 if (iter == descriptor_pool_freed_count.end()) {
531 descriptor_pool_freed_count.insert(std::make_pair(descriptorPool, descriptorSetCount));
532 } else {
533 iter->second += descriptorSetCount;
534 }
535 }
536}
537
Camden5b184be2019-08-13 07:50:19 -0600538bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500539 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600540 bool skip = false;
541
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500542 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700543 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
544 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600545 }
546
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000547 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
548 skip |= LogPerformanceWarning(
549 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
550 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %llu. This is a very small allocation (current "
551 "threshold is %llu bytes). "
552 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
553 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
554 }
555
Camden83a9c372019-08-14 11:41:38 -0600556 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
557
558 return skip;
559}
560
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600561void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
562 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
563 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700564 if (result != VK_SUCCESS) {
565 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
566 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
567 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR};
568 static std::vector<VkResult> success_codes = {};
569 ValidateReturnCodes("vkReleaseFullScreenExclusiveModeEXT", result, error_codes, success_codes);
570 return;
571 }
572 num_mem_objects++;
573}
Camden Stocker9738af92019-10-16 13:54:03 -0700574
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600575void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
576 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700577 auto error = std::find(error_codes.begin(), error_codes.end(), result);
578 if (error != error_codes.end()) {
Mark Lobodzinski629defa2020-04-29 12:00:23 -0600579 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700580 return;
581 }
582 auto success = std::find(success_codes.begin(), success_codes.end(), result);
583 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600584 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
585 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500586 }
587}
588
Jeff Bolz5c801d12019-10-09 10:38:45 -0500589bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
590 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700591 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600592 bool skip = false;
593
Camden Stocker9738af92019-10-16 13:54:03 -0700594 const DEVICE_MEMORY_STATE* mem_info = ValidationStateTracker::GetDevMemState(memory);
Camden83a9c372019-08-14 11:41:38 -0600595
596 for (auto& obj : mem_info->obj_bindings) {
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600597 LogObjectList objlist(device);
598 objlist.add(obj);
599 objlist.add(mem_info->mem);
600 skip |= LogWarning(objlist, layer_name.c_str(), "VK Object %s still has a reference to mem obj %s.",
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700601 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem).c_str());
Camden83a9c372019-08-14 11:41:38 -0600602 }
603
Camden5b184be2019-08-13 07:50:19 -0600604 return skip;
605}
606
607void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700608 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600609 if (memory != VK_NULL_HANDLE) {
610 num_mem_objects--;
611 }
612}
613
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000614bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600615 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500616 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600617
sfricke-samsunge2441192019-11-06 14:07:57 -0800618 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700619 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
620 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
621 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600622 }
623
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000624 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
625
626 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
627 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
628 skip |= LogPerformanceWarning(
629 device, kVUID_BestPractices_SmallDedicatedAllocation,
630 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
631 "The required size of the allocation is %llu, but smaller buffers like this should be sub-allocated from "
632 "larger memory blocks. (Current threshold is %llu bytes.)",
633 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
634 }
635
Camden Stockerb603cc82019-09-03 10:09:02 -0600636 return skip;
637}
638
639bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500640 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600641 bool skip = false;
642 const char* api_name = "BindBufferMemory()";
643
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000644 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600645
646 return skip;
647}
648
649bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500650 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600651 char api_name[64];
652 bool skip = false;
653
654 for (uint32_t i = 0; i < bindInfoCount; i++) {
655 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000656 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600657 }
658
659 return skip;
660}
Camden Stockerb603cc82019-09-03 10:09:02 -0600661
662bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500663 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600664 char api_name[64];
665 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600666
Camden Stocker8b798ab2019-09-03 10:33:28 -0600667 for (uint32_t i = 0; i < bindInfoCount; i++) {
668 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000669 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600670 }
671
672 return skip;
673}
674
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000675bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600676 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500677 const IMAGE_STATE* image_state = GetImageState(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600678
sfricke-samsung71bc6572020-04-29 15:49:43 -0700679 if (image_state->disjoint == false) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700680 if (!image_state->memory_requirements_checked && !image_state->external_memory_handle) {
681 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
682 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
683 api_name, report_data->FormatHandle(image).c_str());
684 }
685 } else {
686 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
687 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600688 }
689
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000690 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
691
692 if (mem_state->alloc_info.allocationSize == image_state->requirements.size &&
693 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
694 skip |= LogPerformanceWarning(
695 device, kVUID_BestPractices_SmallDedicatedAllocation,
696 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
697 "The required size of the allocation is %llu, but smaller images like this should be sub-allocated from "
698 "larger memory blocks. (Current threshold is %llu bytes.)",
699 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
700 }
701
702 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
703 // make sure this type is actually used.
704 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
705 // (i.e.most tile - based renderers)
706 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
707 bool supports_lazy = false;
708 uint32_t suggested_type = 0;
709
710 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
711 if ((1u << i) & image_state->requirements.memoryTypeBits) {
712 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
713 supports_lazy = true;
714 suggested_type = i;
715 break;
716 }
717 }
718 }
719
720 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
721
722 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
723 skip |= LogPerformanceWarning(
724 device, kVUID_BestPractices_NonLazyTransientImage,
725 "%s: Attempting to bind memory type % u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
726 "but this memory type is not LAZILY_ALLOCATED_BIT. You should use memory type %u here instead to save "
727 "%llu bytes of physical memory.",
728 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements.size);
729 }
730 }
731
Camden Stocker8b798ab2019-09-03 10:33:28 -0600732 return skip;
733}
734
735bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500736 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600737 bool skip = false;
738 const char* api_name = "vkBindImageMemory()";
739
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000740 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600741
742 return skip;
743}
744
745bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500746 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600747 char api_name[64];
748 bool skip = false;
749
750 for (uint32_t i = 0; i < bindInfoCount; i++) {
751 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Tony-LunarG5e60b852020-04-27 11:27:54 -0600752 if (!lvl_find_in_chain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
753 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
754 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600755 }
756
757 return skip;
758}
759
760bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500761 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600762 char api_name[64];
763 bool skip = false;
764
765 for (uint32_t i = 0; i < bindInfoCount; i++) {
766 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000767 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600768 }
769
770 return skip;
771}
Camden83a9c372019-08-14 11:41:38 -0600772
Attilio Provenzano02859b22020-02-27 14:17:28 +0000773static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
774 switch (format) {
775 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
776 case VK_FORMAT_R16_SFLOAT:
777 case VK_FORMAT_R16G16_SFLOAT:
778 case VK_FORMAT_R16G16B16_SFLOAT:
779 case VK_FORMAT_R16G16B16A16_SFLOAT:
780 case VK_FORMAT_R32_SFLOAT:
781 case VK_FORMAT_R32G32_SFLOAT:
782 case VK_FORMAT_R32G32B32_SFLOAT:
783 case VK_FORMAT_R32G32B32A32_SFLOAT:
784 return false;
785
786 default:
787 return true;
788 }
789}
790
791bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
792 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
793 bool skip = false;
794
795 for (uint32_t i = 0; i < createInfoCount; i++) {
796 auto pCreateInfo = &pCreateInfos[i];
797
798 if (!pCreateInfo->pColorBlendState || !pCreateInfo->pMultisampleState ||
799 pCreateInfo->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
800 pCreateInfo->pMultisampleState->sampleShadingEnable) {
801 return skip;
802 }
803
804 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
805 auto& subpass = rp_state->createInfo.pSubpasses[pCreateInfo->subpass];
806
807 for (uint32_t j = 0; j < pCreateInfo->pColorBlendState->attachmentCount; j++) {
808 auto& blend_att = pCreateInfo->pColorBlendState->pAttachments[j];
809 uint32_t att = subpass.pColorAttachments[j].attachment;
810
811 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
812 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
813 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
814 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
815 "color attachment #%u makes use "
816 "of a format which cannot be blended at full throughput when using MSAA.",
817 VendorSpecificTag(kBPVendorArm), i, j);
818 }
819 }
820 }
821 }
822
823 return skip;
824}
825
Camden5b184be2019-08-13 07:50:19 -0600826bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
827 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600828 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500829 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600830 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
831 pAllocator, pPipelines, cgpl_state_data);
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600832 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600833
834 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700835 skip |= LogPerformanceWarning(
836 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
837 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
838 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600839 }
840
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000841 for (uint32_t i = 0; i < createInfoCount; i++) {
842 auto& createInfo = pCreateInfos[i];
843
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600844 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
845 auto& vertexInput = *createInfo.pVertexInputState;
846 uint32_t count = 0;
847 for (uint32_t j = 0; j < vertexInput.vertexBindingDescriptionCount; j++) {
848 if (vertexInput.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
849 count++;
850 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000851 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600852 if (count > kMaxInstancedVertexBuffers) {
853 skip |= LogPerformanceWarning(
854 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
855 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
856 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
857 count, kMaxInstancedVertexBuffers);
858 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000859 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000860
Szilard Pappaaf2da32020-06-22 10:37:35 +0100861 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
862 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
863 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f)) {
864 skip |= VendorCheckEnabled(kBPVendorArm) &&
865 LogPerformanceWarning(
866 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
867 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
868 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
869 "efficiency during rasterization. Consider disabling depthBias or increasing either "
870 "depthBiasConstantFactor or depthBiasSlopeFactor.",
871 VendorSpecificTag(kBPVendorArm));
872 }
873
Attilio Provenzano02859b22020-02-27 14:17:28 +0000874 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000875 }
876
Camden5b184be2019-08-13 07:50:19 -0600877 return skip;
878}
879
Sam Walls0961ec02020-03-31 16:39:15 +0100880void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
881 const VkGraphicsPipelineCreateInfo* pCreateInfos,
882 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
883 VkResult result, void* cgpl_state_data) {
884 for (size_t i = 0; i < count; i++) {
885 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
886 const VkPipeline pipeline_handle = pPipelines[i];
887
888 // record depth stencil state and color blend states for depth pre-pass tracking purposes
889 auto gp_cis = graphicsPipelineCIs.find(pipeline_handle);
890
891 // add the tracking state if it doesn't exist
892 if (gp_cis == graphicsPipelineCIs.end()) {
893 auto result = graphicsPipelineCIs.emplace(std::make_pair(pipeline_handle, GraphicsPipelineCIs{}));
894
895 if (!result.second) continue;
896
897 gp_cis = result.first;
898 }
899
Tony-LunarG412b1b72020-07-15 10:30:13 -0600900 gp_cis->second.colorBlendStateCI =
901 cgpl_state->pCreateInfos[i].pColorBlendState
902 ? new safe_VkPipelineColorBlendStateCreateInfo(cgpl_state->pCreateInfos[i].pColorBlendState)
903 : nullptr;
904 gp_cis->second.depthStencilStateCI =
905 cgpl_state->pCreateInfos[i].pDepthStencilState
906 ? new safe_VkPipelineDepthStencilStateCreateInfo(cgpl_state->pCreateInfos[i].pDepthStencilState)
907 : nullptr;
Sam Walls0961ec02020-03-31 16:39:15 +0100908 }
909}
910
Camden5b184be2019-08-13 07:50:19 -0600911bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
912 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600913 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500914 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600915 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
916 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600917
918 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700919 skip |= LogPerformanceWarning(
920 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
921 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
922 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600923 }
924
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100925 if (VendorCheckEnabled(kBPVendorArm)) {
926 for (size_t i = 0; i < createInfoCount; i++) {
927 skip |= ValidateCreateComputePipelineArm(pCreateInfos[i]);
928 }
929 }
930
931 return skip;
932}
933
934bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
935 bool skip = false;
936 auto* module = GetShaderModuleState(createInfo.stage.module);
937
938 uint32_t x = 1, y = 1, z = 1;
939 FindLocalSize(module, x, y, z);
940
941 uint32_t thread_count = x * y * z;
942
943 // Generate a priori warnings about work group sizes.
944 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
945 skip |= LogPerformanceWarning(
946 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
947 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
948 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
949 "groups with less than %u threads, especially when using barrier() or shared memory.",
950 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
951 }
952
953 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
954 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
955 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
956 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
957 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
958 "%u, %u) is not aligned to %u "
959 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
960 "leave threads idle on the shader "
961 "core.",
962 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
963 kThreadGroupDispatchCountAlignmentArm);
964 }
965
966 // Generate warnings about work group sizes based on active resources.
967 auto entrypoint = FindEntrypoint(module, createInfo.stage.pName, createInfo.stage.stage);
968 if (entrypoint == module->end()) return false;
969
970 bool has_writeable_descriptors = false;
locke-lunarg63e4daf2020-08-17 17:53:25 -0600971 bool has_atomic_descriptors = false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100972 auto accessible_ids = MarkAccessibleIds(module, entrypoint);
locke-lunarg63e4daf2020-08-17 17:53:25 -0600973 auto descriptor_uses =
974 CollectInterfaceByDescriptorSlot(module, accessible_ids, &has_writeable_descriptors, &has_atomic_descriptors);
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100975
976 unsigned dimensions = 0;
977 if (x > 1) dimensions++;
978 if (y > 1) dimensions++;
979 if (z > 1) dimensions++;
980 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
981 dimensions = std::max(dimensions, 1u);
982
983 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
984 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
985 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
986 bool accesses_2d = false;
987 for (const auto& usage : descriptor_uses) {
988 auto dim = GetShaderResourceDimensionality(module, usage.second);
989 if (dim < 0) continue;
990 auto spvdim = spv::Dim(dim);
991 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
992 }
993
994 if (accesses_2d && dimensions < 2) {
995 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
996 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
997 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
998 "exhibiting poor spatial locality with respect to one or more shader resources.",
999 VendorSpecificTag(kBPVendorArm), x, y, z);
1000 }
1001
Camden5b184be2019-08-13 07:50:19 -06001002 return skip;
1003}
1004
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001005bool BestPractices::CheckPipelineStageFlags(std::string api_name, const VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001006 bool skip = false;
1007
1008 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001009 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1010 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001011 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001012 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1013 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001014 }
1015
1016 return skip;
1017}
1018
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001019void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001020 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1021 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1022 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1023 LogPerformanceWarning(
1024 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1025 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1026 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1027 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1028 "convenient opportunity.",
1029 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1030 }
1031 }
1032}
1033
Jeff Bolz5c801d12019-10-09 10:38:45 -05001034bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1035 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001036 bool skip = false;
1037
1038 for (uint32_t submit = 0; submit < submitCount; submit++) {
1039 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1040 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1041 }
1042 }
1043
1044 return skip;
1045}
1046
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001047bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1048 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1049 bool skip = false;
1050
1051 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1052 skip |= LogPerformanceWarning(
1053 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1054 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1055 "pool instead.");
1056 }
1057
1058 return skip;
1059}
1060
1061bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1062 const VkCommandBufferBeginInfo* pBeginInfo) const {
1063 bool skip = false;
1064
1065 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1066 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1067 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1068 }
1069
Attilio Provenzano02859b22020-02-27 14:17:28 +00001070 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT)) {
1071 skip |= VendorCheckEnabled(kBPVendorArm) &&
1072 LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
1073 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1074 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1075 VendorSpecificTag(kBPVendorArm));
1076 }
1077
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001078 return skip;
1079}
1080
Jeff Bolz5c801d12019-10-09 10:38:45 -05001081bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001082 bool skip = false;
1083
1084 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1085
1086 return skip;
1087}
1088
Jeff Bolz5c801d12019-10-09 10:38:45 -05001089bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1090 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001091 bool skip = false;
1092
1093 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1094
1095 return skip;
1096}
1097
1098bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1099 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1100 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1101 uint32_t bufferMemoryBarrierCount,
1102 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1103 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001104 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001105 bool skip = false;
1106
1107 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1108 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1109
1110 return skip;
1111}
1112
1113bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1114 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1115 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1116 uint32_t bufferMemoryBarrierCount,
1117 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1118 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001119 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001120 bool skip = false;
1121
1122 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1123 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1124
1125 return skip;
1126}
1127
1128bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001129 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001130 bool skip = false;
1131
1132 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", pipelineStage);
1133
1134 return skip;
1135}
1136
Sam Walls0961ec02020-03-31 16:39:15 +01001137void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1138 VkPipeline pipeline) {
1139 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1140
1141 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1142 // check for depth/blend state tracking
1143 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1144 if (gp_cis != graphicsPipelineCIs.end()) {
1145 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1146 if (prepass_state == cbDepthPrePassStates.end()) {
1147 auto result = cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1148
1149 if (!result.second) return;
1150
1151 prepass_state = result.first;
1152 }
1153
1154 const auto* blend_state = gp_cis->second.colorBlendStateCI;
1155 const auto* stencil_state = gp_cis->second.depthStencilStateCI;
1156
1157 if (blend_state) {
1158 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
1159 prepass_state->second.depthOnly = true;
1160 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1161 if (blend_state->pAttachments[i].colorWriteMask != 0) {
1162 prepass_state->second.depthOnly = false;
1163 }
1164 }
1165 }
1166
1167 // check for depth value usage
1168 prepass_state->second.depthEqualComparison = false;
1169
1170 if (stencil_state && stencil_state->depthTestEnable) {
1171 switch (stencil_state->depthCompareOp) {
1172 case VK_COMPARE_OP_EQUAL:
1173 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1174 case VK_COMPARE_OP_LESS_OR_EQUAL:
1175 prepass_state->second.depthEqualComparison = true;
1176 break;
1177 default:
1178 break;
1179 }
1180 }
1181 } else {
1182 // reset depth pre-pass tracking
1183 cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1184 }
1185 }
1186}
1187
Attilio Provenzano02859b22020-02-27 14:17:28 +00001188static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1189 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1190 auto& subpassInfo = createInfo.pSubpasses[subpass];
1191
1192 // If an attachment is ever used as a color attachment,
1193 // resolve attachment or depth stencil attachment,
1194 // it needs to exist on tile at some point.
1195
1196 for (uint32_t i = 0; i < subpassInfo.colorAttachmentCount; i++)
1197 if (subpassInfo.pColorAttachments[i].attachment == attachment) return true;
1198
1199 if (subpassInfo.pResolveAttachments) {
1200 for (uint32_t i = 0; i < subpassInfo.colorAttachmentCount; i++)
1201 if (subpassInfo.pResolveAttachments[i].attachment == attachment) return true;
1202 }
1203
1204 if (subpassInfo.pDepthStencilAttachment && subpassInfo.pDepthStencilAttachment->attachment == attachment) return true;
1205 }
1206
1207 return false;
1208}
1209
1210bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1211 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1212 bool skip = false;
1213
1214 if (!pRenderPassBegin) {
1215 return skip;
1216 }
1217
1218 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1219 if (rp_state) {
Tony-LunarG767180f2020-04-23 14:03:59 -06001220 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR) {
1221 const VkRenderPassAttachmentBeginInfo* rpabi =
1222 lvl_find_in_chain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1223 if (rpabi) {
1224 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1225 }
1226 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001227 // Check if any attachments have LOAD operation on them
1228 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1229 auto& attachment = rp_state->createInfo.pAttachments[att];
1230
1231 bool attachmentHasReadback = false;
1232 if (!FormatHasStencil(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1233 attachmentHasReadback = true;
1234 }
1235
1236 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1237 attachmentHasReadback = true;
1238 }
1239
1240 bool attachmentNeedsReadback = false;
1241
1242 // Check if the attachment is actually used in any subpass on-tile
1243 if (attachmentHasReadback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1244 attachmentNeedsReadback = true;
1245 }
1246
1247 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
1248 if (attachmentNeedsReadback) {
1249 skip |= VendorCheckEnabled(kBPVendorArm) &&
1250 LogPerformanceWarning(
1251 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1252 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1253 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
1254 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
1255 VendorSpecificTag(kBPVendorArm), att,
1256 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1257 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1258 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
1259 }
1260 }
1261 }
1262
1263 return skip;
1264}
1265
1266bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1267 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001268 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1269 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001270 return skip;
1271}
1272
1273bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1274 const VkRenderPassBeginInfo* pRenderPassBegin,
1275 const VkSubpassBeginInfoKHR* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001276 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1277 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001278 return skip;
1279}
1280
1281bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1282 const VkSubpassBeginInfoKHR* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001283 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1284 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001285 return skip;
1286}
1287
Sam Walls0961ec02020-03-31 16:39:15 +01001288void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1289 const VkRenderPassBeginInfo* pRenderPassBegin) {
1290 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1291
1292 // add the tracking state if it doesn't exist
1293 if (prepass_state == cbDepthPrePassStates.end()) {
1294 auto result = cbDepthPrePassStates.emplace(std::make_pair(commandBuffer, DepthPrePassState{}));
1295
1296 if (!result.second) return;
1297
1298 prepass_state = result.first;
1299 }
1300
1301 // reset the renderpass state
1302 prepass_state->second = {};
1303
1304 const auto* cb_state = GetCBState(commandBuffer);
locke-lunargaecf2152020-05-12 17:15:41 -06001305 const auto* rp_state = cb_state->activeRenderPass.get();
Sam Walls0961ec02020-03-31 16:39:15 +01001306
1307 // track depth / color attachment usage within the renderpass
1308 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1309 // record if depth/color attachments are in use for this renderpass
1310 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) prepass_state->second.depthAttachment = true;
1311
1312 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) prepass_state->second.colorAttachment = true;
1313 }
1314}
1315
1316void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1317 VkSubpassContents contents) {
1318 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1319 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1320}
1321
1322void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1323 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1324 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1325 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1326}
1327
1328void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1329 const VkRenderPassBeginInfo* pRenderPassBegin,
1330 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1331 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1332 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1333}
1334
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001335// Generic function to handle validation for all CmdDraw* type functions
1336bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1337 bool skip = false;
1338 const CMD_BUFFER_STATE* cb_state = GetCBState(cmd_buffer);
1339 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001340 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1341 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001342 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001343
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001344 // Verify vertex binding
1345 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1346 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001347 skip |= LogPerformanceWarning(cb_state->commandBuffer, kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
1348 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
1349 report_data->FormatHandle(cb_state->commandBuffer).c_str(),
1350 report_data->FormatHandle(pipeline_state->pipeline).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001351 }
1352 }
1353 }
1354 return skip;
1355}
1356
Sam Walls0961ec02020-03-31 16:39:15 +01001357void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1358 if (VendorCheckEnabled(kBPVendorArm)) {
1359 RecordCmdDrawTypeArm(cmd_buffer, draw_count, caller);
1360 }
1361}
1362
1363void BestPractices::RecordCmdDrawTypeArm(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1364 auto prepass_state = cbDepthPrePassStates.find(cmd_buffer);
1365 if (prepass_state != cbDepthPrePassStates.end() && draw_count >= kDepthPrePassMinDrawCountArm) {
1366 if (prepass_state->second.depthOnly) prepass_state->second.numDrawCallsDepthOnly++;
1367
1368 if (prepass_state->second.depthEqualComparison) prepass_state->second.numDrawCallsDepthEqualCompare++;
1369 }
1370}
1371
Camden5b184be2019-08-13 07:50:19 -06001372bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001373 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001374 bool skip = false;
1375
1376 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001377 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1378 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001379 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001380 }
1381
1382 return skip;
1383}
1384
Sam Walls0961ec02020-03-31 16:39:15 +01001385void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1386 uint32_t firstVertex, uint32_t firstInstance) {
1387 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
1388 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
1389}
1390
Camden5b184be2019-08-13 07:50:19 -06001391bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001392 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001393 bool skip = false;
1394
1395 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001396 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1397 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001398 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001399 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1400
Attilio Provenzano02859b22020-02-27 14:17:28 +00001401 // Check if we reached the limit for small indexed draw calls.
1402 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1403 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1404 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
1405 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1)) {
1406 skip |= VendorCheckEnabled(kBPVendorArm) &&
1407 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
1408 "The command buffer contains many small indexed drawcalls "
1409 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1410 "You can try batching drawcalls or instancing when applicable.",
1411 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1412 }
1413
Sam Walls8e77e4f2020-03-16 20:47:40 +00001414 if (VendorCheckEnabled(kBPVendorArm)) {
1415 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1416 }
1417
1418 return skip;
1419}
1420
1421bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1422 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1423 bool skip = false;
1424
1425 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1426 const auto* cmd_state = GetCBState(commandBuffer);
1427 if (cmd_state == nullptr) return skip;
1428
locke-lunarg1ae57d62020-11-18 10:49:19 -07001429 const auto* ib_state = cmd_state->index_buffer_binding.buffer_state.get();
1430 if (ib_state == nullptr || cmd_state->index_buffer_binding.buffer_state->destroyed) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001431
1432 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
1433 const auto& ib_mem_state = *ib_state->binding.mem_state;
1434 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1435 const void* ib_mem = ib_mem_state.p_driver_data;
1436 bool primitive_restart_enable = false;
1437
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001438 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1439 const auto& pipeline_binding_iter = cmd_state->lastBound[lv_bind_point];
1440 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001441
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001442 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr)
1443 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001444
1445 // 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 -06001446 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00001447 uint32_t scan_stride;
1448 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1449 scan_stride = sizeof(uint8_t);
1450 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1451 scan_stride = sizeof(uint16_t);
1452 } else {
1453 scan_stride = sizeof(uint32_t);
1454 }
1455
1456 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1457 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1458
1459 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1460 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1461 // irrespective of whether or not they're part of the draw call.
1462
1463 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1464 uint32_t min_index = ~0u;
1465 // start with maximum as 0 and adjust to indices in the buffer
1466 uint32_t max_index = 0u;
1467
1468 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
1469 // for the given index buffer
1470 uint32_t vertex_shade_count = 0;
1471
1472 PostTransformLRUCacheModel post_transform_cache;
1473
1474 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
1475 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
1476 // target architecture.
1477 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
1478 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
1479 post_transform_cache.resize(32);
1480
1481 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1482 uint32_t scan_index;
1483 uint32_t primitive_restart_value;
1484 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1485 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1486 primitive_restart_value = 0xFF;
1487 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1488 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1489 primitive_restart_value = 0xFFFF;
1490 } else {
1491 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1492 primitive_restart_value = 0xFFFFFFFF;
1493 }
1494
1495 max_index = std::max(max_index, scan_index);
1496 min_index = std::min(min_index, scan_index);
1497
1498 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
1499 bool in_cache = post_transform_cache.query_cache(scan_index);
1500 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
1501 if (!in_cache) vertex_shade_count++;
1502 }
1503 }
1504
1505 // 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 +01001506 // 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
1507 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001508
1509 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07001510 skip |=
1511 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1512 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
1513 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
1514 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
1515 "maximum would be loaded, and possibly shaded, whether or not they are used.",
1516 VendorSpecificTag(kBPVendorArm),
1517 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001518 return skip;
1519 }
1520
1521 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
1522 // 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 +01001523 const size_t refs_per_bucket = 64;
1524 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
1525
1526 const uint32_t n_indices = max_index - min_index + 1;
1527 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
1528 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
1529
1530 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
1531 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00001532
1533 // To avoid using too much memory, we run over the indices again.
1534 // Knowing the size from the last scan allows us to record index usage with bitsets
1535 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1536 uint32_t scan_index;
1537 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1538 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1539 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1540 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1541 } else {
1542 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1543 }
1544 // keep track of the set of all indices used to reference vertices in the draw call
1545 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01001546 size_t bitset_bucket_index = index_offset / refs_per_bucket;
1547 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001548 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
1549 }
1550
1551 uint32_t vertex_reference_count = 0;
1552 for (const auto& bitset : vertex_reference_buckets) {
1553 vertex_reference_count += static_cast<uint32_t>(bitset.count());
1554 }
1555
1556 // 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 -07001557 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001558 // 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 -07001559 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001560
1561 if (utilization < 0.5f) {
1562 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1563 "%s The indices which were specified for the draw call only utilise approximately "
1564 "%.02f%% of the bound vertex buffer.",
1565 VendorSpecificTag(kBPVendorArm), utilization);
1566 }
1567
1568 if (cache_hit_rate <= 0.5f) {
1569 skip |=
1570 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
1571 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
1572 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
1573 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
1574 "recently shaded vertices.",
1575 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
1576 }
1577 }
1578
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001579 return skip;
1580}
1581
Attilio Provenzano02859b22020-02-27 14:17:28 +00001582void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1583 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1584 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
1585 firstInstance);
1586
1587 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1588 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
1589 cmd_state->small_indexed_draw_call_count++;
1590 }
1591}
1592
Sam Walls0961ec02020-03-31 16:39:15 +01001593void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1594 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1595 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1596 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
1597}
1598
sfricke-samsung681ab7b2020-10-29 01:53:35 -07001599bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1600 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
1601 uint32_t maxDrawCount, uint32_t stride) const {
1602 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
1603
1604 return skip;
1605}
1606
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001607bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
1608 VkDeviceSize offset, VkBuffer countBuffer,
1609 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
1610 uint32_t stride) const {
1611 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06001612
1613 return skip;
1614}
1615
1616bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001617 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001618 bool skip = false;
1619
1620 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001621 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1622 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001623 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001624 }
1625
1626 return skip;
1627}
1628
Sam Walls0961ec02020-03-31 16:39:15 +01001629void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1630 uint32_t count, uint32_t stride) {
1631 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
1632 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
1633}
1634
Camden5b184be2019-08-13 07:50:19 -06001635bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001636 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001637 bool skip = false;
1638
1639 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001640 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1641 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001642 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001643 }
1644
1645 return skip;
1646}
1647
Sam Walls0961ec02020-03-31 16:39:15 +01001648void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1649 uint32_t count, uint32_t stride) {
1650 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
1651 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
1652}
1653
Camden5b184be2019-08-13 07:50:19 -06001654bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001655 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06001656 bool skip = false;
1657
1658 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001659 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
1660 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
1661 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
1662 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06001663 }
1664
1665 return skip;
1666}
Camden83a9c372019-08-14 11:41:38 -06001667
Sam Walls0961ec02020-03-31 16:39:15 +01001668bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
1669 bool skip = false;
1670
1671 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
1672
1673 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1674
1675 if (prepass_state == cbDepthPrePassStates.end()) return skip;
1676
1677 bool uses_depth = (prepass_state->second.depthAttachment || prepass_state->second.colorAttachment) &&
1678 prepass_state->second.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
1679 prepass_state->second.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
1680 if (uses_depth) {
1681 skip |= LogPerformanceWarning(
1682 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
1683 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
1684 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
1685 "case, using depth pre-passes for hidden surface removal may worsen performance.",
1686 VendorSpecificTag(kBPVendorArm));
1687 }
1688
1689 return skip;
1690}
1691
Camden Stocker9c051442019-11-06 14:28:43 -08001692bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
1693 const char* api_name) const {
1694 bool skip = false;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001695 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08001696
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001697 if (bp_pd_state) {
1698 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
1699 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
1700 "Potential problem with calling %s() without first retrieving properties from "
1701 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
1702 api_name);
1703 }
Camden Stocker9c051442019-11-06 14:28:43 -08001704 }
1705
1706 return skip;
1707}
1708
Camden83a9c372019-08-14 11:41:38 -06001709bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001710 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06001711 bool skip = false;
1712
Camden Stocker9c051442019-11-06 14:28:43 -08001713 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06001714
Camden Stocker9c051442019-11-06 14:28:43 -08001715 return skip;
1716}
1717
1718bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
1719 uint32_t planeIndex,
1720 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
1721 bool skip = false;
1722
1723 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
1724
1725 return skip;
1726}
1727
1728bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
1729 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
1730 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
1731 bool skip = false;
1732
1733 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06001734
1735 return skip;
1736}
Camden05de2d42019-08-19 10:23:56 -06001737
1738bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001739 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06001740 bool skip = false;
1741
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001742 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
Camden05de2d42019-08-19 10:23:56 -06001743
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001744 if ((swapchain_state_itr != swapchain_bp_state_map.cend()) && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06001745 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001746 if (swapchain_state_itr->second.vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001747 skip |=
1748 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
1749 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
1750 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06001751 }
1752 }
1753
1754 return skip;
1755}
1756
1757// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001758bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
1759 uint32_t requested_queue_family_property_count,
1760 bool qfp_null, const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06001761 bool skip = false;
1762 if (!qfp_null) {
1763 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001764 const auto* bp_pd_state = GetPhysicalDeviceStateBP(pd_state->phys_device);
1765 if (bp_pd_state) {
1766 if (UNCALLED == bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState) {
1767 skip |= LogWarning(
1768 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
1769 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
1770 "recommended "
1771 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
1772 caller_name, caller_name);
1773 // Then verify that pCount that is passed in on second call matches what was returned
1774 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
1775 skip |=
1776 LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
1777 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
1778 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
1779 ". It is recommended to instead receive all the properties by calling %s with "
1780 "pQueueFamilyPropertyCount that was "
1781 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
1782 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
1783 caller_name);
1784 }
Camden05de2d42019-08-19 10:23:56 -06001785 }
1786 }
1787
1788 return skip;
1789}
1790
Jeff Bolz5c801d12019-10-09 10:38:45 -05001791bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
1792 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06001793 bool skip = false;
1794
1795 for (uint32_t i = 0; i < bindInfoCount; i++) {
1796 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureState(pBindInfos[i].accelerationStructure);
1797 if (!as_state->memory_requirements_checked) {
1798 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
1799 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
1800 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001801 skip |= LogWarning(
1802 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06001803 "vkBindAccelerationStructureMemoryNV(): "
1804 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
1805 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
1806 }
1807 }
1808
1809 return skip;
1810}
1811
Camden05de2d42019-08-19 10:23:56 -06001812bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
1813 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001814 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001815 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1816 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001817 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001818 (nullptr == pQueueFamilyProperties),
1819 "vkGetPhysicalDeviceQueueFamilyProperties()");
1820}
1821
Jeff Bolz5c801d12019-10-09 10:38:45 -05001822bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(
1823 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount,
1824 VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001825 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1826 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001827 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001828 (nullptr == pQueueFamilyProperties),
1829 "vkGetPhysicalDeviceQueueFamilyProperties2()");
1830}
1831
Jeff Bolz5c801d12019-10-09 10:38:45 -05001832bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
1833 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount,
1834 VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001835 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1836 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001837 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001838 (nullptr == pQueueFamilyProperties),
1839 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
1840}
1841
1842bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
1843 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001844 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06001845 if (!pSurfaceFormats) return false;
1846 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001847 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
1848 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06001849 bool skip = false;
1850 if (call_state == UNCALLED) {
1851 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
1852 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001853 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
1854 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
1855 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06001856 } else {
1857 auto prev_format_count = (uint32_t)physical_device_state->surface_formats.size();
Peter Chene191bd72019-09-16 13:04:37 -04001858 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001859 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
1860 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
1861 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
1862 "when pSurfaceFormatCount was NULL.",
1863 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06001864 }
1865 }
1866 return skip;
1867}
Camden Stocker23cc47d2019-09-03 14:53:57 -06001868
1869bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001870 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001871 bool skip = false;
1872
1873 for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; bindIdx++) {
1874 const VkBindSparseInfo& bindInfo = pBindInfo[bindIdx];
1875 // Store sparse binding image_state and after binding is complete make sure that any requiring metadata have it bound
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001876 std::unordered_set<const IMAGE_STATE*> sparse_images;
1877 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
1878 // in RecordQueueBindSparse.
1879 std::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06001880 // If we're binding sparse image memory make sure reqs were queried and note if metadata is required and bound
1881 for (uint32_t i = 0; i < bindInfo.imageBindCount; ++i) {
1882 const auto& image_bind = bindInfo.pImageBinds[i];
1883 auto image_state = GetImageState(image_bind.image);
1884 if (!image_state)
1885 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1886 sparse_images.insert(image_state);
1887 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1888 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1889 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001890 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1891 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1892 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1893 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001894 }
1895 }
1896 if (!image_state->memory_requirements_checked) {
1897 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001898 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1899 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1900 "vkGetImageMemoryRequirements() to retrieve requirements.",
1901 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001902 }
1903 }
1904 for (uint32_t i = 0; i < bindInfo.imageOpaqueBindCount; ++i) {
1905 const auto& image_opaque_bind = bindInfo.pImageOpaqueBinds[i];
1906 auto image_state = GetImageState(bindInfo.pImageOpaqueBinds[i].image);
1907 if (!image_state)
1908 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1909 sparse_images.insert(image_state);
1910 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1911 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1912 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001913 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1914 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1915 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1916 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001917 }
1918 }
1919 if (!image_state->memory_requirements_checked) {
1920 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001921 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1922 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1923 "vkGetImageMemoryRequirements() to retrieve requirements.",
1924 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001925 }
1926 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1927 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001928 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06001929 }
1930 }
1931 }
1932 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001933 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
1934 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001935 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001936 skip |= LogWarning(sparse_image_state->image, kVUID_Core_MemTrack_InvalidState,
1937 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
1938 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
1939 report_data->FormatHandle(sparse_image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001940 }
1941 }
1942 }
1943
1944 return skip;
1945}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001946
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001947void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
1948 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001949 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001950 return;
1951 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001952
1953 for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; bindIdx++) {
1954 const VkBindSparseInfo& bindInfo = pBindInfo[bindIdx];
1955 for (uint32_t i = 0; i < bindInfo.imageOpaqueBindCount; ++i) {
1956 const auto& image_opaque_bind = bindInfo.pImageOpaqueBinds[i];
1957 auto image_state = GetImageState(bindInfo.pImageOpaqueBinds[i].image);
1958 if (!image_state)
1959 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1960 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1961 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
1962 image_state->sparse_metadata_bound = true;
1963 }
1964 }
1965 }
1966 }
1967}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001968
1969bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06001970 const VkClearAttachment* pAttachments, uint32_t rectCount,
1971 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001972 bool skip = false;
1973 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
1974 if (!cb_node) return skip;
1975
Camden Stockerf55721f2019-09-09 11:04:49 -06001976 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001977 if (!cb_node->hasDrawCmd && (cb_node->activeRenderPassBeginInfo.renderArea.extent.width == pRects[0].rect.extent.width) &&
1978 (cb_node->activeRenderPassBeginInfo.renderArea.extent.height == pRects[0].rect.extent.height)) {
1979 // There are times where app needs to use ClearAttachments (generally when reusing a buffer inside of a render pass)
1980 // This warning should be made more specific. It'd be best to avoid triggering this test if it's a use that must call
1981 // CmdClearAttachments.
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001982 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
1983 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds. It is recommended you "
1984 "use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
1985 report_data->FormatHandle(commandBuffer).c_str());
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001986 }
1987
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001988 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
1989 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06001990 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001991 if (rp) {
1992 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
1993
1994 for (uint32_t i = 0; i < attachmentCount; i++) {
1995 auto& attachment = pAttachments[i];
1996 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
1997 uint32_t color_attachment = attachment.colorAttachment;
1998 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
1999
2000 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2001 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2002 skip |= LogPerformanceWarning(
2003 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2004 "vkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
2005 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2006 "it is more efficient.",
2007 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
2008 }
2009 }
2010 }
2011
2012 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
2013 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2014
2015 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2016 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2017 skip |= LogPerformanceWarning(
2018 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2019 "vkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
2020 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2021 "it is more efficient.",
2022 report_data->FormatHandle(commandBuffer).c_str());
2023 }
2024 }
2025 }
2026
2027 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
2028 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2029
2030 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2031 if (rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2032 skip |= LogPerformanceWarning(
2033 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2034 "vkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
2035 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2036 "it is more efficient.",
2037 report_data->FormatHandle(commandBuffer).c_str());
2038 }
2039 }
2040 }
2041 }
2042 }
2043
Camden Stockerf55721f2019-09-09 11:04:49 -06002044 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002045}
Attilio Provenzano02859b22020-02-27 14:17:28 +00002046
2047bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2048 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2049 const VkImageResolve* pRegions) const {
2050 bool skip = false;
2051
2052 skip |= VendorCheckEnabled(kBPVendorArm) &&
2053 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
2054 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
2055 "This is a very slow and extremely bandwidth intensive path. "
2056 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2057 VendorSpecificTag(kBPVendorArm));
2058
2059 return skip;
2060}
2061
Jeff Leger178b1e52020-10-05 12:22:23 -04002062bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2063 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
2064 bool skip = false;
2065
2066 skip |= VendorCheckEnabled(kBPVendorArm) &&
2067 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
2068 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
2069 "This is a very slow and extremely bandwidth intensive path. "
2070 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2071 VendorSpecificTag(kBPVendorArm));
2072
2073 return skip;
2074}
2075
Attilio Provenzano02859b22020-02-27 14:17:28 +00002076bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
2077 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
2078 bool skip = false;
2079
2080 if (VendorCheckEnabled(kBPVendorArm)) {
2081 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
2082 skip |= LogPerformanceWarning(
2083 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
2084 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
2085 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
2086 "image) are actually used. If you need different wrapping modes, disregard this warning.",
2087 VendorSpecificTag(kBPVendorArm));
2088 }
2089
2090 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
2091 skip |= LogPerformanceWarning(
2092 device, kVUID_BestPractices_CreateSampler_LodClamping,
2093 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
2094 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
2095 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
2096 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
2097 }
2098
2099 if (pCreateInfo->mipLodBias != 0.0f) {
2100 skip |=
2101 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
2102 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
2103 "descriptors being created and may cause reduced performance.",
2104 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
2105 }
2106
2107 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2108 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2109 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
2110 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
2111 skip |= LogPerformanceWarning(
2112 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
2113 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
2114 "This will lead to less efficient descriptors being created and may cause reduced performance. "
2115 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
2116 VendorSpecificTag(kBPVendorArm));
2117 }
2118
2119 if (pCreateInfo->unnormalizedCoordinates) {
2120 skip |= LogPerformanceWarning(
2121 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
2122 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
2123 "descriptors being created and may cause reduced performance.",
2124 VendorSpecificTag(kBPVendorArm));
2125 }
2126
2127 if (pCreateInfo->anisotropyEnable) {
2128 skip |= LogPerformanceWarning(
2129 device, kVUID_BestPractices_CreateSampler_Anisotropy,
2130 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
2131 "and may cause reduced performance.",
2132 VendorSpecificTag(kBPVendorArm));
2133 }
2134 }
2135
2136 return skip;
2137}
Sam Walls8e77e4f2020-03-16 20:47:40 +00002138
2139void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
2140
2141bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
2142 // look for a cache hit
2143 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
2144 if (hit != _entries.end()) {
2145 // mark the cache hit as being most recently used
2146 hit->age = iteration++;
2147 return true;
2148 }
2149
2150 // if there's no cache hit, we need to model the entry being inserted into the cache
2151 CacheEntry new_entry = {value, iteration};
2152 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
2153 // if there is still space left in the cache, use the next available slot
2154 *(_entries.begin() + iteration) = new_entry;
2155 } else {
2156 // otherwise replace the least recently used cache entry
2157 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
2158 *lru = new_entry;
2159 }
2160 iteration++;
2161 return false;
2162}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002163
2164bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
2165 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
2166 const auto swapchain_data = GetSwapchainState(swapchain);
2167 bool skip = false;
2168 if (swapchain_data && swapchain_data->images.size() == 0) {
2169 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
2170 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
2171 "vkGetSwapchainImagesKHR after swapchain creation.");
2172 }
2173 return skip;
2174}
2175
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002176void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2177 uint32_t* pQueueFamilyPropertyCount,
2178 VkQueueFamilyProperties* pQueueFamilyProperties) {
2179 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
2180 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002181 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002182 if (bp_pd_state) {
2183 if (!pQueueFamilyProperties) {
2184 if (UNCALLED == bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState)
2185 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState = QUERY_COUNT;
2186 } else { // Save queue family properties
2187 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState = QUERY_DETAILS;
2188 }
2189 }
2190}
2191
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002192void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
2193 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002194 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2195 if (bp_pd_state) {
2196 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2197 }
2198}
2199
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002200void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
2201 VkPhysicalDeviceFeatures2* pFeatures) {
2202 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002203 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2204 if (bp_pd_state) {
2205 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2206 }
2207}
2208
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002209void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
2210 VkPhysicalDeviceFeatures2* pFeatures) {
2211 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002212 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2213 if (bp_pd_state) {
2214 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2215 }
2216}
2217
2218void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
2219 VkSurfaceKHR surface,
2220 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
2221 VkResult result) {
2222 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2223 if (bp_pd_state) {
2224 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2225 }
2226}
2227
2228void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
2229 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2230 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
2231 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2232 if (bp_pd_state) {
2233 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2234 }
2235}
2236
2237void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
2238 VkSurfaceKHR surface,
2239 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
2240 VkResult result) {
2241 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2242 if (bp_pd_state) {
2243 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2244 }
2245}
2246
2247void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
2248 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
2249 VkPresentModeKHR* pPresentModes, VkResult result) {
2250 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2251 if (bp_pd_data) {
2252 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
2253
2254 if (*pPresentModeCount) {
2255 if (call_state < QUERY_COUNT) {
2256 call_state = QUERY_COUNT;
2257 }
2258 }
2259 if (pPresentModes) {
2260 if (call_state < QUERY_DETAILS) {
2261 call_state = QUERY_DETAILS;
2262 }
2263 }
2264 }
2265}
2266
2267void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2268 uint32_t* pSurfaceFormatCount,
2269 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
2270 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2271 if (bp_pd_data) {
2272 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
2273
2274 if (*pSurfaceFormatCount) {
2275 if (call_state < QUERY_COUNT) {
2276 call_state = QUERY_COUNT;
2277 }
2278 }
2279 if (pSurfaceFormats) {
2280 if (call_state < QUERY_DETAILS) {
2281 call_state = QUERY_DETAILS;
2282 }
2283 }
2284 }
2285}
2286
2287void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
2288 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2289 uint32_t* pSurfaceFormatCount,
2290 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
2291 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2292 if (bp_pd_data) {
2293 if (*pSurfaceFormatCount) {
2294 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
2295 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
2296 }
2297 }
2298 if (pSurfaceFormats) {
2299 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
2300 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
2301 }
2302 }
2303 }
2304}
2305
2306void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
2307 uint32_t* pPropertyCount,
2308 VkDisplayPlanePropertiesKHR* pProperties,
2309 VkResult result) {
2310 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2311 if (bp_pd_data) {
2312 if (*pPropertyCount) {
2313 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
2314 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
2315 }
2316 }
2317 if (pProperties) {
2318 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
2319 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
2320 }
2321 }
2322 }
2323}
2324
2325void BestPractices::ManualPostCallRecordCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
2326 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain,
2327 VkResult result) {
2328 if (VK_SUCCESS == result) {
2329 swapchain_bp_state_map.emplace(*pSwapchain, SWAPCHAIN_STATE_BP{});
2330 }
2331}
2332
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002333void BestPractices::PostCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain,
2334 const VkAllocationCallbacks* pAllocator) {
2335 ValidationStateTracker::PostCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002336 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2337 if (swapchain_state_itr != swapchain_bp_state_map.cend()) {
2338 swapchain_bp_state_map.erase(swapchain_state_itr);
2339 }
2340}
2341
2342void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
2343 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
2344 VkResult result) {
2345 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2346 assert(swapchain_state_itr != swapchain_bp_state_map.cend());
2347 auto& swapchain_state = swapchain_state_itr->second;
2348 if (pSwapchainImages || *pSwapchainImageCount) {
2349 if (swapchain_state.vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
2350 swapchain_state.vkGetSwapchainImagesKHRState = QUERY_DETAILS;
2351 }
2352 }
2353}
2354
2355void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
2356 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
2357 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
2358 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
2359 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
2360 }
2361 }
2362}
2363
2364void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo*, const VkAllocationCallbacks*,
2365 VkDevice*, VkResult result) {
2366 if (VK_SUCCESS == result) {
2367 instance_device_bp_state = &phys_device_bp_state_map[gpu];
2368 }
2369}
2370
2371PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
2372 if (phys_device_bp_state_map.count(phys_device) > 0) {
2373 return &phys_device_bp_state_map.at(phys_device);
2374 } else {
2375 return nullptr;
2376 }
2377}
2378
2379const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
2380 if (phys_device_bp_state_map.count(phys_device) > 0) {
2381 return &phys_device_bp_state_map.at(phys_device);
2382 } else {
2383 return nullptr;
2384 }
2385}
2386
2387PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
2388 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2389 if (bp_state) {
2390 return bp_state;
2391 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2392 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2393 } else {
2394 return nullptr;
2395 }
2396}
2397
2398const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
2399 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2400 if (bp_state) {
2401 return bp_state;
2402 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2403 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2404 } else {
2405 return nullptr;
2406 }
2407}