blob: fae285f61f99735b51c173f483b98b303becda4e [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) {
1340 const auto last_bound_it = cb_state->lastBound.find(VK_PIPELINE_BIND_POINT_GRAPHICS);
1341 const PIPELINE_STATE* pipeline_state = nullptr;
1342 if (last_bound_it != cb_state->lastBound.cend()) {
1343 pipeline_state = last_bound_it->second.pipeline_state;
1344 }
1345 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
1346 // Verify vertex binding
1347 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1348 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001349 skip |= LogPerformanceWarning(cb_state->commandBuffer, kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
1350 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
1351 report_data->FormatHandle(cb_state->commandBuffer).c_str(),
1352 report_data->FormatHandle(pipeline_state->pipeline).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001353 }
1354 }
1355 }
1356 return skip;
1357}
1358
Sam Walls0961ec02020-03-31 16:39:15 +01001359void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1360 if (VendorCheckEnabled(kBPVendorArm)) {
1361 RecordCmdDrawTypeArm(cmd_buffer, draw_count, caller);
1362 }
1363}
1364
1365void BestPractices::RecordCmdDrawTypeArm(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1366 auto prepass_state = cbDepthPrePassStates.find(cmd_buffer);
1367 if (prepass_state != cbDepthPrePassStates.end() && draw_count >= kDepthPrePassMinDrawCountArm) {
1368 if (prepass_state->second.depthOnly) prepass_state->second.numDrawCallsDepthOnly++;
1369
1370 if (prepass_state->second.depthEqualComparison) prepass_state->second.numDrawCallsDepthEqualCompare++;
1371 }
1372}
1373
Camden5b184be2019-08-13 07:50:19 -06001374bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001375 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001376 bool skip = false;
1377
1378 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001379 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1380 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001381 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001382 }
1383
1384 return skip;
1385}
1386
Sam Walls0961ec02020-03-31 16:39:15 +01001387void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1388 uint32_t firstVertex, uint32_t firstInstance) {
1389 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
1390 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
1391}
1392
Camden5b184be2019-08-13 07:50:19 -06001393bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001394 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001395 bool skip = false;
1396
1397 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001398 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1399 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001400 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001401 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1402
Attilio Provenzano02859b22020-02-27 14:17:28 +00001403 // Check if we reached the limit for small indexed draw calls.
1404 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1405 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1406 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
1407 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1)) {
1408 skip |= VendorCheckEnabled(kBPVendorArm) &&
1409 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
1410 "The command buffer contains many small indexed drawcalls "
1411 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1412 "You can try batching drawcalls or instancing when applicable.",
1413 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1414 }
1415
Sam Walls8e77e4f2020-03-16 20:47:40 +00001416 if (VendorCheckEnabled(kBPVendorArm)) {
1417 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1418 }
1419
1420 return skip;
1421}
1422
1423bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1424 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1425 bool skip = false;
1426
1427 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1428 const auto* cmd_state = GetCBState(commandBuffer);
1429 if (cmd_state == nullptr) return skip;
1430
1431 const auto* ib_state = GetBufferState(cmd_state->index_buffer_binding.buffer);
1432 if (ib_state == nullptr) return skip;
1433
1434 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
1435 const auto& ib_mem_state = *ib_state->binding.mem_state;
1436 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1437 const void* ib_mem = ib_mem_state.p_driver_data;
1438 bool primitive_restart_enable = false;
1439
1440 const auto& pipeline_binding_iter = cmd_state->lastBound.find(VK_PIPELINE_BIND_POINT_GRAPHICS);
1441
1442 if (pipeline_binding_iter != cmd_state->lastBound.end()) {
1443 const auto* pipeline_state = pipeline_binding_iter->second.pipeline_state;
1444 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr)
1445 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
1446 }
1447
1448 // no point checking index buffer if the memory is nonexistant/unmapped, or if there is no graphics pipeline bound to this CB
1449 if (ib_mem && pipeline_binding_iter != cmd_state->lastBound.end()) {
1450 uint32_t scan_stride;
1451 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1452 scan_stride = sizeof(uint8_t);
1453 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1454 scan_stride = sizeof(uint16_t);
1455 } else {
1456 scan_stride = sizeof(uint32_t);
1457 }
1458
1459 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1460 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1461
1462 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1463 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1464 // irrespective of whether or not they're part of the draw call.
1465
1466 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1467 uint32_t min_index = ~0u;
1468 // start with maximum as 0 and adjust to indices in the buffer
1469 uint32_t max_index = 0u;
1470
1471 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
1472 // for the given index buffer
1473 uint32_t vertex_shade_count = 0;
1474
1475 PostTransformLRUCacheModel post_transform_cache;
1476
1477 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
1478 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
1479 // target architecture.
1480 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
1481 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
1482 post_transform_cache.resize(32);
1483
1484 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1485 uint32_t scan_index;
1486 uint32_t primitive_restart_value;
1487 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1488 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1489 primitive_restart_value = 0xFF;
1490 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1491 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1492 primitive_restart_value = 0xFFFF;
1493 } else {
1494 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1495 primitive_restart_value = 0xFFFFFFFF;
1496 }
1497
1498 max_index = std::max(max_index, scan_index);
1499 min_index = std::min(min_index, scan_index);
1500
1501 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
1502 bool in_cache = post_transform_cache.query_cache(scan_index);
1503 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
1504 if (!in_cache) vertex_shade_count++;
1505 }
1506 }
1507
1508 // 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 +01001509 // 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
1510 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001511
1512 if (max_index - min_index >= indexCount) {
1513 skip |= LogPerformanceWarning(
1514 device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1515 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
1516 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
1517 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
1518 "maximum would be loaded, and possibly shaded, whether or not they are used.",
1519 VendorSpecificTag(kBPVendorArm), (static_cast<float>(indexCount) / (max_index - min_index)) * 100.0f);
1520 return skip;
1521 }
1522
1523 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
1524 // 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 +01001525 const size_t refs_per_bucket = 64;
1526 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
1527
1528 const uint32_t n_indices = max_index - min_index + 1;
1529 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
1530 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
1531
1532 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
1533 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00001534
1535 // To avoid using too much memory, we run over the indices again.
1536 // Knowing the size from the last scan allows us to record index usage with bitsets
1537 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1538 uint32_t scan_index;
1539 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1540 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1541 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1542 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1543 } else {
1544 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1545 }
1546 // keep track of the set of all indices used to reference vertices in the draw call
1547 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01001548 size_t bitset_bucket_index = index_offset / refs_per_bucket;
1549 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001550 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
1551 }
1552
1553 uint32_t vertex_reference_count = 0;
1554 for (const auto& bitset : vertex_reference_buckets) {
1555 vertex_reference_count += static_cast<uint32_t>(bitset.count());
1556 }
1557
1558 // low index buffer utilization implies that: of the vertices available to the draw call, not all are utilized
1559 float utilization = static_cast<float>(vertex_reference_count) / (max_index - min_index + 1);
1560 // low hit rate (high miss rate) implies the order of indices in the draw call may be possible to improve
1561 float cache_hit_rate = static_cast<float>(vertex_reference_count) / vertex_shade_count;
1562
1563 if (utilization < 0.5f) {
1564 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1565 "%s The indices which were specified for the draw call only utilise approximately "
1566 "%.02f%% of the bound vertex buffer.",
1567 VendorSpecificTag(kBPVendorArm), utilization);
1568 }
1569
1570 if (cache_hit_rate <= 0.5f) {
1571 skip |=
1572 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
1573 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
1574 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
1575 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
1576 "recently shaded vertices.",
1577 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
1578 }
1579 }
1580
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001581 return skip;
1582}
1583
Attilio Provenzano02859b22020-02-27 14:17:28 +00001584void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1585 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1586 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
1587 firstInstance);
1588
1589 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1590 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
1591 cmd_state->small_indexed_draw_call_count++;
1592 }
1593}
1594
Sam Walls0961ec02020-03-31 16:39:15 +01001595void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1596 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1597 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1598 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
1599}
1600
sfricke-samsung681ab7b2020-10-29 01:53:35 -07001601bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1602 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
1603 uint32_t maxDrawCount, uint32_t stride) const {
1604 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
1605
1606 return skip;
1607}
1608
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001609bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
1610 VkDeviceSize offset, VkBuffer countBuffer,
1611 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
1612 uint32_t stride) const {
1613 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06001614
1615 return skip;
1616}
1617
1618bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001619 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001620 bool skip = false;
1621
1622 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001623 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1624 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001625 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001626 }
1627
1628 return skip;
1629}
1630
Sam Walls0961ec02020-03-31 16:39:15 +01001631void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1632 uint32_t count, uint32_t stride) {
1633 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
1634 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
1635}
1636
Camden5b184be2019-08-13 07:50:19 -06001637bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001638 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001639 bool skip = false;
1640
1641 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001642 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1643 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001644 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001645 }
1646
1647 return skip;
1648}
1649
Sam Walls0961ec02020-03-31 16:39:15 +01001650void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1651 uint32_t count, uint32_t stride) {
1652 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
1653 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
1654}
1655
Camden5b184be2019-08-13 07:50:19 -06001656bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001657 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06001658 bool skip = false;
1659
1660 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001661 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
1662 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
1663 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
1664 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06001665 }
1666
1667 return skip;
1668}
Camden83a9c372019-08-14 11:41:38 -06001669
Sam Walls0961ec02020-03-31 16:39:15 +01001670bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
1671 bool skip = false;
1672
1673 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
1674
1675 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1676
1677 if (prepass_state == cbDepthPrePassStates.end()) return skip;
1678
1679 bool uses_depth = (prepass_state->second.depthAttachment || prepass_state->second.colorAttachment) &&
1680 prepass_state->second.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
1681 prepass_state->second.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
1682 if (uses_depth) {
1683 skip |= LogPerformanceWarning(
1684 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
1685 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
1686 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
1687 "case, using depth pre-passes for hidden surface removal may worsen performance.",
1688 VendorSpecificTag(kBPVendorArm));
1689 }
1690
1691 return skip;
1692}
1693
Camden Stocker9c051442019-11-06 14:28:43 -08001694bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
1695 const char* api_name) const {
1696 bool skip = false;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001697 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08001698
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001699 if (bp_pd_state) {
1700 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
1701 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
1702 "Potential problem with calling %s() without first retrieving properties from "
1703 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
1704 api_name);
1705 }
Camden Stocker9c051442019-11-06 14:28:43 -08001706 }
1707
1708 return skip;
1709}
1710
Camden83a9c372019-08-14 11:41:38 -06001711bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001712 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06001713 bool skip = false;
1714
Camden Stocker9c051442019-11-06 14:28:43 -08001715 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06001716
Camden Stocker9c051442019-11-06 14:28:43 -08001717 return skip;
1718}
1719
1720bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
1721 uint32_t planeIndex,
1722 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
1723 bool skip = false;
1724
1725 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
1726
1727 return skip;
1728}
1729
1730bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
1731 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
1732 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
1733 bool skip = false;
1734
1735 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06001736
1737 return skip;
1738}
Camden05de2d42019-08-19 10:23:56 -06001739
1740bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001741 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06001742 bool skip = false;
1743
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001744 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
Camden05de2d42019-08-19 10:23:56 -06001745
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001746 if ((swapchain_state_itr != swapchain_bp_state_map.cend()) && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06001747 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001748 if (swapchain_state_itr->second.vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001749 skip |=
1750 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
1751 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
1752 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06001753 }
1754 }
1755
1756 return skip;
1757}
1758
1759// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001760bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
1761 uint32_t requested_queue_family_property_count,
1762 bool qfp_null, const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06001763 bool skip = false;
1764 if (!qfp_null) {
1765 // 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 -06001766 const auto* bp_pd_state = GetPhysicalDeviceStateBP(pd_state->phys_device);
1767 if (bp_pd_state) {
1768 if (UNCALLED == bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState) {
1769 skip |= LogWarning(
1770 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
1771 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
1772 "recommended "
1773 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
1774 caller_name, caller_name);
1775 // Then verify that pCount that is passed in on second call matches what was returned
1776 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
1777 skip |=
1778 LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
1779 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
1780 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
1781 ". It is recommended to instead receive all the properties by calling %s with "
1782 "pQueueFamilyPropertyCount that was "
1783 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
1784 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
1785 caller_name);
1786 }
Camden05de2d42019-08-19 10:23:56 -06001787 }
1788 }
1789
1790 return skip;
1791}
1792
Jeff Bolz5c801d12019-10-09 10:38:45 -05001793bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
1794 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06001795 bool skip = false;
1796
1797 for (uint32_t i = 0; i < bindInfoCount; i++) {
1798 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureState(pBindInfos[i].accelerationStructure);
1799 if (!as_state->memory_requirements_checked) {
1800 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
1801 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
1802 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001803 skip |= LogWarning(
1804 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06001805 "vkBindAccelerationStructureMemoryNV(): "
1806 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
1807 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
1808 }
1809 }
1810
1811 return skip;
1812}
1813
Camden05de2d42019-08-19 10:23:56 -06001814bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
1815 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001816 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001817 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1818 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001819 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001820 (nullptr == pQueueFamilyProperties),
1821 "vkGetPhysicalDeviceQueueFamilyProperties()");
1822}
1823
Jeff Bolz5c801d12019-10-09 10:38:45 -05001824bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(
1825 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount,
1826 VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001827 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1828 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001829 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001830 (nullptr == pQueueFamilyProperties),
1831 "vkGetPhysicalDeviceQueueFamilyProperties2()");
1832}
1833
Jeff Bolz5c801d12019-10-09 10:38:45 -05001834bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
1835 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount,
1836 VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001837 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1838 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001839 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001840 (nullptr == pQueueFamilyProperties),
1841 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
1842}
1843
1844bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
1845 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001846 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06001847 if (!pSurfaceFormats) return false;
1848 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06001849 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
1850 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06001851 bool skip = false;
1852 if (call_state == UNCALLED) {
1853 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
1854 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001855 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
1856 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
1857 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06001858 } else {
1859 auto prev_format_count = (uint32_t)physical_device_state->surface_formats.size();
Peter Chene191bd72019-09-16 13:04:37 -04001860 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001861 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
1862 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
1863 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
1864 "when pSurfaceFormatCount was NULL.",
1865 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06001866 }
1867 }
1868 return skip;
1869}
Camden Stocker23cc47d2019-09-03 14:53:57 -06001870
1871bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001872 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001873 bool skip = false;
1874
1875 for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; bindIdx++) {
1876 const VkBindSparseInfo& bindInfo = pBindInfo[bindIdx];
1877 // 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 -05001878 std::unordered_set<const IMAGE_STATE*> sparse_images;
1879 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
1880 // in RecordQueueBindSparse.
1881 std::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06001882 // If we're binding sparse image memory make sure reqs were queried and note if metadata is required and bound
1883 for (uint32_t i = 0; i < bindInfo.imageBindCount; ++i) {
1884 const auto& image_bind = bindInfo.pImageBinds[i];
1885 auto image_state = GetImageState(image_bind.image);
1886 if (!image_state)
1887 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1888 sparse_images.insert(image_state);
1889 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1890 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1891 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001892 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1893 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1894 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1895 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001896 }
1897 }
1898 if (!image_state->memory_requirements_checked) {
1899 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001900 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1901 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1902 "vkGetImageMemoryRequirements() to retrieve requirements.",
1903 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001904 }
1905 }
1906 for (uint32_t i = 0; i < bindInfo.imageOpaqueBindCount; ++i) {
1907 const auto& image_opaque_bind = bindInfo.pImageOpaqueBinds[i];
1908 auto image_state = GetImageState(bindInfo.pImageOpaqueBinds[i].image);
1909 if (!image_state)
1910 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1911 sparse_images.insert(image_state);
1912 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1913 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1914 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001915 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1916 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1917 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1918 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001919 }
1920 }
1921 if (!image_state->memory_requirements_checked) {
1922 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001923 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1924 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1925 "vkGetImageMemoryRequirements() to retrieve requirements.",
1926 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001927 }
1928 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1929 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001930 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06001931 }
1932 }
1933 }
1934 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001935 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
1936 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001937 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001938 skip |= LogWarning(sparse_image_state->image, kVUID_Core_MemTrack_InvalidState,
1939 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
1940 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
1941 report_data->FormatHandle(sparse_image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001942 }
1943 }
1944 }
1945
1946 return skip;
1947}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001948
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001949void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
1950 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001951 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001952 return;
1953 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001954
1955 for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; bindIdx++) {
1956 const VkBindSparseInfo& bindInfo = pBindInfo[bindIdx];
1957 for (uint32_t i = 0; i < bindInfo.imageOpaqueBindCount; ++i) {
1958 const auto& image_opaque_bind = bindInfo.pImageOpaqueBinds[i];
1959 auto image_state = GetImageState(bindInfo.pImageOpaqueBinds[i].image);
1960 if (!image_state)
1961 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1962 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1963 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
1964 image_state->sparse_metadata_bound = true;
1965 }
1966 }
1967 }
1968 }
1969}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001970
1971bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06001972 const VkClearAttachment* pAttachments, uint32_t rectCount,
1973 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001974 bool skip = false;
1975 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
1976 if (!cb_node) return skip;
1977
Camden Stockerf55721f2019-09-09 11:04:49 -06001978 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001979 if (!cb_node->hasDrawCmd && (cb_node->activeRenderPassBeginInfo.renderArea.extent.width == pRects[0].rect.extent.width) &&
1980 (cb_node->activeRenderPassBeginInfo.renderArea.extent.height == pRects[0].rect.extent.height)) {
1981 // There are times where app needs to use ClearAttachments (generally when reusing a buffer inside of a render pass)
1982 // This warning should be made more specific. It'd be best to avoid triggering this test if it's a use that must call
1983 // CmdClearAttachments.
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001984 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
1985 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds. It is recommended you "
1986 "use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
1987 report_data->FormatHandle(commandBuffer).c_str());
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001988 }
1989
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001990 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
1991 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06001992 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001993 if (rp) {
1994 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
1995
1996 for (uint32_t i = 0; i < attachmentCount; i++) {
1997 auto& attachment = pAttachments[i];
1998 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
1999 uint32_t color_attachment = attachment.colorAttachment;
2000 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
2001
2002 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2003 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2004 skip |= LogPerformanceWarning(
2005 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2006 "vkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
2007 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2008 "it is more efficient.",
2009 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
2010 }
2011 }
2012 }
2013
2014 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
2015 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2016
2017 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2018 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2019 skip |= LogPerformanceWarning(
2020 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2021 "vkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
2022 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2023 "it is more efficient.",
2024 report_data->FormatHandle(commandBuffer).c_str());
2025 }
2026 }
2027 }
2028
2029 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
2030 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2031
2032 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2033 if (rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2034 skip |= LogPerformanceWarning(
2035 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2036 "vkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
2037 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2038 "it is more efficient.",
2039 report_data->FormatHandle(commandBuffer).c_str());
2040 }
2041 }
2042 }
2043 }
2044 }
2045
Camden Stockerf55721f2019-09-09 11:04:49 -06002046 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002047}
Attilio Provenzano02859b22020-02-27 14:17:28 +00002048
2049bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2050 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2051 const VkImageResolve* pRegions) const {
2052 bool skip = false;
2053
2054 skip |= VendorCheckEnabled(kBPVendorArm) &&
2055 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
2056 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
2057 "This is a very slow and extremely bandwidth intensive path. "
2058 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2059 VendorSpecificTag(kBPVendorArm));
2060
2061 return skip;
2062}
2063
Jeff Leger178b1e52020-10-05 12:22:23 -04002064bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2065 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
2066 bool skip = false;
2067
2068 skip |= VendorCheckEnabled(kBPVendorArm) &&
2069 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
2070 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
2071 "This is a very slow and extremely bandwidth intensive path. "
2072 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2073 VendorSpecificTag(kBPVendorArm));
2074
2075 return skip;
2076}
2077
Attilio Provenzano02859b22020-02-27 14:17:28 +00002078bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
2079 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
2080 bool skip = false;
2081
2082 if (VendorCheckEnabled(kBPVendorArm)) {
2083 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
2084 skip |= LogPerformanceWarning(
2085 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
2086 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
2087 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
2088 "image) are actually used. If you need different wrapping modes, disregard this warning.",
2089 VendorSpecificTag(kBPVendorArm));
2090 }
2091
2092 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
2093 skip |= LogPerformanceWarning(
2094 device, kVUID_BestPractices_CreateSampler_LodClamping,
2095 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
2096 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
2097 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
2098 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
2099 }
2100
2101 if (pCreateInfo->mipLodBias != 0.0f) {
2102 skip |=
2103 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
2104 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
2105 "descriptors being created and may cause reduced performance.",
2106 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
2107 }
2108
2109 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2110 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2111 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
2112 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
2113 skip |= LogPerformanceWarning(
2114 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
2115 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
2116 "This will lead to less efficient descriptors being created and may cause reduced performance. "
2117 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
2118 VendorSpecificTag(kBPVendorArm));
2119 }
2120
2121 if (pCreateInfo->unnormalizedCoordinates) {
2122 skip |= LogPerformanceWarning(
2123 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
2124 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
2125 "descriptors being created and may cause reduced performance.",
2126 VendorSpecificTag(kBPVendorArm));
2127 }
2128
2129 if (pCreateInfo->anisotropyEnable) {
2130 skip |= LogPerformanceWarning(
2131 device, kVUID_BestPractices_CreateSampler_Anisotropy,
2132 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
2133 "and may cause reduced performance.",
2134 VendorSpecificTag(kBPVendorArm));
2135 }
2136 }
2137
2138 return skip;
2139}
Sam Walls8e77e4f2020-03-16 20:47:40 +00002140
2141void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
2142
2143bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
2144 // look for a cache hit
2145 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
2146 if (hit != _entries.end()) {
2147 // mark the cache hit as being most recently used
2148 hit->age = iteration++;
2149 return true;
2150 }
2151
2152 // if there's no cache hit, we need to model the entry being inserted into the cache
2153 CacheEntry new_entry = {value, iteration};
2154 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
2155 // if there is still space left in the cache, use the next available slot
2156 *(_entries.begin() + iteration) = new_entry;
2157 } else {
2158 // otherwise replace the least recently used cache entry
2159 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
2160 *lru = new_entry;
2161 }
2162 iteration++;
2163 return false;
2164}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002165
2166bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
2167 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
2168 const auto swapchain_data = GetSwapchainState(swapchain);
2169 bool skip = false;
2170 if (swapchain_data && swapchain_data->images.size() == 0) {
2171 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
2172 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
2173 "vkGetSwapchainImagesKHR after swapchain creation.");
2174 }
2175 return skip;
2176}
2177
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002178void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2179 uint32_t* pQueueFamilyPropertyCount,
2180 VkQueueFamilyProperties* pQueueFamilyProperties) {
2181 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
2182 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002183 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002184 if (bp_pd_state) {
2185 if (!pQueueFamilyProperties) {
2186 if (UNCALLED == bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState)
2187 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState = QUERY_COUNT;
2188 } else { // Save queue family properties
2189 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState = QUERY_DETAILS;
2190 }
2191 }
2192}
2193
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002194void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
2195 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002196 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2197 if (bp_pd_state) {
2198 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2199 }
2200}
2201
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002202void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
2203 VkPhysicalDeviceFeatures2* pFeatures) {
2204 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002205 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2206 if (bp_pd_state) {
2207 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2208 }
2209}
2210
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002211void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
2212 VkPhysicalDeviceFeatures2* pFeatures) {
2213 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002214 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2215 if (bp_pd_state) {
2216 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2217 }
2218}
2219
2220void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
2221 VkSurfaceKHR surface,
2222 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
2223 VkResult result) {
2224 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2225 if (bp_pd_state) {
2226 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2227 }
2228}
2229
2230void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
2231 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2232 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
2233 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2234 if (bp_pd_state) {
2235 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2236 }
2237}
2238
2239void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
2240 VkSurfaceKHR surface,
2241 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
2242 VkResult result) {
2243 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2244 if (bp_pd_state) {
2245 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2246 }
2247}
2248
2249void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
2250 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
2251 VkPresentModeKHR* pPresentModes, VkResult result) {
2252 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2253 if (bp_pd_data) {
2254 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
2255
2256 if (*pPresentModeCount) {
2257 if (call_state < QUERY_COUNT) {
2258 call_state = QUERY_COUNT;
2259 }
2260 }
2261 if (pPresentModes) {
2262 if (call_state < QUERY_DETAILS) {
2263 call_state = QUERY_DETAILS;
2264 }
2265 }
2266 }
2267}
2268
2269void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2270 uint32_t* pSurfaceFormatCount,
2271 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
2272 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2273 if (bp_pd_data) {
2274 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
2275
2276 if (*pSurfaceFormatCount) {
2277 if (call_state < QUERY_COUNT) {
2278 call_state = QUERY_COUNT;
2279 }
2280 }
2281 if (pSurfaceFormats) {
2282 if (call_state < QUERY_DETAILS) {
2283 call_state = QUERY_DETAILS;
2284 }
2285 }
2286 }
2287}
2288
2289void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
2290 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2291 uint32_t* pSurfaceFormatCount,
2292 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
2293 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2294 if (bp_pd_data) {
2295 if (*pSurfaceFormatCount) {
2296 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
2297 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
2298 }
2299 }
2300 if (pSurfaceFormats) {
2301 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
2302 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
2303 }
2304 }
2305 }
2306}
2307
2308void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
2309 uint32_t* pPropertyCount,
2310 VkDisplayPlanePropertiesKHR* pProperties,
2311 VkResult result) {
2312 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2313 if (bp_pd_data) {
2314 if (*pPropertyCount) {
2315 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
2316 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
2317 }
2318 }
2319 if (pProperties) {
2320 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
2321 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
2322 }
2323 }
2324 }
2325}
2326
2327void BestPractices::ManualPostCallRecordCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
2328 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain,
2329 VkResult result) {
2330 if (VK_SUCCESS == result) {
2331 swapchain_bp_state_map.emplace(*pSwapchain, SWAPCHAIN_STATE_BP{});
2332 }
2333}
2334
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002335void BestPractices::PostCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain,
2336 const VkAllocationCallbacks* pAllocator) {
2337 ValidationStateTracker::PostCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002338 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2339 if (swapchain_state_itr != swapchain_bp_state_map.cend()) {
2340 swapchain_bp_state_map.erase(swapchain_state_itr);
2341 }
2342}
2343
2344void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
2345 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
2346 VkResult result) {
2347 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2348 assert(swapchain_state_itr != swapchain_bp_state_map.cend());
2349 auto& swapchain_state = swapchain_state_itr->second;
2350 if (pSwapchainImages || *pSwapchainImageCount) {
2351 if (swapchain_state.vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
2352 swapchain_state.vkGetSwapchainImagesKHRState = QUERY_DETAILS;
2353 }
2354 }
2355}
2356
2357void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
2358 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
2359 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
2360 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
2361 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
2362 }
2363 }
2364}
2365
2366void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo*, const VkAllocationCallbacks*,
2367 VkDevice*, VkResult result) {
2368 if (VK_SUCCESS == result) {
2369 instance_device_bp_state = &phys_device_bp_state_map[gpu];
2370 }
2371}
2372
2373PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
2374 if (phys_device_bp_state_map.count(phys_device) > 0) {
2375 return &phys_device_bp_state_map.at(phys_device);
2376 } else {
2377 return nullptr;
2378 }
2379}
2380
2381const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
2382 if (phys_device_bp_state_map.count(phys_device) > 0) {
2383 return &phys_device_bp_state_map.at(phys_device);
2384 } else {
2385 return nullptr;
2386 }
2387}
2388
2389PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
2390 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2391 if (bp_state) {
2392 return bp_state;
2393 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2394 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2395 } else {
2396 return nullptr;
2397 }
2398}
2399
2400const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
2401 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2402 if (bp_state) {
2403 return bp_state;
2404 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2405 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2406 } else {
2407 return nullptr;
2408 }
2409}