blob: 36f54b0ba6ef4956d9170b1c952418e2ba34cbcd [file] [log] [blame]
Karl Schultz7b024b42018-08-30 16:18:18 -06001/* Copyright (c) 2015-2019 The Khronos Group Inc.
2 * Copyright (c) 2015-2019 Valve Corporation
3 * Copyright (c) 2015-2019 LunarG, Inc.
4 * Copyright (C) 2015-2019 Google Inc.
Chris Forbes47567b72017-06-09 12:09:45 -07005 *
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: Chris Forbes <chrisf@ijw.co.nz>
19 */
20#ifndef VULKAN_SHADER_VALIDATION_H
21#define VULKAN_SHADER_VALIDATION_H
22
Jeff Bolz104e7432019-02-09 08:04:42 -060023#include <SPIRV/spirv.hpp>
Cort Strattona81851c2017-11-06 19:13:53 -080024#include <spirv_tools_commit_id.h>
Mark Lobodzinskibbaa6a22018-11-02 12:03:35 -060025#include "spirv-tools/optimizer.hpp"
Cort Strattona81851c2017-11-06 19:13:53 -080026
Chris Forbes47567b72017-06-09 12:09:45 -070027// A forward iterator over spirv instructions. Provides easy access to len, opcode, and content words
28// without the caller needing to care too much about the physical SPIRV module layout.
29struct spirv_inst_iter {
30 std::vector<uint32_t>::const_iterator zero;
31 std::vector<uint32_t>::const_iterator it;
32
33 uint32_t len() {
34 auto result = *it >> 16;
35 assert(result > 0);
36 return result;
37 }
38
39 uint32_t opcode() { return *it & 0x0ffffu; }
40
41 uint32_t const &word(unsigned n) {
42 assert(n < len());
43 return it[n];
44 }
45
46 uint32_t offset() { return (uint32_t)(it - zero); }
47
48 spirv_inst_iter() {}
49
50 spirv_inst_iter(std::vector<uint32_t>::const_iterator zero, std::vector<uint32_t>::const_iterator it) : zero(zero), it(it) {}
51
52 bool operator==(spirv_inst_iter const &other) { return it == other.it; }
53
54 bool operator!=(spirv_inst_iter const &other) { return it != other.it; }
55
56 spirv_inst_iter operator++(int) { // x++
57 spirv_inst_iter ii = *this;
58 it += len();
59 return ii;
60 }
61
62 spirv_inst_iter operator++() { // ++x;
63 it += len();
64 return *this;
65 }
66
67 // The iterator and the value are the same thing.
68 spirv_inst_iter &operator*() { return *this; }
69 spirv_inst_iter const &operator*() const { return *this; }
70};
71
Mark Lobodzinski3c59d972019-04-25 11:28:14 -060072struct SHADER_MODULE_STATE {
Chris Forbes47567b72017-06-09 12:09:45 -070073 // The spirv image itself
74 std::vector<uint32_t> words;
75 // A mapping of <id> to the first word of its def. this is useful because walking type
76 // trees, constant expressions, etc requires jumping all over the instruction stream.
77 std::unordered_map<unsigned, unsigned> def_index;
78 bool has_valid_spirv;
Mark Young4e919b22018-05-21 15:53:59 -060079 VkShaderModule vk_shader_module;
Karl Schultz7b024b42018-08-30 16:18:18 -060080 uint32_t gpu_validation_shader_id;
Chris Forbes47567b72017-06-09 12:09:45 -070081
Mark Lobodzinskibbaa6a22018-11-02 12:03:35 -060082 std::vector<uint32_t> PreprocessShaderBinary(uint32_t *src_binary, size_t binary_size, spv_target_env env) {
Jeff Bolz104e7432019-02-09 08:04:42 -060083 std::vector<uint32_t> src(src_binary, src_binary + binary_size / sizeof(uint32_t));
84
85 // Check if there are any group decoration instructions, and flatten them if found.
86 bool has_group_decoration = false;
87 bool done = false;
88
89 // Walk through the first part of the SPIR-V module, looking for group decoration instructions.
90 // Skip the header (5 words).
91 auto itr = spirv_inst_iter(src.begin(), src.begin() + 5);
92 auto itrend = spirv_inst_iter(src.begin(), src.end());
93 while (itr != itrend && !done) {
94 spv::Op opcode = (spv::Op)itr.opcode();
95 switch (opcode) {
96 case spv::OpDecorationGroup:
97 case spv::OpGroupDecorate:
98 case spv::OpGroupMemberDecorate:
99 has_group_decoration = true;
100 done = true;
101 break;
102 case spv::OpFunction:
103 // An OpFunction indicates there are no more decorations
104 done = true;
105 break;
106 default:
107 break;
108 }
109 itr++;
110 }
111
112 if (has_group_decoration) {
113 spvtools::Optimizer optimizer(env);
114 optimizer.RegisterPass(spvtools::CreateFlattenDecorationPass());
115 std::vector<uint32_t> optimized_binary;
Mark Lobodzinskif2bad662019-04-16 15:06:09 -0600116 // Run optimizer to flatten decorations only, set skip_validation so as to not re-run validator
117 auto result =
118 optimizer.Run(src_binary, binary_size / sizeof(uint32_t), &optimized_binary, spvtools::ValidatorOptions(), true);
Jeff Bolz104e7432019-02-09 08:04:42 -0600119 if (result) {
120 return optimized_binary;
121 }
122 }
123 // Return the original module.
124 return src;
Mark Lobodzinskibbaa6a22018-11-02 12:03:35 -0600125 }
126
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600127 SHADER_MODULE_STATE(VkShaderModuleCreateInfo const *pCreateInfo, VkShaderModule shaderModule, spv_target_env env,
128 uint32_t unique_shader_id)
Mark Lobodzinskibbaa6a22018-11-02 12:03:35 -0600129 : words(PreprocessShaderBinary((uint32_t *)pCreateInfo->pCode, pCreateInfo->codeSize, env)),
Chris Forbes47567b72017-06-09 12:09:45 -0700130 def_index(),
Mark Young4e919b22018-05-21 15:53:59 -0600131 has_valid_spirv(true),
Karl Schultz7b024b42018-08-30 16:18:18 -0600132 vk_shader_module(shaderModule),
133 gpu_validation_shader_id(unique_shader_id) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600134 BuildDefIndex();
Chris Forbes47567b72017-06-09 12:09:45 -0700135 }
136
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600137 SHADER_MODULE_STATE() : has_valid_spirv(false), vk_shader_module(VK_NULL_HANDLE) {}
Chris Forbes47567b72017-06-09 12:09:45 -0700138
139 // Expose begin() / end() to enable range-based for
140 spirv_inst_iter begin() const { return spirv_inst_iter(words.begin(), words.begin() + 5); } // First insn
141 spirv_inst_iter end() const { return spirv_inst_iter(words.begin(), words.end()); } // Just past last insn
142 // Given an offset into the module, produce an iterator there.
143 spirv_inst_iter at(unsigned offset) const { return spirv_inst_iter(words.begin(), words.begin() + offset); }
144
145 // Gets an iterator to the definition of an id
146 spirv_inst_iter get_def(unsigned id) const {
147 auto it = def_index.find(id);
148 if (it == def_index.end()) {
149 return end();
150 }
151 return at(it->second);
152 }
153
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600154 void BuildDefIndex();
Chris Forbes47567b72017-06-09 12:09:45 -0700155};
156
Chris Forbes9a61e082017-07-24 15:35:29 -0700157class ValidationCache {
158 // hashes of shaders that have passed validation before, and can be skipped.
159 // we don't store negative results, as we would have to also store what was
160 // wrong with them; also, we expect they will get fixed, so we're less
161 // likely to see them again.
162 std::unordered_set<uint32_t> good_shader_hashes;
163 ValidationCache() {}
164
Dave Houltona9df0ce2018-02-07 10:51:23 -0700165 public:
Chris Forbes9a61e082017-07-24 15:35:29 -0700166 static VkValidationCacheEXT Create(VkValidationCacheCreateInfoEXT const *pCreateInfo) {
167 auto cache = new ValidationCache();
168 cache->Load(pCreateInfo);
169 return VkValidationCacheEXT(cache);
170 }
171
172 void Load(VkValidationCacheCreateInfoEXT const *pCreateInfo) {
Cort Stratton77955d82018-02-01 23:14:50 -0800173 const auto headerSize = 2 * sizeof(uint32_t) + VK_UUID_SIZE;
174 auto size = headerSize;
Dave Houltona9df0ce2018-02-07 10:51:23 -0700175 if (!pCreateInfo->pInitialData || pCreateInfo->initialDataSize < size) return;
Chris Forbes9a61e082017-07-24 15:35:29 -0700176
177 uint32_t const *data = (uint32_t const *)pCreateInfo->pInitialData;
Dave Houltona9df0ce2018-02-07 10:51:23 -0700178 if (data[0] != size) return;
179 if (data[1] != VK_VALIDATION_CACHE_HEADER_VERSION_ONE_EXT) return;
Cort Stratton77955d82018-02-01 23:14:50 -0800180 uint8_t expected_uuid[VK_UUID_SIZE];
181 Sha1ToVkUuid(SPIRV_TOOLS_COMMIT_ID, expected_uuid);
Dave Houltona9df0ce2018-02-07 10:51:23 -0700182 if (memcmp(&data[2], expected_uuid, VK_UUID_SIZE) != 0) return; // different version
Chris Forbes9a61e082017-07-24 15:35:29 -0700183
Dave Houltona9df0ce2018-02-07 10:51:23 -0700184 data = (uint32_t const *)(reinterpret_cast<uint8_t const *>(data) + headerSize);
Chris Forbes9a61e082017-07-24 15:35:29 -0700185
Dave Houltona9df0ce2018-02-07 10:51:23 -0700186 for (; size < pCreateInfo->initialDataSize; data++, size += sizeof(uint32_t)) {
Chris Forbes9a61e082017-07-24 15:35:29 -0700187 good_shader_hashes.insert(*data);
188 }
189 }
190
191 void Write(size_t *pDataSize, void *pData) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700192 const auto headerSize = 2 * sizeof(uint32_t) + VK_UUID_SIZE; // 4 bytes for header size + 4 bytes for version number + UUID
Chris Forbes9a61e082017-07-24 15:35:29 -0700193 if (!pData) {
194 *pDataSize = headerSize + good_shader_hashes.size() * sizeof(uint32_t);
195 return;
196 }
197
198 if (*pDataSize < headerSize) {
199 *pDataSize = 0;
Dave Houltona9df0ce2018-02-07 10:51:23 -0700200 return; // Too small for even the header!
Chris Forbes9a61e082017-07-24 15:35:29 -0700201 }
202
203 uint32_t *out = (uint32_t *)pData;
204 size_t actualSize = headerSize;
205
206 // Write the header
207 *out++ = headerSize;
208 *out++ = VK_VALIDATION_CACHE_HEADER_VERSION_ONE_EXT;
Dave Houltona9df0ce2018-02-07 10:51:23 -0700209 Sha1ToVkUuid(SPIRV_TOOLS_COMMIT_ID, reinterpret_cast<uint8_t *>(out));
210 out = (uint32_t *)(reinterpret_cast<uint8_t *>(out) + VK_UUID_SIZE);
Chris Forbes9a61e082017-07-24 15:35:29 -0700211
Dave Houltona9df0ce2018-02-07 10:51:23 -0700212 for (auto it = good_shader_hashes.begin(); it != good_shader_hashes.end() && actualSize < *pDataSize;
Chris Forbes9a61e082017-07-24 15:35:29 -0700213 it++, out++, actualSize += sizeof(uint32_t)) {
214 *out = *it;
215 }
216
217 *pDataSize = actualSize;
218 }
219
220 void Merge(ValidationCache const *other) {
Chris Forbesf73483b2017-11-22 16:54:46 -0800221 good_shader_hashes.reserve(good_shader_hashes.size() + other->good_shader_hashes.size());
Dave Houltona9df0ce2018-02-07 10:51:23 -0700222 for (auto h : other->good_shader_hashes) good_shader_hashes.insert(h);
Chris Forbes9a61e082017-07-24 15:35:29 -0700223 }
224
225 static uint32_t MakeShaderHash(VkShaderModuleCreateInfo const *smci);
226
Dave Houltona9df0ce2018-02-07 10:51:23 -0700227 bool Contains(uint32_t hash) { return good_shader_hashes.count(hash) != 0; }
Chris Forbes9a61e082017-07-24 15:35:29 -0700228
Dave Houltona9df0ce2018-02-07 10:51:23 -0700229 void Insert(uint32_t hash) { good_shader_hashes.insert(hash); }
230
231 private:
232 void Sha1ToVkUuid(const char *sha1_str, uint8_t uuid[VK_UUID_SIZE]) {
233 // Convert sha1_str from a hex string to binary. We only need VK_UUID_BYTES of
234 // output, so pad with zeroes if the input string is shorter than that, and truncate
235 // if it's longer.
236 char padded_sha1_str[2 * VK_UUID_SIZE + 1] = {};
237 strncpy(padded_sha1_str, sha1_str, 2 * VK_UUID_SIZE + 1);
238 char byte_str[3] = {};
239 for (uint32_t i = 0; i < VK_UUID_SIZE; ++i) {
240 byte_str[0] = padded_sha1_str[2 * i + 0];
241 byte_str[1] = padded_sha1_str[2 * i + 1];
242 uuid[i] = static_cast<uint8_t>(strtol(byte_str, NULL, 16));
243 }
Cort Strattonb614d332017-11-22 16:05:49 -0800244 }
Chris Forbes9a61e082017-07-24 15:35:29 -0700245};
246
Chris Forbes47567b72017-06-09 12:09:45 -0700247typedef std::pair<unsigned, unsigned> descriptor_slot_t;
Chris Forbes47567b72017-06-09 12:09:45 -0700248
Dave Houltona9df0ce2018-02-07 10:51:23 -0700249#endif // VULKAN_SHADER_VALIDATION_H