-
Notifications
You must be signed in to change notification settings - Fork 500
Expand file tree
/
Copy pathgpuav_shader_instrumentor.cpp
More file actions
1993 lines (1742 loc) · 109 KB
/
Copy pathgpuav_shader_instrumentor.cpp
File metadata and controls
1993 lines (1742 loc) · 109 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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2020-2026 The Khronos Group Inc.
* Copyright (c) 2020-2026 Valve Corporation
* Copyright (c) 2020-2026 LunarG, 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.
*/
#include "gpuav/instrumentation/gpuav_shader_instrumentor.h"
#include <vulkan/vulkan_core.h>
#include <cstdint>
#include "error_message/error_location.h"
#include "generated/vk_extension_helper.h"
#include "generated/dispatch_functions.h"
#include "chassis/chassis_modification_state.h"
#include "gpuav/spirv/interface.h"
#include "utils/shader_utils.h"
#include "utils/spirv_tools_utils.h"
#include "utils/math_utils.h"
#include "gpuav/shaders/gpuav_shaders_constants.h"
#include "gpuav/shaders/gpuav_error_codes.h"
#include "gpuav/shaders/gpuav_error_header.h"
#include "gpuav/spirv/log_error_pass.h"
#include "gpuav/spirv/poison_pass.h"
#include "error_message/spirv_logging.h"
#include <spirv/unified1/NonSemanticShaderDebugInfo100.h>
#include <spirv/unified1/spirv.hpp>
#include "state_tracker/pipeline_state.h"
#include "state_tracker/descriptor_sets.h"
#include "state_tracker/shader_object_state.h"
#include "state_tracker/descriptor_mode.h"
#include "gpuav/resources/gpuav_state_trackers.h"
#include "gpuav/spirv/module.h"
#include "gpuav/spirv/descriptor_indexing_oob_pass.h"
#include "gpuav/spirv/buffer_device_address_pass.h"
#include "gpuav/spirv/descriptor_indexing_oob_pass.h"
#include "gpuav/spirv/descriptor_class_general_buffer_pass.h"
#include "gpuav/spirv/descriptor_class_texel_buffer_pass.h"
#include "gpuav/spirv/ray_query_pass.h"
#include "gpuav/spirv/ray_hit_object_pass.h"
#include "gpuav/spirv/shared_memory_data_race_pass.h"
#include "gpuav/spirv/mesh_shading_pass.h"
#include "gpuav/spirv/debug_printf_pass.h"
#include "gpuav/spirv/debug_descriptor_pass.h"
#include "gpuav/spirv/post_process_descriptor_indexing_pass.h"
#include "gpuav/spirv/vertex_attribute_fetch_oob_pass.h"
#include "gpuav/spirv/sanitizer_pass.h"
#include <cassert>
#include <string>
#include <filesystem>
namespace fs = std::filesystem;
namespace gpuav {
ReadLockGuard GpuShaderInstrumentor::ReadLock() const {
if (global_settings.fine_grained_locking) {
return ReadLockGuard(validation_object_mutex, std::defer_lock);
} else {
return ReadLockGuard(validation_object_mutex);
}
}
WriteLockGuard GpuShaderInstrumentor::WriteLock() {
if (global_settings.fine_grained_locking) {
return WriteLockGuard(validation_object_mutex, std::defer_lock);
} else {
return WriteLockGuard(validation_object_mutex);
}
}
void GpuShaderInstrumentor::SetupClassicDescriptor(const Location& loc) {
const VkDescriptorSetLayoutCreateInfo debug_desc_layout_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, nullptr, 0,
static_cast<uint32_t>(instrumentation_bindings_.size()),
instrumentation_bindings_.data()};
VkResult result = DispatchCreateDescriptorSetLayout(device, &debug_desc_layout_info, nullptr,
&instrumentation_desc_layout_[vvl::DescriptorModeClassic]);
if (result != VK_SUCCESS) {
InternalError(device, loc, "vkCreateDescriptorSetLayout failed for internal descriptor set");
Cleanup();
return;
}
const VkDescriptorSetLayoutCreateInfo dummy_desc_layout_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, nullptr, 0,
0, nullptr};
result = DispatchCreateDescriptorSetLayout(device, &dummy_desc_layout_info, nullptr,
&dummy_desc_layout_[vvl::DescriptorModeClassic]);
if (result != VK_SUCCESS) {
InternalError(device, loc, "vkCreateDescriptorSetLayout failed for internal dummy descriptor set");
Cleanup();
return;
}
std::vector<VkDescriptorSetLayout> debug_layouts;
for (uint32_t j = 0; j < instrumentation_desc_set_bind_index_; ++j) {
debug_layouts.push_back(dummy_desc_layout_[vvl::DescriptorModeClassic]);
}
debug_layouts.push_back(instrumentation_desc_layout_[vvl::DescriptorModeClassic]);
const VkPipelineLayoutCreateInfo debug_pipeline_layout_info = {VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
nullptr,
0u,
static_cast<uint32_t>(debug_layouts.size()),
debug_layouts.data(),
0u,
nullptr};
result = DispatchCreatePipelineLayout(device, &debug_pipeline_layout_info, nullptr,
&instrumentation_pipeline_layout_[vvl::DescriptorModeClassic]);
if (result != VK_SUCCESS) {
InternalError(device, loc, "vkCreateDescriptorSetLayout failed for internal pipeline layout");
Cleanup();
return;
}
}
void GpuShaderInstrumentor::SetupDescriptorBuffers(const Location& loc) {
if (!IsExtEnabled(extensions.vk_ext_descriptor_buffer)) {
return;
}
// We don't use dynamic offset in descriptor buffer, instead we just map the offset each call
// This isn't ideal to set like this, will not be a problem when we get Root Node working
instrumentation_bindings_[glsl::kBindingInstActionIndex].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
instrumentation_bindings_[glsl::kBindingInstCmdResourceIndex].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
const VkDescriptorSetLayoutCreateInfo descriptor_buffer_dsl_info = {
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, nullptr, VK_DESCRIPTOR_SET_LAYOUT_CREATE_DESCRIPTOR_BUFFER_BIT_EXT,
static_cast<uint32_t>(instrumentation_bindings_.size()), instrumentation_bindings_.data()};
VkResult result = DispatchCreateDescriptorSetLayout(device, &descriptor_buffer_dsl_info, nullptr,
&instrumentation_desc_layout_[vvl::DescriptorModeBuffer]);
if (result != VK_SUCCESS) {
InternalError(device, loc, "vkCreateDescriptorSetLayout failed for internal descriptor set for descriptor buffer");
Cleanup();
return;
}
const VkDescriptorSetLayoutCreateInfo descriptor_buffer_dummy_dsl_info = {
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, nullptr, VK_DESCRIPTOR_SET_LAYOUT_CREATE_DESCRIPTOR_BUFFER_BIT_EXT, 0,
nullptr};
result = DispatchCreateDescriptorSetLayout(device, &descriptor_buffer_dummy_dsl_info, nullptr,
&dummy_desc_layout_[vvl::DescriptorModeBuffer]);
if (result != VK_SUCCESS) {
InternalError(device, loc, "vkCreateDescriptorSetLayout failed for internal dummy descriptor set for descriptor buffer");
Cleanup();
return;
}
std::vector<VkDescriptorSetLayout> debug_layouts;
for (uint32_t j = 0; j < instrumentation_desc_set_bind_index_; ++j) {
debug_layouts.push_back(dummy_desc_layout_[vvl::DescriptorModeBuffer]);
}
debug_layouts.push_back(instrumentation_desc_layout_[vvl::DescriptorModeBuffer]);
const VkPipelineLayoutCreateInfo debug_pipeline_layout_db_info = {VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
nullptr,
0u,
static_cast<uint32_t>(debug_layouts.size()),
debug_layouts.data(),
0u,
nullptr};
result = DispatchCreatePipelineLayout(device, &debug_pipeline_layout_db_info, nullptr,
&instrumentation_pipeline_layout_[vvl::DescriptorModeBuffer]);
if (result != VK_SUCCESS) {
InternalError(device, loc, "vkCreateDescriptorSetLayout failed for internal pipeline layout for descriptor buffer");
Cleanup();
return;
}
VkDeviceSize bytes_to_reserve = 0;
DispatchGetDescriptorSetLayoutSizeEXT(device, instrumentation_desc_layout_[vvl::DescriptorModeBuffer], &bytes_to_reserve);
resource_descriptor_buffer_size_ = bytes_to_reserve;
resource_descriptor_buffer_offsets_.resize(glsl::kTotalBindings);
for (uint32_t i = 0; i < glsl::kTotalBindings; i++) {
DispatchGetDescriptorSetLayoutBindingOffsetEXT(device, instrumentation_desc_layout_[vvl::DescriptorModeBuffer], i,
&resource_descriptor_buffer_offsets_[i]);
}
// Revert, because classic needs for fixing disturbed pipelines
instrumentation_bindings_[glsl::kBindingInstActionIndex].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC;
instrumentation_bindings_[glsl::kBindingInstCmdResourceIndex].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC;
}
void GpuShaderInstrumentor::SetupDescriptorHeap(const Location& loc) {
if (!IsExtEnabled(extensions.vk_ext_descriptor_heap)) {
return;
}
const VkPhysicalDeviceDescriptorHeapPropertiesEXT& descriptor_heap_props = phys_dev_ext_props.descriptor_heap_props;
VkDeviceSize bytes_to_reserve =
Align(descriptor_heap_props.bufferDescriptorSize * glsl::kTotalBindings, descriptor_heap_props.bufferDescriptorAlignment);
resource_heap_reserved_bytes_ = bytes_to_reserve;
buffer_descriptor_size_ = descriptor_heap_props.bufferDescriptorSize;
buffer_descriptor_alignment_ = descriptor_heap_props.bufferDescriptorAlignment;
push_data_offset_ = static_cast<uint32_t>(descriptor_heap_props.maxPushDataSize) - 8u;
}
// In charge of getting things for shader instrumentation that both GPU-AV and DebugPrintF will need
void GpuShaderInstrumentor::FinishDeviceSetup(const VkDeviceCreateInfo* pCreateInfo, const Location& loc) {
DeviceProxy::FinishDeviceSetup(pCreateInfo, loc);
// Update feature and extension state based on changes made to the create info.
GetEnabledDeviceFeatures(pCreateInfo, &modified_features, api_version);
modified_extensions = DeviceExtensions(extensions, api_version, pCreateInfo);
// Check hard requirements for GPU-AV against what we enabled.
if (!modified_features.fragmentStoresAndAtomics) {
InternalError(
device, loc,
"GPU Shader Instrumentation requires fragmentStoresAndAtomics to allow witting out data inside the fragment shader.");
return;
}
if (!modified_features.vertexPipelineStoresAndAtomics) {
InternalError(device, loc,
"GPU Shader Instrumentation requires vertexPipelineStoresAndAtomics to allow witting out data inside the "
"vertex shader.");
return;
}
if (!modified_features.timelineSemaphore) {
InternalError(device, loc,
"GPU Shader Instrumentation requires timelineSemaphore to manage when command buffers are submitted at queue "
"submit time.");
return;
}
if (!modified_features.bufferDeviceAddress) {
InternalError(device, loc, "GPU Shader Instrumentation requires bufferDeviceAddress to manage witting out of the shader.");
return;
}
if (!modified_features.scalarBlockLayout) {
InternalError(device, loc, "GPU Shader Instrumentation requires scalarBlockLayout to pack data in a shader.");
return;
}
if (modified_features.vulkanMemoryModel && !modified_features.vulkanMemoryModelDeviceScope) {
InternalError(device, loc,
"GPU Shader Instrumentation requires vulkanMemoryModelDeviceScope feature (if vulkanMemoryModel is enabled) "
"to let us call atomicAdd to the output buffer.");
return;
}
// maxBoundDescriptorSets limit, but possibly adjusted
const uint32_t adjusted_max_desc_sets_limit =
std::min(kMaxAdjustedBoundDescriptorSet, phys_dev_props.limits.maxBoundDescriptorSets);
// If gpu_validation_reserve_binding_slot: the max slot is where we reserved
// else: always use the last possible set as least likely to be used
instrumentation_desc_set_bind_index_ = adjusted_max_desc_sets_limit - 1;
// We can't do anything if there is only one.
// Device probably not a legit Vulkan device, since there should be at least 4. Protect ourselves.
if (adjusted_max_desc_sets_limit == 1) {
InternalError(device, loc, "Device can bind only a single descriptor set.");
return;
}
SetupClassicDescriptor(loc);
SetupDescriptorBuffers(loc);
SetupDescriptorHeap(loc);
// Settings we will want for every SPIR-V instrumention pass
instrumentation_device_settings_.output_buffer_descriptor_set = instrumentation_desc_set_bind_index_;
instrumentation_device_settings_.safe_mode = gpuav_settings.safe_mode;
instrumentation_device_settings_.print_debug_info = gpuav_settings.debug_print_instrumentation_info;
instrumentation_device_settings_.max_instrumentations_count = gpuav_settings.debug_max_instrumentations_count;
instrumentation_device_settings_.support_non_semantic_info =
IsExtEnabled(extensions.vk_khr_shader_non_semantic_info) && !IsExtEnabled(extensions.vk_khr_portability_subset);
instrumentation_device_settings_.error_buffer_data_length = glsl::kErrorBufferDataLength;
instrumentation_device_settings_.debug_printf_buffer_size = gpuav_settings.debug_printf_buffer_size;
instrumentation_device_settings_.max_compute_shared_memory_size = phys_dev_props.limits.maxComputeSharedMemorySize;
}
void GpuShaderInstrumentor::Cleanup() {
for (uint32_t i = 0; i < vvl::DescriptorModeCount; i++) {
if (instrumentation_desc_layout_[i]) {
DispatchDestroyDescriptorSetLayout(device, instrumentation_desc_layout_[i], nullptr);
instrumentation_desc_layout_[i] = VK_NULL_HANDLE;
}
if (dummy_desc_layout_[i]) {
DispatchDestroyDescriptorSetLayout(device, dummy_desc_layout_[i], nullptr);
dummy_desc_layout_[i] = VK_NULL_HANDLE;
}
if (instrumentation_pipeline_layout_[i]) {
DispatchDestroyPipelineLayout(device, instrumentation_pipeline_layout_[i], nullptr);
instrumentation_pipeline_layout_[i] = VK_NULL_HANDLE;
}
}
}
void GpuShaderInstrumentor::PreCallRecordDestroyDevice(VkDevice device, const VkAllocationCallbacks* pAllocator,
const RecordObject& record_obj) {
Cleanup();
DeviceProxy::PreCallRecordDestroyDevice(device, pAllocator, record_obj);
}
// Just gives a warning about a possible deadlock.
bool GpuShaderInstrumentor::ValidateCmdWaitEvents(VkCommandBuffer command_buffer, VkPipelineStageFlags2 src_stage_mask,
const Location& loc) const {
if (src_stage_mask & VK_PIPELINE_STAGE_2_HOST_BIT) {
std::ostringstream error_msg;
error_msg << loc.Message()
<< " recorded with VK_PIPELINE_STAGE_HOST_BIT set. GPU-Assisted validation waits on queue completion. This wait "
"could block the host's signaling of this event, resulting in deadlock.";
InternalError(command_buffer, loc, error_msg.str().c_str());
}
return false;
}
bool GpuShaderInstrumentor::PreCallValidateCmdWaitEvents(
VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents, VkPipelineStageFlags srcStageMask,
VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier* pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
const VkImageMemoryBarrier* pImageMemoryBarriers, const ErrorObject& error_obj) const {
return ValidateCmdWaitEvents(commandBuffer, static_cast<VkPipelineStageFlags2>(srcStageMask), error_obj.location);
}
bool GpuShaderInstrumentor::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount,
const VkEvent* pEvents, const VkDependencyInfoKHR* pDependencyInfos,
const ErrorObject& error_obj) const {
return PreCallValidateCmdWaitEvents2(commandBuffer, eventCount, pEvents, pDependencyInfos, error_obj);
}
bool GpuShaderInstrumentor::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount,
const VkEvent* pEvents, const VkDependencyInfo* pDependencyInfos,
const ErrorObject& error_obj) const {
VkPipelineStageFlags2 src_stage_mask = 0;
for (uint32_t i = 0; i < eventCount; i++) {
auto exec_scopes = sync_utils::GetExecScopes(pDependencyInfos[i]);
src_stage_mask |= exec_scopes.src;
}
return ValidateCmdWaitEvents(commandBuffer, src_stage_mask, error_obj.location);
}
vvl::DescriptorMode GpuShaderInstrumentor::SelectDescriptorModeFromDSL(uint32_t set_layout_count,
const VkDescriptorSetLayout* set_layouts) const {
vvl::DescriptorMode mode = vvl::DescriptorModeClassic;
if (IsExtEnabled(extensions.vk_ext_descriptor_buffer)) {
if (set_layout_count > 0) {
// It is valid to have null DSL (using GPL) so need to find the first valid
for (uint32_t i = 0; i < set_layout_count; i++) {
// VU 08008 forces all layouts to have this flag, so only need to check first flag
if (set_layouts[i]) {
const auto& dsl_state = Get<vvl::DescriptorSetLayout>(set_layouts[i]);
if (dsl_state->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_DESCRIPTOR_BUFFER_BIT_EXT) {
mode = vvl::DescriptorModeBuffer;
break;
}
}
}
} else if (enabled_features.descriptorBuffer) {
// At this point, we have actually zero way to know how this VkPipelineLayout/VkShaderEXT is going to be used because
// the extension never added a flag for creation time here.... so assume that if the descriptorBuffer feature is
// enabled, app is using it. This is such a rare case it likely is good enough of a solution for now, otherwise we will
// have to create 2 versions a modified handle and swap it out later.
mode = vvl::DescriptorModeBuffer;
}
}
return mode;
}
void GpuShaderInstrumentor::PreCallRecordCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkPipelineLayout* pPipelineLayout, const RecordObject& record_obj,
chassis::CreatePipelineLayout& chassis_state) {
if (gpuav_settings.IsSpirvModified()) {
if (chassis_state.modified_create_info.setLayoutCount > instrumentation_desc_set_bind_index_) {
std::ostringstream strm;
strm << "pCreateInfo::setLayoutCount (" << chassis_state.modified_create_info.setLayoutCount
<< ") will conflicts with validation's descriptor set at slot " << instrumentation_desc_set_bind_index_ << ". "
<< "This Pipeline Layout has too many descriptor sets that will not allow GPU shader instrumentation to be setup "
"for pipelines created with it, therefore no validation error will be repored for them by GPU-AV at runtime.";
InternalWarning(device, record_obj.location, strm.str().c_str());
} else {
vvl::DescriptorMode mode = SelectDescriptorModeFromDSL(pCreateInfo->setLayoutCount, pCreateInfo->pSetLayouts);
// Modify the pipeline layout by:
// 1. Copying the caller's descriptor set desc_layouts
// 2. Fill in dummy descriptor layouts up to the max binding
// 3. Fill in with the debug descriptor layout at the max binding slot
chassis_state.new_layouts.reserve(instrumentation_desc_set_bind_index_ + 1);
chassis_state.new_layouts.insert(chassis_state.new_layouts.end(), &pCreateInfo->pSetLayouts[0],
&pCreateInfo->pSetLayouts[pCreateInfo->setLayoutCount]);
for (uint32_t i = pCreateInfo->setLayoutCount; i < instrumentation_desc_set_bind_index_; ++i) {
chassis_state.new_layouts.push_back(dummy_desc_layout_[mode]);
}
chassis_state.new_layouts.push_back(instrumentation_desc_layout_[mode]);
chassis_state.modified_create_info.pSetLayouts = chassis_state.new_layouts.data();
chassis_state.modified_create_info.setLayoutCount = instrumentation_desc_set_bind_index_ + 1;
}
}
}
void GpuShaderInstrumentor::PostCallRecordCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator, VkShaderModule* pShaderModule,
const RecordObject& record_obj,
chassis::CreateShaderModule& chassis_state) {
if (record_obj.result != VK_SUCCESS) {
return;
}
// By default, we instrument everything, but if the setting is enabled, we only will instrument the shaders the app picks
if (gpuav_settings.select_instrumented_shaders && IsSelectiveInstrumentationEnabled(pCreateInfo->pNext)) {
// If this is being filled up, likely only a few shaders and the app scope is narrowed down, so no need to spend time
// removing these later
selected_instrumented_shaders.insert(*pShaderModule);
};
}
// We on the spot create a VkShaderEXT without instrumentation to return to the user
// We assume people are not trying to use GPU-AV while calling vkGetShaderBinaryDataEXT
// But this is needed for things like CTS that are using this to mock a fake Binary Shader Object
void GpuShaderInstrumentor::PreCallRecordGetShaderBinaryDataEXT(VkDevice device, VkShaderEXT shader, size_t* pDataSize, void* pData,
const RecordObject& record_obj,
chassis::ShaderBinaryData& chassis_state) {
const auto& shader_object_state = Get<vvl::ShaderObject>(shader);
ASSERT_AND_RETURN(shader_object_state);
auto& sub_state = SubState(*shader_object_state);
VkShaderEXT original_handle = VK_NULL_HANDLE;
auto it = instrumented_shaders_map_.find(sub_state.unique_shader_id);
if (it == instrumented_shaders_map_.end() || it->second.original_spirv.empty()) {
// This will occur if the shader was so simple we didn't even instrument anything
return;
}
// The original pCode might be gone, so need to make a shallow copy and put original SPIR-V inside
VkShaderCreateInfoEXT create_info_copy = *sub_state.original_create_info.ptr();
// The pCode doesn't live in the safe struct, we need to grab it from our other map
const gpuav::InstrumentedShader* instrumented_shader = &it->second;
create_info_copy.pCode = instrumented_shader->original_spirv.data();
create_info_copy.codeSize = instrumented_shader->original_spirv.size() * sizeof(uint32_t);
// Only warn on the first call to query the size
if (pData == nullptr) {
InternalWarning(
shader, record_obj.location,
"GPU-AV instruments all shaders at vkCreateShadersEXT time, this means there are embedded descriptors bound "
"that we can't detect if needed or not later.\nWe will be calling vkCreateShadersEXT again now to create the "
"original shader to pass down to the drivere.");
}
// vkGetShaderBinaryDataEXT will be called twice, only need to re-created once
if (sub_state.original_handle == VK_NULL_HANDLE) {
DispatchCreateShadersEXT(device, 1, &create_info_copy, nullptr, &original_handle);
sub_state.original_handle = original_handle; // will be destroyed later
}
chassis_state.modified_shader_handle = sub_state.original_handle;
}
bool GpuShaderInstrumentor::PreCallRecordShaderObjectInstrumentation(vku::safe_VkShaderCreateInfoEXT& modified_create_info,
const Location& create_info_loc,
chassis::ShaderObjectInstrumentationData& instrumentation_data,
const vvl::DescriptorMode descriptor_mode) {
const uint32_t unique_shader_id = unique_shader_module_id_++;
std::vector<uint32_t>& instrumented_spirv = instrumentation_data.instrumented_spirv;
spirv::InstrumentationInterface interface(create_info_loc);
interface.unique_shader_id = unique_shader_id;
interface.entry_point_name = modified_create_info.pName;
interface.entry_point_stage = modified_create_info.stage;
interface.specialization_info = modified_create_info.pSpecializationInfo->ptr();
interface.has_task_shader = (modified_create_info.flags & VK_SHADER_CREATE_NO_TASK_SHADER_BIT_EXT) == 0;
interface.descriptor_mode = descriptor_mode;
BuildDescriptorSetLayoutInfo(modified_create_info, interface.instrumentation_dsl);
const bool is_shader_instrumented = InstrumentShader(
vvl::make_span(static_cast<const uint32_t*>(modified_create_info.pCode), modified_create_info.codeSize / sizeof(uint32_t)),
interface, instrumented_spirv);
if (is_shader_instrumented) {
instrumentation_data.unique_shader_id = unique_shader_id;
modified_create_info.pCode = instrumented_spirv.data();
modified_create_info.codeSize = instrumented_spirv.size() * sizeof(uint32_t);
}
return is_shader_instrumented;
}
void GpuShaderInstrumentor::PreCallRecordCreateShadersEXT(VkDevice device, uint32_t createInfoCount,
const VkShaderCreateInfoEXT* pCreateInfos,
const VkAllocationCallbacks* pAllocator, VkShaderEXT* pShaders,
const RecordObject& record_obj, chassis::ShaderObject& chassis_state) {
if (!gpuav_settings.IsSpirvModified()) return;
// Resize here so if using just CoreCheck we don't waste time allocating this
chassis_state.instrumentations_data.resize(createInfoCount);
chassis_state.modified_create_infos.resize(createInfoCount);
for (uint32_t i = 0; i < createInfoCount; ++i) {
// Need deep copy as there might be pNext items
vku::safe_VkShaderCreateInfoEXT& new_create_info = chassis_state.modified_create_infos[i];
new_create_info.initialize(&pCreateInfos[i]);
if (new_create_info.codeType != VK_SHADER_CODE_TYPE_SPIRV_EXT) {
continue;
} else if (!chassis_state.module_states[i]) {
continue;
}
const Location& create_info_loc = record_obj.location.dot(vvl::Field::pCreateInfos, i);
auto& instrumentation_data = chassis_state.instrumentations_data[i];
// See pipeline version for explanation
if (new_create_info.flags & VK_SHADER_CREATE_INDIRECT_BINDABLE_BIT_EXT) {
InternalError(device, create_info_loc,
"Unable to instrument shader using VkIndirectExecutionSetEXT validly, things might work, but likely will "
"not because of GPU-AV's usage of VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC (If you don't "
"need VK_SHADER_CREATE_INDIRECT_BINDABLE_BIT_EXT, turn it off).");
}
if (new_create_info.setLayoutCount > instrumentation_desc_set_bind_index_) {
std::ostringstream strm;
strm << "pCreateInfos[" << i << "]::setLayoutCount (" << new_create_info.setLayoutCount
<< ") will conflicts with validation's descriptor set at slot " << instrumentation_desc_set_bind_index_ << ". "
<< "This Shader Object has too many descriptor sets that will not allow GPU shader instrumentation to be setup "
"for VkShaderEXT created with it, therefore no validation error will be repored for them by GPU-AV at "
"runtime.";
InternalWarning(device, record_obj.location, strm.str().c_str());
} else if (gpuav_settings.select_instrumented_shaders && !IsSelectiveInstrumentationEnabled(new_create_info.pNext)) {
continue;
} else {
// Modify the pipeline layout by:
// 1. Copying the caller's descriptor set desc_layouts
// 2. Fill in dummy descriptor layouts up to the max binding
// 3. Fill in with the debug descriptor layout at the max binding slot
const VkShaderCreateInfoEXT& original_create_info = pCreateInfos[i];
const vvl::DescriptorMode mode =
(original_create_info.flags & VK_SHADER_CREATE_DESCRIPTOR_HEAP_BIT_EXT)
? vvl::DescriptorMode::DescriptorModeHeap
: SelectDescriptorModeFromDSL(original_create_info.setLayoutCount, original_create_info.pSetLayouts);
if (mode == vvl::DescriptorMode::DescriptorModeHeap) {
AddDescriptorHeapMappings(reinterpret_cast<VkBaseOutStructure*>(&new_create_info));
chassis_state.is_modified |=
PreCallRecordShaderObjectInstrumentation(new_create_info, create_info_loc, instrumentation_data, mode);
} else {
// We need to remove the old layouts we copied in safe_VkShaderCreateInfoEXT::initialize
if (new_create_info.pSetLayouts) {
delete[] new_create_info.pSetLayouts;
}
new_create_info.setLayoutCount = instrumentation_desc_set_bind_index_ + 1;
new_create_info.pSetLayouts = new VkDescriptorSetLayout[new_create_info.setLayoutCount];
for (uint32_t k = 0; k < original_create_info.setLayoutCount; ++k) {
new_create_info.pSetLayouts[k] = original_create_info.pSetLayouts[k];
}
for (uint32_t k = original_create_info.setLayoutCount; k < instrumentation_desc_set_bind_index_; ++k) {
new_create_info.pSetLayouts[k] = dummy_desc_layout_[mode];
}
new_create_info.pSetLayouts[instrumentation_desc_set_bind_index_] = instrumentation_desc_layout_[mode];
chassis_state.is_modified |=
PreCallRecordShaderObjectInstrumentation(new_create_info, create_info_loc, instrumentation_data, mode);
}
}
}
chassis_state.pCreateInfos = reinterpret_cast<VkShaderCreateInfoEXT*>(chassis_state.modified_create_infos.data());
}
void GpuShaderInstrumentor::PostCallRecordCreateShadersEXT(VkDevice device, uint32_t createInfoCount,
const VkShaderCreateInfoEXT* pCreateInfos,
const VkAllocationCallbacks* pAllocator, VkShaderEXT* pShaders,
const RecordObject& record_obj, chassis::ShaderObject& chassis_state) {
if (!gpuav_settings.IsSpirvModified()) {
return;
}
// This can occur if the driver failed to compile the instrumented shader or if a PreCall step failed
if (!chassis_state.is_modified) {
return;
}
for (uint32_t i = 0; i < createInfoCount; ++i) {
// If there are multiple shaders being created, and one is bad, will return a non VK_SUCCESS but we need to check if the
// VkShaderEXT was null or not to actually know if it was created
const VkShaderEXT shader_handle = pShaders[i];
if (shader_handle == VK_NULL_HANDLE) {
continue;
}
auto& instrumentation_data = chassis_state.instrumentations_data[i];
// if the shader for some reason was not instrumented, there is nothing to save
// (like not using VK_SHADER_CODE_TYPE_SPIRV_EXT)
if (!instrumentation_data.IsInstrumented()) {
continue;
}
const auto& shader_object_state = Get<vvl::ShaderObject>(shader_handle);
ASSERT_AND_CONTINUE(shader_object_state);
auto& sub_state = SubState(*shader_object_state);
sub_state.was_instrumented = true;
sub_state.unique_shader_id = instrumentation_data.unique_shader_id;
// Note - this doesn't make a deep copy of the pCode, but does of the DescriptorSetLayout which we
sub_state.original_create_info.initialize(&pCreateInfos[i]);
// We currently need to store a copy of the original, non-instrumented shader so if there is debug information.
std::vector<uint32_t> code;
if (shader_object_state->stage.spirv_state) {
code = shader_object_state->stage.spirv_state->words_;
}
instrumented_shaders_map_.insert_or_assign(instrumentation_data.unique_shader_id, VK_NULL_HANDLE, VK_NULL_HANDLE,
shader_handle, std::move(code));
}
}
void GpuShaderInstrumentor::PreCallRecordDestroyShaderEXT(VkDevice device, VkShaderEXT shader,
const VkAllocationCallbacks* pAllocator, const RecordObject& record_obj) {
if (auto shader_object_state = Get<vvl::ShaderObject>(shader)) {
auto& sub_state = SubState(*shader_object_state);
instrumented_shaders_map_.pop(sub_state.unique_shader_id);
if (sub_state.original_handle != VK_NULL_HANDLE) {
DispatchDestroyShaderEXT(device, sub_state.original_handle, nullptr);
}
}
}
void GpuShaderInstrumentor::PreCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
const VkGraphicsPipelineCreateInfo* pCreateInfos,
const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
const RecordObject& record_obj, PipelineStates& pipeline_states,
chassis::CreateGraphicsPipelines& chassis_state) {
if (!gpuav_settings.IsSpirvModified()) return;
chassis_state.shader_instrumentations_metadata.resize(count);
chassis_state.modified_create_infos.resize(count);
for (uint32_t i = 0; i < count; ++i) {
const auto& pipeline_state = pipeline_states[i];
const Location create_info_loc = record_obj.location.dot(vvl::Field::pCreateInfos, i);
// Need to make a deep copy so if SPIR-V is inlined, user doesn't see it after the call
auto& new_pipeline_ci = chassis_state.modified_create_infos[i];
new_pipeline_ci.initialize(&pipeline_state->GraphicsCreateInfo());
if (!NeedPipelineCreationShaderInstrumentation(*pipeline_state, create_info_loc)) {
continue;
}
auto& shader_instrumentation_metadata = chassis_state.shader_instrumentations_metadata[i];
bool success = false;
if (pipeline_state->linking_shaders != 0) {
success = PreCallRecordPipelineCreationShaderInstrumentationGPL(pAllocator, *pipeline_state, new_pipeline_ci,
create_info_loc, shader_instrumentation_metadata);
} else {
success = PreCallRecordPipelineCreationShaderInstrumentation(pAllocator, *pipeline_state, new_pipeline_ci,
uint32_t(pipeline_state->stage_states.size()),
create_info_loc, shader_instrumentation_metadata);
}
if (!success) {
return;
}
}
chassis_state.is_modified = true;
chassis_state.pCreateInfos = reinterpret_cast<VkGraphicsPipelineCreateInfo*>(chassis_state.modified_create_infos.data());
}
void GpuShaderInstrumentor::PreCallRecordCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
const VkComputePipelineCreateInfo* pCreateInfos,
const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
const RecordObject& record_obj, PipelineStates& pipeline_states,
chassis::CreateComputePipelines& chassis_state) {
if (!gpuav_settings.IsSpirvModified()) return;
chassis_state.shader_instrumentations_metadata.resize(count);
chassis_state.modified_create_infos.resize(count);
for (uint32_t i = 0; i < count; ++i) {
const auto& pipeline_state = pipeline_states[i];
const Location create_info_loc = record_obj.location.dot(vvl::Field::pCreateInfos, i);
// Need to make a deep copy so if SPIR-V is inlined, user doesn't see it after the call
auto& new_pipeline_ci = chassis_state.modified_create_infos[i];
new_pipeline_ci.initialize(&pipeline_state->ComputeCreateInfo());
if (!NeedPipelineCreationShaderInstrumentation(*pipeline_state, create_info_loc)) {
continue;
}
auto& shader_instrumentation_metadata = chassis_state.shader_instrumentations_metadata[i];
bool success = PreCallRecordPipelineCreationShaderInstrumentation(pAllocator, *pipeline_state, new_pipeline_ci, 1,
create_info_loc, shader_instrumentation_metadata);
if (!success) {
return;
}
}
chassis_state.is_modified = true;
chassis_state.pCreateInfos = reinterpret_cast<VkComputePipelineCreateInfo*>(chassis_state.modified_create_infos.data());
}
void GpuShaderInstrumentor::PreCallRecordCreateRayTracingPipelinesKHR(
VkDevice device, VkDeferredOperationKHR deferredOperation, VkPipelineCache pipelineCache, uint32_t count,
const VkRayTracingPipelineCreateInfoKHR* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
const RecordObject& record_obj, PipelineStates& pipeline_states, chassis::CreateRayTracingPipelinesKHR& chassis_state) {
if (!gpuav_settings.IsSpirvModified()) {
return;
}
chassis_state.shader_instrumentations_metadata.resize(count);
chassis_state.modified_create_infos.resize(count);
for (uint32_t i = 0; i < count; ++i) {
const auto& pipeline_state = pipeline_states[i];
const Location create_info_loc = record_obj.location.dot(vvl::Field::pCreateInfos, i);
// Need to make a deep copy so if SPIR-V is inlined, user doesn't see it after the call
auto& new_pipeline_ci = chassis_state.modified_create_infos[i];
new_pipeline_ci.initialize(&pipeline_state->RayTracingCreateInfo());
if (!NeedPipelineCreationShaderInstrumentation(*pipeline_state, create_info_loc)) {
continue;
}
auto& shader_instrumentation_metadata = chassis_state.shader_instrumentations_metadata[i];
// Ray tracing pipelines can be made of libraries, but contrary to GPL instrumentation is not postponed
// to final link time, and done at ray tracing library creation time.
// => No need to iterate over shader stages coming from libraries,
// stop at VkRayTracingPipelineCreateInfoKHR::stageCount
// Note: This code implicitly relies on the fact that in pipeline_state->stage_states,
// stages coming from libraries are added last.
bool success = PreCallRecordPipelineCreationShaderInstrumentation(pAllocator, *pipeline_state, new_pipeline_ci,
new_pipeline_ci.stageCount, create_info_loc,
shader_instrumentation_metadata);
if (!success) {
return;
}
}
chassis_state.is_modified = true;
chassis_state.pCreateInfos = reinterpret_cast<VkRayTracingPipelineCreateInfoKHR*>(chassis_state.modified_create_infos.data());
}
template <typename CreateInfos, typename SafeCreateInfos>
static void UtilCopyCreatePipelineFeedbackData(CreateInfos& create_info, SafeCreateInfos& safe_create_info) {
auto src_feedback_struct = vku::FindStructInPNextChain<VkPipelineCreationFeedbackCreateInfo>(safe_create_info.pNext);
if (!src_feedback_struct) return;
auto dst_feedback_struct = const_cast<VkPipelineCreationFeedbackCreateInfo*>(
vku::FindStructInPNextChain<VkPipelineCreationFeedbackCreateInfo>(create_info.pNext));
*dst_feedback_struct->pPipelineCreationFeedback = *src_feedback_struct->pPipelineCreationFeedback;
for (uint32_t j = 0; j < src_feedback_struct->pipelineStageCreationFeedbackCount; j++) {
dst_feedback_struct->pPipelineStageCreationFeedbacks[j] = src_feedback_struct->pPipelineStageCreationFeedbacks[j];
}
}
void GpuShaderInstrumentor::PostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
const VkGraphicsPipelineCreateInfo* pCreateInfos,
const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
const RecordObject& record_obj, PipelineStates& pipeline_states,
chassis::CreateGraphicsPipelines& chassis_state) {
if (!gpuav_settings.IsSpirvModified()) return;
// VK_PIPELINE_COMPILE_REQUIRED means that the current pipeline creation call was used to poke the driver cache,
// no pipeline is created in this case
if (record_obj.result == VK_PIPELINE_COMPILE_REQUIRED) return;
// This can occur if the driver failed to compile the instrumented shader or if a PreCall step failed
if (!chassis_state.is_modified) return;
for (uint32_t i = 0; i < count; ++i) {
const VkPipeline pipeline_handle = pPipelines[i];
if (pipeline_handle == VK_NULL_HANDLE) {
continue; // vkspec.html#pipelines-multiple
}
UtilCopyCreatePipelineFeedbackData(pCreateInfos[i], chassis_state.modified_create_infos[i]);
auto pipeline_state = Get<vvl::Pipeline>(pipeline_handle);
ASSERT_AND_CONTINUE(pipeline_state);
// Move all instrumentation until the final linking time
if (pipeline_state->create_flags & VK_PIPELINE_CREATE_LIBRARY_BIT_KHR) continue;
auto& shader_instrumentation_metadata = chassis_state.shader_instrumentations_metadata[i];
if (pipeline_state->linking_shaders != 0) {
PostCallRecordPipelineCreationShaderInstrumentationGPL(*pipeline_state, shader_instrumentation_metadata);
} else {
PostCallRecordPipelineCreationShaderInstrumentation(*pipeline_state, uint32_t(pipeline_state->stage_states.size()),
shader_instrumentation_metadata);
}
}
}
void GpuShaderInstrumentor::PostCallRecordCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
const VkComputePipelineCreateInfo* pCreateInfos,
const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
const RecordObject& record_obj, PipelineStates& pipeline_states,
chassis::CreateComputePipelines& chassis_state) {
if (!gpuav_settings.IsSpirvModified()) return;
// VK_PIPELINE_COMPILE_REQUIRED means that the current pipeline creation call was used to poke the driver cache,
// no pipeline is created in this case
if (record_obj.result == VK_PIPELINE_COMPILE_REQUIRED) return;
// This can occur if the driver failed to compile the instrumented shader or if a PreCall step failed
if (!chassis_state.is_modified) return;
for (uint32_t i = 0; i < count; ++i) {
const VkPipeline pipeline_handle = pPipelines[i];
if (pipeline_handle == VK_NULL_HANDLE) {
continue; // vkspec.html#pipelines-multiple
}
UtilCopyCreatePipelineFeedbackData(pCreateInfos[i], chassis_state.modified_create_infos[i]);
auto pipeline_state = Get<vvl::Pipeline>(pipeline_handle);
ASSERT_AND_CONTINUE(pipeline_state);
auto& shader_instrumentation_metadata = chassis_state.shader_instrumentations_metadata[i];
PostCallRecordPipelineCreationShaderInstrumentation(*pipeline_state, 1, shader_instrumentation_metadata);
}
}
void GpuShaderInstrumentor::PostCallRecordCreateRayTracingPipelinesKHR(
VkDevice device, VkDeferredOperationKHR deferredOperation, VkPipelineCache pipelineCache, uint32_t count,
const VkRayTracingPipelineCreateInfoKHR* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
const RecordObject& record_obj, PipelineStates& pipeline_states,
std::shared_ptr<chassis::CreateRayTracingPipelinesKHR> chassis_state) {
// This can occur if the driver failed to compile the instrumented shader or if a PreCall step failed
if (!chassis_state->is_modified) {
return;
}
if (!gpuav_settings.IsSpirvModified()) {
return;
}
// VK_PIPELINE_COMPILE_REQUIRED means that the current pipeline creation call was used to poke the driver cache,
// no pipeline is created in this case
if (record_obj.result == VK_PIPELINE_COMPILE_REQUIRED) {
return;
}
const bool is_operation_deferred = deferredOperation != VK_NULL_HANDLE && record_obj.result == VK_OPERATION_DEFERRED_KHR;
if (is_operation_deferred) {
for (uint32_t i = 0; i < count; ++i) {
UtilCopyCreatePipelineFeedbackData(pCreateInfos[i], chassis_state->modified_create_infos[i]);
}
if (dispatch_device_->wrap_handles) {
deferredOperation = dispatch_device_->Unwrap(deferredOperation);
}
auto found = dispatch_device_->deferred_operation_post_check.pop(deferredOperation);
std::vector<std::function<void(std::pair<uint32_t, VkPipeline*>)>> deferred_op_post_checks;
if (found->first) {
deferred_op_post_checks = std::move(found->second);
} else {
// vvl::Device::PostCallRecordCreateRayTracingPipelinesKHR should have added a lambda in
// deferred_operation_post_check for the current deferredOperation.
// This lambda is responsible for initializing the pipeline state we maintain,
// this state will be accessed in the following lambda.
// Given how PostCallRecordCreateRayTracingPipelinesKHR is called in
// GpuShaderInstrumentor::PostCallRecordCreateRayTracingPipelinesKHR
// conditions holds as of writing. But it is something we need to be aware of.
assert(false);
return;
}
deferred_op_post_checks.emplace_back([this, held_chassis_state =
chassis_state](std::pair<uint32_t, VkPipeline*> pipelines) mutable {
for (const auto [pipe_i, pipe] : vvl::enumerate(pipelines.second, pipelines.first)) {
std::shared_ptr<vvl::Pipeline> pipeline_state = ((GpuShaderInstrumentor*)this)->Get<vvl::Pipeline>(pipe);
ASSERT_AND_CONTINUE(pipeline_state);
if (pipeline_state->ray_tracing_library_ci) {
for (VkPipeline lib : vvl::make_span(pipeline_state->ray_tracing_library_ci->pLibraries,
pipeline_state->ray_tracing_library_ci->libraryCount)) {
auto lib_state = ((GpuShaderInstrumentor*)this)->Get<vvl::Pipeline>(lib);
ASSERT_AND_CONTINUE(lib_state);
pipeline_state->instrumentation_data.was_instrumented |= lib_state->instrumentation_data.was_instrumented;
}
}
auto& shader_instrumentation_metadata = held_chassis_state->shader_instrumentations_metadata[pipe_i];
// Ray tracing pipelines can be made of libraries, but contrary to GPL instrumentation is not postponed
// to final link time, and done at ray tracing library creation time.
// => No need to iterate over shader stages coming from libraries,
// stop at VkRayTracingPipelineCreateInfoKHR::stageCount
// Note: This code implicitly relies on the fact that in pipeline_state->stage_states,
// stages coming from libraries are added last.
PostCallRecordPipelineCreationShaderInstrumentation(
*pipeline_state, pipeline_state->RayTracingCreateInfo().stageCount, shader_instrumentation_metadata);
}
});
dispatch_device_->deferred_operation_post_check.insert(deferredOperation, std::move(deferred_op_post_checks));
} else {
for (uint32_t i = 0; i < count; ++i) {
const VkPipeline pipeline_handle = pPipelines[i];
if (pipeline_handle == VK_NULL_HANDLE) {
continue; // vkspec.html#pipelines-multiple
}
UtilCopyCreatePipelineFeedbackData(pCreateInfos[i], chassis_state->modified_create_infos[i]);
auto pipeline_state = Get<vvl::Pipeline>(pipeline_handle);
if (pipeline_state->ray_tracing_library_ci) {
for (VkPipeline lib : vvl::make_span(pipeline_state->ray_tracing_library_ci->pLibraries,
pipeline_state->ray_tracing_library_ci->libraryCount)) {
auto lib_state = Get<vvl::Pipeline>(lib);
ASSERT_AND_CONTINUE(lib_state);
pipeline_state->instrumentation_data.was_instrumented |= lib_state->instrumentation_data.was_instrumented;
}
}
auto& shader_instrumentation_metadata = chassis_state->shader_instrumentations_metadata[i];
// Ray tracing pipelines can be made of libraries, but contrary to GPL instrumentation is not postponed
// to final link time, and done at ray tracing library creation time.
// => No need to iterate over shader stages coming from libraries,
// stop at VkRayTracingPipelineCreateInfoKHR::stageCount
// Note: This code implicitly relies on the fact that in pipeline_state->stage_states,
// stages coming from libraries are added last.
PostCallRecordPipelineCreationShaderInstrumentation(*pipeline_state, pipeline_state->RayTracingCreateInfo().stageCount,
shader_instrumentation_metadata);
}
}
}
// Remove all the shader trackers associated with this destroyed pipeline.
void GpuShaderInstrumentor::PreCallRecordDestroyPipeline(VkDevice device, VkPipeline pipeline,
const VkAllocationCallbacks* pAllocator, const RecordObject& record_obj) {
if (auto pipeline_state = Get<vvl::Pipeline>(pipeline)) {
for (auto shader_module_handle : pipeline_state->instrumentation_data.shader_modules) {
DispatchDestroyShaderModule(device, shader_module_handle, pAllocator);
}
if (pipeline_state->instrumentation_data.instrumented_pipeline_lib != VK_NULL_HANDLE) {
DispatchDestroyPipeline(device, pipeline_state->instrumentation_data.instrumented_pipeline_lib, pAllocator);
}
}
}
template <typename CreateInfo>
VkShaderModule GetShaderModule(const CreateInfo& create_info, VkShaderStageFlagBits stage) {
for (uint32_t i = 0; i < create_info.stageCount; ++i) {
if (create_info.pStages[i].stage == stage) {
return create_info.pStages[i].module;
}
}
return {};
}
template <>
VkShaderModule GetShaderModule(const VkComputePipelineCreateInfo& create_info, VkShaderStageFlagBits) {
return create_info.stage.module;
}
template <typename SafeType>
void SetShaderModule(SafeType& create_info, const vku::safe_VkPipelineShaderStageCreateInfo& stage_info,
VkShaderModule shader_module, uint32_t stage_ci_index) {
create_info.pStages[stage_ci_index] = stage_info;
create_info.pStages[stage_ci_index].module = shader_module;
}
template <>
void SetShaderModule(vku::safe_VkComputePipelineCreateInfo& create_info,
const vku::safe_VkPipelineShaderStageCreateInfo& stage_info, VkShaderModule shader_module,
uint32_t stage_ci_index) {
assert(stage_ci_index == 0);
create_info.stage = stage_info;
create_info.stage.module = shader_module;
}
template <typename CreateInfo, typename StageInfo>
StageInfo& GetShaderStageCI(CreateInfo& ci, VkShaderStageFlagBits stage) {
static StageInfo null_stage{};
for (uint32_t i = 0; i < ci.stageCount; ++i) {
if (ci.pStages[i].stage == stage) {
return ci.pStages[i];
}
}
return null_stage;
}
template <>
vku::safe_VkPipelineShaderStageCreateInfo& GetShaderStageCI(vku::safe_VkComputePipelineCreateInfo& ci, VkShaderStageFlagBits) {
return ci.stage;
}
bool GpuShaderInstrumentor::IsSelectiveInstrumentationEnabled(const void* pNext) {
if (auto features = vku::FindStructInPNextChain<VkValidationFeaturesEXT>(pNext)) {
for (uint32_t i = 0; i < features->enabledValidationFeatureCount; i++) {
if (features->pEnabledValidationFeatures[i] == VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT) {
return true;
}
}
}