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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
|
#include "slang-emit-wgsl.h"
// A note on row/column "terminology reversal".
//
// This is an "terminology reversing" implementation in the sense that
// * "column" in Slang code maps to "row" in the generated WGSL code, and
// * "row" in Slang code maps to "column" in the generated WGSL code.
//
// This means that matrices in Slang code end up getting translated to
// matrices that actually represent the transpose of what the Slang matrix
// represented.
// Both API's adopt the standard matrix multiplication convention whereby the
// column count of the matrix on the left hand side needs to match row count of
// the matrix on the right hand side.
// For these reasons, and due to the fact that (M_1 ... M_n)^T = M_n^T ... M_1^T,
// the order of matrix (and vector-matrix products) products must also reversed
// in the WGSL code.
//
// This may lead to confusion (which is why this note is referenced in several
// places), but the benefit of doing this is that the generated WGSL code is
// simpler to generate and should be faster to compile.
// A "terminology preserving" implementation would have to generate lots of
// 'transpose' calls, or else perform more complicated transformations that
// end up duplicating expressions many times.
namespace Slang
{
void WGSLSourceEmitter::emitSwitchCaseSelectorsImpl(
const SwitchRegion::Case *const currentCase,
const bool isDefault)
{
// WGSL has special syntax for blocks sharing case labels:
// "case 2, 3, 4: ...;" instead of the C-like syntax
// "case 2: case 3: case 4: ...;".
m_writer->emit("case ");
for (auto caseVal : currentCase->values)
{
emitOperand(caseVal, getInfo(EmitOp::General));
m_writer->emit(", ");
}
if (isDefault)
{
m_writer->emit("default, ");
}
m_writer->emit(":\n");
}
void WGSLSourceEmitter::emitParameterGroupImpl(
IRGlobalParam* varDecl,
IRUniformParameterGroupType* type)
{
auto varLayout = getVarLayout(varDecl);
SLANG_RELEASE_ASSERT(varLayout);
for (auto attr : varLayout->getOffsetAttrs())
{
const LayoutResourceKind kind = attr->getResourceKind();
switch (kind)
{
case LayoutResourceKind::VaryingInput:
case LayoutResourceKind::VaryingOutput:
m_writer->emit("@location(");
m_writer->emit(attr->getOffset());
m_writer->emit(")");
if (attr->getSpace())
{
// TODO: Not sure what 'space' should map to in WGSL
SLANG_ASSERT(false);
}
break;
case LayoutResourceKind::SpecializationConstant:
// TODO:
// Consider moving to a differently named function.
// This is not technically an attribute, but a declaration.
//
// https://www.w3.org/TR/WGSL/#override-decls
m_writer->emit("override");
break;
case LayoutResourceKind::Uniform:
case LayoutResourceKind::ConstantBuffer:
case LayoutResourceKind::ShaderResource:
case LayoutResourceKind::UnorderedAccess:
case LayoutResourceKind::SamplerState:
case LayoutResourceKind::DescriptorTableSlot:
m_writer->emit("@binding(");
m_writer->emit(attr->getOffset());
m_writer->emit(") ");
m_writer->emit("@group(");
m_writer->emit(attr->getSpace());
m_writer->emit(") ");
break;
}
}
auto elementType = type->getElementType();
m_writer->emit("var<uniform> ");
m_writer->emit(getName(varDecl));
m_writer->emit(" : ");
emitType(elementType);
m_writer->emit(";\n");
}
void WGSLSourceEmitter::emitEntryPointAttributesImpl(
IRFunc* irFunc,
IREntryPointDecoration* entryPointDecor)
{
auto stage = entryPointDecor->getProfile().getStage();
switch (stage)
{
case Stage::Fragment:
m_writer->emit("@fragment\n");
break;
case Stage::Vertex:
m_writer->emit("@vertex\n");
break;
case Stage::Compute:
{
m_writer->emit("@compute\n");
{
Int sizeAlongAxis[kThreadGroupAxisCount];
getComputeThreadGroupSize(irFunc, sizeAlongAxis);
m_writer->emit("@workgroup_size(");
for (int ii = 0; ii < kThreadGroupAxisCount; ++ii)
{
if (ii != 0)
m_writer->emit(", ");
m_writer->emit(sizeAlongAxis[ii]);
}
m_writer->emit(")\n");
}
}
break;
default:
SLANG_ABORT_COMPILATION("unsupported stage.");
}
}
// This is 'function_header' from the WGSL specification
void WGSLSourceEmitter::emitFuncHeaderImpl(IRFunc* func)
{
Slang::IRType * resultType = func->getResultType();
auto name = getName(func);
m_writer->emit("fn ");
m_writer->emit(name);
emitSimpleFuncParamsImpl(func);
// An absence of return type is expressed by skipping the optional '->' part of the
// header.
if (resultType->getOp() != kIROp_VoidType)
{
m_writer->emit(" -> ");
emitType(resultType);
}
}
void WGSLSourceEmitter::emitSimpleFuncParamImpl(IRParam* param)
{
if (auto sysSemanticDecor = param->findDecoration<IRTargetSystemValueDecoration>())
{
m_writer->emit("@builtin(");
m_writer->emit(sysSemanticDecor->getSemantic());
m_writer->emit(")");
}
CLikeSourceEmitter::emitSimpleFuncParamImpl(param);
}
void WGSLSourceEmitter::emitMatrixType(
IRType *const elementType, const IRIntegerValue& rowCountWGSL,
const IRIntegerValue& colCountWGSL
)
{
// WGSL uses CxR convention
m_writer->emit("mat");
m_writer->emit(colCountWGSL);
m_writer->emit("x");
m_writer->emit(rowCountWGSL);
m_writer->emit("<");
emitType(elementType);
m_writer->emit(">");
}
void WGSLSourceEmitter::emitStructDeclarationSeparatorImpl()
{
m_writer->emit(",");
}
static bool isPowerOf2(const uint32_t n)
{
return (n != 0U) && ((n - 1U) & n) == 0U;
}
void WGSLSourceEmitter::emitStructFieldAttributes(IRStructType * structType, IRStructField * field)
{
// Tint emits errors unless we explicitly spell out the layout in some cases, so emit
// offset and align attribtues for all fields.
IRSizeAndAlignmentDecoration *const sizeAndAlignmentDecoration =
structType->findDecoration<IRSizeAndAlignmentDecoration>();
// NullDifferential struct doesn't have size and alignment decoration
if (sizeAndAlignmentDecoration == nullptr)
return;
SLANG_ASSERT(sizeAndAlignmentDecoration->getAlignment() > IRIntegerValue{0});
SLANG_ASSERT(
sizeAndAlignmentDecoration->getAlignment() <= IRIntegerValue{UINT32_MAX}
);
const uint32_t structAlignment =
static_cast<uint32_t>(sizeAndAlignmentDecoration->getAlignment());
IROffsetDecoration *const fieldOffsetDecoration =
field->findDecoration<IROffsetDecoration>();
SLANG_ASSERT(fieldOffsetDecoration->getOffset() >= IRIntegerValue{0});
SLANG_ASSERT(fieldOffsetDecoration->getOffset() <= IRIntegerValue{UINT32_MAX});
SLANG_ASSERT(isPowerOf2(structAlignment));
const uint32_t fieldOffset =
static_cast<uint32_t>(fieldOffsetDecoration->getOffset());
// Alignment is GCD(fieldOffset, structAlignment)
// TODO: Use builtin/intrinsic (e.g. __builtin_ffs)
uint32_t fieldAlignment = 1U;
while (((fieldAlignment & (structAlignment | fieldOffset)) == 0U))
fieldAlignment = fieldAlignment << 1U;
m_writer->emit("@align(");
m_writer->emit(fieldAlignment);
m_writer->emit(")");
}
void WGSLSourceEmitter::emit(const AddressSpace addressSpace)
{
switch (addressSpace)
{
case AddressSpace::Uniform:
m_writer->emit("uniform");
break;
case AddressSpace::StorageBuffer:
m_writer->emit("storage");
break;
case AddressSpace::Generic:
m_writer->emit("function");
break;
case AddressSpace::ThreadLocal:
m_writer->emit("private");
break;
case AddressSpace::GroupShared:
m_writer->emit("workgroup");
break;
}
}
static const char* getWgslImageFormat(IRTextureTypeBase* type)
{
// You can find the supported WGSL texel format from the URL:
// https://www.w3.org/TR/WGSL/#storage-texel-formats
//
ImageFormat imageFormat = type->hasFormat() ? (ImageFormat)type->getFormat() : ImageFormat::unknown;
switch (imageFormat)
{
case ImageFormat::rgba8: return "rgba8unorm";
case ImageFormat::rgba8_snorm: return "rgba8snorm";
case ImageFormat::rgba8ui: return "rgba8uint";
case ImageFormat::rgba8i: return "rgba8sint";
case ImageFormat::rgba16ui: return "rgba16uint";
case ImageFormat::rgba16i: return "rgba16sint";
case ImageFormat::rgba16f: return "rgba16float";
case ImageFormat::r32ui: return "r32uint";
case ImageFormat::r32i: return "r32sint";
case ImageFormat::r32f: return "r32float";
case ImageFormat::rg32ui: return "rg32uint";
case ImageFormat::rg32i: return "rg32sint";
case ImageFormat::rg32f: return "rg32float";
case ImageFormat::rgba32ui: return "rgba32uint";
case ImageFormat::rgba32i: return "rgba32sint";
case ImageFormat::rgba32f: return "rgba32float";
case ImageFormat::unknown:
// Unlike SPIR-V, WGSL doesn't have a texel format for "unknown".
return "rgba32float";
default:
// We may need to print a warning for types WGSL doesn't support
return "rgba32float";
}
}
void WGSLSourceEmitter::emitSimpleTypeImpl(IRType* type)
{
switch (type->getOp())
{
case kIROp_HLSLRWStructuredBufferType:
case kIROp_HLSLStructuredBufferType:
case kIROp_HLSLRasterizerOrderedStructuredBufferType:
{
auto structuredBufferType = as<IRHLSLStructuredBufferTypeBase>(type);
m_writer->emit("array");
m_writer->emit("<");
emitType(structuredBufferType->getElementType());
m_writer->emit(">");
}
break;
case kIROp_HLSLByteAddressBufferType:
case kIROp_HLSLRWByteAddressBufferType:
{
m_writer->emit("array<u32>");
}
break;
case kIROp_VoidType:
{
// There is no void type in WGSL.
// A return type of "void" is expressed by skipping the end part of the
// 'function_header' term:
// "
// function_header :
// 'fn' ident '(' param_list ? ')'
// ( '->' attribute * template_elaborated_ident ) ?
// "
// In other words, in WGSL we should never even get to the point where we're
// asking to emit 'void'.
SLANG_UNEXPECTED("'void' type emitted");
return;
}
case kIROp_FloatType:
m_writer->emit("f32");
break;
case kIROp_DoubleType:
// There is no "f64" type in WGSL
SLANG_UNEXPECTED("'double' type emitted");
break;
case kIROp_Int8Type:
case kIROp_UInt8Type:
// There is no "[i|u]8" type in WGSL
SLANG_UNEXPECTED("8 bit integer type emitted");
break;
case kIROp_HalfType:
m_f16ExtensionEnabled = true;
m_writer->emit("f16");
break;
case kIROp_BoolType:
m_writer->emit("bool");
break;
case kIROp_IntType:
m_writer->emit("i32");
break;
case kIROp_UIntType:
m_writer->emit("u32");
break;
case kIROp_UInt64Type:
{
m_writer->emit(getDefaultBuiltinTypeName(type->getOp()));
return;
}
case kIROp_Int16Type:
case kIROp_UInt16Type:
SLANG_UNEXPECTED("16 bit integer value emitted");
return;
case kIROp_Int64Type:
case kIROp_IntPtrType:
m_writer->emit("i64");
return;
case kIROp_UIntPtrType:
m_writer->emit("u64");
return;
case kIROp_StructType:
m_writer->emit(getName(type));
return;
case kIROp_VectorType:
{
auto vecType = (IRVectorType*)type;
emitVectorTypeNameImpl(
vecType->getElementType(), getIntVal(vecType->getElementCount())
);
return;
}
case kIROp_MatrixType:
{
auto matType = (IRMatrixType*)type;
// We map matrices in Slang to WGSL matrices that represent the transpose.
// (See note on "terminology reversal".)
const IRIntegerValue colCountWGSL = getIntVal(matType->getRowCount());
const IRIntegerValue rowCountWGSL = getIntVal(matType->getColumnCount());
emitMatrixType(matType->getElementType(), rowCountWGSL, colCountWGSL);
return;
}
case kIROp_SamplerStateType:
{
m_writer->emit("sampler");
return;
}
case kIROp_SamplerComparisonStateType:
{
m_writer->emit("sampler_comparison");
return;
}
case kIROp_PtrType:
case kIROp_InOutType:
case kIROp_OutType:
case kIROp_RefType:
case kIROp_ConstRefType:
{
auto ptrType = cast<IRPtrTypeBase>(type);
m_writer->emit("ptr<");
emit((AddressSpace)ptrType->getAddressSpace());
m_writer->emit(", ");
emitType((IRType*)ptrType->getValueType());
m_writer->emit(">");
return;
}
case kIROp_ArrayType:
{
m_writer->emit("array<");
emitType((IRType*)type->getOperand(0));
m_writer->emit(", ");
emitVal(type->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(">");
return;
}
case kIROp_TextureType:
if (auto texType = as<IRTextureType>(type))
{
switch (texType->getAccess())
{
case SLANG_RESOURCE_ACCESS_READ_WRITE:
m_writer->emit("texture_storage");
break;
default:
m_writer->emit("texture");
break;
}
if (texType->isShadow())
{
m_writer->emit("_depth");
}
if (texType->isMultisample())
{
m_writer->emit("_multisampled");
}
switch (texType->GetBaseShape())
{
case SLANG_TEXTURE_1D: m_writer->emit("_1d"); break;
case SLANG_TEXTURE_2D: m_writer->emit("_2d"); break;
case SLANG_TEXTURE_3D: m_writer->emit("_3d"); break;
case SLANG_TEXTURE_CUBE: m_writer->emit("_cube"); break;
}
if (texType->isArray())
m_writer->emit("_array");
if (!texType->isShadow())
{
m_writer->emit("<");
auto elemType = texType->getElementType();
switch (texType->getAccess())
{
case SLANG_RESOURCE_ACCESS_READ_WRITE:
m_writer->emit(getWgslImageFormat(texType));
m_writer->emit(", read_write");
break;
default:
if (auto vecElemType = as<IRVectorType>(elemType))
emitSimpleType(vecElemType->getElementType());
else
emitType(elemType);
break;
}
m_writer->emit(">");
}
}
return;
case kIROp_AtomicType:
{
m_writer->emit("atomic<");
emitType(cast<IRAtomicType>(type)->getElementType());
m_writer->emit(">");
return;
}
default:
break;
}
}
void WGSLSourceEmitter::emitLayoutQualifiersImpl(IRVarLayout* layout)
{
for (auto attr : layout->getOffsetAttrs())
{
LayoutResourceKind kind = attr->getResourceKind();
// TODO:
// This is not correct. For the moment this is just here as a hack to make
// @binding and @group unique, so that we can pass WGSL compile tests.
// This will have to be revisited when we actually want to supply resources to
// shaders.
if (kind == LayoutResourceKind::DescriptorTableSlot)
{
m_writer->emit("@binding(");
m_writer->emit(attr->getOffset());
m_writer->emit(") ");
m_writer->emit("@group(");
m_writer->emit(attr->getSpace());
m_writer->emit(") ");
return;
}
}
}
void WGSLSourceEmitter::emitVarKeywordImpl(IRType * type, IRInst* varDecl)
{
switch (varDecl->getOp())
{
case kIROp_GlobalParam:
case kIROp_GlobalVar:
case kIROp_Var:
m_writer->emit("var");
break;
default:
if (as<IRModuleInst>(varDecl->getParent()))
{
m_writer->emit("const");
}
else
{
m_writer->emit("var");
}
break;
}
if (as<IRGroupSharedRate>(varDecl->getRate()))
{
m_writer->emit("<workgroup>");
}
else if (type->getOp() == kIROp_HLSLRWStructuredBufferType ||
type->getOp() == kIROp_HLSLRasterizerOrderedStructuredBufferType ||
type->getOp() == kIROp_HLSLRWByteAddressBufferType)
{
m_writer->emit("<");
m_writer->emit("storage, read_write");
m_writer->emit(">");
}
else if (type->getOp() == kIROp_HLSLStructuredBufferType ||
type->getOp() == kIROp_HLSLByteAddressBufferType)
{
m_writer->emit("<");
m_writer->emit("storage, read");
m_writer->emit(">");
}
else if(varDecl->getOp() == kIROp_GlobalVar)
{
// Global ("module-scope") non-handle variables need to specify storage space
// https://www.w3.org/TR/WGSL/#var-decls
// "
// Variables in the private, storage, uniform, workgroup, and handle address
// spaces must only be declared in module scope, while variables in the function
// address space must only be declared in function scope. The address space must
// be specified for all address spaces except handle and function. The handle
// address space must not be specified. Specifying the function address space is
// optional.
// "
m_writer->emit("<private>");
}
}
void WGSLSourceEmitter::_emitType(IRType* type, DeclaratorInfo* declarator)
{
// C-like languages bake array-ness, pointer-ness and reference-ness into the
// declarator, which happens in the default _emitType implementation.
// WGSL on the other hand, don't have special syntax -- these are just types.
switch (type->getOp())
{
case kIROp_ArrayType:
case kIROp_AttributedType:
case kIROp_UnsizedArrayType:
emitSimpleTypeAndDeclarator(type, declarator);
break;
default:
CLikeSourceEmitter::_emitType(type, declarator);
break;
}
}
void WGSLSourceEmitter::emitDeclaratorImpl(DeclaratorInfo* declarator)
{
if (!declarator) return;
m_writer->emit(" ");
switch (declarator->flavor)
{
case DeclaratorInfo::Flavor::Name:
{
auto nameDeclarator = (NameDeclaratorInfo*)declarator;
m_writer->emitName(*nameDeclarator->nameAndLoc);
}
break;
case DeclaratorInfo::Flavor::SizedArray:
{
// Sized arrays are just types (array<T, N>) in WGSL -- they are not
// supported at the syntax level
// https://www.w3.org/TR/WGSL/#array
SLANG_UNEXPECTED("Sized array declarator");
}
break;
case DeclaratorInfo::Flavor::UnsizedArray:
{
// Unsized arrays are just types (array<T>) in WGSL -- they are not
// supported at the syntax level
// https://www.w3.org/TR/WGSL/#array
SLANG_UNEXPECTED("Unsized array declarator");
}
break;
case DeclaratorInfo::Flavor::Ptr:
{
// Pointers (ptr<AS,T,AM>) are just types in WGSL -- they are not supported at
// the syntax level
// https://www.w3.org/TR/WGSL/#ref-ptr-types
SLANG_UNEXPECTED("Pointer declarator");
}
break;
case DeclaratorInfo::Flavor::Ref:
{
// References (ref<AS,T,AM>) are just types in WGSL -- they are not supported
// at the syntax level
// https://www.w3.org/TR/WGSL/#ref-ptr-types
SLANG_UNEXPECTED("Reference declarator");
}
break;
case DeclaratorInfo::Flavor::LiteralSizedArray:
{
// Sized arrays are just types (array<T, N>) in WGSL -- they are not supported
// at the syntax level
// https://www.w3.org/TR/WGSL/#array
SLANG_UNEXPECTED("Literal-sized array declarator");
}
break;
case DeclaratorInfo::Flavor::Attributed:
{
auto attributedDeclarator = (AttributedDeclaratorInfo*)declarator;
auto instWithAttributes = attributedDeclarator->instWithAttributes;
for (auto attr : instWithAttributes->getAllAttrs())
{
_emitPostfixTypeAttr(attr);
}
emitDeclarator(attributedDeclarator->next);
}
break;
default:
SLANG_DIAGNOSE_UNEXPECTED(getSink(), SourceLoc(), "unknown declarator flavor");
break;
}
}
void WGSLSourceEmitter::emitOperandImpl(IRInst* operand, EmitOpInfo const& outerPrec)
{
if (operand->getOp() == kIROp_Param && as<IRPtrTypeBase>(operand->getDataType()))
{
// If we are emitting a reference to a pointer typed operand, then
// we should dereference it now since we want to treat all the remaining
// part of wgsl as pointer-free target.
m_writer->emit("(*");
m_writer->emit(getName(operand));
m_writer->emit(")");
}
else
{
CLikeSourceEmitter::emitOperandImpl(operand, outerPrec);
}
}
void WGSLSourceEmitter::emitSimpleTypeAndDeclaratorImpl(
IRType* type,
DeclaratorInfo* declarator)
{
if (declarator)
{
emitDeclarator(declarator);
m_writer->emit(" : ");
}
emitSimpleType(type);
}
void WGSLSourceEmitter::emitSimpleValueImpl(IRInst* inst)
{
switch (inst->getOp())
{
case kIROp_IntLit:
{
auto litInst = static_cast<IRConstant*>(inst);
IRBasicType* type = as<IRBasicType>(inst->getDataType());
if (type)
{
switch (type->getBaseType())
{
default:
case BaseType::Int8:
case BaseType::UInt8:
{
SLANG_UNEXPECTED("8 bit integer value emitted");
break;
}
case BaseType::Int16:
case BaseType::UInt16:
{
SLANG_UNEXPECTED("16 bit integer value emitted");
break;
}
case BaseType::Int:
{
m_writer->emit("i32(");
m_writer->emit(int32_t(litInst->value.intVal));
m_writer->emit(")");
return;
}
case BaseType::UInt:
{
m_writer->emit("u32(");
m_writer->emit(UInt(uint32_t(litInst->value.intVal)));
m_writer->emit(")");
break;
}
case BaseType::Int64:
{
m_writer->emit("i64(");
m_writer->emitInt64(int64_t(litInst->value.intVal));
m_writer->emit(")");
break;
}
case BaseType::UInt64:
{
m_writer->emit("u64(");
SLANG_COMPILE_TIME_ASSERT(
sizeof(litInst->value.intVal) >= sizeof(uint64_t)
);
m_writer->emitUInt64(uint64_t(litInst->value.intVal));
m_writer->emit(")");
break;
}
case BaseType::IntPtr:
{
#if SLANG_PTR_IS_64
m_writer->emit("i64(");
m_writer->emitInt64(int64_t(litInst->value.intVal));
m_writer->emit(")");
#else
m_writer->emit("i32(");
m_writer->emit(int(litInst->value.intVal));
m_writer->emit(")");
#endif
break;
}
case BaseType::UIntPtr:
{
#if SLANG_PTR_IS_64
m_writer->emit("u64(");
m_writer->emitUInt64(uint64_t(litInst->value.intVal));
m_writer->emit(")");
#else
m_writer->emit("u32(");
m_writer->emit(UInt(uint32_t(litInst->value.intVal)));
m_writer->emit(")");
#endif
break;
}
}
}
else
{
// If no type... just output what we have
m_writer->emit(litInst->value.intVal);
}
break;
}
case kIROp_FloatLit:
{
auto litInst = static_cast<IRConstant*>(inst);
IRBasicType* type = as<IRBasicType>(inst->getDataType());
if (type)
{
switch (type->getBaseType())
{
default:
case BaseType::Half:
{
m_writer->emit(litInst->value.floatVal);
m_writer->emit("h");
m_f16ExtensionEnabled = true;
}
break;
case BaseType::Float:
{
m_writer->emit(litInst->value.floatVal);
m_writer->emit("f");
}
break;
case BaseType::Double:
{
// There is not "f64" in WGSL
SLANG_UNEXPECTED("'double' type emitted");
}
break;
}
}
else
{
// If no type... just output what we have
m_writer->emit(litInst->value.floatVal);
}
}
break;
case kIROp_BoolLit:
{
bool val = ((IRConstant*)inst)->value.intVal != 0;
m_writer->emit(val ? "true" : "false");
}
break;
default:
SLANG_UNIMPLEMENTED_X("val case for emit");
break;
}
}
void WGSLSourceEmitter::emitParamTypeImpl(IRType* type, const String& name)
{
emitType(type, name);
}
bool WGSLSourceEmitter::tryEmitInstStmtImpl(IRInst* inst)
{
switch (inst->getOp())
{
default:
return false;
case kIROp_AtomicLoad:
{
emitInstResultDecl(inst);
m_writer->emit("atomicLoad(&(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit("));\n");
return true;
}
case kIROp_AtomicStore:
{
m_writer->emit("atomicStore(&(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit("), ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(");\n");
return true;
}
case kIROp_AtomicExchange:
{
emitInstResultDecl(inst);
m_writer->emit("atomicExchange(&(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit("), ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(");\n");
return true;
}
case kIROp_AtomicCompareExchange:
{
emitInstResultDecl(inst);
m_writer->emit("atomicCompareExchangeWeak(&(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit("), ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(", ");
emitOperand(inst->getOperand(2), getInfo(EmitOp::General));
m_writer->emit(").old_value;\n");
return true;
}
case kIROp_AtomicAdd:
{
emitInstResultDecl(inst);
m_writer->emit("atomicAdd(&(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit("), ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(");\n");
return true;
}
case kIROp_AtomicSub:
{
emitInstResultDecl(inst);
m_writer->emit("atomicSub(&(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit("), ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(");\n");
return true;
}
case kIROp_AtomicAnd:
{
emitInstResultDecl(inst);
m_writer->emit("atomicAnd(&(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit("), ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(");\n");
return true;
}
case kIROp_AtomicOr:
{
emitInstResultDecl(inst);
m_writer->emit("atomicOr(&(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit("), ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(");\n");
return true;
}
case kIROp_AtomicXor:
{
emitInstResultDecl(inst);
m_writer->emit("atomicXor(&(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit("), ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(");\n");
return true;
}
case kIROp_AtomicMin:
{
emitInstResultDecl(inst);
m_writer->emit("atomicMin(&(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit("), ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(");\n");
return true;
}
case kIROp_AtomicMax:
{
emitInstResultDecl(inst);
m_writer->emit("atomicMax(&(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit("), ");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(");\n");
return true;
}
case kIROp_AtomicInc:
{
emitInstResultDecl(inst);
m_writer->emit("atomicAdd(&(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit("), ");
emitType(inst->getDataType());
m_writer->emit("(1));\n");
return true;
}
case kIROp_AtomicDec:
{
emitInstResultDecl(inst);
m_writer->emit("atomicSub(&(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit("), ");
emitType(inst->getDataType());
m_writer->emit("(1));\n");
return true;
}
}
}
void WGSLSourceEmitter::emitCallArg(IRInst* inst)
{
if (as<IRPtrTypeBase>(inst->getDataType()))
{
// If we are calling a function with a pointer-typed argument, we need to
// explicitly prefix the argument with `&` to pass a pointer.
//
m_writer->emit("&(");
emitOperand(inst, getInfo(EmitOp::General));
m_writer->emit(")");
}
else
{
emitOperand(inst, getInfo(EmitOp::General));
}
}
bool WGSLSourceEmitter::tryEmitInstExprImpl(IRInst* inst, const EmitOpInfo& inOuterPrec)
{
EmitOpInfo outerPrec = inOuterPrec;
switch (inst->getOp())
{
case kIROp_MakeVectorFromScalar:
{
// In WGSL this is done by calling the vec* overloads listed in [1]
// [1] https://www.w3.org/TR/WGSL/#value-constructor-builtin-function
emitType(inst->getDataType());
m_writer->emit("(");
auto prec = getInfo(EmitOp::Prefix);
emitOperand(inst->getOperand(0), rightSide(outerPrec, prec));
m_writer->emit(")");
return true;
}
break;
case kIROp_BitCast:
{
// In WGSL there is a built-in bitcast function!
// https://www.w3.org/TR/WGSL/#bitcast-builtin
m_writer->emit("bitcast");
m_writer->emit("<");
emitType(inst->getDataType());
m_writer->emit(">");
m_writer->emit("(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit(")");
return true;
}
break;
case kIROp_MakeArray:
case kIROp_MakeStruct:
{
// It seems there are currently no designated initializers in WGSL.
// Similarly for array initializers.
// https://github.com/gpuweb/gpuweb/issues/4210
// There is a constructor named like the struct/array type itself
auto type = inst->getDataType();
emitType(type);
m_writer->emit("( ");
UInt argCount = inst->getOperandCount();
for (UInt aa = 0; aa < argCount; ++aa)
{
if (aa != 0) m_writer->emit(", ");
emitOperand(inst->getOperand(aa), getInfo(EmitOp::General));
}
m_writer->emit(" )");
return true;
}
break;
case kIROp_MakeArrayFromElement:
{
// It seems there are currently no array initializers in WGSL.
// There is a constructor named like the array type itself
auto type = inst->getDataType();
emitType(type);
m_writer->emit("(");
UInt argCount =
(UInt)cast<IRIntLit>(
cast<IRArrayType>(inst->getDataType())->getElementCount()
)->getValue();
for (UInt aa = 0; aa < argCount; ++aa)
{
if (aa != 0) m_writer->emit(", ");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
}
m_writer->emit(")");
return true;
}
break;
case kIROp_StructuredBufferLoad:
case kIROp_RWStructuredBufferLoad:
case kIROp_RWStructuredBufferGetElementPtr:
{
emitOperand(inst->getOperand(0), leftSide(outerPrec, getInfo(EmitOp::Postfix)));
m_writer->emit("[");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit("]");
return true;
}
break;
case kIROp_Rsh:
case kIROp_Lsh:
{
// Shift amounts must be an unsigned type in WGSL
// https://www.w3.org/TR/WGSL/#bit-expr
IRInst *const shiftAmount = inst->getOperand(1);
IRType *const shiftAmountType = shiftAmount->getDataType();
if (shiftAmountType->getOp() == kIROp_IntType)
{
// Dawn complains about "mixing '<<' and '|' requires parenthesis", so let's
// add parenthesis.
m_writer->emit("(");
const auto emitOp = getEmitOpForOp(inst->getOp());
const auto info = getInfo(emitOp);
const bool needClose = maybeEmitParens(outerPrec, info);
emitOperand(inst->getOperand(0), leftSide(outerPrec, info));
m_writer->emit(" ");
m_writer->emit(info.op);
m_writer->emit(" ");
m_writer->emit("bitcast<u32>(");
emitOperand(inst->getOperand(1), rightSide(outerPrec, info));
m_writer->emit(")");
maybeCloseParens(needClose);
m_writer->emit(")");
return true;
}
}
break;
case kIROp_ByteAddressBufferLoad:
{
// Indices in Slang code count bytes, but in WASM they count u32's since
// byte address buffers translate to array<u32> in WASM, so divide by 4.
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit("[(");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(")/4]");
return true;
}
break;
case kIROp_ByteAddressBufferStore:
{
// Indices in Slang code count bytes, but in WASM they count u32's since
// byte address buffers translate to array<u32> in WASM, so divide by 4.
auto base = inst->getOperand(0);
emitOperand(base, EmitOpInfo());
m_writer->emit("[(");
emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
m_writer->emit(")/4] = ");
emitOperand(inst->getOperand(inst->getOperandCount() - 1), getInfo(EmitOp::General));
return true;
}
break;
}
return false;
}
void WGSLSourceEmitter::emitVectorTypeNameImpl(IRType* elementType, IRIntegerValue elementCount)
{
if (elementCount > 1)
{
m_writer->emit("vec");
m_writer->emit(elementCount);
m_writer->emit("<");
emitSimpleType(elementType);
m_writer->emit(">");
}
else
{
emitSimpleType(elementType);
}
}
void WGSLSourceEmitter::emitFrontMatterImpl(TargetRequest* /* targetReq */)
{
if (m_f16ExtensionEnabled)
{
m_writer->emit("enable f16;\n");
m_writer->emit("\n");
}
}
void WGSLSourceEmitter::emitIntrinsicCallExprImpl(
IRCall* inst,
UnownedStringSlice intrinsicDefinition,
IRInst* intrinsicInst,
EmitOpInfo const& inOuterPrec
)
{
// The f16 constructor is generated for f32tof16
if (intrinsicDefinition.startsWith("f16"))
{
m_f16ExtensionEnabled = true;
}
CLikeSourceEmitter::emitIntrinsicCallExprImpl(
inst, intrinsicDefinition, intrinsicInst, inOuterPrec
);
}
} // namespace Slang
|