-
Notifications
You must be signed in to change notification settings - Fork 40
/
program.cpp
2318 lines (2080 loc) · 88.3 KB
/
program.cpp
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 2018 The clvk authors.
//
// 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 <algorithm>
#include <cstring>
#include <filesystem>
#include <iostream>
#include <map>
#include <sstream>
#include <system_error>
#include <utility>
#include <vector>
#include <vulkan/vulkan.h>
#include "clspv/Sampler.h"
#include "utils.hpp"
#ifdef CLSPV_ONLINE_COMPILER
#ifdef ENABLE_SPIRV_IL
#include "LLVMSPIRVLib.h"
#include "llvm/Bitcode/BitcodeWriter.h"
#include "llvm/Support/CommandLine.h" // FIXME(#380) remove
#include "llvm/Support/raw_ostream.h"
#endif
#include "clspv/Compiler.h"
#endif
#include "spirv-tools/linker.hpp"
#include "spirv-tools/optimizer.hpp"
#include "spirv/unified1/NonSemanticClspvReflection.h"
#include "spirv/unified1/spirv.hpp"
#include "config.hpp"
#include "init.hpp"
#include "log.hpp"
#include "program.hpp"
#include "tracing.hpp"
struct membuf : public std::streambuf {
membuf(const unsigned char* begin, const unsigned char* end) {
auto sbegin =
reinterpret_cast<char*>(const_cast<unsigned char*>(begin));
auto send = reinterpret_cast<char*>(const_cast<unsigned char*>(end));
setg(sbegin, sbegin, send);
}
membuf(unsigned char* begin, unsigned char* end) {
auto sbegin = reinterpret_cast<char*>(begin);
auto send = reinterpret_cast<char*>(end);
setp(sbegin, send);
}
pos_type seekoff(off_type off, std::ios_base::seekdir dir,
std::ios_base::openmode which) override {
UNUSED(which);
char* whence = eback();
if (dir == std::ios_base::cur) {
whence = gptr();
} else if (dir == std::ios_base::end) {
whence = egptr();
}
char* to = whence + off;
if (to >= eback() && to <= egptr()) {
setg(eback(), to, egptr());
return gptr() - eback();
}
return -1;
}
pos_type seekpos(pos_type pos, std::ios_base::openmode which) override {
UNUSED(which);
char* to = eback() + pos;
if (to >= eback() && to <= egptr()) {
setg(eback(), to, egptr());
return gptr() - eback();
}
return -1;
}
};
struct reflection_parse_data {
uint32_t uint_id = 0;
std::unordered_map<uint32_t, uint32_t> constants;
std::unordered_map<uint32_t, std::string> strings;
spir_binary* binary;
std::unordered_map<uint32_t, kernel_argument_info> arg_infos;
};
spv_result_t parse_reflection(void* user_data,
const spv_parsed_instruction_t* inst) {
// Helper function to map instruction to argument type.
auto inst_to_arg_kind = [](uint32_t inst) {
switch (static_cast<NonSemanticClspvReflectionInstructions>(inst)) {
case NonSemanticClspvReflectionArgumentStorageBuffer:
return kernel_argument_kind::buffer;
case NonSemanticClspvReflectionArgumentUniform:
return kernel_argument_kind::buffer_ubo;
case NonSemanticClspvReflectionArgumentPodStorageBuffer:
return kernel_argument_kind::pod;
case NonSemanticClspvReflectionArgumentPodUniform:
return kernel_argument_kind::pod_ubo;
case NonSemanticClspvReflectionArgumentPodPushConstant:
return kernel_argument_kind::pod_pushconstant;
case NonSemanticClspvReflectionArgumentPointerUniform:
return kernel_argument_kind::pointer_ubo;
case NonSemanticClspvReflectionArgumentPointerPushConstant:
return kernel_argument_kind::pointer_pushconstant;
case NonSemanticClspvReflectionArgumentSampledImage:
return kernel_argument_kind::sampled_image;
case NonSemanticClspvReflectionArgumentStorageImage:
return kernel_argument_kind::storage_image;
case NonSemanticClspvReflectionArgumentStorageTexelBuffer:
return kernel_argument_kind::storage_texel_buffer;
case NonSemanticClspvReflectionArgumentUniformTexelBuffer:
return kernel_argument_kind::uniform_texel_buffer;
case NonSemanticClspvReflectionArgumentSampler:
return kernel_argument_kind::sampler;
case NonSemanticClspvReflectionArgumentWorkgroup:
return kernel_argument_kind::local;
default:
cvk_error_fn("Unhandled reflection instruction for arg kind");
break;
}
return kernel_argument_kind::buffer;
};
// Helper function to map instruction to push constant type.
auto inst_to_push_constant = [](uint32_t inst) {
switch (static_cast<NonSemanticClspvReflectionInstructions>(inst)) {
case NonSemanticClspvReflectionPushConstantGlobalOffset:
return pushconstant::global_offset;
case NonSemanticClspvReflectionPushConstantEnqueuedLocalSize:
return pushconstant::enqueued_local_size;
case NonSemanticClspvReflectionPushConstantGlobalSize:
return pushconstant::global_size;
case NonSemanticClspvReflectionPushConstantRegionOffset:
return pushconstant::region_offset;
case NonSemanticClspvReflectionPushConstantNumWorkgroups:
return pushconstant::num_workgroups;
case NonSemanticClspvReflectionPushConstantRegionGroupOffset:
return pushconstant::region_group_offset;
case NonSemanticClspvReflectionImageArgumentInfoChannelOrderPushConstant:
return pushconstant::image_metadata;
case NonSemanticClspvReflectionImageArgumentInfoChannelDataTypePushConstant:
return pushconstant::image_metadata;
case NonSemanticClspvReflectionConstantDataPointerPushConstant:
return pushconstant::module_constants_pointer;
case NonSemanticClspvReflectionPrintfBufferPointerPushConstant:
return pushconstant::printf_buffer_pointer;
case NonSemanticClspvReflectionNormalizedSamplerMaskPushConstant:
return pushconstant::normalized_sampler_mask;
default:
cvk_error_fn("Unhandled reflection instruction for push constant");
break;
}
return pushconstant::global_offset;
};
auto* parse_data = reinterpret_cast<reflection_parse_data*>(user_data);
switch (inst->opcode) {
case spv::OpTypeInt:
if (inst->words[2] == 32 && inst->words[3] == 0) {
parse_data->uint_id = inst->result_id;
}
break;
case spv::OpConstant:
if (inst->words[1] == parse_data->uint_id) {
parse_data->constants[inst->result_id] = inst->words[3];
}
break;
case spv::OpString:
parse_data->strings[inst->result_id] =
std::string(reinterpret_cast<const char*>(&inst->words[2]));
break;
case spv::OpExtInst:
if (inst->ext_inst_type ==
SPV_EXT_INST_TYPE_NONSEMANTIC_CLSPVREFLECTION) {
auto ext_inst = inst->words[4];
switch (ext_inst) {
case NonSemanticClspvReflectionKernel: {
// Record the kernel name.
const auto& name = parse_data->strings[inst->words[6]];
const auto& num_args = parse_data->constants[inst->words[7]];
const auto& flags = parse_data->constants[inst->words[8]];
const auto& attributes = parse_data->strings[inst->words[9]];
parse_data->strings[inst->result_id] = name;
parse_data->binary->add_kernel(name, num_args, attributes,
flags);
break;
}
case NonSemanticClspvReflectionArgumentInfo: {
// Record the argument info.
kernel_argument_info info;
info.name = parse_data->strings[inst->words[5]];
if (inst->num_operands > 6) {
info.type_name = parse_data->strings[inst->words[6]];
info.address_qualifier =
parse_data->constants[inst->words[7]];
info.access_qualifier =
parse_data->constants[inst->words[8]];
info.type_qualifier = parse_data->constants[inst->words[9]];
info.extended_valid = true;
}
parse_data->arg_infos[inst->result_id] = info;
break;
}
case NonSemanticClspvReflectionNormalizedSamplerMaskPushConstant: {
auto kernel = parse_data->strings[inst->words[5]];
auto ordinal = parse_data->constants[inst->words[6]];
auto offset = parse_data->constants[inst->words[7]];
auto size = parse_data->constants[inst->words[8]];
parse_data->binary->add_sampler_metadata(kernel, ordinal,
offset);
auto pc = inst_to_push_constant(ext_inst);
parse_data->binary->add_push_constant(pc, {offset, size});
break;
}
case NonSemanticClspvReflectionImageArgumentInfoChannelOrderPushConstant: {
auto kernel = parse_data->strings[inst->words[5]];
auto ordinal = parse_data->constants[inst->words[6]];
auto offset = parse_data->constants[inst->words[7]];
auto size = parse_data->constants[inst->words[8]];
parse_data->binary->add_image_channel_order_metadata(
kernel, ordinal, offset);
auto pc = inst_to_push_constant(ext_inst);
parse_data->binary->add_push_constant(pc, {offset, size});
break;
}
case NonSemanticClspvReflectionImageArgumentInfoChannelDataTypePushConstant: {
auto kernel = parse_data->strings[inst->words[5]];
auto ordinal = parse_data->constants[inst->words[6]];
auto offset = parse_data->constants[inst->words[7]];
auto size = parse_data->constants[inst->words[8]];
parse_data->binary->add_image_channel_data_type_metadata(
kernel, ordinal, offset);
auto pc = inst_to_push_constant(ext_inst);
parse_data->binary->add_push_constant(pc, {offset, size});
break;
}
case NonSemanticClspvReflectionArgumentStorageBuffer:
case NonSemanticClspvReflectionArgumentUniform:
case NonSemanticClspvReflectionArgumentSampledImage:
case NonSemanticClspvReflectionArgumentStorageImage:
case NonSemanticClspvReflectionArgumentStorageTexelBuffer:
case NonSemanticClspvReflectionArgumentUniformTexelBuffer:
case NonSemanticClspvReflectionArgumentSampler: {
// These arguments have descriptor set, binding and an optional
// arg info.
auto kernel = parse_data->strings[inst->words[5]];
auto ordinal = parse_data->constants[inst->words[6]];
auto descriptor_set = parse_data->constants[inst->words[7]];
if (descriptor_set >= spir_binary::MAX_DESCRIPTOR_SETS)
return SPV_ERROR_INVALID_DATA;
auto binding = parse_data->constants[inst->words[8]];
kernel_argument_info arg_info;
if (inst->num_operands == 9) {
arg_info = parse_data->arg_infos[inst->words[9]];
}
auto kind = inst_to_arg_kind(ext_inst);
kernel_argument arg = {arg_info, ordinal, descriptor_set,
binding, 0, 0,
kind, 0, 0};
parse_data->binary->add_kernel_argument(kernel, std::move(arg));
break;
}
case NonSemanticClspvReflectionArgumentPodStorageBuffer:
case NonSemanticClspvReflectionArgumentPodUniform:
case NonSemanticClspvReflectionArgumentPointerUniform: {
// These arguments have descriptor set, binding, offset, size
// and an optional arg info.
auto kernel = parse_data->strings[inst->words[5]];
auto ordinal = parse_data->constants[inst->words[6]];
auto descriptor_set = parse_data->constants[inst->words[7]];
if (descriptor_set >= spir_binary::MAX_DESCRIPTOR_SETS)
return SPV_ERROR_INVALID_DATA;
auto binding = parse_data->constants[inst->words[8]];
auto offset = parse_data->constants[inst->words[9]];
auto size = parse_data->constants[inst->words[10]];
kernel_argument_info arg_info;
if (inst->num_operands == 11) {
arg_info = parse_data->arg_infos[inst->words[11]];
}
auto kind = inst_to_arg_kind(ext_inst);
kernel_argument arg = {arg_info, ordinal, descriptor_set,
binding, offset, size,
kind, 0, 0};
parse_data->binary->add_kernel_argument(kernel, std::move(arg));
break;
}
case NonSemanticClspvReflectionArgumentPodPushConstant:
case NonSemanticClspvReflectionArgumentPointerPushConstant: {
// These arguments have offset, size and an optional arg info.
auto kernel = parse_data->strings[inst->words[5]];
auto ordinal = parse_data->constants[inst->words[6]];
auto offset = parse_data->constants[inst->words[7]];
auto size = parse_data->constants[inst->words[8]];
kernel_argument_info arg_info;
if (inst->num_operands == 9) {
arg_info = parse_data->arg_infos[inst->words[9]];
}
auto kind = inst_to_arg_kind(ext_inst);
kernel_argument arg = {arg_info, ordinal, 0, 0, offset,
size, kind, 0, 0};
parse_data->binary->add_kernel_argument(kernel, std::move(arg));
break;
}
case NonSemanticClspvReflectionArgumentWorkgroup: {
// These arguments have spec id, elem size and an optional arg
// info.
auto kernel = parse_data->strings[inst->words[5]];
auto ordinal = parse_data->constants[inst->words[6]];
auto spec_id = parse_data->constants[inst->words[7]];
auto size = parse_data->constants[inst->words[8]];
kernel_argument_info arg_info;
if (inst->num_operands == 9) {
arg_info = parse_data->arg_infos[inst->words[9]];
}
auto kind = inst_to_arg_kind(ext_inst);
kernel_argument arg = {arg_info, ordinal, 0, 0, 0,
0, kind, spec_id, size};
parse_data->binary->add_kernel_argument(kernel, std::move(arg));
break;
}
case NonSemanticClspvReflectionSpecConstantWorkgroupSize: {
// Reflection encodes all three spec ids in a single
// instruction.
auto x_id = parse_data->constants[inst->words[5]];
auto y_id = parse_data->constants[inst->words[6]];
auto z_id = parse_data->constants[inst->words[7]];
parse_data->binary->add_spec_constant(
spec_constant::workgroup_size_x, x_id);
parse_data->binary->add_spec_constant(
spec_constant::workgroup_size_y, y_id);
parse_data->binary->add_spec_constant(
spec_constant::workgroup_size_z, z_id);
break;
}
case NonSemanticClspvReflectionSpecConstantGlobalOffset: {
// Reflection encodes all three spec ids in a single
// instruction.
auto x_id = parse_data->constants[inst->words[5]];
auto y_id = parse_data->constants[inst->words[6]];
auto z_id = parse_data->constants[inst->words[7]];
parse_data->binary->add_spec_constant(
spec_constant::global_offset_x, x_id);
parse_data->binary->add_spec_constant(
spec_constant::global_offset_y, y_id);
parse_data->binary->add_spec_constant(
spec_constant::global_offset_z, z_id);
break;
}
case NonSemanticClspvReflectionSpecConstantWorkDim: {
auto dim_id = parse_data->constants[inst->words[5]];
parse_data->binary->add_spec_constant(spec_constant::work_dim,
dim_id);
break;
}
case NonSemanticClspvReflectionSpecConstantSubgroupMaxSize: {
auto size_id = parse_data->constants[inst->words[5]];
parse_data->binary->add_spec_constant(
spec_constant::subgroup_max_size, size_id);
break;
}
case NonSemanticClspvReflectionPushConstantGlobalOffset:
case NonSemanticClspvReflectionPushConstantEnqueuedLocalSize:
case NonSemanticClspvReflectionPushConstantGlobalSize:
case NonSemanticClspvReflectionPushConstantRegionOffset:
case NonSemanticClspvReflectionPushConstantNumWorkgroups:
case NonSemanticClspvReflectionPushConstantRegionGroupOffset: {
auto offset = parse_data->constants[inst->words[5]];
auto size = parse_data->constants[inst->words[6]];
auto pc = inst_to_push_constant(ext_inst);
parse_data->binary->add_push_constant(pc, {offset, size});
break;
}
case NonSemanticClspvReflectionLiteralSampler: {
// Track descriptor set and binding. Decode the sampler mask.
auto descriptor_set = parse_data->constants[inst->words[5]];
if (descriptor_set >= spir_binary::MAX_DESCRIPTOR_SETS)
return SPV_ERROR_INVALID_DATA;
auto binding = parse_data->constants[inst->words[6]];
auto mask = parse_data->constants[inst->words[7]];
uint32_t coords = mask & clspv::kSamplerNormalizedCoordsMask;
bool normalized_coords =
coords == clspv::CLK_NORMALIZED_COORDS_TRUE;
cl_addressing_mode addressing;
switch (mask & clspv::kSamplerAddressMask) {
case clspv::CLK_ADDRESS_NONE:
default:
addressing = CL_ADDRESS_NONE;
break;
case clspv::CLK_ADDRESS_CLAMP_TO_EDGE:
addressing = CL_ADDRESS_CLAMP_TO_EDGE;
break;
case clspv::CLK_ADDRESS_CLAMP:
addressing = CL_ADDRESS_CLAMP;
break;
case clspv::CLK_ADDRESS_MIRRORED_REPEAT:
addressing = CL_ADDRESS_MIRRORED_REPEAT;
break;
case clspv::CLK_ADDRESS_REPEAT:
addressing = CL_ADDRESS_REPEAT;
break;
}
cl_filter_mode filter;
switch (mask & clspv::kSamplerFilterMask) {
case clspv::CLK_FILTER_NEAREST:
default:
filter = CL_FILTER_NEAREST;
break;
case clspv::CLK_FILTER_LINEAR:
filter = CL_FILTER_LINEAR;
break;
}
parse_data->binary->add_literal_sampler(
{descriptor_set, binding, normalized_coords, addressing,
filter});
break;
}
case NonSemanticClspvReflectionPropertyRequiredWorkgroupSize: {
auto kernel = parse_data->strings[inst->words[5]];
auto x = parse_data->constants[inst->words[6]];
auto y = parse_data->constants[inst->words[7]];
auto z = parse_data->constants[inst->words[8]];
parse_data->binary->set_required_work_group_size(kernel, x, y,
z);
break;
}
case NonSemanticClspvReflectionConstantDataStorageBuffer:
case NonSemanticClspvReflectionConstantDataPointerPushConstant: {
auto char2int = [](char c) {
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
return 0;
};
auto hex2bin = [&char2int](const char* str, char* bin) {
while (str[0] && str[1]) {
*(bin++) = char2int(str[0]) * 16 + char2int(str[1]);
str += 2;
}
};
auto data = parse_data->strings[inst->words[7]];
if (data.size() & 1) {
cvk_error_fn("invalid constant data buffer string (odd "
"number of digits)");
return SPV_ERROR_INVALID_DATA;
}
constant_data_buffer_info binfo{};
auto data_size = data.size() / 2;
binfo.data.resize(data_size);
hex2bin(data.c_str(), binfo.data.data());
if (ext_inst ==
NonSemanticClspvReflectionConstantDataStorageBuffer) {
binfo.type = module_buffer_type::storage_buffer;
binfo.set = parse_data->constants[inst->words[5]];
if (binfo.set >= spir_binary::MAX_DESCRIPTOR_SETS)
return SPV_ERROR_INVALID_DATA;
binfo.binding = parse_data->constants[inst->words[6]];
} else {
binfo.type = module_buffer_type::pointer_push_constant;
binfo.pc_offset = parse_data->constants[inst->words[5]];
parse_data->binary->add_push_constant(
pushconstant::module_constants_pointer,
{binfo.pc_offset, 8u});
}
parse_data->binary->set_constant_data_buffer(binfo);
break;
}
case NonSemanticClspvReflectionPrintfInfo: {
uint32_t printf_id = parse_data->constants[inst->words[5]];
std::string printf_string = parse_data->strings[inst->words[6]];
std::vector<uint32_t> printf_arg_sizes;
for (int i = 6; i < inst->num_operands; i++) {
printf_arg_sizes.push_back(
parse_data
->constants[inst->words[inst->operands[i].offset]]);
}
parse_data->binary->add_printf_descriptor(
{printf_id, printf_string, printf_arg_sizes});
break;
}
case NonSemanticClspvReflectionPrintfBufferStorageBuffer: {
printf_buffer_desc_info binfo;
binfo.type = module_buffer_type::storage_buffer;
binfo.set = parse_data->constants[inst->words[5]];
binfo.binding = parse_data->constants[inst->words[6]];
binfo.size = parse_data->constants[inst->words[7]];
parse_data->binary->set_printf_buffer_info(binfo);
break;
}
case NonSemanticClspvReflectionPrintfBufferPointerPushConstant: {
printf_buffer_desc_info binfo;
binfo.type = module_buffer_type::pointer_push_constant;
binfo.pc_offset = parse_data->constants[inst->words[5]];
binfo.size = parse_data->constants[inst->words[7]];
parse_data->binary->set_printf_buffer_info(binfo);
parse_data->binary->add_push_constant(
pushconstant::printf_buffer_pointer, {binfo.pc_offset, 8u});
break;
}
default:
return SPV_ERROR_INVALID_DATA;
}
}
break;
default:
break;
}
return SPV_SUCCESS;
}
bool spir_binary::load(const char* fname) {
std::ifstream ifile;
ifile.open(fname, std::ios::in | std::ios::binary);
if (!ifile.is_open()) {
cvk_error("Failed to open %s", fname);
return false;
}
ifile.seekg(0, std::ios::end);
uint32_t size = ifile.tellg();
ifile.seekg(0, std::ios::beg);
return load(ifile, size);
}
bool spir_binary::load(std::istream& istream, uint32_t size) {
m_code.assign(size / SPIR_WORD_SIZE, 0);
istream.read(reinterpret_cast<char*>(m_code.data()), size);
if (!istream.good()) {
cvk_warn("Failed to load SPIR-V (size: %u)", size);
return false;
}
return true;
}
bool spir_binary::read(const unsigned char* src, size_t size) {
m_loaded_from_binary = true;
membuf bufview(src, src + size);
std::istream istream(&bufview);
return load(istream, size);
}
bool spir_binary::save(std::ostream& ostream) const {
ostream.write(reinterpret_cast<const char*>(m_code.data()), size());
return ostream.good();
}
bool spir_binary::save(const char* fname) const {
std::ofstream ofile;
ofile.open(fname, std::ios::out | std::ios::binary);
if (!ofile.is_open()) {
return false;
}
return save(ofile);
}
size_t spir_binary::size() const { return m_code.size() * SPIR_WORD_SIZE; }
bool spir_binary::write(unsigned char* dst) const {
membuf bufview(dst, dst + size());
std::ostream ostream(&bufview);
return save(ostream);
}
void spir_binary::use(std::vector<uint32_t>&& src) { m_code = std::move(src); }
void spir_binary::set_target_env(spv_target_env env) {
spvContextDestroy(m_context);
m_context = spvContextCreate(env);
}
bool spir_binary::validate(const spirv_validation_options& val_options) const {
spv_diagnostic diag;
spv_validator_options options = spvValidatorOptionsCreate();
spvValidatorOptionsSetUniformBufferStandardLayout(
options, val_options.uniform_buffer_std_layout);
spv_const_binary_t binary{m_code.data(), m_code.size()};
spv_result_t res =
spvValidateWithOptions(m_context, options, &binary, &diag);
spvDiagnosticPrint(diag);
spvDiagnosticDestroy(diag);
spvValidatorOptionsDestroy(options);
return res == SPV_SUCCESS;
}
bool spir_binary::strip_reflection(std::vector<uint32_t>* stripped) {
const spvtools::MessageConsumer consumer =
[](spv_message_level_t level, const char*,
const spv_position_t& position, const char* message) {
#define msgtpl "spvtools says '%s' at position %zu"
switch (level) {
case SPV_MSG_FATAL:
case SPV_MSG_INTERNAL_ERROR:
case SPV_MSG_ERROR:
cvk_error(msgtpl, message, position.index);
break;
case SPV_MSG_WARNING:
cvk_warn(msgtpl, message, position.index);
break;
case SPV_MSG_INFO:
cvk_info(msgtpl, message, position.index);
break;
case SPV_MSG_DEBUG:
cvk_debug(msgtpl, message, position.index);
break;
}
#undef msgtpl
};
#if COMPILER_AVAILABLE || USING_SWIFTSHADER
spvtools::Optimizer opt(m_target_env);
opt.SetMessageConsumer(consumer);
opt.RegisterPass(spvtools::CreateStripReflectInfoPass());
spvtools::OptimizerOptions options;
options.set_run_validator(false);
if (!opt.Run(m_code.data(), m_code.size(), stripped, options)) {
return false;
}
#else
*stripped = m_code;
#endif
return true;
}
bool spir_binary::load_descriptor_map() {
reflection_parse_data parse_data;
parse_data.binary = this;
// TODO: The parser assumes a valid SPIR-V module, but validation is not
// run until later.
auto result =
spvBinaryParse(m_context, &parse_data, m_code.data(), m_code.size(),
nullptr, parse_reflection, nullptr);
if (result != SPV_SUCCESS) {
cvk_error_fn("Parsing SPIR-V module reflection failed: %d", result);
return false;
}
return true;
}
bool spir_binary::get_capabilities(
std::vector<spv::Capability>& capabilities) const {
// Callback for receiving parsed instructions.
// The `user_data` parameter will be a pointer to the vector of
// capabilities (we cannot use a lambda capture for this as it prevents the
// lambda from being able to be converted to a function pointer).
auto parse_inst = [](void* user_data,
const spv_parsed_instruction_t* inst) {
// Stop parsing at first instruction that is not an OpCapability.
if (inst->opcode != spv::Op::OpCapability) {
return SPV_END_OF_STREAM;
}
// Add the capability to the list.
uint32_t capability = inst->words[inst->operands[0].offset];
auto capabilities =
reinterpret_cast<std::vector<spv::Capability>*>(user_data);
capabilities->push_back(static_cast<spv::Capability>(capability));
return SPV_SUCCESS;
};
// Parse the SPIR-V binary to build the list of required capabilities.
spv_result_t result =
spvBinaryParse(m_context, &capabilities, m_code.data(), m_code.size(),
nullptr, parse_inst, nullptr);
if (result != SPV_SUCCESS && result != SPV_END_OF_STREAM) {
cvk_error_fn("Parsing SPIR-V module failed: %d", result);
return false;
}
return true;
}
namespace {
#if COMPILER_AVAILABLE
bool save_cstring_to_file(
const std::string& fname, const char* data, size_t size,
std::ios_base::openmode open_mode = std::ios_base::out) {
std::filesystem::path ofname(fname);
if (ofname.has_parent_path()) {
std::error_code error;
std::filesystem::create_directories(ofname.parent_path(), error);
if (error) {
cvk_error_fn("create_directories failed: '%s' (%u)",
error.message().c_str(), error.value());
return false;
}
}
std::ofstream ofile{fname, open_mode};
if (!ofile.is_open()) {
return false;
}
ofile.write(data, size);
ofile.close();
return ofile.good();
}
bool save_string_to_file(const std::string& fname, const std::string& text) {
return save_cstring_to_file(fname, text.c_str(), text.size());
}
#ifndef CLSPV_ONLINE_COMPILER
bool save_il_to_file(const std::string& fname, const std::vector<uint8_t>& il) {
return save_cstring_to_file(fname, reinterpret_cast<const char*>(il.data()),
il.size(), std::ios::binary);
}
#endif // CLSPV_ONLINE_COMPILER
#endif // COMPILER_AVAILABLE
struct temp_folder_deletion {
temp_folder_deletion(const std::string& path) : m_path(path) {}
~temp_folder_deletion() {
if (!config.keep_temporaries && !m_path.empty())
std::filesystem::remove_all(m_path.c_str());
}
private:
std::string m_path;
};
enum class spirv_validation_level
{
skip,
warn,
error,
};
bool validate_binary(spir_binary const& binary,
spirv_validation_options const& val_options) {
spirv_validation_level level = spirv_validation_level::error;
if (config.spirv_validation.set) {
if (config.spirv_validation == 0) {
level = spirv_validation_level::skip;
} else if (config.spirv_validation == 1) {
level = spirv_validation_level::warn;
}
}
if (level == spirv_validation_level::skip) {
cvk_info("Skipping validation of SPIR-V binary.");
return true;
}
if (binary.validate(val_options)) {
cvk_info("SPIR-V binary is valid.");
return true;
}
if (level == spirv_validation_level::warn) {
cvk_warn("SPIR-V binary is invalid.");
return true;
}
cvk_error("SPIR-V binary is invalid.");
return false;
}
const uint32_t clvk_binary_magic =
0x6B766C63; // "clvk" in ASCII in little-endian
const uint32_t clvk_binary_version = 1;
struct clvk_binary_header {
uint32_t magic;
uint32_t version;
uint32_t binary_type;
};
#define COPY_WORD(dst, src) \
do { \
((unsigned char*)dst)[0] = ((unsigned char*)(src))[0]; \
((unsigned char*)dst)[1] = ((unsigned char*)(src))[1]; \
((unsigned char*)dst)[2] = ((unsigned char*)(src))[2]; \
((unsigned char*)dst)[3] = ((unsigned char*)(src))[3]; \
} while (0)
} // namespace
bool cvk_program::read_llvm_bitcode(const unsigned char* src, size_t size) {
if (size >= 4 &&
(src[0] == 'B' && src[1] == 'C' && src[2] == 0xc0 && src[3] == 0xde)) {
m_ir.resize(size);
memcpy(m_ir.data(), src, size);
m_dev_status[m_context->device()] = CL_BUILD_SUCCESS;
return true;
}
return false;
}
void cvk_program::write_binary_header(unsigned char* dst) const {
struct clvk_binary_header* header = (struct clvk_binary_header*)dst;
COPY_WORD(&header->magic, &clvk_binary_magic);
COPY_WORD(&header->version, &clvk_binary_version);
COPY_WORD(&header->binary_type, &m_binary_type);
}
cl_program_binary_type cvk_program::read_binary_header(const unsigned char* src,
size_t size) {
struct clvk_binary_header* header = (struct clvk_binary_header*)src;
if (size < sizeof(header)) {
return CL_PROGRAM_BINARY_TYPE_NONE;
}
uint32_t magic, version, binary_type;
COPY_WORD(&magic, &header->magic);
COPY_WORD(&version, &header->version);
COPY_WORD(&binary_type, &header->binary_type);
if (magic != clvk_binary_magic) {
cvk_info_fn("magic not found");
return CL_PROGRAM_BINARY_TYPE_NONE;
}
if (version != clvk_binary_version) {
cvk_warn_fn("wrong version");
return CL_PROGRAM_BINARY_TYPE_NONE;
}
return binary_type;
}
bool cvk_program::read(const unsigned char* src, size_t size) {
bool success = false;
auto binary_type = read_binary_header(src, size);
// if the binary does not have a clvk binary header, let's try to read
// it first as a llvm ir buffer, then as a vulkan spirv buffer.
if (binary_type == CL_PROGRAM_BINARY_TYPE_NONE) {
cvk_info_fn("no clvk binary header found, looking for llvm bitcode");
if (read_llvm_bitcode(src, size)) {
m_binary_type = CL_PROGRAM_BINARY_TYPE_COMPILED_OBJECT;
cvk_info_fn("llvm bitcode compiled object found");
return true;
}
cvk_info_fn("llvm bitcode not found, looking for Vulkan SPIR-V binary");
if (m_binary.read(src, size)) {
m_binary_type = CL_PROGRAM_BINARY_TYPE_EXECUTABLE;
cvk_info_fn("Vulkan SPIR-V binary executable found");
return true;
}
cvk_error_fn("unable to read binary");
return success;
}
auto header_size = sizeof(struct clvk_binary_header);
src += header_size;
size -= header_size;
switch (binary_type) {
case CL_PROGRAM_BINARY_TYPE_LIBRARY:
case CL_PROGRAM_BINARY_TYPE_COMPILED_OBJECT:
success = read_llvm_bitcode(src, size);
break;
case CL_PROGRAM_BINARY_TYPE_EXECUTABLE:
success = m_binary.read(src, size);
break;
}
if (success) {
m_binary_type = binary_type;
}
return success;
}
bool cvk_program::write(unsigned char* dst) const {
write_binary_header(dst);
dst += sizeof(struct clvk_binary_header);
switch (m_binary_type) {
case CL_PROGRAM_BINARY_TYPE_LIBRARY:
case CL_PROGRAM_BINARY_TYPE_COMPILED_OBJECT:
memcpy(dst, m_ir.data(), m_ir.size());
return true;
case CL_PROGRAM_BINARY_TYPE_EXECUTABLE:
return m_binary.write(dst);
}
return false;
}
size_t cvk_program::binary_size() const {
auto header_size = sizeof(struct clvk_binary_header);
switch (m_binary_type) {
case CL_PROGRAM_BINARY_TYPE_LIBRARY:
case CL_PROGRAM_BINARY_TYPE_COMPILED_OBJECT:
return header_size + m_ir.size();
case CL_PROGRAM_BINARY_TYPE_EXECUTABLE:
return header_size + m_binary.size();
}
return 0;
}
std::string cvk_program::prepare_build_options(const cvk_device* device) const {
// Strip off a few options we can't handle
std::string options;
if (m_build_options.size() > 0) {
options += " ";
options += m_build_options;
}
std::vector<std::pair<std::string, std::string>> option_substitutions = {
// FIXME The 1.2 conformance tests shouldn't pass this option.
// It doesn't exist after OpenCL 1.0.
{"-cl-strict-aliasing", ""},
// clspv require entrypoint inlining for OpenCL 2.0 and OpenCL 3.0 (for
// generic addrspace for example).
{"-cl-std=CL2.0", "-cl-std=CL2.0 -inline-entry-points"},
{"-cl-std=CL3.0", "-cl-std=CL3.0 -inline-entry-points"},
{"-create-library", ""},
};
for (auto& subst : option_substitutions) {
size_t loc = options.find(subst.first);
if (loc != std::string::npos) {
options.replace(loc, subst.first.length(), subst.second);
}
}
// Check for some options we need and add them if not present.
std::string necessary_options[] = {
"-cl-single-precision-constant",
"-cl-kernel-arg-info",
};
for (std::string option : necessary_options) {
if (options.find(option) == std::string::npos) {
options += " " + option + " ";
}
}
// The device sets up some compiler options based on its capabilities.
options += " " + device->get_device_specific_compile_options() + " ";
// Features
if (options.find("-cl-std=CL3.0") != std::string::npos) {
auto features = device->opencl_c_features();
if (!features.empty()) {
options += "-enable-feature-macros=";
for (auto& feature : features) {
options += feature.name;
options += ',';
}
options.back() = ' '; // replace the final comma
}
}
auto buff_size = m_context->get_printf_buffersize();
options += " -enable-printf ";
options += " -printf-buffer-size=" + std::to_string(buff_size) + " ";
#if COMPILER_AVAILABLE
options += " " + config.clspv_options() + " ";
#endif
// split options into a vector
std::istringstream iss(options);
std::vector<std::string> vector_options;
std::string token;
while (std::getline(iss, token, ' ')) {
vector_options.push_back(token);
}
// loop through the options and quote the ones that need it
std::string quoted_options;
for (size_t i = 0; i < vector_options.size(); i++) {
if (vector_options[i].empty()) {
continue;
}
if (vector_options[i].find("-") == 0) {
quoted_options += vector_options[i];
} else {
quoted_options += "\"" + vector_options[i] + "\"";
}
quoted_options += " ";
}
return quoted_options;