Skip to content
Navigation Menu
{{ message }}
forked from LunarG/VulkanSamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidation_cache.cpp
More file actions
419 lines (375 loc) · 16.9 KB
/
Copy pathvalidation_cache.cpp
File metadata and controls
419 lines (375 loc) · 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/*
* Vulkan Samples
*
* Copyright (C) 2016-2020 Valve Corporation
* Copyright (C) 2016-2020 LunarG, Inc.
* Copyright (C) 2016-2020 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
VULKAN_SAMPLE_SHORT_DESCRIPTION
Create and use a validation cache across runs.
*/
#include <util_init.hpp>
#include <array>
#include <assert.h>
#include <string.h>
#include <cstdlib>
#include "cube_data.h"
// This sample tries to save and reuse validation cache data between runs.
// On first run, no cache will be found, it will be created and saved
// to disk. On later runs, the cache should be found, loaded, and used.
// Hopefully a speedup will observed. In the future, the shader could
// be complicated a bit, to show a greater cache benefit. Also, two
// caches could be created and merged.
// The fragment shader contains a 32-bit integer constant (tweak_value)
// which we can search for in the compiled SPIRV and replace with new
// values to generate "different" shaders.
struct ShaderVariant {
std::vector<uint32_t> spv;
#if defined(VK_EXT_validation_cache)
VkShaderModuleValidationCacheCreateInfoEXT moduleValidationCacheCreateInfo;
#endif
VkShaderModuleCreateInfo moduleCreateInfo;
VkShaderModule module;
};
int sample_main(int argc, char *argv[]) {
VkResult U_ASSERT_ONLY res;
struct sample_info info = {};
char sample_title[] = "Validation Cache";
const bool depthPresent = true;
process_command_line_args(info, argc, argv);
init_global_layer_properties(info);
// Android headers don't have validation cache yet
#ifndef ANDROID
#if !defined(VK_EXT_validation_cache)
fprintf(stderr, "%s not defined at build time.\n", VK_EXT_VALIDATION_CACHE_EXTENSION_NAME);
fprintf(stderr, "To build this sample, update your Vulkan SDK to 1.0.61 or later.\n");
return 0;
#endif
init_instance_extension_names(info);
init_device_extension_names(info);
// The VK_EXT_validation_cache extension is implemented by the validation layers, so
// they must be enabled in order to use it.
info.instance_layer_names.push_back("VK_LAYER_KHRONOS_validation");
if (!demo_check_layers(info.instance_layer_properties, info.instance_layer_names)) {
std::cout << "Set the environment variable VK_LAYER_PATH to point to the location of your layers" << std::endl;
exit(1);
}
init_instance(info, sample_title);
init_enumerate_device(info);
init_window_size(info, 500, 500);
init_connection(info);
init_window(info);
init_swapchain_extension(info);
#if defined(VK_EXT_validation_cache)
bool foundExtension = false;
for (const auto &layer_props : info.instance_layer_properties) {
for (const auto &ext_props : layer_props.device_extensions) {
if (strcmp(ext_props.extensionName, VK_EXT_VALIDATION_CACHE_EXTENSION_NAME) == 0) {
foundExtension = true;
break;
}
}
}
if (!foundExtension) {
fprintf(stderr, "%s not supported.\n", VK_EXT_VALIDATION_CACHE_EXTENSION_NAME);
fprintf(stderr, "(Is VK_LAYER_KHRONOS_validation enabled and up to date?)");
return 0;
}
info.device_extension_names.push_back(VK_EXT_VALIDATION_CACHE_EXTENSION_NAME);
#endif
init_device(info);
init_command_pool(info);
init_command_buffer(info);
execute_begin_command_buffer(info);
init_device_queue(info);
init_swap_chain(info);
init_depth_buffer(info);
init_texture(info, "blue.ppm");
init_uniform_buffer(info);
init_descriptor_and_pipeline_layouts(info, true);
init_renderpass(info, depthPresent);
#include "validation_cache.vert.h"
#include "validation_cache.frag.h"
VkShaderModuleCreateInfo vert_info = {};
VkShaderModuleCreateInfo frag_info = {};
vert_info.sType = frag_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
vert_info.codeSize = sizeof(validation_cache_vert);
vert_info.pCode = validation_cache_vert;
frag_info.codeSize = sizeof(validation_cache_frag);
frag_info.pCode = validation_cache_frag;
init_shaders(info, &vert_info, &frag_info);
init_framebuffers(info, depthPresent);
init_vertex_buffer(info, g_vb_texture_Data, sizeof(g_vb_texture_Data), sizeof(g_vb_texture_Data[0]), true);
init_descriptor_pool(info, true);
init_descriptor_set(info, true);
/* VULKAN_KEY_START */
// Check disk for existing cache data
size_t startCacheSize = 0;
void *startCacheData = nullptr;
std::string directoryName = get_file_directory();
std::string readFileName = directoryName + "validation_cache_data.bin";
FILE *pReadFile = fopen(readFileName.c_str(), "rb");
if (pReadFile) {
// Determine cache size
fseek(pReadFile, 0, SEEK_END);
startCacheSize = ftell(pReadFile);
rewind(pReadFile);
// Allocate memory to hold the initial cache data
startCacheData = (char *)malloc(sizeof(char) * startCacheSize);
if (startCacheData == nullptr) {
fputs("Memory error", stderr);
exit(EXIT_FAILURE);
}
// Read the data into our buffer
size_t result = fread(startCacheData, 1, startCacheSize, pReadFile);
if (result != startCacheSize) {
fputs("Reading error", stderr);
free(startCacheData);
exit(EXIT_FAILURE);
}
// Clean up and print results
fclose(pReadFile);
printf(" Validation cache HIT!\n");
printf(" cacheData loaded from %s\n", readFileName.c_str());
} else {
// No cache found on disk
printf(" Validation cache miss!\n");
}
if (startCacheData != nullptr) {
// clang-format off
//
// Check for cache validity
//
// TODO: Update this as the spec evolves. The fields are not defined by the header.
//
// The code below supports SDK 1.0.65 Vulkan spec, which contains the following table:
//
// Offset Size Meaning
// ------ ------------ ------------------------------------------------------------------
// 0 4 length in bytes of the entire validation cache header written as a
// stream of bytes, with the least significant byte first
// 4 4 a VkValidationCacheHeaderVersionEXT value written as a stream of
// bytes, with the least significant byte first
// 8 VK_UUID_SIZE a layer commit ID expressed as a UUID, which uniquely identifies
// the version of the validation layers used to generate these
// validation results
//
// clang-format on
uint32_t headerLength = 0;
uint32_t cacheHeaderVersion = 0;
uint8_t validationCacheUUID[VK_UUID_SIZE] = {};
memcpy(&headerLength, (uint8_t *)startCacheData + 0, 4);
memcpy(&cacheHeaderVersion, (uint8_t *)startCacheData + 4, 4);
memcpy(validationCacheUUID, (uint8_t *)startCacheData + 8, VK_UUID_SIZE);
// Check each field and report bad values before freeing existing cache
bool badCache = false;
if (headerLength <= 0) {
badCache = true;
printf(" Bad header length in %s.\n", readFileName.c_str());
printf(" Cache contains: 0x%.8x\n", headerLength);
}
if (cacheHeaderVersion != VK_PIPELINE_CACHE_HEADER_VERSION_ONE) {
badCache = true;
printf(" Unsupported cache header version in %s.\n", readFileName.c_str());
printf(" Cache contains: 0x%.8x\n", cacheHeaderVersion);
}
// Unlike pipeline caches, there's nothing meaningful for an application to compare the cache's UUID
// field to. The UUID is checked internally to make sure it matches the version of the SPIRV validator
// used to build the layers. We'll print it here anyway, for informational purposes.
printf("Cache UUID: ");
print_UUID(validationCacheUUID);
printf("\n");
if (badCache) {
// Don't submit initial cache data if any version info is incorrect
free(startCacheData);
startCacheSize = 0;
startCacheData = nullptr;
// And clear out the old cache file for use in next run
printf(" Deleting cache entry %s to repopulate.\n", readFileName.c_str());
if (remove(readFileName.c_str()) != 0) {
fputs("Reading error", stderr);
exit(EXIT_FAILURE);
}
}
}
#if defined(VK_EXT_validation_cache)
// Load extension functions
auto vkCreateValidationCache = (PFN_vkCreateValidationCacheEXT)vkGetDeviceProcAddr(info.device, "vkCreateValidationCacheEXT");
auto vkDestroyValidationCache =
(PFN_vkDestroyValidationCacheEXT)vkGetDeviceProcAddr(info.device, "vkDestroyValidationCacheEXT");
auto vkGetValidationCacheData =
(PFN_vkGetValidationCacheDataEXT)vkGetDeviceProcAddr(info.device, "vkGetValidationCacheDataEXT");
// Feed the initial cache data into cache creation
VkValidationCacheCreateInfoEXT validationCacheCreateInfo;
validationCacheCreateInfo.sType = VK_STRUCTURE_TYPE_VALIDATION_CACHE_CREATE_INFO_EXT;
validationCacheCreateInfo.pNext = NULL;
validationCacheCreateInfo.initialDataSize = startCacheSize;
validationCacheCreateInfo.pInitialData = startCacheData;
validationCacheCreateInfo.flags = 0;
VkValidationCacheEXT validationCache = VK_NULL_HANDLE;
res = vkCreateValidationCache(info.device, &validationCacheCreateInfo, nullptr, &validationCache);
assert(res == VK_SUCCESS);
#endif
// Free our initialData now that validation cache has been created
free(startCacheData);
startCacheData = NULL;
// Generate a set of "different" SPIRV modules by patching in new
// values for tweak_value in the fragment shader.
int32_t tweakValueIndex = -1;
for (size_t i = 0; i < sizeof(validation_cache_frag); ++i) {
if (validation_cache_frag[i] == 0xdeadbeef) {
tweakValueIndex = i;
break;
}
}
assert(tweakValueIndex >= 0);
// Generate the unique variants from the template
const size_t SHADER_COUNT = 10000;
std::vector<ShaderVariant> shaderVariants(SHADER_COUNT);
for (size_t i = 0; i < SHADER_COUNT; ++i) {
auto ptr = const_cast<uint32_t *>(validation_cache_frag);
shaderVariants[i].spv = std::vector<uint32_t>(ptr, ptr + sizeof(validation_cache_frag));
shaderVariants[i].spv[tweakValueIndex] = i;
#if defined(VK_EXT_validation_cache)
shaderVariants[i].moduleValidationCacheCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_VALIDATION_CACHE_CREATE_INFO_EXT;
shaderVariants[i].moduleValidationCacheCreateInfo.pNext = 0;
shaderVariants[i].moduleValidationCacheCreateInfo.validationCache = validationCache;
shaderVariants[i].moduleCreateInfo.pNext = &shaderVariants[i].moduleValidationCacheCreateInfo;
#endif
shaderVariants[i].moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
shaderVariants[i].moduleCreateInfo.codeSize = sizeof(validation_cache_frag);
shaderVariants[i].moduleCreateInfo.pCode = shaderVariants[i].spv.data();
shaderVariants[i].moduleCreateInfo.flags = 0;
}
// Time (roughly) taken to create (and validate) the shader modules.
timestamp_t start = get_milliseconds();
for (auto &variant : shaderVariants) {
res = vkCreateShaderModule(info.device, &variant.moduleCreateInfo, NULL, &variant.module);
assert(res == VK_SUCCESS);
}
timestamp_t elapsed = get_milliseconds() - start;
printf(" vkCreateShaderModule time: %0.f ms for %u calls\n", static_cast<double>(elapsed),
static_cast<uint32_t>(SHADER_COUNT));
// Delete module variants
for (auto &variant : shaderVariants) {
vkDestroyShaderModule(info.device, variant.module, NULL);
}
// Replace the module entry of info.shaderStages with a module created with the
// validation cache active
vkDestroyShaderModule(info.device, info.shaderStages[1].module, NULL);
res = vkCreateShaderModule(info.device, &shaderVariants[0].moduleCreateInfo, NULL, &info.shaderStages[1].module);
assert(res == VK_SUCCESS);
// Begin standard draw stuff
init_pipeline(info, depthPresent);
init_presentable_image(info);
VkClearValue clear_values[2];
init_clear_color_and_depth(info, clear_values);
VkRenderPassBeginInfo rp_begin;
init_render_pass_begin_info(info, rp_begin);
rp_begin.clearValueCount = 2;
rp_begin.pClearValues = clear_values;
vkCmdBeginRenderPass(info.cmd, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(info.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, info.pipeline);
vkCmdBindDescriptorSets(info.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, info.pipeline_layout, 0, NUM_DESCRIPTOR_SETS,
info.desc_set.data(), 0, NULL);
const VkDeviceSize offsets[1] = {0};
vkCmdBindVertexBuffers(info.cmd, 0, 1, &info.vertex_buffer.buf, offsets);
init_viewports(info);
init_scissors(info);
vkCmdDraw(info.cmd, 12 * 3, 1, 0, 0);
vkCmdEndRenderPass(info.cmd);
res = vkEndCommandBuffer(info.cmd);
assert(res == VK_SUCCESS);
VkFence drawFence = {};
init_fence(info, drawFence);
VkPipelineStageFlags pipe_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
VkSubmitInfo submit_info = {};
init_submit_info(info, submit_info, pipe_stage_flags);
/* Queue the command buffer for execution */
res = vkQueueSubmit(info.graphics_queue, 1, &submit_info, drawFence);
assert(res == VK_SUCCESS);
/* Now present the image in the window */
VkPresentInfoKHR present = {};
init_present_info(info, present);
/* Make sure command buffer is finished before presenting */
do {
res = vkWaitForFences(info.device, 1, &drawFence, VK_TRUE, FENCE_TIMEOUT);
} while (res == VK_TIMEOUT);
assert(res == VK_SUCCESS);
res = vkQueuePresentKHR(info.present_queue, &present);
assert(res == VK_SUCCESS);
wait_seconds(1);
if (info.save_images) {
write_ppm(info, "validation_cache");
}
// End standard draw stuff
#if defined(VK_EXT_validation_cache)
// TODO: Create another validation cache, preferably different from the first
// one and merge it here. Then store the merged one.
// Store away the cache that we've populated. This could conceivably happen
// earlier, depends on when the validation cache stops being populated
// internally.
size_t endCacheSize = 0;
void *endCacheData = nullptr;
// Call with nullptr to get cache size
res = vkGetValidationCacheData(info.device, validationCache, &endCacheSize, nullptr);
assert(res == VK_SUCCESS);
// Allocate memory to hold the populated cache data
endCacheData = (char *)malloc(sizeof(char) * endCacheSize);
if (!endCacheData) {
fputs("Memory error", stderr);
exit(EXIT_FAILURE);
}
// Call again with pointer to buffer
res = vkGetValidationCacheData(info.device, validationCache, &endCacheSize, endCacheData);
assert(res == VK_SUCCESS);
// Write the file to disk, overwriting whatever was there
FILE *pWriteFile;
std::string writeFileName = directoryName + "validation_cache_data.bin";
pWriteFile = fopen(writeFileName.c_str(), "wb");
if (pWriteFile) {
fwrite(endCacheData, sizeof(char), endCacheSize, pWriteFile);
fclose(pWriteFile);
printf(" %u bytes of cacheData written to %s\n", static_cast<uint32_t>(endCacheSize), writeFileName.c_str());
} else {
// Something bad happened
printf(" Unable to write cache data to disk!\n");
}
vkDestroyValidationCache(info.device, validationCache, NULL);
#endif
/* VULKAN_KEY_END */
vkDestroyFence(info.device, drawFence, NULL);
vkDestroySemaphore(info.device, info.imageAcquiredSemaphore, NULL);
destroy_pipeline(info);
destroy_pipeline_cache(info);
destroy_textures(info);
destroy_descriptor_pool(info);
destroy_vertex_buffer(info);
destroy_framebuffers(info);
destroy_shaders(info);
destroy_renderpass(info);
destroy_descriptor_and_pipeline_layouts(info);
destroy_uniform_buffer(info);
destroy_depth_buffer(info);
destroy_swap_chain(info);
destroy_command_buffer(info);
destroy_command_pool(info);
destroy_device(info);
destroy_window(info);
destroy_instance(info);
#endif
return 0;
}
You can’t perform that action at this time.
