-
Notifications
You must be signed in to change notification settings - Fork 0
/
replay.go
1248 lines (1141 loc) · 40.5 KB
/
replay.go
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) 2017 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.
package vulkan
import (
"bytes"
"context"
"fmt"
"strings"
"github.com/google/gapid/core/image"
"github.com/google/gapid/core/log"
"github.com/google/gapid/core/os/device"
"github.com/google/gapid/gapis/api"
"github.com/google/gapid/gapis/api/transform"
"github.com/google/gapid/gapis/capture"
"github.com/google/gapid/gapis/config"
"github.com/google/gapid/gapis/memory"
"github.com/google/gapid/gapis/replay"
"github.com/google/gapid/gapis/resolve/dependencygraph2"
"github.com/google/gapid/gapis/resolve/initialcmds"
"github.com/google/gapid/gapis/service"
"github.com/google/gapid/gapis/service/path"
"github.com/google/gapid/gapis/trace"
)
var (
// Interface compliance tests
_ = replay.QueryIssues(API{})
_ = replay.QueryFramebufferAttachment(API{})
_ = replay.Support(API{})
_ = replay.QueryTimestamps(API{})
_ = replay.Profiler(API{})
)
// GetReplayPriority returns a uint32 representing the preference for
// replaying this trace on the given device.
// A lower number represents a higher priority, and Zero represents
// an inability for the trace to be replayed on the given device.
func (a API) GetReplayPriority(ctx context.Context, i *device.Instance, h *capture.Header) uint32 {
devConf := i.GetConfiguration()
devAbis := devConf.GetABIs()
devVkDriver := devConf.GetDrivers().GetVulkan()
traceVkDriver := h.GetDevice().GetConfiguration().GetDrivers().GetVulkan()
if traceVkDriver == nil {
log.E(ctx, "Vulkan trace does not contain VulkanDriver info.")
return 0
}
// The device does not support Vulkan
if devVkDriver == nil {
return 0
}
for _, abi := range devAbis {
// Memory layout must match.
if !abi.GetMemoryLayout().SameAs(h.GetABI().GetMemoryLayout()) {
continue
}
// If there is no physical devices, the trace must not contain
// vkCreateInstance, any ABI compatible Vulkan device should be able to
// replay.
if len(traceVkDriver.GetPhysicalDevices()) == 0 {
return 1
}
// Requires same vendor, device and version of API.
for _, devPhyInfo := range devVkDriver.GetPhysicalDevices() {
for _, tracePhyInfo := range traceVkDriver.GetPhysicalDevices() {
// TODO: More sophisticated rules
if devPhyInfo.GetVendorId() != tracePhyInfo.GetVendorId() {
continue
}
if devPhyInfo.GetDeviceId() != tracePhyInfo.GetDeviceId() {
continue
}
// Ignore the API patch level (bottom 12 bits) when comparing the API version.
if (devPhyInfo.GetApiVersion() & ^uint32(0xfff)) != (tracePhyInfo.GetApiVersion() & ^uint32(0xfff)) {
continue
}
return 1
}
}
}
return 0
}
// makeAttachementReadable is a transformation marking all color/depth/stencil
// attachment images created via vkCreateImage commands as readable (by patching
// the transfer src bit).
type makeAttachementReadable struct {
imagesOnly bool
}
// drawConfig is a replay.Config used by colorBufferRequest and
// depthBufferRequests.
type drawConfig struct {
startScope api.CmdID
endScope api.CmdID
subindices string // drawConfig needs to be comparable, so we cannot use a slice
drawMode service.DrawMode
disableReplayOptimization bool
}
type imgRes struct {
img *image.Data // The image data.
err error // The error that occurred generating the image.
}
// framebufferRequest requests a postback of a framebuffer's attachment.
type framebufferRequest struct {
after []uint64
width, height uint32
attachment api.FramebufferAttachment
framebufferIndex uint32
out chan imgRes
wireframeOverlay bool
displayToSurface bool
}
// color/depth/stencil attachment bit.
func patchImageUsage(usage VkImageUsageFlags) (VkImageUsageFlags, bool) {
hasBit := func(flag VkImageUsageFlags, bit VkImageUsageFlagBits) bool {
return (uint32(flag) & uint32(bit)) == uint32(bit)
}
if hasBit(usage, VkImageUsageFlagBits_VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) ||
hasBit(usage, VkImageUsageFlagBits_VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
return VkImageUsageFlags(uint32(usage) | uint32(VkImageUsageFlagBits_VK_IMAGE_USAGE_TRANSFER_SRC_BIT)), true
}
return usage, false
}
// Add VK_BUFFER_USAGE_TRANSFER_SRC_BIT to the buffer usage bit.
// TODO(renfeng) using shader to do the copy instead of change the usage bit.
func patchBufferusage(usage VkBufferUsageFlags) (VkBufferUsageFlags, bool) {
hasBit := func(flag VkBufferUsageFlags, bit VkBufferUsageFlagBits) bool {
return (uint32(flag) & uint32(bit)) == uint32(bit)
}
if hasBit(usage, VkBufferUsageFlagBits_VK_BUFFER_USAGE_TRANSFER_SRC_BIT) {
return usage, false
}
return VkBufferUsageFlags(uint32(usage) | uint32(VkBufferUsageFlagBits_VK_BUFFER_USAGE_TRANSFER_SRC_BIT)), true
}
func (t *makeAttachementReadable) Transform(ctx context.Context, id api.CmdID, cmd api.Cmd, out transform.Writer) error {
s := out.State()
l := s.MemoryLayout
cb := CommandBuilder{Thread: cmd.Thread(), Arena: s.Arena}
cmd.Extras().Observations().ApplyReads(s.Memory.ApplicationPool())
if image, ok := cmd.(*VkCreateImage); ok {
pinfo := image.PCreateInfo()
info := pinfo.MustRead(ctx, image, s, nil)
if newUsage, changed := patchImageUsage(info.Usage()); changed {
device := image.Device()
palloc := memory.Pointer(image.PAllocator())
pimage := memory.Pointer(image.PImage())
result := image.Result()
info.SetUsage(newUsage)
newInfo := s.AllocDataOrPanic(ctx, info)
newCmd := cb.VkCreateImage(device, newInfo.Ptr(), palloc, pimage, result)
// Carry all non-observation extras through.
for _, e := range image.Extras().All() {
if _, ok := e.(*api.CmdObservations); !ok {
newCmd.Extras().Add(e)
}
}
// Carry observations through. We cannot merge these code with the
// above code for handling extras together since we'd like to change
// the observations, which are slices.
observations := image.Extras().Observations()
for _, r := range observations.Reads {
// TODO: filter out the old VkImageCreateInfo. That should be done via
// creating new observations for data we are interested from t.state.
newCmd.AddRead(r.Range, r.ID)
}
// Use our new VkImageCreateInfo.
newCmd.AddRead(newInfo.Data())
for _, w := range observations.Writes {
newCmd.AddWrite(w.Range, w.ID)
}
return out.MutateAndWrite(ctx, id, newCmd)
}
} else if swapchain, ok := cmd.(*VkCreateSwapchainKHR); ok {
pinfo := swapchain.PCreateInfo()
info := pinfo.MustRead(ctx, swapchain, s, nil)
if newUsage, changed := patchImageUsage(info.ImageUsage()); changed {
device := swapchain.Device()
palloc := memory.Pointer(swapchain.PAllocator())
pswapchain := memory.Pointer(swapchain.PSwapchain())
result := swapchain.Result()
info.SetImageUsage(newUsage)
newInfo := s.AllocDataOrPanic(ctx, info)
newCmd := cb.VkCreateSwapchainKHR(device, newInfo.Ptr(), palloc, pswapchain, result)
for _, e := range swapchain.Extras().All() {
if _, ok := e.(*api.CmdObservations); !ok {
newCmd.Extras().Add(e)
}
}
observations := swapchain.Extras().Observations()
for _, r := range observations.Reads {
// TODO: filter out the old VkSwapchainCreateInfoKHR. That should be done via
// creating new observations for data we are interested from t.state.
newCmd.AddRead(r.Range, r.ID)
}
newCmd.AddRead(newInfo.Data())
for _, w := range observations.Writes {
newCmd.AddWrite(w.Range, w.ID)
}
return out.MutateAndWrite(ctx, id, newCmd)
}
} else if createRenderPass, ok := cmd.(*VkCreateRenderPass); ok && !t.imagesOnly {
pInfo := createRenderPass.PCreateInfo()
info := pInfo.MustRead(ctx, createRenderPass, s, nil)
pAttachments := info.PAttachments()
attachments := pAttachments.Slice(0, uint64(info.AttachmentCount()), l).MustRead(ctx, createRenderPass, s, nil)
changed := false
for i := range attachments {
if attachments[i].StoreOp() == VkAttachmentStoreOp_VK_ATTACHMENT_STORE_OP_DONT_CARE {
changed = true
attachments[i].SetStoreOp(VkAttachmentStoreOp_VK_ATTACHMENT_STORE_OP_STORE)
}
}
// Returns if no attachment description needs to be changed
if !changed {
return out.MutateAndWrite(ctx, id, cmd)
}
// Build new attachments data, new create info and new command
newAttachments := s.AllocDataOrPanic(ctx, attachments)
info.SetPAttachments(NewVkAttachmentDescriptionᶜᵖ(newAttachments.Ptr()))
newInfo := s.AllocDataOrPanic(ctx, info)
newCmd := cb.VkCreateRenderPass(createRenderPass.Device(),
newInfo.Ptr(),
memory.Pointer(createRenderPass.PAllocator()),
memory.Pointer(createRenderPass.PRenderPass()),
createRenderPass.Result())
// Add back the extras and read/write observations
for _, e := range createRenderPass.Extras().All() {
if _, ok := e.(*api.CmdObservations); !ok {
newCmd.Extras().Add(e)
}
}
for _, r := range createRenderPass.Extras().Observations().Reads {
newCmd.AddRead(r.Range, r.ID)
}
newCmd.AddRead(newInfo.Data()).AddRead(newAttachments.Data())
for _, w := range createRenderPass.Extras().Observations().Writes {
newCmd.AddWrite(w.Range, w.ID)
}
return out.MutateAndWrite(ctx, id, newCmd)
} else if e, ok := cmd.(*VkEnumeratePhysicalDevices); ok && !t.imagesOnly {
if e.PPhysicalDevices() == 0 {
// Querying for the number of devices.
// No changes needed here.
return out.MutateAndWrite(ctx, id, cmd)
}
l := s.MemoryLayout
cmd.Extras().Observations().ApplyWrites(s.Memory.ApplicationPool())
numDev := e.PPhysicalDeviceCount().Slice(0, 1, l).MustRead(ctx, cmd, s, nil)[0]
devSlice := e.PPhysicalDevices().Slice(0, uint64(numDev), l)
devs := devSlice.MustRead(ctx, cmd, s, nil)
allProps := externs{ctx, cmd, id, s, nil, nil}.fetchPhysicalDeviceProperties(e.Instance(), devSlice)
propList := []VkPhysicalDeviceProperties{}
for _, dev := range devs {
propList = append(propList, allProps.PhyDevToProperties().Get(dev).Clone(s.Arena, api.CloneContext{}))
}
newEnumerate := buildReplayEnumeratePhysicalDevices(ctx, s, cb, e.Instance(), numDev, devs, propList)
for _, e := range cmd.Extras().All() {
newEnumerate.Extras().Add(e)
}
return out.MutateAndWrite(ctx, id, newEnumerate)
} else if buffer, ok := cmd.(*VkCreateBuffer); ok {
pinfo := buffer.PCreateInfo()
info := pinfo.MustRead(ctx, buffer, s, nil)
if newUsage, changed := patchBufferusage(info.Usage()); changed {
info.SetUsage(newUsage)
newInfo := s.AllocDataOrPanic(ctx, info)
newCmd := cb.VkCreateBuffer(buffer.Device(), newInfo.Ptr(), buffer.PAllocator(), buffer.PBuffer(), buffer.Result())
for _, e := range buffer.Extras().All() {
if _, ok := e.(*api.CmdObservations); !ok {
newCmd.Extras().Add(e)
}
}
observations := buffer.Extras().Observations()
for _, r := range observations.Reads {
newCmd.AddRead(r.Range, r.ID)
}
newCmd.AddRead(newInfo.Data())
for _, w := range observations.Writes {
newCmd.AddWrite(w.Range, w.ID)
}
return out.MutateAndWrite(ctx, id, newCmd)
}
}
return out.MutateAndWrite(ctx, id, cmd)
}
func (t *makeAttachementReadable) Flush(ctx context.Context, out transform.Writer) error { return nil }
func (t *makeAttachementReadable) PreLoop(ctx context.Context, out transform.Writer) {}
func (t *makeAttachementReadable) PostLoop(ctx context.Context, out transform.Writer) {}
func (t *makeAttachementReadable) BuffersCommands() bool { return false }
func buildReplayEnumeratePhysicalDevices(
ctx context.Context, s *api.GlobalState, cb CommandBuilder, instance VkInstance,
count uint32, devices []VkPhysicalDevice,
propertiesInOrder []VkPhysicalDeviceProperties) *ReplayEnumeratePhysicalDevices {
numDevData := s.AllocDataOrPanic(ctx, count)
phyDevData := s.AllocDataOrPanic(ctx, devices)
dids := make([]uint64, 0)
for i := uint32(0); i < count; i++ {
dids = append(dids, uint64(
propertiesInOrder[i].VendorID())<<32|
uint64(propertiesInOrder[i].DeviceID()))
}
devIDData := s.AllocDataOrPanic(ctx, dids)
return cb.ReplayEnumeratePhysicalDevices(
instance, numDevData.Ptr(), phyDevData.Ptr(), devIDData.Ptr(),
VkResult_VK_SUCCESS).AddRead(
numDevData.Data()).AddRead(phyDevData.Data()).AddRead(devIDData.Data())
}
// dropInvalidDestroy is a transformation that drops all VkDestroyXXX commands
// whose destroying targets are not recorded in the state.
type dropInvalidDestroy struct{ tag string }
func (t *dropInvalidDestroy) Transform(ctx context.Context, id api.CmdID, cmd api.Cmd, out transform.Writer) error {
s := out.State()
l := s.MemoryLayout
cb := CommandBuilder{Thread: cmd.Thread(), Arena: s.Arena}
warnDropCmd := func(handles ...interface{}) {
log.W(ctx, "[%v] Dropping [%d]:%v because the creation of %v was not recorded", t.tag, id, cmd, handles)
}
warnModCmd := func(handles ...interface{}) {
log.W(ctx, "[%v] Modifing [%d]:%v to remove the reference to %v because the creation of them were not recorded", t.tag, id, cmd, handles)
}
switch cmd := cmd.(type) {
case *VkDestroyInstance:
if !GetState(s).Instances().Contains(cmd.Instance()) {
warnDropCmd(cmd.Instance())
return nil
}
case *VkDestroyDevice:
if !GetState(s).Devices().Contains(cmd.Device()) {
warnDropCmd(cmd.Device())
return nil
}
case *VkFreeCommandBuffers:
cmdBufCount := cmd.CommandBufferCount()
if cmdBufCount > 0 {
cmd.Extras().Observations().ApplyWrites(out.State().Memory.ApplicationPool())
cmdBufs := cmd.PCommandBuffers().Slice(0, uint64(cmdBufCount), l).MustRead(ctx, cmd, s, nil)
newCmdBufs := []VkCommandBuffer{}
dropped := []VkCommandBuffer{}
for _, b := range cmdBufs {
if GetState(s).CommandBuffers().Contains(b) {
newCmdBufs = append(newCmdBufs, b)
} else {
dropped = append(dropped, b)
}
}
if len(newCmdBufs) == 0 {
// no need to have this command
warnDropCmd(cmdBufs)
return nil
}
if len(newCmdBufs) != len(cmdBufs) {
// need to modify the command to drop the command buffers not
// in the state out of the command
warnModCmd(dropped)
newCmdBufsData := s.AllocDataOrPanic(ctx, newCmdBufs)
defer newCmdBufsData.Free()
newCmd := cb.VkFreeCommandBuffers(cmd.Device(), cmd.CommandPool(), uint32(len(newCmdBufs)), newCmdBufsData.Ptr()).AddRead(newCmdBufsData.Data())
return out.MutateAndWrite(ctx, id, newCmd)
}
// No need to modify the command, just mutate and write the command
// like others.
}
case *VkFreeMemory:
if !GetState(s).DeviceMemories().Contains(cmd.Memory()) {
warnDropCmd(cmd.Memory())
return nil
}
case *VkDestroyBuffer:
if !GetState(s).Buffers().Contains(cmd.Buffer()) {
warnDropCmd(cmd.Buffer())
return nil
}
case *VkDestroyBufferView:
if !GetState(s).BufferViews().Contains(cmd.BufferView()) {
warnDropCmd(cmd.BufferView())
return nil
}
case *VkDestroyImage:
if !GetState(s).Images().Contains(cmd.Image()) {
warnDropCmd(cmd.Image())
return nil
}
case *VkDestroyImageView:
if !GetState(s).ImageViews().Contains(cmd.ImageView()) {
warnDropCmd(cmd.ImageView())
return nil
}
case *VkDestroyShaderModule:
if !GetState(s).ShaderModules().Contains(cmd.ShaderModule()) {
warnDropCmd(cmd.ShaderModule())
return nil
}
case *VkDestroyPipeline:
if !GetState(s).GraphicsPipelines().Contains(cmd.Pipeline()) &&
!GetState(s).ComputePipelines().Contains(cmd.Pipeline()) {
warnDropCmd(cmd.Pipeline())
return nil
}
case *VkDestroyPipelineLayout:
if !GetState(s).PipelineLayouts().Contains(cmd.PipelineLayout()) {
warnDropCmd(cmd.PipelineLayout())
return nil
}
case *VkDestroyPipelineCache:
if !GetState(s).PipelineCaches().Contains(cmd.PipelineCache()) {
warnDropCmd(cmd.PipelineCache())
return nil
}
case *VkDestroySampler:
if !GetState(s).Samplers().Contains(cmd.Sampler()) {
warnDropCmd(cmd.Sampler())
return nil
}
case *VkFreeDescriptorSets:
descSetCount := cmd.DescriptorSetCount()
if descSetCount > 0 {
cmd.Extras().Observations().ApplyWrites(out.State().Memory.ApplicationPool())
descSets := cmd.PDescriptorSets().Slice(0, uint64(descSetCount), l).MustRead(ctx, cmd, s, nil)
newDescSets := []VkDescriptorSet{}
dropped := []VkDescriptorSet{}
for _, ds := range descSets {
if GetState(s).DescriptorSets().Contains(ds) {
newDescSets = append(newDescSets, ds)
} else {
dropped = append(dropped, ds)
}
}
if len(newDescSets) == 0 {
// no need to have this command
warnDropCmd(descSets)
return nil
}
if len(newDescSets) != len(descSets) {
// need to modify the command to drop the command buffers not
// in the state out of the command
warnModCmd(dropped)
newDescSetsData := s.AllocDataOrPanic(ctx, newDescSets)
defer newDescSetsData.Free()
newCmd := cb.VkFreeDescriptorSets(
cmd.Device(), cmd.DescriptorPool(), uint32(len(newDescSets)),
newDescSetsData.Ptr(), VkResult_VK_SUCCESS).AddRead(newDescSetsData.Data())
return out.MutateAndWrite(ctx, id, newCmd)
}
// No need to modify the command, just mutate and write the command
// like others.
}
case *VkDestroyDescriptorSetLayout:
if !GetState(s).DescriptorSetLayouts().Contains(cmd.DescriptorSetLayout()) {
warnDropCmd(cmd.DescriptorSetLayout())
return nil
}
case *VkDestroyDescriptorPool:
if !GetState(s).DescriptorPools().Contains(cmd.DescriptorPool()) {
warnDropCmd(cmd.DescriptorPool())
return nil
}
case *VkDestroyFence:
if !GetState(s).Fences().Contains(cmd.Fence()) {
warnDropCmd(cmd.Fence())
return nil
}
case *VkDestroySemaphore:
if !GetState(s).Semaphores().Contains(cmd.Semaphore()) {
warnDropCmd(cmd.Semaphore())
return nil
}
case *VkDestroyEvent:
if !GetState(s).Events().Contains(cmd.Event()) {
warnDropCmd(cmd.Event())
return nil
}
case *VkDestroyQueryPool:
if !GetState(s).QueryPools().Contains(cmd.QueryPool()) {
warnDropCmd(cmd.QueryPool())
return nil
}
case *VkDestroyFramebuffer:
if !GetState(s).Framebuffers().Contains(cmd.Framebuffer()) {
warnDropCmd(cmd.Framebuffer())
return nil
}
case *VkDestroyRenderPass:
if !GetState(s).RenderPasses().Contains(cmd.RenderPass()) {
warnDropCmd(cmd.RenderPass())
return nil
}
case *VkDestroyCommandPool:
if !GetState(s).CommandPools().Contains(cmd.CommandPool()) {
warnDropCmd(cmd.CommandPool())
return nil
}
case *VkDestroySurfaceKHR:
if !GetState(s).Surfaces().Contains(cmd.Surface()) {
warnDropCmd(cmd.Surface())
return nil
}
case *VkDestroySwapchainKHR:
if !GetState(s).Swapchains().Contains(cmd.Swapchain()) {
warnDropCmd(cmd.Swapchain())
return nil
}
case *VkDestroyDebugReportCallbackEXT:
if !GetState(s).DebugReportCallbacks().Contains(cmd.Callback()) {
warnDropCmd(cmd.Callback())
return nil
}
}
return out.MutateAndWrite(ctx, id, cmd)
}
func (t *dropInvalidDestroy) Flush(ctx context.Context, out transform.Writer) error { return nil }
func (t *dropInvalidDestroy) PreLoop(ctx context.Context, out transform.Writer) {}
func (t *dropInvalidDestroy) PostLoop(ctx context.Context, out transform.Writer) {}
func (t *dropInvalidDestroy) BuffersCommands() bool { return false }
// destroyResourceAtEOS is a transformation that destroys all active
// resources at the end of stream.
type destroyResourcesAtEOS struct {
}
func (t *destroyResourcesAtEOS) Transform(ctx context.Context, id api.CmdID, cmd api.Cmd, out transform.Writer) error {
return out.MutateAndWrite(ctx, id, cmd)
}
func (t *destroyResourcesAtEOS) Flush(ctx context.Context, out transform.Writer) error {
s := out.State()
so := getStateObject(s)
id := api.CmdNoID
cb := CommandBuilder{Thread: 0, Arena: s.Arena} // TODO: Check that using any old thread is okay.
// TODO: use the correct pAllocator once we handle it.
p := memory.Nullptr
// Wait all queues in all devices to finish their jobs first.
for handle := range so.Devices().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDeviceWaitIdle(handle, VkResult_VK_SUCCESS)); err != nil {
return err
}
}
// Synchronization primitives.
for handle, object := range so.Events().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroyEvent(object.Device(), handle, p)); err != nil {
return err
}
}
for handle, object := range so.Fences().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroyFence(object.Device(), handle, p)); err != nil {
return err
}
}
for handle, object := range so.Semaphores().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroySemaphore(object.Device(), handle, p)); err != nil {
return err
}
}
// SamplerYcbcrConversions
for handle, object := range so.SamplerYcbcrConversions().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroySamplerYcbcrConversion(object.Device(), handle, p)); err != nil {
return err
}
}
// Framebuffers, samplers.
for handle, object := range so.Framebuffers().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroyFramebuffer(object.Device(), handle, p)); err != nil {
return err
}
}
for handle, object := range so.Samplers().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroySampler(object.Device(), handle, p)); err != nil {
return err
}
}
// Descriptor sets.
for handle, object := range so.DescriptorPools().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroyDescriptorPool(object.Device(), handle, p)); err != nil {
return err
}
}
for handle, object := range so.DescriptorSetLayouts().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroyDescriptorSetLayout(object.Device(), handle, p)); err != nil {
return err
}
}
// Buffers.
for handle, object := range so.BufferViews().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroyBufferView(object.Device(), handle, p)); err != nil {
return err
}
}
for handle, object := range so.Buffers().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroyBuffer(object.Device(), handle, p)); err != nil {
return err
}
}
// Shader modules.
for handle, object := range so.ShaderModules().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroyShaderModule(object.Device(), handle, p)); err != nil {
return err
}
}
// Pipelines.
for handle, object := range so.GraphicsPipelines().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroyPipeline(object.Device(), handle, p)); err != nil {
return err
}
}
for handle, object := range so.ComputePipelines().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroyPipeline(object.Device(), handle, p)); err != nil {
return err
}
}
for handle, object := range so.PipelineLayouts().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroyPipelineLayout(object.Device(), handle, p)); err != nil {
return err
}
}
for handle, object := range so.PipelineCaches().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroyPipelineCache(object.Device(), handle, p)); err != nil {
return err
}
}
// Render passes.
for handle, object := range so.RenderPasses().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroyRenderPass(object.Device(), handle, p)); err != nil {
return err
}
}
for handle, object := range so.QueryPools().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroyQueryPool(object.Device(), handle, p)); err != nil {
return err
}
}
// Command buffers.
for handle, object := range so.CommandPools().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroyCommandPool(object.Device(), handle, p)); err != nil {
return err
}
}
// Swapchains.
for handle, object := range so.Swapchains().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroySwapchainKHR(object.Device(), handle, p)); err != nil {
return err
}
}
// Memories.
for handle, object := range so.DeviceMemories().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkFreeMemory(object.Device(), handle, p)); err != nil {
return err
}
}
// Images
for handle, object := range so.ImageViews().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroyImageView(object.Device(), handle, p)); err != nil {
return err
}
}
// Note: so.Images also contains Swapchain images. We do not want
// to delete those, as that must be handled by VkDestroySwapchainKHR
for handle, object := range so.Images().All() {
if !object.IsSwapchainImage() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroyImage(object.Device(), handle, p)); err != nil {
return err
}
}
}
// Devices.
for handle := range so.Devices().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroyDevice(handle, p)); err != nil {
return err
}
}
// Surfaces.
for handle, object := range so.Surfaces().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroySurfaceKHR(object.Instance(), handle, p)); err != nil {
return err
}
}
// Debug report callbacks
for handle, object := range so.DebugReportCallbacks().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroyDebugReportCallbackEXT(object.Instance(), handle, p)); err != nil {
return err
}
}
// Instances.
for handle := range so.Instances().All() {
if err := out.MutateAndWrite(ctx, id, cb.VkDestroyInstance(handle, p)); err != nil {
return err
}
}
return nil
}
func (t *destroyResourcesAtEOS) PreLoop(ctx context.Context, out transform.Writer) {}
func (t *destroyResourcesAtEOS) PostLoop(ctx context.Context, out transform.Writer) {}
func (t *destroyResourcesAtEOS) BuffersCommands() bool { return false }
func newDisplayToSurface() *DisplayToSurface {
return &DisplayToSurface{
SurfaceTypes: map[uint64]uint32{},
}
}
// DisplayToSurface is a transformation that enables rendering during replay to
// the original surface.
func (t *DisplayToSurface) Transform(ctx context.Context, id api.CmdID, cmd api.Cmd, out transform.Writer) error {
switch c := cmd.(type) {
case *VkCreateSwapchainKHR:
newCmd := c.clone(out.State().Arena)
newCmd.extras = api.CmdExtras{}
// Add an extra to indicate to custom_replay to add a flag to
// the virtual swapchain pNext
newCmd.extras = append(api.CmdExtras{t}, cmd.Extras().All()...)
return out.MutateAndWrite(ctx, id, newCmd)
case *VkCreateAndroidSurfaceKHR:
cmd.Extras().Observations().ApplyWrites(out.State().Memory.ApplicationPool())
surface := c.PSurface().MustRead(ctx, cmd, out.State(), nil)
t.SurfaceTypes[uint64(surface)] = uint32(VkStructureType_VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR)
case *VkCreateWaylandSurfaceKHR:
cmd.Extras().Observations().ApplyWrites(out.State().Memory.ApplicationPool())
surface := c.PSurface().MustRead(ctx, cmd, out.State(), nil)
t.SurfaceTypes[uint64(surface)] = uint32(VkStructureType_VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR)
case *VkCreateWin32SurfaceKHR:
cmd.Extras().Observations().ApplyWrites(out.State().Memory.ApplicationPool())
surface := c.PSurface().MustRead(ctx, cmd, out.State(), nil)
t.SurfaceTypes[uint64(surface)] = uint32(VkStructureType_VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR)
case *VkCreateXcbSurfaceKHR:
cmd.Extras().Observations().ApplyWrites(out.State().Memory.ApplicationPool())
surface := c.PSurface().MustRead(ctx, cmd, out.State(), nil)
t.SurfaceTypes[uint64(surface)] = uint32(VkStructureType_VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR)
case *VkCreateXlibSurfaceKHR:
cmd.Extras().Observations().ApplyWrites(out.State().Memory.ApplicationPool())
surface := c.PSurface().MustRead(ctx, cmd, out.State(), nil)
t.SurfaceTypes[uint64(surface)] = uint32(VkStructureType_VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR)
case *VkCreateMacOSSurfaceMVK:
cmd.Extras().Observations().ApplyWrites(out.State().Memory.ApplicationPool())
surface := c.PSurface().MustRead(ctx, cmd, out.State(), nil)
t.SurfaceTypes[uint64(surface)] = uint32(VkStructureType_VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK)
case *VkCreateStreamDescriptorSurfaceGGP:
cmd.Extras().Observations().ApplyWrites(out.State().Memory.ApplicationPool())
surface := c.PSurface().MustRead(ctx, cmd, out.State(), nil)
t.SurfaceTypes[uint64(surface)] = uint32(VkStructureType_VK_STRUCTURE_TYPE_STREAM_DESCRIPTOR_SURFACE_CREATE_INFO_GGP)
}
return out.MutateAndWrite(ctx, id, cmd)
}
func (t *DisplayToSurface) Flush(ctx context.Context, out transform.Writer) error { return nil }
func (t *DisplayToSurface) PreLoop(ctx context.Context, out transform.Writer) {}
func (t *DisplayToSurface) PostLoop(ctx context.Context, out transform.Writer) {}
func (t *DisplayToSurface) BuffersCommands() bool { return false }
// issuesConfig is a replay.Config used by issuesRequests.
type issuesConfig struct {
}
// issuesRequest requests all issues found during replay to be reported to out.
type issuesRequest struct {
out chan<- replay.Issue
displayToSurface bool
loopCount int32
}
type timestampsConfig struct {
}
type timestampsRequest struct {
handler service.TimeStampsHandler
loopCount int32
}
// uniqueConfig returns a replay.Config that is guaranteed to be unique.
// Any requests made with a Config returned from uniqueConfig will not be
// batched with any other request.
func uniqueConfig() replay.Config {
return &struct{}{}
}
type profileRequest struct {
traceOptions *service.TraceOptions
handler *replay.SignalHandler
buffer *bytes.Buffer
handleMappings *map[uint64][]service.VulkanHandleMappingItem
}
func (a API) GetInitialPayload(ctx context.Context,
capture *path.Capture,
device *device.Instance,
out transform.Writer) error {
transforms := transform.Transforms{}
transforms.Add(&makeAttachementReadable{false})
transforms.Add(&dropInvalidDestroy{tag: "GetInitialPayload"})
initialCmds, im, _ := initialcmds.InitialCommands(ctx, capture)
out.State().Allocator.ReserveRanges(im)
return transforms.TransformAll(ctx, initialCmds, uint64(len(initialCmds)), out)
}
func (a API) CleanupResources(ctx context.Context,
device *device.Instance,
out transform.Writer) error {
transforms := transform.Transforms{}
transforms.Add(&destroyResourcesAtEOS{})
return transforms.TransformAll(ctx, []api.Cmd{}, 0, out)
}
func (a API) Replay(
ctx context.Context,
intent replay.Intent,
cfg replay.Config,
dependentPayload string,
rrs []replay.RequestAndResult,
device *device.Instance,
c *capture.GraphicsCapture,
out transform.Writer) error {
if a.GetReplayPriority(ctx, device, c.Header) == 0 {
return log.Errf(ctx, nil, "Cannot replay Vulkan commands on device '%v'", device.Name)
}
optimize := !config.DisableDeadCodeElimination
cmds := c.Commands
transforms := transform.Transforms{}
makeReadable := &makeAttachementReadable{false}
transforms.Add(makeReadable)
transforms.Add(&dropInvalidDestroy{tag: "Replay"})
splitter := NewCommandSplitter(ctx)
readFramebuffer := newReadFramebuffer(ctx)
injector := &transform.Injector{}
// Gathers and reports any issues found.
var issues *findIssues
var timestamps *queryTimestamps
var frameloop *frameLoop
earlyTerminator, err := NewVulkanTerminator(ctx, intent.Capture)
if err != nil {
return err
}
// Populate the dead-code eliminitation later, only once we are sure
// we will need it.
var dceBuilder *dependencygraph2.DCEBuilder
initCmdExpandedWithOpt := false
numInitialCmdWithOpt := 0
initCmdExpandedWithoutOpt := false
numInitialCmdWithoutOpt := 0
dceExpanded := false
expandCommands := func(opt bool) (int, error) {
if opt && initCmdExpandedWithOpt {
return numInitialCmdWithOpt, nil
}
if !opt && initCmdExpandedWithoutOpt {
return numInitialCmdWithoutOpt, nil
}
if opt {
if dceBuilder == nil && !dceExpanded {
cfg := dependencygraph2.DependencyGraphConfig{
MergeSubCmdNodes: !config.DeadSubCmdElimination,
IncludeInitialCommands: dependentPayload == "",
}
graph, err := dependencygraph2.TryGetDependencyGraph(ctx, capture.Get(ctx), cfg)
if err != nil {
return 0, fmt.Errorf("Could not build dependency graph for DCE: %v", err)
}
if graph != nil {
log.I(ctx, "Got Dependency Graph")
dceBuilder = dependencygraph2.NewDCEBuilder(graph)
} else {
log.I(ctx, "Dependency Graph still pending")
}
}
dceExpanded = true
if dceBuilder != nil {
cmds = []api.Cmd{}
}
return 0, nil
}
// If we do not depend on another payload to get us into the right state,
// we should get ourselves into the intial state
if dependentPayload == "" {
initialCmds, im, _ := initialcmds.InitialCommands(ctx, intent.Capture)
out.State().Allocator.ReserveRanges(im)
numInitialCmdWithoutOpt = len(initialCmds)
if len(initialCmds) > 0 {
cmds = append(initialCmds, cmds...)
}
}
initCmdExpandedWithoutOpt = true
return numInitialCmdWithoutOpt, nil
}
frameLoopEndCmdID := func(cmds []api.Cmd) api.CmdID {
lastCmdID := api.CmdID(0)
for i := len(cmds) - 1; i >= 0; i-- {
if cmds[i].Terminated() {
lastCmdID = api.CmdID(i)
break
}
}
return lastCmdID
}
wire := false
doDisplayToSurface := false
var overdraw *stencilOverdraw
var profile *replay.EndOfReplay
for _, rr := range rrs {
switch req := rr.Request.(type) {
case issuesRequest:
if issues == nil {
issues = newFindIssues(ctx, c)
}
issues.AddResult(rr.Result)
optimize = false
if req.displayToSurface {
doDisplayToSurface = true
}
willLoop := req.loopCount > 1
if willLoop {
frameloop = newFrameLoop(ctx, c, api.CmdID(0), frameLoopEndCmdID(cmds), req.loopCount)
}
case timestampsRequest:
if timestamps == nil {
willLoop := req.loopCount > 1
if willLoop {
frameloop = newFrameLoop(ctx, c, api.CmdID(0), frameLoopEndCmdID(cmds), req.loopCount)
}
timestamps = newQueryTimestamps(ctx, c, cmds, willLoop, req.handler)
}
timestamps.AddResult(rr.Result)
optimize = false
case framebufferRequest:
cfg := cfg.(drawConfig)
if cfg.disableReplayOptimization {
optimize = false
}
cmdID := req.after[0]
if optimize {
// Should have been built in expandCommands()
if dceBuilder != nil {
dceBuilder.Request(ctx, api.SubCmdIdx{cmdID})