133657a7c4bd1b7518da52d4c7d96ed1ff40856b
[platform/upstream/Vulkan-LoaderAndValidationLayers.git] / layers / descriptor_sets.h
1 /* Copyright (c) 2015-2016 The Khronos Group Inc.
2  * Copyright (c) 2015-2016 Valve Corporation
3  * Copyright (c) 2015-2016 LunarG, Inc.
4  * Copyright (C) 2015-2016 Google Inc.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * Author: Tobin Ehlis <tobine@google.com>
19  *         John Zulauf <jzulauf@lunarg.com>
20  */
21 #ifndef CORE_VALIDATION_DESCRIPTOR_SETS_H_
22 #define CORE_VALIDATION_DESCRIPTOR_SETS_H_
23
24 #include "core_validation_error_enums.h"
25 #include "vk_validation_error_messages.h"
26 #include "core_validation_types.h"
27 #include "hash_vk_types.h"
28 #include "vk_layer_logging.h"
29 #include "vk_layer_utils.h"
30 #include "vk_safe_struct.h"
31 #include "vulkan/vk_layer.h"
32 #include "vk_object_types.h"
33 #include <map>
34 #include <memory>
35 #include <set>
36 #include <unordered_map>
37 #include <unordered_set>
38 #include <vector>
39
40 using core_validation::layer_data;
41
42 // Descriptor Data structures
43 namespace cvdescriptorset {
44
45 // Utility structs/classes/types
46 // Index range for global indices below, end is exclusive, i.e. [start,end)
47 struct IndexRange {
48     IndexRange(uint32_t start_in, uint32_t end_in) : start(start_in), end(end_in) {}
49     IndexRange() = default;
50     uint32_t start;
51     uint32_t end;
52 };
53 typedef std::map<uint32_t, descriptor_req> BindingReqMap;
54
55 /*
56  * DescriptorSetLayoutDef/DescriptorSetLayout classes
57  *
58  * Overview - These two classes encapsulate the Vulkan VkDescriptorSetLayout data (layout).
59  *   A layout consists of some number of bindings, each of which has a binding#, a
60  *   type, descriptor count, stage flags, and pImmutableSamplers.
61
62  *   The DescriptorSetLayoutDef represents a canonicalization of the input data and contains
63  *   neither per handle or per device state.  It is possible for different handles on
64  *   different devices to share a common def.  This is used and useful for quick compatibiltiy
65  *   validation.  The DescriptorSetLayout refers to a DescriptorSetLayoutDef and contains
66  *   all per handle state.
67  *
68  * Index vs Binding - A layout is created with an array of VkDescriptorSetLayoutBinding
69  *  where each array index will have a corresponding binding# that is defined in that struct.
70  *  The binding#, then, is decoupled from VkDescriptorSetLayoutBinding index, which allows
71  *  bindings to be defined out-of-order. This DescriptorSetLayout class, however, stores
72  *  the bindings internally in-order. This is useful for operations which may "roll over"
73  *  from a single binding to the next consecutive binding.
74  *
75  *  Note that although the bindings are stored in-order, there still may be "gaps" in the
76  *  binding#. For example, if the binding creation order is 8, 7, 10, 3, 4, then the
77  *  internal binding array will have five entries stored in binding order 3, 4, 7, 8, 10.
78  *  To process all of the bindings in a layout you can iterate from 0 to GetBindingCount()
79  *  and use the Get*FromIndex() functions for each index. To just process a single binding,
80  *  use the Get*FromBinding() functions.
81  *
82  * Global Index - The binding vector index has as many indices as there are bindings.
83  *  This class also has the concept of a Global Index. For the global index functions,
84  *  there are as many global indices as there are descriptors in the layout.
85  *  For the global index, consider all of the bindings to be a flat array where
86  *  descriptor 0 of of the lowest binding# is index 0 and each descriptor in the layout
87  *  increments from there. So if the lowest binding# in this example had descriptorCount of
88  *  10, then the GlobalStartIndex of the 2nd lowest binding# will be 10 where 0-9 are the
89  *  global indices for the lowest binding#.
90  */
91 class DescriptorSetLayoutDef {
92    public:
93     // Constructors and destructor
94     DescriptorSetLayoutDef(const VkDescriptorSetLayoutCreateInfo *p_create_info);
95     size_t hash() const;
96
97     uint32_t GetTotalDescriptorCount() const { return descriptor_count_; };
98     uint32_t GetDynamicDescriptorCount() const { return dynamic_descriptor_count_; };
99     VkDescriptorSetLayoutCreateFlags GetCreateFlags() const { return flags_; }
100     // For a given binding, return the number of descriptors in that binding and all successive bindings
101     uint32_t GetBindingCount() const { return binding_count_; };
102     // Non-empty binding numbers in order
103     const std::set<uint32_t> &GetSortedBindingSet() const { return non_empty_bindings_; }
104     // Return true if given binding is present in this layout
105     bool HasBinding(const uint32_t binding) const { return binding_to_index_map_.count(binding) > 0; };
106     // Return true if this DSL Def (referenced by the 1st layout) is compatible with another DSL Def (ref'd from the 2nd layout)
107     // else return false and update error_msg with description of incompatibility
108     bool IsCompatible(VkDescriptorSetLayout, VkDescriptorSetLayout, DescriptorSetLayoutDef const *const, std::string *) const;
109     // Return true if binding 1 beyond given exists and has same type, stageFlags & immutable sampler use
110     bool IsNextBindingConsistent(const uint32_t) const;
111     uint32_t GetIndexFromBinding(uint32_t binding) const;
112     // Various Get functions that can either be passed a binding#, which will
113     //  be automatically translated into the appropriate index, or the index# can be passed in directly
114     uint32_t GetMaxBinding() const { return bindings_[bindings_.size() - 1].binding; }
115     VkDescriptorSetLayoutBinding const *GetDescriptorSetLayoutBindingPtrFromIndex(const uint32_t) const;
116     VkDescriptorSetLayoutBinding const *GetDescriptorSetLayoutBindingPtrFromBinding(uint32_t binding) const {
117         return GetDescriptorSetLayoutBindingPtrFromIndex(GetIndexFromBinding(binding));
118     }
119     const std::vector<safe_VkDescriptorSetLayoutBinding> &GetBindings() const { return bindings_; }
120     uint32_t GetDescriptorCountFromIndex(const uint32_t) const;
121     uint32_t GetDescriptorCountFromBinding(const uint32_t binding) const {
122         return GetDescriptorCountFromIndex(GetIndexFromBinding(binding));
123     }
124     VkDescriptorType GetTypeFromIndex(const uint32_t) const;
125     VkDescriptorType GetTypeFromBinding(const uint32_t binding) const { return GetTypeFromIndex(GetIndexFromBinding(binding)); }
126     VkShaderStageFlags GetStageFlagsFromIndex(const uint32_t) const;
127     VkShaderStageFlags GetStageFlagsFromBinding(const uint32_t binding) const {
128         return GetStageFlagsFromIndex(GetIndexFromBinding(binding));
129     }
130     uint32_t GetIndexFromGlobalIndex(const uint32_t global_index) const;
131     VkDescriptorType GetTypeFromGlobalIndex(const uint32_t global_index) const {
132         return GetTypeFromIndex(GetIndexFromGlobalIndex(global_index));
133     }
134     VkSampler const *GetImmutableSamplerPtrFromBinding(const uint32_t) const;
135     VkSampler const *GetImmutableSamplerPtrFromIndex(const uint32_t) const;
136     // For a given binding and array index, return the corresponding index into the dynamic offset array
137     int32_t GetDynamicOffsetIndexFromBinding(uint32_t binding) const {
138         auto dyn_off = binding_to_dynamic_array_idx_map_.find(binding);
139         if (dyn_off == binding_to_dynamic_array_idx_map_.end()) {
140             assert(0);  // Requesting dyn offset for invalid binding/array idx pair
141             return -1;
142         }
143         return dyn_off->second;
144     }
145     // For a particular binding, get the global index range
146     //  This call should be guarded by a call to "HasBinding(binding)" to verify that the given binding exists
147     const IndexRange &GetGlobalIndexRangeFromBinding(const uint32_t) const;
148
149     // Helper function to get the next valid binding for a descriptor
150     uint32_t GetNextValidBinding(const uint32_t) const;
151     // For a particular binding starting at offset and having update_count descriptors
152     //  updated, verify that for any binding boundaries crossed, the update is consistent
153     bool VerifyUpdateConsistency(uint32_t, uint32_t, uint32_t, const char *, const VkDescriptorSet, std::string *) const;
154     bool IsPushDescriptor() const { return GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR; };
155
156     struct BindingTypeStats {
157         uint32_t dynamic_buffer_count;
158         uint32_t non_dynamic_buffer_count;
159         uint32_t image_sampler_count;
160     };
161     const BindingTypeStats &GetBindingTypeStats() const { return binding_type_stats_; }
162
163    private:
164     // Only the first two data members are used for hash and equality checks, the other members are derived from them, and are used
165     // to speed up the various lookups/queries/validations
166     VkDescriptorSetLayoutCreateFlags flags_;
167     std::vector<safe_VkDescriptorSetLayoutBinding> bindings_;
168
169     // Convenience data structures for rapid lookup of various descriptor set layout properties
170     std::set<uint32_t> non_empty_bindings_;  // Containing non-emtpy bindings in numerical order
171     std::unordered_map<uint32_t, uint32_t> binding_to_index_map_;
172     // The following map allows an non-iterative lookup of a binding from a global index...
173     std::map<uint32_t, uint32_t> global_start_to_index_map_;  // The index corresponding for a starting global (descriptor) index
174     std::unordered_map<uint32_t, IndexRange> binding_to_global_index_range_map_;  // range is exclusive of .end
175     // For a given binding map to associated index in the dynamic offset array
176     std::unordered_map<uint32_t, uint32_t> binding_to_dynamic_array_idx_map_;
177
178     uint32_t binding_count_;  // # of bindings in this layout
179     uint32_t descriptor_count_;  // total # descriptors in this layout
180     uint32_t dynamic_descriptor_count_;
181     BindingTypeStats binding_type_stats_;
182 };
183
184 static bool operator==(const DescriptorSetLayoutDef &lhs, const DescriptorSetLayoutDef &rhs) {
185     return (lhs.GetCreateFlags() == rhs.GetCreateFlags()) && (lhs.GetBindings() == rhs.GetBindings());
186 }
187
188 // Canonical dictionary of DSL definitions -- independent of device or handle
189 using DescriptorSetLayoutDict = hash_util::Dictionary<DescriptorSetLayoutDef, hash_util::HasHashMember<DescriptorSetLayoutDef>>;
190 using DescriptorSetLayoutId = DescriptorSetLayoutDict::Id;
191
192 class DescriptorSetLayout {
193    public:
194     // Constructors and destructor
195     DescriptorSetLayout(const VkDescriptorSetLayoutCreateInfo *p_create_info, const VkDescriptorSetLayout layout);
196     // Validate create info - should be called prior to creation
197     static bool ValidateCreateInfo(const debug_report_data *, const VkDescriptorSetLayoutCreateInfo *, const bool, const uint32_t);
198     bool HasBinding(const uint32_t binding) const { return layout_id_->HasBinding(binding); }
199     // Return true if this layout is compatible with passed in layout from a pipelineLayout,
200     //   else return false and update error_msg with description of incompatibility
201     bool IsCompatible(DescriptorSetLayout const *const, std::string *) const;
202     // Straightforward Get functions
203     VkDescriptorSetLayout GetDescriptorSetLayout() const { return layout_; };
204     bool IsDestroyed() const { return layout_destroyed_; }
205     void MarkDestroyed() { layout_destroyed_ = true; }
206     const DescriptorSetLayoutDef *get_layout_def() const { return layout_id_.get(); }
207     DescriptorSetLayoutId get_layout_id() const { return layout_id_; }
208     uint32_t GetTotalDescriptorCount() const { return layout_id_->GetTotalDescriptorCount(); };
209     uint32_t GetDynamicDescriptorCount() const { return layout_id_->GetDynamicDescriptorCount(); };
210     uint32_t GetBindingCount() const { return layout_id_->GetBindingCount(); };
211     VkDescriptorSetLayoutCreateFlags GetCreateFlags() const { return layout_id_->GetCreateFlags(); }
212     bool IsNextBindingConsistent(const uint32_t) const;
213     uint32_t GetIndexFromBinding(uint32_t binding) const { return layout_id_->GetIndexFromBinding(binding); }
214     // Various Get functions that can either be passed a binding#, which will
215     //  be automatically translated into the appropriate index, or the index# can be passed in directly
216     uint32_t GetMaxBinding() const { return layout_id_->GetMaxBinding(); }
217     VkDescriptorSetLayoutBinding const *GetDescriptorSetLayoutBindingPtrFromIndex(const uint32_t index) const {
218         return layout_id_->GetDescriptorSetLayoutBindingPtrFromIndex(index);
219     }
220     VkDescriptorSetLayoutBinding const *GetDescriptorSetLayoutBindingPtrFromBinding(uint32_t binding) const {
221         return layout_id_->GetDescriptorSetLayoutBindingPtrFromBinding(binding);
222     }
223     const std::vector<safe_VkDescriptorSetLayoutBinding> &GetBindings() const { return layout_id_->GetBindings(); }
224     uint32_t GetDescriptorCountFromIndex(const uint32_t index) const { return layout_id_->GetDescriptorCountFromIndex(index); }
225     uint32_t GetDescriptorCountFromBinding(const uint32_t binding) const {
226         return layout_id_->GetDescriptorCountFromBinding(binding);
227     }
228     VkDescriptorType GetTypeFromIndex(const uint32_t index) const { return layout_id_->GetTypeFromIndex(index); }
229     VkDescriptorType GetTypeFromBinding(const uint32_t binding) const { return layout_id_->GetTypeFromBinding(binding); }
230     VkShaderStageFlags GetStageFlagsFromIndex(const uint32_t index) const { return layout_id_->GetStageFlagsFromIndex(index); }
231     VkShaderStageFlags GetStageFlagsFromBinding(const uint32_t binding) const {
232         return layout_id_->GetStageFlagsFromBinding(binding);
233     }
234     uint32_t GetIndexFromGlobalIndex(const uint32_t global_index) const {
235         return layout_id_->GetIndexFromGlobalIndex(global_index);
236     }
237     VkDescriptorType GetTypeFromGlobalIndex(const uint32_t global_index) const {
238         return GetTypeFromIndex(GetIndexFromGlobalIndex(global_index));
239     }
240     VkSampler const *GetImmutableSamplerPtrFromBinding(const uint32_t binding) const {
241         return layout_id_->GetImmutableSamplerPtrFromBinding(binding);
242     }
243     VkSampler const *GetImmutableSamplerPtrFromIndex(const uint32_t index) const {
244         return layout_id_->GetImmutableSamplerPtrFromIndex(index);
245     }
246     // For a given binding and array index, return the corresponding index into the dynamic offset array
247     int32_t GetDynamicOffsetIndexFromBinding(uint32_t binding) const {
248         return layout_id_->GetDynamicOffsetIndexFromBinding(binding);
249     }
250     // For a particular binding, get the global index range
251     //  This call should be guarded by a call to "HasBinding(binding)" to verify that the given binding exists
252     const IndexRange &GetGlobalIndexRangeFromBinding(const uint32_t binding) const {
253         return layout_id_->GetGlobalIndexRangeFromBinding(binding);
254     }
255     // Helper function to get the next valid binding for a descriptor
256     uint32_t GetNextValidBinding(const uint32_t binding) const { return layout_id_->GetNextValidBinding(binding); }
257     // For a particular binding starting at offset and having update_count descriptors
258     //  updated, verify that for any binding boundaries crossed, the update is consistent
259     bool VerifyUpdateConsistency(uint32_t current_binding, uint32_t offset, uint32_t update_count, const char *type,
260                                  const VkDescriptorSet set, std::string *error_msg) const {
261         return layout_id_->VerifyUpdateConsistency(current_binding, offset, update_count, type, set, error_msg);
262     }
263     bool IsPushDescriptor() const { return layout_id_->IsPushDescriptor(); }
264
265     using BindingTypeStats = DescriptorSetLayoutDef::BindingTypeStats;
266     const BindingTypeStats &GetBindingTypeStats() const { return layout_id_->GetBindingTypeStats(); }
267
268    private:
269     VkDescriptorSetLayout layout_;
270     bool layout_destroyed_;
271     DescriptorSetLayoutId layout_id_;
272 };
273
274 /*
275  * Descriptor classes
276  *  Descriptor is an abstract base class from which 5 separate descriptor types are derived.
277  *   This allows the WriteUpdate() and CopyUpdate() operations to be specialized per
278  *   descriptor type, but all descriptors in a set can be accessed via the common Descriptor*.
279  */
280
281 // Slightly broader than type, each c++ "class" will has a corresponding "DescriptorClass"
282 enum DescriptorClass { PlainSampler, ImageSampler, Image, TexelBuffer, GeneralBuffer };
283
284 class Descriptor {
285    public:
286     virtual ~Descriptor(){};
287     virtual void WriteUpdate(const VkWriteDescriptorSet *, const uint32_t) = 0;
288     virtual void CopyUpdate(const Descriptor *) = 0;
289     // Create binding between resources of this descriptor and given cb_node
290     virtual void BindCommandBuffer(const core_validation::layer_data *, GLOBAL_CB_NODE *) = 0;
291     virtual DescriptorClass GetClass() const { return descriptor_class; };
292     // Special fast-path check for SamplerDescriptors that are immutable
293     virtual bool IsImmutableSampler() const { return false; };
294     // Check for dynamic descriptor type
295     virtual bool IsDynamic() const { return false; };
296     // Check for storage descriptor type
297     virtual bool IsStorage() const { return false; };
298     bool updated;  // Has descriptor been updated?
299     DescriptorClass descriptor_class;
300 };
301 // Shared helper functions - These are useful because the shared sampler image descriptor type
302 //  performs common functions with both sampler and image descriptors so they can share their common functions
303 bool ValidateSampler(const VkSampler, const core_validation::layer_data *);
304 bool ValidateImageUpdate(VkImageView, VkImageLayout, VkDescriptorType, const core_validation::layer_data *,
305                          UNIQUE_VALIDATION_ERROR_CODE *, std::string *);
306
307 class SamplerDescriptor : public Descriptor {
308    public:
309     SamplerDescriptor(const VkSampler *);
310     void WriteUpdate(const VkWriteDescriptorSet *, const uint32_t) override;
311     void CopyUpdate(const Descriptor *) override;
312     void BindCommandBuffer(const core_validation::layer_data *, GLOBAL_CB_NODE *) override;
313     virtual bool IsImmutableSampler() const override { return immutable_; };
314     VkSampler GetSampler() const { return sampler_; }
315
316    private:
317     // bool ValidateSampler(const VkSampler) const;
318     VkSampler sampler_;
319     bool immutable_;
320 };
321
322 class ImageSamplerDescriptor : public Descriptor {
323    public:
324     ImageSamplerDescriptor(const VkSampler *);
325     void WriteUpdate(const VkWriteDescriptorSet *, const uint32_t) override;
326     void CopyUpdate(const Descriptor *) override;
327     void BindCommandBuffer(const core_validation::layer_data *, GLOBAL_CB_NODE *) override;
328     virtual bool IsImmutableSampler() const override { return immutable_; };
329     VkSampler GetSampler() const { return sampler_; }
330     VkImageView GetImageView() const { return image_view_; }
331     VkImageLayout GetImageLayout() const { return image_layout_; }
332
333    private:
334     VkSampler sampler_;
335     bool immutable_;
336     VkImageView image_view_;
337     VkImageLayout image_layout_;
338 };
339
340 class ImageDescriptor : public Descriptor {
341    public:
342     ImageDescriptor(const VkDescriptorType);
343     void WriteUpdate(const VkWriteDescriptorSet *, const uint32_t) override;
344     void CopyUpdate(const Descriptor *) override;
345     void BindCommandBuffer(const core_validation::layer_data *, GLOBAL_CB_NODE *) override;
346     virtual bool IsStorage() const override { return storage_; }
347     VkImageView GetImageView() const { return image_view_; }
348     VkImageLayout GetImageLayout() const { return image_layout_; }
349
350    private:
351     bool storage_;
352     VkImageView image_view_;
353     VkImageLayout image_layout_;
354 };
355
356 class TexelDescriptor : public Descriptor {
357    public:
358     TexelDescriptor(const VkDescriptorType);
359     void WriteUpdate(const VkWriteDescriptorSet *, const uint32_t) override;
360     void CopyUpdate(const Descriptor *) override;
361     void BindCommandBuffer(const core_validation::layer_data *, GLOBAL_CB_NODE *) override;
362     virtual bool IsStorage() const override { return storage_; }
363     VkBufferView GetBufferView() const { return buffer_view_; }
364
365    private:
366     VkBufferView buffer_view_;
367     bool storage_;
368 };
369
370 class BufferDescriptor : public Descriptor {
371    public:
372     BufferDescriptor(const VkDescriptorType);
373     void WriteUpdate(const VkWriteDescriptorSet *, const uint32_t) override;
374     void CopyUpdate(const Descriptor *) override;
375     void BindCommandBuffer(const core_validation::layer_data *, GLOBAL_CB_NODE *) override;
376     virtual bool IsDynamic() const override { return dynamic_; }
377     virtual bool IsStorage() const override { return storage_; }
378     VkBuffer GetBuffer() const { return buffer_; }
379     VkDeviceSize GetOffset() const { return offset_; }
380     VkDeviceSize GetRange() const { return range_; }
381
382    private:
383     bool storage_;
384     bool dynamic_;
385     VkBuffer buffer_;
386     VkDeviceSize offset_;
387     VkDeviceSize range_;
388 };
389 // Structs to contain common elements that need to be shared between Validate* and Perform* calls below
390 struct AllocateDescriptorSetsData {
391     uint32_t required_descriptors_by_type[VK_DESCRIPTOR_TYPE_RANGE_SIZE];
392     std::vector<std::shared_ptr<DescriptorSetLayout const>> layout_nodes;
393     AllocateDescriptorSetsData(uint32_t);
394 };
395 // Helper functions for descriptor set functions that cross multiple sets
396 // "Validate" will make sure an update is ok without actually performing it
397 bool ValidateUpdateDescriptorSets(const debug_report_data *, const core_validation::layer_data *, uint32_t,
398                                   const VkWriteDescriptorSet *, uint32_t, const VkCopyDescriptorSet *);
399 // "Perform" does the update with the assumption that ValidateUpdateDescriptorSets() has passed for the given update
400 void PerformUpdateDescriptorSets(const core_validation::layer_data *, uint32_t, const VkWriteDescriptorSet *, uint32_t,
401                                  const VkCopyDescriptorSet *);
402 // Similar to PerformUpdateDescriptorSets, this function will do the same for updating via templates
403 void PerformUpdateDescriptorSetsWithTemplateKHR(layer_data *, VkDescriptorSet, std::unique_ptr<TEMPLATE_STATE> const &,
404                                                 const void *);
405 // Update the common AllocateDescriptorSetsData struct which can then be shared between Validate* and Perform* funcs below
406 void UpdateAllocateDescriptorSetsData(const layer_data *dev_data, const VkDescriptorSetAllocateInfo *,
407                                       AllocateDescriptorSetsData *);
408 // Validate that Allocation state is ok
409 bool ValidateAllocateDescriptorSets(const core_validation::layer_data *, const VkDescriptorSetAllocateInfo *,
410                                     const AllocateDescriptorSetsData *);
411 // Update state based on allocating new descriptorsets
412 void PerformAllocateDescriptorSets(const VkDescriptorSetAllocateInfo *, const VkDescriptorSet *, const AllocateDescriptorSetsData *,
413                                    std::unordered_map<VkDescriptorPool, DESCRIPTOR_POOL_STATE *> *,
414                                    std::unordered_map<VkDescriptorSet, cvdescriptorset::DescriptorSet *> *,
415                                    core_validation::layer_data *);
416
417 /*
418  * DescriptorSet class
419  *
420  * Overview - This class encapsulates the Vulkan VkDescriptorSet data (set).
421  *   A set has an underlying layout which defines the bindings in the set and the
422  *   types and numbers of descriptors in each descriptor slot. Most of the layout
423  *   interfaces are exposed through identically-named functions in the set class.
424  *   Please refer to the DescriptorSetLayout comment above for a description of
425  *   index, binding, and global index.
426  *
427  * At construction a vector of Descriptor* is created with types corresponding to the
428  *   layout. The primary operation performed on the descriptors is to update them
429  *   via write or copy updates, and validate that the update contents are correct.
430  *   In order to validate update contents, the DescriptorSet stores a bunch of ptrs
431  *   to data maps where various Vulkan objects can be looked up. The management of
432  *   those maps is performed externally. The set class relies on their contents to
433  *   be correct at the time of update.
434  */
435 class DescriptorSet : public BASE_NODE {
436    public:
437     DescriptorSet(const VkDescriptorSet, const VkDescriptorPool, const std::shared_ptr<DescriptorSetLayout const> &,
438                   core_validation::layer_data *);
439     ~DescriptorSet();
440     // A number of common Get* functions that return data based on layout from which this set was created
441     uint32_t GetTotalDescriptorCount() const { return p_layout_->GetTotalDescriptorCount(); };
442     uint32_t GetDynamicDescriptorCount() const { return p_layout_->GetDynamicDescriptorCount(); };
443     uint32_t GetBindingCount() const { return p_layout_->GetBindingCount(); };
444     VkDescriptorType GetTypeFromIndex(const uint32_t index) const { return p_layout_->GetTypeFromIndex(index); };
445     VkDescriptorType GetTypeFromGlobalIndex(const uint32_t index) const { return p_layout_->GetTypeFromGlobalIndex(index); };
446     VkDescriptorType GetTypeFromBinding(const uint32_t binding) const { return p_layout_->GetTypeFromBinding(binding); };
447     uint32_t GetDescriptorCountFromIndex(const uint32_t index) const { return p_layout_->GetDescriptorCountFromIndex(index); };
448     uint32_t GetDescriptorCountFromBinding(const uint32_t binding) const {
449         return p_layout_->GetDescriptorCountFromBinding(binding);
450     };
451     // Return index into dynamic offset array for given binding
452     int32_t GetDynamicOffsetIndexFromBinding(uint32_t binding) const {
453         return p_layout_->GetDynamicOffsetIndexFromBinding(binding);
454     }
455     // Return true if given binding is present in this set
456     bool HasBinding(const uint32_t binding) const { return p_layout_->HasBinding(binding); };
457     // Is this set compatible with the given layout?
458     bool IsCompatible(DescriptorSetLayout const *const, std::string *) const;
459     // For given bindings validate state at time of draw is correct, returning false on error and writing error details into string*
460     bool ValidateDrawState(const std::map<uint32_t, descriptor_req> &, const std::vector<uint32_t> &, GLOBAL_CB_NODE *,
461                            const char *caller, std::string *) const;
462     // For given set of bindings, add any buffers and images that will be updated to their respective unordered_sets & return number
463     // of objects inserted
464     uint32_t GetStorageUpdates(const std::map<uint32_t, descriptor_req> &, std::unordered_set<VkBuffer> *,
465                                std::unordered_set<VkImageView> *) const;
466
467     // Descriptor Update functions. These functions validate state and perform update separately
468     // Validate contents of a WriteUpdate
469     bool ValidateWriteUpdate(const debug_report_data *, const VkWriteDescriptorSet *, UNIQUE_VALIDATION_ERROR_CODE *,
470                              std::string *);
471     // Perform a WriteUpdate whose contents were just validated using ValidateWriteUpdate
472     void PerformWriteUpdate(const VkWriteDescriptorSet *);
473     // Validate contents of a CopyUpdate
474     bool ValidateCopyUpdate(const debug_report_data *, const VkCopyDescriptorSet *, const DescriptorSet *,
475                             UNIQUE_VALIDATION_ERROR_CODE *, std::string *);
476     // Perform a CopyUpdate whose contents were just validated using ValidateCopyUpdate
477     void PerformCopyUpdate(const VkCopyDescriptorSet *, const DescriptorSet *);
478
479     const std::shared_ptr<DescriptorSetLayout const> GetLayout() const { return p_layout_; };
480     VkDescriptorSet GetSet() const { return set_; };
481     // Return unordered_set of all command buffers that this set is bound to
482     std::unordered_set<GLOBAL_CB_NODE *> GetBoundCmdBuffers() const { return cb_bindings; }
483     // Bind given cmd_buffer to this descriptor set
484     void BindCommandBuffer(GLOBAL_CB_NODE *, const std::map<uint32_t, descriptor_req> &);
485
486     // Track work that has been bound or validated to avoid duplicate work, important when large descriptor arrays
487     // are present
488     typedef std::unordered_set<uint32_t> TrackedBindings;
489     static void FilterAndTrackOneBindingReq(const BindingReqMap::value_type &binding_req_pair, const BindingReqMap &in_req,
490                                             BindingReqMap *out_req, TrackedBindings *set);
491     static void FilterAndTrackOneBindingReq(const BindingReqMap::value_type &binding_req_pair, const BindingReqMap &in_req,
492                                             BindingReqMap *out_req, TrackedBindings *set, uint32_t limit);
493     void FilterAndTrackBindingReqs(GLOBAL_CB_NODE *, const BindingReqMap &in_req, BindingReqMap *out_req);
494     void FilterAndTrackBindingReqs(GLOBAL_CB_NODE *, PIPELINE_STATE *, const BindingReqMap &in_req, BindingReqMap *out_req);
495     void ClearCachedDynamicDescriptorValidation(GLOBAL_CB_NODE *cb_state) { cached_validation_[cb_state].dynamic_buffers.clear(); }
496     void ClearCachedValidation(GLOBAL_CB_NODE *cb_state) { cached_validation_.erase(cb_state); }
497     // If given cmd_buffer is in the cb_bindings set, remove it
498     void RemoveBoundCommandBuffer(GLOBAL_CB_NODE *cb_node) {
499         cb_bindings.erase(cb_node);
500         ClearCachedValidation(cb_node);
501     }
502     VkSampler const *GetImmutableSamplerPtrFromBinding(const uint32_t index) const {
503         return p_layout_->GetImmutableSamplerPtrFromBinding(index);
504     };
505     // For a particular binding, get the global index
506     const IndexRange &GetGlobalIndexRangeFromBinding(const uint32_t binding) const {
507         return p_layout_->GetGlobalIndexRangeFromBinding(binding);
508     };
509     // Return true if any part of set has ever been updated
510     bool IsUpdated() const { return some_update_; };
511     bool IsPushDescriptor() const { return p_layout_->IsPushDescriptor(); };
512
513    private:
514     bool VerifyWriteUpdateContents(const VkWriteDescriptorSet *, const uint32_t, UNIQUE_VALIDATION_ERROR_CODE *,
515                                    std::string *) const;
516     bool VerifyCopyUpdateContents(const VkCopyDescriptorSet *, const DescriptorSet *, VkDescriptorType, uint32_t,
517                                   UNIQUE_VALIDATION_ERROR_CODE *, std::string *) const;
518     bool ValidateBufferUsage(BUFFER_STATE const *, VkDescriptorType, UNIQUE_VALIDATION_ERROR_CODE *, std::string *) const;
519     bool ValidateBufferUpdate(VkDescriptorBufferInfo const *, VkDescriptorType, UNIQUE_VALIDATION_ERROR_CODE *,
520                               std::string *) const;
521     // Private helper to set all bound cmd buffers to INVALID state
522     void InvalidateBoundCmdBuffers();
523     bool some_update_;  // has any part of the set ever been updated?
524     VkDescriptorSet set_;
525     DESCRIPTOR_POOL_STATE *pool_state_;
526     const std::shared_ptr<DescriptorSetLayout const> p_layout_;
527     std::vector<std::unique_ptr<Descriptor>> descriptors_;
528     // Ptr to device data used for various data look-ups
529     core_validation::layer_data *const device_data_;
530     const VkPhysicalDeviceLimits limits_;
531
532     // Cached binding and validation support:
533     //
534     // For the lifespan of a given command buffer recording, do lazy evaluation, caching, and dirtying of
535     // expensive validation operation (typically per-draw)
536     typedef std::unordered_map<GLOBAL_CB_NODE *, TrackedBindings> TrackedBindingMap;
537     typedef std::unordered_map<PIPELINE_STATE *, TrackedBindingMap> ValidatedBindings;
538     // Track the validation caching of bindings vs. the command buffer and draw state
539     typedef std::unordered_map<uint32_t, GLOBAL_CB_NODE::ImageLayoutUpdateCount> VersionedBindings;
540     struct CachedValidation {
541         TrackedBindings command_binding_and_usage;                               // Persistent for the life of the recording
542         TrackedBindings non_dynamic_buffers;                                     // Persistent for the life of the recording
543         TrackedBindings dynamic_buffers;                                         // Dirtied (flushed) each BindDescriptorSet
544         std::unordered_map<PIPELINE_STATE *, VersionedBindings> image_samplers;  // Tested vs. changes to CB's ImageLayout
545     };
546     typedef std::unordered_map<GLOBAL_CB_NODE *, CachedValidation> CachedValidationMap;
547     // Image and ImageView bindings are validated per pipeline and not invalidate by repeated binding
548     CachedValidationMap cached_validation_;
549 };
550 // For the "bindless" style resource usage with many descriptors, need to optimize binding and validation
551 class PrefilterBindRequestMap {
552    public:
553     static const uint32_t kManyDescriptors_ = 64;  // TODO base this number on measured data
554     std::unique_ptr<BindingReqMap> filtered_map_;
555     const BindingReqMap &orig_map_;
556
557     PrefilterBindRequestMap(DescriptorSet &ds, const BindingReqMap &in_map, GLOBAL_CB_NODE *cb_state);
558     PrefilterBindRequestMap(DescriptorSet &ds, const BindingReqMap &in_map, GLOBAL_CB_NODE *cb_state, PIPELINE_STATE *);
559     const BindingReqMap &Map() const { return (filtered_map_) ? *filtered_map_ : orig_map_; }
560 };
561 }  // namespace cvdescriptorset
562 #endif  // CORE_VALIDATION_DESCRIPTOR_SETS_H_