blob: 3dc29086ee9f57c5ce4e077b9c925cecca7ee338 [file] [log] [blame]
sfricke-samsung8f658d42020-05-03 20:12:24 -07001/* Copyright (c) 2015-2017, 2019-2020 The Khronos Group Inc.
2 * Copyright (c) 2015-2017, 2019-2020 Valve Corporation
3 * Copyright (c) 2015-2017, 2019-2020 LunarG, Inc.
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -06004 *
Jon Ashburn3ebf1252016-04-19 11:30:31 -06005 * 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
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -06008 *
Jon Ashburn3ebf1252016-04-19 11:30:31 -06009 * http://www.apache.org/licenses/LICENSE-2.0
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -060010 *
Jon Ashburn3ebf1252016-04-19 11:30:31 -060011 * 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.
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -060016 *
Jon Ashburne922f712015-11-03 13:41:23 -070017 * Author: Mark Lobodzinski <mark@lunarg.com>
18 * Author: Courtney Goeltzenleuchter <courtney@LunarG.com>
Dave Houlton59a20702017-02-02 17:26:23 -070019 * Author: Dave Houlton <daveh@lunarg.com>
Mark Lobodzinski6eda00a2016-02-02 15:55:36 -070020 */
21
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -060022#pragma once
John Zulauff05b3772019-04-03 18:04:23 -060023
24#include <cassert>
25#include <cstddef>
26#include <functional>
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -060027#include <stdbool.h>
John Zulauf965d88d2018-04-12 15:47:26 -060028#include <string>
Mark Lobodzinski1079e1b2016-03-15 14:21:59 -060029#include <vector>
Mark Lobodzinskia0555012018-08-15 16:43:49 -060030#include <set>
John Zulauf2c2ccd42019-04-05 13:13:13 -060031#include "cast_utils.h"
Dave Houlton3c9fca72017-03-27 17:25:54 -060032#include "vk_format_utils.h"
Mark Lobodzinski1079e1b2016-03-15 14:21:59 -060033#include "vk_layer_logging.h"
34
Courtney Goeltzenleuchterd2635502015-10-21 17:08:06 -060035#ifndef WIN32
Mark Lobodzinski64318ba2017-01-26 13:34:13 -070036#include <strings.h> // For ffs()
Courtney Goeltzenleuchter3698c622015-10-27 11:23:21 -060037#else
Mark Lobodzinski64318ba2017-01-26 13:34:13 -070038#include <intrin.h> // For __lzcnt()
Courtney Goeltzenleuchterd2635502015-10-21 17:08:06 -060039#endif
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -060040
Petr Krausc3382e92019-12-14 00:41:30 +010041#define STRINGIFY(s) STRINGIFY_HELPER(s)
42#define STRINGIFY_HELPER(s) #s
43
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -060044#ifdef __cplusplus
John Zulauf965d88d2018-04-12 15:47:26 -060045// Traits objects to allow string_join to operate on collections of const char *
46template <typename String>
47struct StringJoinSizeTrait {
48 static size_t size(const String &str) { return str.size(); }
49};
50
51template <>
52struct StringJoinSizeTrait<const char *> {
53 static size_t size(const char *str) {
54 if (!str) return 0;
55 return strlen(str);
56 }
57};
58// Similar to perl/python join
59// * String must support size, reserve, append, and be default constructable
60// * StringCollection must support size, const forward iteration, and store
61// strings compatible with String::append
62// * Accessor trait can be set if default accessors (compatible with string
63// and const char *) don't support size(StringCollection::value_type &)
64//
65// Return type based on sep type
66template <typename String = std::string, typename StringCollection = std::vector<String>,
67 typename Accessor = StringJoinSizeTrait<typename StringCollection::value_type>>
68static inline String string_join(const String &sep, const StringCollection &strings) {
69 String joined;
70 const size_t count = strings.size();
71 if (!count) return joined;
72
73 // Prereserved storage, s.t. we will execute in linear time (avoids reallocation copies)
74 size_t reserve = (count - 1) * sep.size();
75 for (const auto &str : strings) {
76 reserve += Accessor::size(str); // abstracted to allow const char * type in StringCollection
77 }
78 joined.reserve(reserve + 1);
79
80 // Seps only occur *between* strings entries, so first is special
81 auto current = strings.cbegin();
82 joined.append(*current);
83 ++current;
84 for (; current != strings.cend(); ++current) {
85 joined.append(sep);
86 joined.append(*current);
87 }
88 return joined;
89}
90
91// Requires StringCollection::value_type has a const char * constructor and is compatible the string_join::String above
92template <typename StringCollection = std::vector<std::string>, typename SepString = std::string>
93static inline SepString string_join(const char *sep, const StringCollection &strings) {
94 return string_join<SepString, StringCollection>(SepString(sep), strings);
95}
96
Petr Kraus168417e2019-09-07 16:45:40 +020097static inline std::string string_trim(const std::string &s) {
98 const char *whitespace = " \t\f\v\n\r";
99
100 const auto trimmed_beg = s.find_first_not_of(whitespace);
101 if (trimmed_beg == std::string::npos) return "";
102
103 const auto trimmed_end = s.find_last_not_of(whitespace);
104 assert(trimmed_end != std::string::npos && trimmed_beg <= trimmed_end);
105
106 return s.substr(trimmed_beg, trimmed_end - trimmed_beg + 1);
107}
108
John Zulaufdf851b12018-06-12 14:49:04 -0600109// Perl/Python style join operation for general types using stream semantics
110// Note: won't be as fast as string_join above, but simpler to use (and code)
111// Note: Modifiable reference doesn't match the google style but does match std style for stream handling and algorithms
112template <typename Stream, typename String, typename ForwardIt>
113Stream &stream_join(Stream &stream, const String &sep, ForwardIt first, ForwardIt last) {
114 if (first != last) {
115 stream << *first;
116 ++first;
117 while (first != last) {
118 stream << sep << *first;
119 ++first;
120 }
121 }
122 return stream;
123}
124
125// stream_join For whole collections with forward iterators
126template <typename Stream, typename String, typename Collection>
127Stream &stream_join(Stream &stream, const String &sep, const Collection &values) {
128 return stream_join(stream, sep, values.cbegin(), values.cend());
129}
130
Mark Lobodzinskic1b5b882018-06-25 14:54:04 -0600131typedef void *dispatch_key;
132static inline dispatch_key get_dispatch_key(const void *object) { return (dispatch_key) * (VkLayerDispatchTable **)object; }
133
134VK_LAYER_EXPORT VkLayerInstanceCreateInfo *get_chain_info(const VkInstanceCreateInfo *pCreateInfo, VkLayerFunction func);
135VK_LAYER_EXPORT VkLayerDeviceCreateInfo *get_chain_info(const VkDeviceCreateInfo *pCreateInfo, VkLayerFunction func);
136
Chris Mayer334e72f2018-11-29 14:25:41 +0100137static inline bool IsPowerOfTwo(unsigned x) { return x && !(x & (x - 1)); }
Chris Mayer9bc9d092018-11-12 12:29:10 +0100138
sfricke-samsung8f658d42020-05-03 20:12:24 -0700139static inline uint32_t SampleCountSize(VkSampleCountFlagBits sample_count) {
140 uint32_t size = 0;
141 switch (sample_count) {
142 case VK_SAMPLE_COUNT_1_BIT:
143 size = 1;
144 break;
145 case VK_SAMPLE_COUNT_2_BIT:
146 size = 2;
147 break;
148 case VK_SAMPLE_COUNT_4_BIT:
149 size = 4;
150 break;
151 case VK_SAMPLE_COUNT_8_BIT:
152 size = 8;
153 break;
154 case VK_SAMPLE_COUNT_16_BIT:
155 size = 16;
156 break;
157 case VK_SAMPLE_COUNT_32_BIT:
158 size = 32;
159 break;
160 case VK_SAMPLE_COUNT_64_BIT:
161 size = 64;
162 break;
163 default:
164 size = 0;
165 }
166 return size;
167}
168
sfricke-samsungbd0e8052020-06-06 01:36:39 -0700169static inline bool IsIdentitySwizzle(VkComponentMapping components) {
170 // clang-format off
171 return (
172 ((components.r == VK_COMPONENT_SWIZZLE_IDENTITY) || (components.r == VK_COMPONENT_SWIZZLE_R)) &&
173 ((components.g == VK_COMPONENT_SWIZZLE_IDENTITY) || (components.g == VK_COMPONENT_SWIZZLE_G)) &&
174 ((components.b == VK_COMPONENT_SWIZZLE_IDENTITY) || (components.b == VK_COMPONENT_SWIZZLE_B)) &&
175 ((components.a == VK_COMPONENT_SWIZZLE_IDENTITY) || (components.a == VK_COMPONENT_SWIZZLE_A))
176 );
177 // clang-format on
178}
179
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -0600180extern "C" {
181#endif
182
Jon Ashburnd883d812016-03-24 08:32:09 -0600183#define VK_LAYER_API_VERSION VK_MAKE_VERSION(1, 0, VK_HEADER_VERSION)
Mark Lobodzinskiadaac9d2016-01-08 11:07:56 -0700184
Mark Lobodzinskia9f33492016-01-11 14:17:05 -0700185typedef enum VkStringErrorFlagBits {
Jon Ashburn5484e0c2016-03-08 17:48:44 -0700186 VK_STRING_ERROR_NONE = 0x00000000,
187 VK_STRING_ERROR_LENGTH = 0x00000001,
188 VK_STRING_ERROR_BAD_DATA = 0x00000002,
Mark Lobodzinskia9f33492016-01-11 14:17:05 -0700189} VkStringErrorFlagBits;
190typedef VkFlags VkStringErrorFlags;
Mark Lobodzinski1ed594e2016-02-03 09:57:14 -0700191
Petr Kraus4ed81e32019-09-02 23:41:19 +0200192VK_LAYER_EXPORT void layer_debug_report_actions(debug_report_data *report_data, const VkAllocationCallbacks *pAllocator,
193 const char *layer_identifier);
Mark Young6ba8abe2017-11-09 10:37:04 -0700194
Petr Kraus4ed81e32019-09-02 23:41:19 +0200195VK_LAYER_EXPORT void layer_debug_messenger_actions(debug_report_data *report_data, const VkAllocationCallbacks *pAllocator,
196 const char *layer_identifier);
Mark Lobodzinski1079e1b2016-03-15 14:21:59 -0600197
Mike Stroyana551bc02016-09-28 09:42:28 -0600198VK_LAYER_EXPORT VkStringErrorFlags vk_string_validate(const int max_length, const char *char_array);
Mark Lobodzinskia0555012018-08-15 16:43:49 -0600199VK_LAYER_EXPORT bool white_list(const char *item, const std::set<std::string> &whitelist);
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -0600200
Jon Ashburn5484e0c2016-03-08 17:48:44 -0700201static inline int u_ffs(int val) {
Courtney Goeltzenleuchterd2635502015-10-21 17:08:06 -0600202#ifdef WIN32
Mark Lobodzinski5ddf6c32015-12-16 17:47:28 -0700203 unsigned long bit_pos = 0;
Mike Stroyandebb9842016-01-07 10:05:21 -0700204 if (_BitScanForward(&bit_pos, val) != 0) {
Mark Lobodzinski5ddf6c32015-12-16 17:47:28 -0700205 bit_pos += 1;
206 }
207 return bit_pos;
Courtney Goeltzenleuchterd2635502015-10-21 17:08:06 -0600208#else
Mark Lobodzinski5ddf6c32015-12-16 17:47:28 -0700209 return ffs(val);
Courtney Goeltzenleuchterd2635502015-10-21 17:08:06 -0600210#endif
211}
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -0600212
213#ifdef __cplusplus
214}
215#endif
Jeff Bolz89b9a502019-08-20 08:58:51 -0500216
Bruce Dawson5fab7f82020-06-09 16:23:07 -0700217// Minimum Visual Studio 2015 Update 2, or libc++ with C++17
218#if defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 190023918 && NTDDI_VERSION > NTDDI_WIN10_RS2 && \
219 (!defined(_LIBCPP_VERSION) || __cplusplus >= 201703)
Jeff Bolz89b9a502019-08-20 08:58:51 -0500220#include <shared_mutex>
221#endif
222
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500223class ReadWriteLock {
224 private:
Bruce Dawson5fab7f82020-06-09 16:23:07 -0700225#if defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 190023918 && NTDDI_VERSION > NTDDI_WIN10_RS2 && \
226 (!defined(_LIBCPP_VERSION) || __cplusplus >= 201703)
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500227 typedef std::shared_mutex lock_t;
228#else
229 typedef std::mutex lock_t;
230#endif
231
232 public:
233 void lock() { m_lock.lock(); }
234 bool try_lock() { return m_lock.try_lock(); }
235 void unlock() { m_lock.unlock(); }
Bruce Dawson5fab7f82020-06-09 16:23:07 -0700236#if defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 190023918 && NTDDI_VERSION > NTDDI_WIN10_RS2 && \
237 (!defined(_LIBCPP_VERSION) || __cplusplus >= 201703)
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500238 void lock_shared() { m_lock.lock_shared(); }
239 bool try_lock_shared() { return m_lock.try_lock_shared(); }
240 void unlock_shared() { m_lock.unlock_shared(); }
241#else
242 void lock_shared() { lock(); }
243 bool try_lock_shared() { return try_lock(); }
244 void unlock_shared() { unlock(); }
245#endif
246 private:
247 lock_t m_lock;
248};
249
Bruce Dawson5fab7f82020-06-09 16:23:07 -0700250#if defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 190023918 && NTDDI_VERSION > NTDDI_WIN10_RS2 && \
251 (!defined(_LIBCPP_VERSION) || __cplusplus >= 201703)
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500252typedef std::shared_lock<ReadWriteLock> read_lock_guard_t;
253typedef std::unique_lock<ReadWriteLock> write_lock_guard_t;
254#else
255typedef std::unique_lock<ReadWriteLock> read_lock_guard_t;
256typedef std::unique_lock<ReadWriteLock> write_lock_guard_t;
257#endif
258
Jeff Bolz89b9a502019-08-20 08:58:51 -0500259// Limited concurrent_unordered_map that supports internally-synchronized
260// insert/erase/access. Splits locking across N buckets and uses shared_mutex
261// for read/write locking. Iterators are not supported. The following
262// operations are supported:
263//
264// insert_or_assign: Insert a new element or update an existing element.
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500265// insert: Insert a new element and return whether it was inserted.
Jeff Bolz89b9a502019-08-20 08:58:51 -0500266// erase: Remove an element.
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500267// contains: Returns true if the key is in the map.
Jeff Bolz89b9a502019-08-20 08:58:51 -0500268// find: Returns != end() if found, value is in ret->second.
269// pop: Erases and returns the erased value if found.
270//
271// find/end: find returns a vaguely iterator-like type that can be compared to
272// end and can use iter->second to retrieve the reference. This is to ease porting
273// for existing code that combines the existence check and lookup in a single
274// operation (and thus a single lock). i.e.:
275//
276// auto iter = map.find(key);
277// if (iter != map.end()) {
278// T t = iter->second;
279// ...
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500280//
281// snapshot: Return an array of elements (key, value pairs) that satisfy an optional
282// predicate. This can be used as a substitute for iterators in exceptional cases.
Jeff Bolzb3514112019-08-23 21:46:18 -0500283template <typename Key, typename T, int BUCKETSLOG2 = 2, typename Hash = std::hash<Key>>
Jeff Bolz89b9a502019-08-20 08:58:51 -0500284class vl_concurrent_unordered_map {
Petr Kraus4ed81e32019-09-02 23:41:19 +0200285 public:
Jeff Bolz89b9a502019-08-20 08:58:51 -0500286 void insert_or_assign(const Key &key, const T &value) {
287 uint32_t h = ConcurrentMapHashObject(key);
288 write_lock_guard_t lock(locks[h].lock);
289 maps[h][key] = value;
290 }
291
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500292 bool insert(const Key &key, const T &value) {
293 uint32_t h = ConcurrentMapHashObject(key);
294 write_lock_guard_t lock(locks[h].lock);
295 auto ret = maps[h].insert(typename std::unordered_map<Key, T>::value_type(key, value));
296 return ret.second;
297 }
298
Jeff Bolz89b9a502019-08-20 08:58:51 -0500299 // returns size_type
300 size_t erase(const Key &key) {
301 uint32_t h = ConcurrentMapHashObject(key);
302 write_lock_guard_t lock(locks[h].lock);
303 return maps[h].erase(key);
304 }
305
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500306 bool contains(const Key &key) const {
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500307 uint32_t h = ConcurrentMapHashObject(key);
308 read_lock_guard_t lock(locks[h].lock);
309 return maps[h].count(key) != 0;
310 }
311
Jeff Bolz89b9a502019-08-20 08:58:51 -0500312 // type returned by find() and end().
313 class FindResult {
Petr Kraus4ed81e32019-09-02 23:41:19 +0200314 public:
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500315 FindResult(bool a, T b) : result(a, std::move(b)) {}
Jeff Bolz89b9a502019-08-20 08:58:51 -0500316
317 // == and != only support comparing against end()
318 bool operator==(const FindResult &other) const {
319 if (result.first == false && other.result.first == false) {
320 return true;
321 }
322 return false;
323 }
324 bool operator!=(const FindResult &other) const { return !(*this == other); }
325
326 // Make -> act kind of like an iterator.
327 std::pair<bool, T> *operator->() { return &result; }
328 const std::pair<bool, T> *operator->() const { return &result; }
329
Petr Kraus4ed81e32019-09-02 23:41:19 +0200330 private:
Jeff Bolz89b9a502019-08-20 08:58:51 -0500331 // (found, reference to element)
332 std::pair<bool, T> result;
333 };
334
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500335 // find()/end() return a FindResult containing a copy of the value. For end(),
336 // return a default value.
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500337 FindResult end() const { return FindResult(false, T()); }
Jeff Bolz89b9a502019-08-20 08:58:51 -0500338
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500339 FindResult find(const Key &key) const {
Jeff Bolz89b9a502019-08-20 08:58:51 -0500340 uint32_t h = ConcurrentMapHashObject(key);
341 read_lock_guard_t lock(locks[h].lock);
342
343 auto itr = maps[h].find(key);
344 bool found = itr != maps[h].end();
345
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500346 if (found) {
347 return FindResult(true, itr->second);
348 } else {
349 return end();
350 }
Jeff Bolz89b9a502019-08-20 08:58:51 -0500351 }
352
353 FindResult pop(const Key &key) {
354 uint32_t h = ConcurrentMapHashObject(key);
355 write_lock_guard_t lock(locks[h].lock);
356
357 auto itr = maps[h].find(key);
358 bool found = itr != maps[h].end();
359
360 if (found) {
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500361 auto ret = std::move(FindResult(true, itr->second));
Jeff Bolz89b9a502019-08-20 08:58:51 -0500362 maps[h].erase(itr);
363 return ret;
364 } else {
365 return end();
366 }
367 }
368
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500369 std::vector<std::pair<const Key, T>> snapshot(std::function<bool(T)> f = nullptr) const {
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500370 std::vector<std::pair<const Key, T>> ret;
371 for (int h = 0; h < BUCKETS; ++h) {
372 read_lock_guard_t lock(locks[h].lock);
373 for (auto j : maps[h]) {
374 if (!f || f(j.second)) {
375 ret.push_back(j);
376 }
377 }
378 }
379 return ret;
380 }
381
Petr Kraus4ed81e32019-09-02 23:41:19 +0200382 private:
Jeff Bolz89b9a502019-08-20 08:58:51 -0500383 static const int BUCKETS = (1 << BUCKETSLOG2);
Jeff Bolz89b9a502019-08-20 08:58:51 -0500384
Jeff Bolzb3514112019-08-23 21:46:18 -0500385 std::unordered_map<Key, T, Hash> maps[BUCKETS];
Jeff Bolz89b9a502019-08-20 08:58:51 -0500386 struct {
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500387 mutable ReadWriteLock lock;
Jeff Bolz89b9a502019-08-20 08:58:51 -0500388 // Put each lock on its own cache line to avoid false cache line sharing.
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500389 char padding[(-int(sizeof(ReadWriteLock))) & 63];
Jeff Bolz89b9a502019-08-20 08:58:51 -0500390 } locks[BUCKETS];
391
392 uint32_t ConcurrentMapHashObject(const Key &object) const {
393 uint64_t u64 = (uint64_t)(uintptr_t)object;
394 uint32_t hash = (uint32_t)(u64 >> 32) + (uint32_t)u64;
395 hash ^= (hash >> BUCKETSLOG2) ^ (hash >> (2 * BUCKETSLOG2));
396 hash &= (BUCKETS - 1);
397 return hash;
398 }
399};