1 // Copyright (c) 2018 The Khronos Group Inc.
2 // Copyright (c) 2018 Valve Corporation
3 // Copyright (c) 2018 LunarG Inc.
4 //
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 #ifndef LIBSPIRV_OPT_INST_BINDLESS_CHECK_PASS_H_
18 #define LIBSPIRV_OPT_INST_BINDLESS_CHECK_PASS_H_
19 
20 #include "instrument_pass.h"
21 
22 namespace spvtools {
23 namespace opt {
24 
25 // This class/pass is designed to support the bindless (descriptor indexing)
26 // GPU-assisted validation layer of
27 // https://github.com/KhronosGroup/Vulkan-ValidationLayers. Its internal and
28 // external design may change as the layer evolves.
29 class InstBindlessCheckPass : public InstrumentPass {
30  public:
31   // Deprecated interface
InstBindlessCheckPass(uint32_t desc_set,uint32_t shader_id,bool input_length_enable,bool input_init_enable,uint32_t version)32   InstBindlessCheckPass(uint32_t desc_set, uint32_t shader_id,
33                         bool input_length_enable, bool input_init_enable,
34                         uint32_t version)
35       : InstrumentPass(desc_set, shader_id, kInstValidationIdBindless, version),
36         input_length_enabled_(input_length_enable),
37         input_init_enabled_(input_init_enable) {}
38   // Preferred Interface
InstBindlessCheckPass(uint32_t desc_set,uint32_t shader_id,bool input_length_enable,bool input_init_enable)39   InstBindlessCheckPass(uint32_t desc_set, uint32_t shader_id,
40                         bool input_length_enable, bool input_init_enable)
41       : InstrumentPass(desc_set, shader_id, kInstValidationIdBindless),
42         input_length_enabled_(input_length_enable),
43         input_init_enabled_(input_init_enable) {}
44 
45   ~InstBindlessCheckPass() override = default;
46 
47   // See optimizer.hpp for pass user documentation.
48   Status Process() override;
49 
name()50   const char* name() const override { return "inst-bindless-check-pass"; }
51 
52  private:
53   // These functions do bindless checking instrumentation on a single
54   // instruction which references through a descriptor (ie references into an
55   // image or buffer). Refer to Vulkan API for further information on
56   // descriptors. GenBoundsCheckCode checks that an index into a descriptor
57   // array (array of images or buffers) is in-bounds. GenInitCheckCode
58   // checks that the referenced descriptor has been initialized, if the
59   // SPV_EXT_descriptor_indexing extension is enabled.
60   //
61   // TODO(greg-lunarg): Add support for buffers. Currently only does
62   // checking of references of images.
63   //
64   // The functions are designed to be passed to
65   // InstrumentPass::InstProcessEntryPointCallTree(), which applies the
66   // function to each instruction in a module and replaces the instruction
67   // if warranted.
68   //
69   // If |ref_inst_itr| is a bindless reference, return in |new_blocks| the
70   // result of instrumenting it with validation code within its block at
71   // |ref_block_itr|.  The validation code first executes a check for the
72   // specific condition called for. If the check passes, it executes
73   // the remainder of the reference, otherwise writes a record to the debug
74   // output buffer stream including |function_idx, instruction_idx, stage_idx|
75   // and replaces the reference with the null value of the original type. The
76   // block at |ref_block_itr| can just be replaced with the blocks in
77   // |new_blocks|, which will contain at least two blocks. The last block will
78   // comprise all instructions following |ref_inst_itr|,
79   // preceded by a phi instruction.
80   //
81   // These instrumentation functions utilize GenDebugDirectRead() to read data
82   // from the debug input buffer, specifically the lengths of variable length
83   // descriptor arrays, and the initialization status of each descriptor.
84   // The format of the debug input buffer is documented in instrument.hpp.
85   //
86   // These instrumentation functions utilize GenDebugStreamWrite() to write its
87   // error records. The validation-specific part of the error record will
88   // have the format:
89   //
90   //    Validation Error Code (=kInstErrorBindlessBounds)
91   //    Descriptor Index
92   //    Descriptor Array Size
93   //
94   // The Descriptor Index is the index which has been determined to be
95   // out-of-bounds.
96   //
97   // The Descriptor Array Size is the size of the descriptor array which was
98   // indexed.
99   void GenBoundsCheckCode(BasicBlock::iterator ref_inst_itr,
100                           UptrVectorIterator<BasicBlock> ref_block_itr,
101                           uint32_t stage_idx,
102                           std::vector<std::unique_ptr<BasicBlock>>* new_blocks);
103 
104   void GenInitCheckCode(BasicBlock::iterator ref_inst_itr,
105                         UptrVectorIterator<BasicBlock> ref_block_itr,
106                         uint32_t stage_idx,
107                         std::vector<std::unique_ptr<BasicBlock>>* new_blocks);
108 
109   // Generate instructions into |builder| to read length of runtime descriptor
110   // array |var_id| from debug input buffer and return id of value.
111   uint32_t GenDebugReadLength(uint32_t var_id, InstructionBuilder* builder);
112 
113   // Generate instructions into |builder| to read initialization status of
114   // descriptor array |image_id| at |index_id| from debug input buffer and
115   // return id of value.
116   uint32_t GenDebugReadInit(uint32_t image_id, uint32_t index_id,
117                             InstructionBuilder* builder);
118 
119   // Analysis data for descriptor reference components, generated by
120   // AnalyzeDescriptorReference. It is necessary and sufficient for further
121   // analysis and regeneration of the reference.
122   typedef struct ref_analysis {
123     uint32_t desc_load_id;
124     uint32_t image_id;
125     uint32_t load_id;
126     uint32_t ptr_id;
127     uint32_t var_id;
128     uint32_t index_id;
129     Instruction* ref_inst;
130   } ref_analysis;
131 
132   // Clone original original reference encapsulated by |ref| into |builder|.
133   // This may generate more than one instruction if neccessary.
134   uint32_t CloneOriginalReference(ref_analysis* ref,
135                                   InstructionBuilder* builder);
136 
137   // If |inst| references through an image, return the id of the image it
138   // references through. Else return 0.
139   uint32_t GetImageId(Instruction* inst);
140 
141   // Get descriptor type inst of variable |var_inst|.
142   Instruction* GetDescriptorTypeInst(Instruction* var_inst);
143 
144   // Analyze descriptor reference |ref_inst| and save components into |ref|.
145   // Return true if |ref_inst| is a descriptor reference, false otherwise.
146   bool AnalyzeDescriptorReference(Instruction* ref_inst, ref_analysis* ref);
147 
148   // Generate instrumentation code for generic test result |check_id|, starting
149   // with |builder| of block |new_blk_ptr|, adding new blocks to |new_blocks|.
150   // Generate conditional branch to a valid or invalid branch. Generate valid
151   // block which does original reference |ref|. Generate invalid block which
152   // writes debug error output utilizing |ref|, |error_id|, |length_id| and
153   // |stage_idx|. Generate merge block for valid and invalid branches. Kill
154   // original reference.
155   void GenCheckCode(uint32_t check_id, uint32_t error_id, uint32_t length_id,
156                     uint32_t stage_idx, ref_analysis* ref,
157                     std::vector<std::unique_ptr<BasicBlock>>* new_blocks);
158 
159   // Initialize state for instrumenting bindless checking
160   void InitializeInstBindlessCheck();
161 
162   // Apply GenBoundsCheckCode to every instruction in module. Then apply
163   // GenInitCheckCode to every instruction in module.
164   Pass::Status ProcessImpl();
165 
166   // Enable instrumentation of runtime array length checking
167   bool input_length_enabled_;
168 
169   // Enable instrumentation of descriptor initialization checking
170   bool input_init_enabled_;
171 
172   // Mapping from variable to descriptor set
173   std::unordered_map<uint32_t, uint32_t> var2desc_set_;
174 
175   // Mapping from variable to binding
176   std::unordered_map<uint32_t, uint32_t> var2binding_;
177 };
178 
179 }  // namespace opt
180 }  // namespace spvtools
181 
182 #endif  // LIBSPIRV_OPT_INST_BINDLESS_CHECK_PASS_H_
183