Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(718)

Side by Side Diff: src/sksl/SkSLSPIRVCodeGenerator.cpp

Issue 1984363002: initial checkin of SkSL compiler (Closed) Base URL: https://skia.googlesource.com/skia@master
Patch Set: fixed CMake build Created 4 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « src/sksl/SkSLSPIRVCodeGenerator.h ('k') | src/sksl/SkSLToken.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 /*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "SkSLSPIRVCodeGenerator.h"
9
10 #include "string.h"
11
12 #include "GLSL.std.450.h"
13
14 #include "ir/SkSLExpressionStatement.h"
15 #include "ir/SkSLExtension.h"
16 #include "ir/SkSLIndexExpression.h"
17 #include "ir/SkSLVariableReference.h"
18
19 namespace SkSL {
20
21 #define SPIRV_DEBUG 0
22
23 static const int32_t SKSL_MAGIC = 0x0; // FIXME: we should probably register a magic number
24
25 void SPIRVCodeGenerator::setupIntrinsics() {
26 #define ALL_GLSL(x) std::make_tuple(kGLSL_STD_450_IntrinsicKind, GLSLstd450 ## x , GLSLstd450 ## x, \
27 GLSLstd450 ## x, GLSLstd450 ## x)
28 #define BY_TYPE_GLSL(ifFloat, ifInt, ifUInt) std::make_tuple(kGLSL_STD_450_Intri nsicKind, \
29 GLSLstd450 ## ifFlo at, \
30 GLSLstd450 ## ifInt , \
31 GLSLstd450 ## ifUIn t, \
32 SpvOpUndef)
33 #define SPECIAL(x) std::make_tuple(kSpecial_IntrinsicKind, k ## x ## _SpecialInt rinsic, \
34 k ## x ## _SpecialIntrinsic, k ## x ## _Speci alIntrinsic, \
35 k ## x ## _SpecialIntrinsic)
36 fIntrinsicMap["round"] = ALL_GLSL(Round);
37 fIntrinsicMap["roundEven"] = ALL_GLSL(RoundEven);
38 fIntrinsicMap["trunc"] = ALL_GLSL(Trunc);
39 fIntrinsicMap["abs"] = BY_TYPE_GLSL(FAbs, SAbs, SAbs);
40 fIntrinsicMap["sign"] = BY_TYPE_GLSL(FSign, SSign, SSign);
41 fIntrinsicMap["floor"] = ALL_GLSL(Floor);
42 fIntrinsicMap["ceil"] = ALL_GLSL(Ceil);
43 fIntrinsicMap["fract"] = ALL_GLSL(Fract);
44 fIntrinsicMap["radians"] = ALL_GLSL(Radians);
45 fIntrinsicMap["degrees"] = ALL_GLSL(Degrees);
46 fIntrinsicMap["sin"] = ALL_GLSL(Sin);
47 fIntrinsicMap["cos"] = ALL_GLSL(Cos);
48 fIntrinsicMap["tan"] = ALL_GLSL(Tan);
49 fIntrinsicMap["asin"] = ALL_GLSL(Asin);
50 fIntrinsicMap["acos"] = ALL_GLSL(Acos);
51 fIntrinsicMap["atan"] = SPECIAL(Atan);
52 fIntrinsicMap["sinh"] = ALL_GLSL(Sinh);
53 fIntrinsicMap["cosh"] = ALL_GLSL(Cosh);
54 fIntrinsicMap["tanh"] = ALL_GLSL(Tanh);
55 fIntrinsicMap["asinh"] = ALL_GLSL(Asinh);
56 fIntrinsicMap["acosh"] = ALL_GLSL(Acosh);
57 fIntrinsicMap["atanh"] = ALL_GLSL(Atanh);
58 fIntrinsicMap["pow"] = ALL_GLSL(Pow);
59 fIntrinsicMap["exp"] = ALL_GLSL(Exp);
60 fIntrinsicMap["log"] = ALL_GLSL(Log);
61 fIntrinsicMap["exp2"] = ALL_GLSL(Exp2);
62 fIntrinsicMap["log2"] = ALL_GLSL(Log2);
63 fIntrinsicMap["sqrt"] = ALL_GLSL(Sqrt);
64 fIntrinsicMap["inversesqrt"] = ALL_GLSL(InverseSqrt);
65 fIntrinsicMap["determinant"] = ALL_GLSL(Determinant);
66 fIntrinsicMap["matrixInverse"] = ALL_GLSL(MatrixInverse);
67 fIntrinsicMap["mod"] = std::make_tuple(kSPIRV_IntrinsicKind, SpvOp FMod, SpvOpSMod,
68 SpvOpUMod, SpvOpUndef);
69 fIntrinsicMap["min"] = BY_TYPE_GLSL(FMin, SMin, UMin);
70 fIntrinsicMap["max"] = BY_TYPE_GLSL(FMax, SMax, UMax);
71 fIntrinsicMap["clamp"] = BY_TYPE_GLSL(FClamp, SClamp, UClamp);
72 fIntrinsicMap["dot"] = std::make_tuple(kSPIRV_IntrinsicKind, SpvOp Dot, SpvOpUndef,
73 SpvOpUndef, SpvOpUndef);
74 fIntrinsicMap["mix"] = ALL_GLSL(FMix);
75 fIntrinsicMap["step"] = ALL_GLSL(Step);
76 fIntrinsicMap["smoothstep"] = ALL_GLSL(SmoothStep);
77 fIntrinsicMap["fma"] = ALL_GLSL(Fma);
78 fIntrinsicMap["frexp"] = ALL_GLSL(Frexp);
79 fIntrinsicMap["ldexp"] = ALL_GLSL(Ldexp);
80
81 #define PACK(type) fIntrinsicMap["pack" #type] = ALL_GLSL(Pack ## type); \
82 fIntrinsicMap["unpack" #type] = ALL_GLSL(Unpack ## type)
83 PACK(Snorm4x8);
84 PACK(Unorm4x8);
85 PACK(Snorm2x16);
86 PACK(Unorm2x16);
87 PACK(Half2x16);
88 PACK(Double2x32);
89 fIntrinsicMap["length"] = ALL_GLSL(Length);
90 fIntrinsicMap["distance"] = ALL_GLSL(Distance);
91 fIntrinsicMap["cross"] = ALL_GLSL(Cross);
92 fIntrinsicMap["normalize"] = ALL_GLSL(Normalize);
93 fIntrinsicMap["faceForward"] = ALL_GLSL(FaceForward);
94 fIntrinsicMap["reflect"] = ALL_GLSL(Reflect);
95 fIntrinsicMap["refract"] = ALL_GLSL(Refract);
96 fIntrinsicMap["findLSB"] = ALL_GLSL(FindILsb);
97 fIntrinsicMap["findMSB"] = BY_TYPE_GLSL(FindSMsb, FindSMsb, FindUMsb);
98 fIntrinsicMap["dFdx"] = std::make_tuple(kSPIRV_IntrinsicKind, SpvOpDP dx, SpvOpUndef,
99 SpvOpUndef, SpvOpUndef);
100 fIntrinsicMap["dFdy"] = std::make_tuple(kSPIRV_IntrinsicKind, SpvOpDP dy, SpvOpUndef,
101 SpvOpUndef, SpvOpUndef);
102 fIntrinsicMap["dFdy"] = std::make_tuple(kSPIRV_IntrinsicKind, SpvOpDP dy, SpvOpUndef,
103 SpvOpUndef, SpvOpUndef);
104 fIntrinsicMap["texture"] = SPECIAL(Texture);
105 fIntrinsicMap["texture2D"] = SPECIAL(Texture2D);
106 fIntrinsicMap["textureProj"] = SPECIAL(TextureProj);
107
108 fIntrinsicMap["any"] = std::make_tuple(kSPIRV_IntrinsicKind, Sp vOpUndef,
109 SpvOpUndef, SpvOpUndef, SpvOpAny);
110 fIntrinsicMap["all"] = std::make_tuple(kSPIRV_IntrinsicKind, Sp vOpUndef,
111 SpvOpUndef, SpvOpUndef, SpvOpAll);
112 fIntrinsicMap["equal"] = std::make_tuple(kSPIRV_IntrinsicKind, Sp vOpFOrdEqual,
113 SpvOpIEqual, SpvOpIEqual ,
114 SpvOpLogicalEqual);
115 fIntrinsicMap["notEqual"] = std::make_tuple(kSPIRV_IntrinsicKind, Sp vOpFOrdNotEqual,
116 SpvOpINotEqual, SpvOpINo tEqual,
117 SpvOpLogicalNotEqual);
118 fIntrinsicMap["lessThan"] = std::make_tuple(kSPIRV_IntrinsicKind, Sp vOpSLessThan,
119 SpvOpULessThan, SpvOpFOr dLessThan,
120 SpvOpUndef);
121 fIntrinsicMap["lessThanEqual"] = std::make_tuple(kSPIRV_IntrinsicKind, Sp vOpSLessThanEqual,
122 SpvOpULessThanEqual, Spv OpFOrdLessThanEqual,
123 SpvOpUndef);
124 fIntrinsicMap["greaterThan"] = std::make_tuple(kSPIRV_IntrinsicKind, Sp vOpSGreaterThan,
125 SpvOpUGreaterThan, SpvOp FOrdGreaterThan,
126 SpvOpUndef);
127 fIntrinsicMap["greaterThanEqual"] = std::make_tuple(kSPIRV_IntrinsicKind,
128 SpvOpSGreaterThanEqual,
129 SpvOpUGreaterThanEqual,
130 SpvOpFOrdGreaterThanEqua l,
131 SpvOpUndef);
132
133 // interpolateAt* not yet supported...
134 }
135
136 void SPIRVCodeGenerator::writeWord(int32_t word, std::ostream& out) {
137 #if SPIRV_DEBUG
138 out << "(" << word << ") ";
139 #else
140 out.write((const char*) &word, sizeof(word));
141 #endif
142 }
143
144 static bool is_float(const Type& type) {
145 if (type.kind() == Type::kVector_Kind) {
146 return is_float(*type.componentType());
147 }
148 return type == *kFloat_Type || type == *kDouble_Type;
149 }
150
151 static bool is_signed(const Type& type) {
152 if (type.kind() == Type::kVector_Kind) {
153 return is_signed(*type.componentType());
154 }
155 return type == *kInt_Type;
156 }
157
158 static bool is_unsigned(const Type& type) {
159 if (type.kind() == Type::kVector_Kind) {
160 return is_unsigned(*type.componentType());
161 }
162 return type == *kUInt_Type;
163 }
164
165 static bool is_bool(const Type& type) {
166 if (type.kind() == Type::kVector_Kind) {
167 return is_bool(*type.componentType());
168 }
169 return type == *kBool_Type;
170 }
171
172 static bool is_out(std::shared_ptr<Variable> var) {
173 return (var->fModifiers.fFlags & Modifiers::kOut_Flag) != 0;
174 }
175
176 #if SPIRV_DEBUG
177 static std::string opcode_text(SpvOp_ opCode) {
178 switch (opCode) {
179 case SpvOpNop:
180 return "Nop";
181 case SpvOpUndef:
182 return "Undef";
183 case SpvOpSourceContinued:
184 return "SourceContinued";
185 case SpvOpSource:
186 return "Source";
187 case SpvOpSourceExtension:
188 return "SourceExtension";
189 case SpvOpName:
190 return "Name";
191 case SpvOpMemberName:
192 return "MemberName";
193 case SpvOpString:
194 return "String";
195 case SpvOpLine:
196 return "Line";
197 case SpvOpExtension:
198 return "Extension";
199 case SpvOpExtInstImport:
200 return "ExtInstImport";
201 case SpvOpExtInst:
202 return "ExtInst";
203 case SpvOpMemoryModel:
204 return "MemoryModel";
205 case SpvOpEntryPoint:
206 return "EntryPoint";
207 case SpvOpExecutionMode:
208 return "ExecutionMode";
209 case SpvOpCapability:
210 return "Capability";
211 case SpvOpTypeVoid:
212 return "TypeVoid";
213 case SpvOpTypeBool:
214 return "TypeBool";
215 case SpvOpTypeInt:
216 return "TypeInt";
217 case SpvOpTypeFloat:
218 return "TypeFloat";
219 case SpvOpTypeVector:
220 return "TypeVector";
221 case SpvOpTypeMatrix:
222 return "TypeMatrix";
223 case SpvOpTypeImage:
224 return "TypeImage";
225 case SpvOpTypeSampler:
226 return "TypeSampler";
227 case SpvOpTypeSampledImage:
228 return "TypeSampledImage";
229 case SpvOpTypeArray:
230 return "TypeArray";
231 case SpvOpTypeRuntimeArray:
232 return "TypeRuntimeArray";
233 case SpvOpTypeStruct:
234 return "TypeStruct";
235 case SpvOpTypeOpaque:
236 return "TypeOpaque";
237 case SpvOpTypePointer:
238 return "TypePointer";
239 case SpvOpTypeFunction:
240 return "TypeFunction";
241 case SpvOpTypeEvent:
242 return "TypeEvent";
243 case SpvOpTypeDeviceEvent:
244 return "TypeDeviceEvent";
245 case SpvOpTypeReserveId:
246 return "TypeReserveId";
247 case SpvOpTypeQueue:
248 return "TypeQueue";
249 case SpvOpTypePipe:
250 return "TypePipe";
251 case SpvOpTypeForwardPointer:
252 return "TypeForwardPointer";
253 case SpvOpConstantTrue:
254 return "ConstantTrue";
255 case SpvOpConstantFalse:
256 return "ConstantFalse";
257 case SpvOpConstant:
258 return "Constant";
259 case SpvOpConstantComposite:
260 return "ConstantComposite";
261 case SpvOpConstantSampler:
262 return "ConstantSampler";
263 case SpvOpConstantNull:
264 return "ConstantNull";
265 case SpvOpSpecConstantTrue:
266 return "SpecConstantTrue";
267 case SpvOpSpecConstantFalse:
268 return "SpecConstantFalse";
269 case SpvOpSpecConstant:
270 return "SpecConstant";
271 case SpvOpSpecConstantComposite:
272 return "SpecConstantComposite";
273 case SpvOpSpecConstantOp:
274 return "SpecConstantOp";
275 case SpvOpFunction:
276 return "Function";
277 case SpvOpFunctionParameter:
278 return "FunctionParameter";
279 case SpvOpFunctionEnd:
280 return "FunctionEnd";
281 case SpvOpFunctionCall:
282 return "FunctionCall";
283 case SpvOpVariable:
284 return "Variable";
285 case SpvOpImageTexelPointer:
286 return "ImageTexelPointer";
287 case SpvOpLoad:
288 return "Load";
289 case SpvOpStore:
290 return "Store";
291 case SpvOpCopyMemory:
292 return "CopyMemory";
293 case SpvOpCopyMemorySized:
294 return "CopyMemorySized";
295 case SpvOpAccessChain:
296 return "AccessChain";
297 case SpvOpInBoundsAccessChain:
298 return "InBoundsAccessChain";
299 case SpvOpPtrAccessChain:
300 return "PtrAccessChain";
301 case SpvOpArrayLength:
302 return "ArrayLength";
303 case SpvOpGenericPtrMemSemantics:
304 return "GenericPtrMemSemantics";
305 case SpvOpInBoundsPtrAccessChain:
306 return "InBoundsPtrAccessChain";
307 case SpvOpDecorate:
308 return "Decorate";
309 case SpvOpMemberDecorate:
310 return "MemberDecorate";
311 case SpvOpDecorationGroup:
312 return "DecorationGroup";
313 case SpvOpGroupDecorate:
314 return "GroupDecorate";
315 case SpvOpGroupMemberDecorate:
316 return "GroupMemberDecorate";
317 case SpvOpVectorExtractDynamic:
318 return "VectorExtractDynamic";
319 case SpvOpVectorInsertDynamic:
320 return "VectorInsertDynamic";
321 case SpvOpVectorShuffle:
322 return "VectorShuffle";
323 case SpvOpCompositeConstruct:
324 return "CompositeConstruct";
325 case SpvOpCompositeExtract:
326 return "CompositeExtract";
327 case SpvOpCompositeInsert:
328 return "CompositeInsert";
329 case SpvOpCopyObject:
330 return "CopyObject";
331 case SpvOpTranspose:
332 return "Transpose";
333 case SpvOpSampledImage:
334 return "SampledImage";
335 case SpvOpImageSampleImplicitLod:
336 return "ImageSampleImplicitLod";
337 case SpvOpImageSampleExplicitLod:
338 return "ImageSampleExplicitLod";
339 case SpvOpImageSampleDrefImplicitLod:
340 return "ImageSampleDrefImplicitLod";
341 case SpvOpImageSampleDrefExplicitLod:
342 return "ImageSampleDrefExplicitLod";
343 case SpvOpImageSampleProjImplicitLod:
344 return "ImageSampleProjImplicitLod";
345 case SpvOpImageSampleProjExplicitLod:
346 return "ImageSampleProjExplicitLod";
347 case SpvOpImageSampleProjDrefImplicitLod:
348 return "ImageSampleProjDrefImplicitLod";
349 case SpvOpImageSampleProjDrefExplicitLod:
350 return "ImageSampleProjDrefExplicitLod";
351 case SpvOpImageFetch:
352 return "ImageFetch";
353 case SpvOpImageGather:
354 return "ImageGather";
355 case SpvOpImageDrefGather:
356 return "ImageDrefGather";
357 case SpvOpImageRead:
358 return "ImageRead";
359 case SpvOpImageWrite:
360 return "ImageWrite";
361 case SpvOpImage:
362 return "Image";
363 case SpvOpImageQueryFormat:
364 return "ImageQueryFormat";
365 case SpvOpImageQueryOrder:
366 return "ImageQueryOrder";
367 case SpvOpImageQuerySizeLod:
368 return "ImageQuerySizeLod";
369 case SpvOpImageQuerySize:
370 return "ImageQuerySize";
371 case SpvOpImageQueryLod:
372 return "ImageQueryLod";
373 case SpvOpImageQueryLevels:
374 return "ImageQueryLevels";
375 case SpvOpImageQuerySamples:
376 return "ImageQuerySamples";
377 case SpvOpConvertFToU:
378 return "ConvertFToU";
379 case SpvOpConvertFToS:
380 return "ConvertFToS";
381 case SpvOpConvertSToF:
382 return "ConvertSToF";
383 case SpvOpConvertUToF:
384 return "ConvertUToF";
385 case SpvOpUConvert:
386 return "UConvert";
387 case SpvOpSConvert:
388 return "SConvert";
389 case SpvOpFConvert:
390 return "FConvert";
391 case SpvOpQuantizeToF16:
392 return "QuantizeToF16";
393 case SpvOpConvertPtrToU:
394 return "ConvertPtrToU";
395 case SpvOpSatConvertSToU:
396 return "SatConvertSToU";
397 case SpvOpSatConvertUToS:
398 return "SatConvertUToS";
399 case SpvOpConvertUToPtr:
400 return "ConvertUToPtr";
401 case SpvOpPtrCastToGeneric:
402 return "PtrCastToGeneric";
403 case SpvOpGenericCastToPtr:
404 return "GenericCastToPtr";
405 case SpvOpGenericCastToPtrExplicit:
406 return "GenericCastToPtrExplicit";
407 case SpvOpBitcast:
408 return "Bitcast";
409 case SpvOpSNegate:
410 return "SNegate";
411 case SpvOpFNegate:
412 return "FNegate";
413 case SpvOpIAdd:
414 return "IAdd";
415 case SpvOpFAdd:
416 return "FAdd";
417 case SpvOpISub:
418 return "ISub";
419 case SpvOpFSub:
420 return "FSub";
421 case SpvOpIMul:
422 return "IMul";
423 case SpvOpFMul:
424 return "FMul";
425 case SpvOpUDiv:
426 return "UDiv";
427 case SpvOpSDiv:
428 return "SDiv";
429 case SpvOpFDiv:
430 return "FDiv";
431 case SpvOpUMod:
432 return "UMod";
433 case SpvOpSRem:
434 return "SRem";
435 case SpvOpSMod:
436 return "SMod";
437 case SpvOpFRem:
438 return "FRem";
439 case SpvOpFMod:
440 return "FMod";
441 case SpvOpVectorTimesScalar:
442 return "VectorTimesScalar";
443 case SpvOpMatrixTimesScalar:
444 return "MatrixTimesScalar";
445 case SpvOpVectorTimesMatrix:
446 return "VectorTimesMatrix";
447 case SpvOpMatrixTimesVector:
448 return "MatrixTimesVector";
449 case SpvOpMatrixTimesMatrix:
450 return "MatrixTimesMatrix";
451 case SpvOpOuterProduct:
452 return "OuterProduct";
453 case SpvOpDot:
454 return "Dot";
455 case SpvOpIAddCarry:
456 return "IAddCarry";
457 case SpvOpISubBorrow:
458 return "ISubBorrow";
459 case SpvOpUMulExtended:
460 return "UMulExtended";
461 case SpvOpSMulExtended:
462 return "SMulExtended";
463 case SpvOpAny:
464 return "Any";
465 case SpvOpAll:
466 return "All";
467 case SpvOpIsNan:
468 return "IsNan";
469 case SpvOpIsInf:
470 return "IsInf";
471 case SpvOpIsFinite:
472 return "IsFinite";
473 case SpvOpIsNormal:
474 return "IsNormal";
475 case SpvOpSignBitSet:
476 return "SignBitSet";
477 case SpvOpLessOrGreater:
478 return "LessOrGreater";
479 case SpvOpOrdered:
480 return "Ordered";
481 case SpvOpUnordered:
482 return "Unordered";
483 case SpvOpLogicalEqual:
484 return "LogicalEqual";
485 case SpvOpLogicalNotEqual:
486 return "LogicalNotEqual";
487 case SpvOpLogicalOr:
488 return "LogicalOr";
489 case SpvOpLogicalAnd:
490 return "LogicalAnd";
491 case SpvOpLogicalNot:
492 return "LogicalNot";
493 case SpvOpSelect:
494 return "Select";
495 case SpvOpIEqual:
496 return "IEqual";
497 case SpvOpINotEqual:
498 return "INotEqual";
499 case SpvOpUGreaterThan:
500 return "UGreaterThan";
501 case SpvOpSGreaterThan:
502 return "SGreaterThan";
503 case SpvOpUGreaterThanEqual:
504 return "UGreaterThanEqual";
505 case SpvOpSGreaterThanEqual:
506 return "SGreaterThanEqual";
507 case SpvOpULessThan:
508 return "ULessThan";
509 case SpvOpSLessThan:
510 return "SLessThan";
511 case SpvOpULessThanEqual:
512 return "ULessThanEqual";
513 case SpvOpSLessThanEqual:
514 return "SLessThanEqual";
515 case SpvOpFOrdEqual:
516 return "FOrdEqual";
517 case SpvOpFUnordEqual:
518 return "FUnordEqual";
519 case SpvOpFOrdNotEqual:
520 return "FOrdNotEqual";
521 case SpvOpFUnordNotEqual:
522 return "FUnordNotEqual";
523 case SpvOpFOrdLessThan:
524 return "FOrdLessThan";
525 case SpvOpFUnordLessThan:
526 return "FUnordLessThan";
527 case SpvOpFOrdGreaterThan:
528 return "FOrdGreaterThan";
529 case SpvOpFUnordGreaterThan:
530 return "FUnordGreaterThan";
531 case SpvOpFOrdLessThanEqual:
532 return "FOrdLessThanEqual";
533 case SpvOpFUnordLessThanEqual:
534 return "FUnordLessThanEqual";
535 case SpvOpFOrdGreaterThanEqual:
536 return "FOrdGreaterThanEqual";
537 case SpvOpFUnordGreaterThanEqual:
538 return "FUnordGreaterThanEqual";
539 case SpvOpShiftRightLogical:
540 return "ShiftRightLogical";
541 case SpvOpShiftRightArithmetic:
542 return "ShiftRightArithmetic";
543 case SpvOpShiftLeftLogical:
544 return "ShiftLeftLogical";
545 case SpvOpBitwiseOr:
546 return "BitwiseOr";
547 case SpvOpBitwiseXor:
548 return "BitwiseXor";
549 case SpvOpBitwiseAnd:
550 return "BitwiseAnd";
551 case SpvOpNot:
552 return "Not";
553 case SpvOpBitFieldInsert:
554 return "BitFieldInsert";
555 case SpvOpBitFieldSExtract:
556 return "BitFieldSExtract";
557 case SpvOpBitFieldUExtract:
558 return "BitFieldUExtract";
559 case SpvOpBitReverse:
560 return "BitReverse";
561 case SpvOpBitCount:
562 return "BitCount";
563 case SpvOpDPdx:
564 return "DPdx";
565 case SpvOpDPdy:
566 return "DPdy";
567 case SpvOpFwidth:
568 return "Fwidth";
569 case SpvOpDPdxFine:
570 return "DPdxFine";
571 case SpvOpDPdyFine:
572 return "DPdyFine";
573 case SpvOpFwidthFine:
574 return "FwidthFine";
575 case SpvOpDPdxCoarse:
576 return "DPdxCoarse";
577 case SpvOpDPdyCoarse:
578 return "DPdyCoarse";
579 case SpvOpFwidthCoarse:
580 return "FwidthCoarse";
581 case SpvOpEmitVertex:
582 return "EmitVertex";
583 case SpvOpEndPrimitive:
584 return "EndPrimitive";
585 case SpvOpEmitStreamVertex:
586 return "EmitStreamVertex";
587 case SpvOpEndStreamPrimitive:
588 return "EndStreamPrimitive";
589 case SpvOpControlBarrier:
590 return "ControlBarrier";
591 case SpvOpMemoryBarrier:
592 return "MemoryBarrier";
593 case SpvOpAtomicLoad:
594 return "AtomicLoad";
595 case SpvOpAtomicStore:
596 return "AtomicStore";
597 case SpvOpAtomicExchange:
598 return "AtomicExchange";
599 case SpvOpAtomicCompareExchange:
600 return "AtomicCompareExchange";
601 case SpvOpAtomicCompareExchangeWeak:
602 return "AtomicCompareExchangeWeak";
603 case SpvOpAtomicIIncrement:
604 return "AtomicIIncrement";
605 case SpvOpAtomicIDecrement:
606 return "AtomicIDecrement";
607 case SpvOpAtomicIAdd:
608 return "AtomicIAdd";
609 case SpvOpAtomicISub:
610 return "AtomicISub";
611 case SpvOpAtomicSMin:
612 return "AtomicSMin";
613 case SpvOpAtomicUMin:
614 return "AtomicUMin";
615 case SpvOpAtomicSMax:
616 return "AtomicSMax";
617 case SpvOpAtomicUMax:
618 return "AtomicUMax";
619 case SpvOpAtomicAnd:
620 return "AtomicAnd";
621 case SpvOpAtomicOr:
622 return "AtomicOr";
623 case SpvOpAtomicXor:
624 return "AtomicXor";
625 case SpvOpPhi:
626 return "Phi";
627 case SpvOpLoopMerge:
628 return "LoopMerge";
629 case SpvOpSelectionMerge:
630 return "SelectionMerge";
631 case SpvOpLabel:
632 return "Label";
633 case SpvOpBranch:
634 return "Branch";
635 case SpvOpBranchConditional:
636 return "BranchConditional";
637 case SpvOpSwitch:
638 return "Switch";
639 case SpvOpKill:
640 return "Kill";
641 case SpvOpReturn:
642 return "Return";
643 case SpvOpReturnValue:
644 return "ReturnValue";
645 case SpvOpUnreachable:
646 return "Unreachable";
647 case SpvOpLifetimeStart:
648 return "LifetimeStart";
649 case SpvOpLifetimeStop:
650 return "LifetimeStop";
651 case SpvOpGroupAsyncCopy:
652 return "GroupAsyncCopy";
653 case SpvOpGroupWaitEvents:
654 return "GroupWaitEvents";
655 case SpvOpGroupAll:
656 return "GroupAll";
657 case SpvOpGroupAny:
658 return "GroupAny";
659 case SpvOpGroupBroadcast:
660 return "GroupBroadcast";
661 case SpvOpGroupIAdd:
662 return "GroupIAdd";
663 case SpvOpGroupFAdd:
664 return "GroupFAdd";
665 case SpvOpGroupFMin:
666 return "GroupFMin";
667 case SpvOpGroupUMin:
668 return "GroupUMin";
669 case SpvOpGroupSMin:
670 return "GroupSMin";
671 case SpvOpGroupFMax:
672 return "GroupFMax";
673 case SpvOpGroupUMax:
674 return "GroupUMax";
675 case SpvOpGroupSMax:
676 return "GroupSMax";
677 case SpvOpReadPipe:
678 return "ReadPipe";
679 case SpvOpWritePipe:
680 return "WritePipe";
681 case SpvOpReservedReadPipe:
682 return "ReservedReadPipe";
683 case SpvOpReservedWritePipe:
684 return "ReservedWritePipe";
685 case SpvOpReserveReadPipePackets:
686 return "ReserveReadPipePackets";
687 case SpvOpReserveWritePipePackets:
688 return "ReserveWritePipePackets";
689 case SpvOpCommitReadPipe:
690 return "CommitReadPipe";
691 case SpvOpCommitWritePipe:
692 return "CommitWritePipe";
693 case SpvOpIsValidReserveId:
694 return "IsValidReserveId";
695 case SpvOpGetNumPipePackets:
696 return "GetNumPipePackets";
697 case SpvOpGetMaxPipePackets:
698 return "GetMaxPipePackets";
699 case SpvOpGroupReserveReadPipePackets:
700 return "GroupReserveReadPipePackets";
701 case SpvOpGroupReserveWritePipePackets:
702 return "GroupReserveWritePipePackets";
703 case SpvOpGroupCommitReadPipe:
704 return "GroupCommitReadPipe";
705 case SpvOpGroupCommitWritePipe:
706 return "GroupCommitWritePipe";
707 case SpvOpEnqueueMarker:
708 return "EnqueueMarker";
709 case SpvOpEnqueueKernel:
710 return "EnqueueKernel";
711 case SpvOpGetKernelNDrangeSubGroupCount:
712 return "GetKernelNDrangeSubGroupCount";
713 case SpvOpGetKernelNDrangeMaxSubGroupSize:
714 return "GetKernelNDrangeMaxSubGroupSize";
715 case SpvOpGetKernelWorkGroupSize:
716 return "GetKernelWorkGroupSize";
717 case SpvOpGetKernelPreferredWorkGroupSizeMultiple:
718 return "GetKernelPreferredWorkGroupSizeMultiple";
719 case SpvOpRetainEvent:
720 return "RetainEvent";
721 case SpvOpReleaseEvent:
722 return "ReleaseEvent";
723 case SpvOpCreateUserEvent:
724 return "CreateUserEvent";
725 case SpvOpIsValidEvent:
726 return "IsValidEvent";
727 case SpvOpSetUserEventStatus:
728 return "SetUserEventStatus";
729 case SpvOpCaptureEventProfilingInfo:
730 return "CaptureEventProfilingInfo";
731 case SpvOpGetDefaultQueue:
732 return "GetDefaultQueue";
733 case SpvOpBuildNDRange:
734 return "BuildNDRange";
735 case SpvOpImageSparseSampleImplicitLod:
736 return "ImageSparseSampleImplicitLod";
737 case SpvOpImageSparseSampleExplicitLod:
738 return "ImageSparseSampleExplicitLod";
739 case SpvOpImageSparseSampleDrefImplicitLod:
740 return "ImageSparseSampleDrefImplicitLod";
741 case SpvOpImageSparseSampleDrefExplicitLod:
742 return "ImageSparseSampleDrefExplicitLod";
743 case SpvOpImageSparseSampleProjImplicitLod:
744 return "ImageSparseSampleProjImplicitLod";
745 case SpvOpImageSparseSampleProjExplicitLod:
746 return "ImageSparseSampleProjExplicitLod";
747 case SpvOpImageSparseSampleProjDrefImplicitLod:
748 return "ImageSparseSampleProjDrefImplicitLod";
749 case SpvOpImageSparseSampleProjDrefExplicitLod:
750 return "ImageSparseSampleProjDrefExplicitLod";
751 case SpvOpImageSparseFetch:
752 return "ImageSparseFetch";
753 case SpvOpImageSparseGather:
754 return "ImageSparseGather";
755 case SpvOpImageSparseDrefGather:
756 return "ImageSparseDrefGather";
757 case SpvOpImageSparseTexelsResident:
758 return "ImageSparseTexelsResident";
759 case SpvOpNoLine:
760 return "NoLine";
761 case SpvOpAtomicFlagTestAndSet:
762 return "AtomicFlagTestAndSet";
763 case SpvOpAtomicFlagClear:
764 return "AtomicFlagClear";
765 case SpvOpImageSparseRead:
766 return "ImageSparseRead";
767 default:
768 ABORT("unsupported SPIR-V op");
769 }
770 }
771 #endif
772
773 void SPIRVCodeGenerator::writeOpCode(SpvOp_ opCode, int length, std::ostream& ou t) {
774 ASSERT(opCode != SpvOpUndef);
775 switch (opCode) {
776 case SpvOpReturn: // fall through
777 case SpvOpReturnValue: // fall through
778 case SpvOpBranch: // fall through
779 case SpvOpBranchConditional:
780 ASSERT(fCurrentBlock);
781 fCurrentBlock = 0;
782 break;
783 case SpvOpConstant: // fall through
784 case SpvOpConstantTrue: // fall through
785 case SpvOpConstantFalse: // fall through
786 case SpvOpConstantComposite: // fall through
787 case SpvOpTypeVoid: // fall through
788 case SpvOpTypeInt: // fall through
789 case SpvOpTypeFloat: // fall through
790 case SpvOpTypeBool: // fall through
791 case SpvOpTypeVector: // fall through
792 case SpvOpTypeMatrix: // fall through
793 case SpvOpTypeArray: // fall through
794 case SpvOpTypePointer: // fall through
795 case SpvOpTypeFunction: // fall through
796 case SpvOpTypeRuntimeArray: // fall through
797 case SpvOpTypeStruct: // fall through
798 case SpvOpTypeImage: // fall through
799 case SpvOpTypeSampledImage: // fall through
800 case SpvOpVariable: // fall through
801 case SpvOpFunction: // fall through
802 case SpvOpFunctionParameter: // fall through
803 case SpvOpFunctionEnd: // fall through
804 case SpvOpExecutionMode: // fall through
805 case SpvOpMemoryModel: // fall through
806 case SpvOpCapability: // fall through
807 case SpvOpExtInstImport: // fall through
808 case SpvOpEntryPoint: // fall through
809 case SpvOpSource: // fall through
810 case SpvOpSourceExtension: // fall through
811 case SpvOpName: // fall through
812 case SpvOpMemberName: // fall through
813 case SpvOpDecorate: // fall through
814 case SpvOpMemberDecorate:
815 break;
816 default:
817 ASSERT(fCurrentBlock);
818 }
819 #if SPIRV_DEBUG
820 out << std::endl << opcode_text(opCode) << " ";
821 #else
822 this->writeWord((length << 16) | opCode, out);
823 #endif
824 }
825
826 void SPIRVCodeGenerator::writeLabel(SpvId label, std::ostream& out) {
827 fCurrentBlock = label;
828 this->writeInstruction(SpvOpLabel, label, out);
829 }
830
831 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, std::ostream& out) {
832 this->writeOpCode(opCode, 1, out);
833 }
834
835 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, std::ost ream& out) {
836 this->writeOpCode(opCode, 2, out);
837 this->writeWord(word1, out);
838 }
839
840 void SPIRVCodeGenerator::writeString(const char* string, std::ostream& out) {
841 size_t length = strlen(string);
842 out << string;
843 switch (length % 4) {
844 case 1:
845 out << (char) 0;
846 // fall through
847 case 2:
848 out << (char) 0;
849 // fall through
850 case 3:
851 out << (char) 0;
852 break;
853 default:
854 this->writeWord(0, out);
855 }
856 }
857
858 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, const char* string, std ::ostream& out) {
859 int32_t length = (int32_t) strlen(string);
860 this->writeOpCode(opCode, 1 + (length + 4) / 4, out);
861 this->writeString(string, out);
862 }
863
864
865 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, const ch ar* string,
866 std::ostream& out) {
867 int32_t length = (int32_t) strlen(string);
868 this->writeOpCode(opCode, 2 + (length + 4) / 4, out);
869 this->writeWord(word1, out);
870 this->writeString(string, out);
871 }
872
873 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
874 const char* string, std::ostream& out) {
875 int32_t length = (int32_t) strlen(string);
876 this->writeOpCode(opCode, 3 + (length + 4) / 4, out);
877 this->writeWord(word1, out);
878 this->writeWord(word2, out);
879 this->writeString(string, out);
880 }
881
882 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
883 std::ostream& out) {
884 this->writeOpCode(opCode, 3, out);
885 this->writeWord(word1, out);
886 this->writeWord(word2, out);
887 }
888
889 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
890 int32_t word3, std::ostream& out) {
891 this->writeOpCode(opCode, 4, out);
892 this->writeWord(word1, out);
893 this->writeWord(word2, out);
894 this->writeWord(word3, out);
895 }
896
897 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
898 int32_t word3, int32_t word4, std::ost ream& out) {
899 this->writeOpCode(opCode, 5, out);
900 this->writeWord(word1, out);
901 this->writeWord(word2, out);
902 this->writeWord(word3, out);
903 this->writeWord(word4, out);
904 }
905
906 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
907 int32_t word3, int32_t word4, int32_t word5,
908 std::ostream& out) {
909 this->writeOpCode(opCode, 6, out);
910 this->writeWord(word1, out);
911 this->writeWord(word2, out);
912 this->writeWord(word3, out);
913 this->writeWord(word4, out);
914 this->writeWord(word5, out);
915 }
916
917 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
918 int32_t word3, int32_t word4, int32_t word5,
919 int32_t word6, std::ostream& out) {
920 this->writeOpCode(opCode, 7, out);
921 this->writeWord(word1, out);
922 this->writeWord(word2, out);
923 this->writeWord(word3, out);
924 this->writeWord(word4, out);
925 this->writeWord(word5, out);
926 this->writeWord(word6, out);
927 }
928
929 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
930 int32_t word3, int32_t word4, int32_t word5,
931 int32_t word6, int32_t word7, std::ost ream& out) {
932 this->writeOpCode(opCode, 8, out);
933 this->writeWord(word1, out);
934 this->writeWord(word2, out);
935 this->writeWord(word3, out);
936 this->writeWord(word4, out);
937 this->writeWord(word5, out);
938 this->writeWord(word6, out);
939 this->writeWord(word7, out);
940 }
941
942 void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
943 int32_t word3, int32_t word4, int32_t word5,
944 int32_t word6, int32_t word7, int32_t word8,
945 std::ostream& out) {
946 this->writeOpCode(opCode, 9, out);
947 this->writeWord(word1, out);
948 this->writeWord(word2, out);
949 this->writeWord(word3, out);
950 this->writeWord(word4, out);
951 this->writeWord(word5, out);
952 this->writeWord(word6, out);
953 this->writeWord(word7, out);
954 this->writeWord(word8, out);
955 }
956
957 void SPIRVCodeGenerator::writeCapabilities(std::ostream& out) {
958 for (uint64_t i = 0, bit = 1; i <= kLast_Capability; i++, bit <<= 1) {
959 if (fCapabilities & bit) {
960 this->writeInstruction(SpvOpCapability, (SpvId) i, out);
961 }
962 }
963 }
964
965 SpvId SPIRVCodeGenerator::nextId() {
966 return fIdCount++;
967 }
968
969 void SPIRVCodeGenerator::writeStruct(const Type& type, SpvId resultId) {
970 this->writeInstruction(SpvOpName, resultId, type.name().c_str(), fNameBuffer );
971 // go ahead and write all of the field types, so we don't inadvertently writ e them while we're
972 // in the middle of writing the struct instruction
973 std::vector<SpvId> types;
974 for (const auto& f : type.fields()) {
975 types.push_back(this->getType(*f.fType));
976 }
977 this->writeOpCode(SpvOpTypeStruct, 2 + (int32_t) types.size(), fConstantBuff er);
978 this->writeWord(resultId, fConstantBuffer);
979 for (SpvId id : types) {
980 this->writeWord(id, fConstantBuffer);
981 }
982 size_t offset = 0;
983 for (int32_t i = 0; i < (int32_t) type.fields().size(); i++) {
984 size_t size = type.fields()[i].fType->size();
985 size_t alignment = type.fields()[i].fType->alignment();
986 size_t mod = offset % alignment;
987 if (mod != 0) {
988 offset += alignment - mod;
989 }
990 this->writeInstruction(SpvOpMemberName, resultId, i, type.fields()[i].fN ame.c_str(),
991 fNameBuffer);
992 this->writeLayout(type.fields()[i].fModifiers.fLayout, resultId, i);
993 if (type.fields()[i].fModifiers.fLayout.fBuiltin < 0) {
994 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i, Spv DecorationOffset,
995 (SpvId) offset, fDecorationBuffer);
996 }
997 if (type.fields()[i].fType->kind() == Type::kMatrix_Kind) {
998 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorati onColMajor,
999 fDecorationBuffer);
1000 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorati onMatrixStride,
1001 (SpvId) type.fields()[i].fType->stride(), fDe corationBuffer);
1002 }
1003 offset += size;
1004 Type::Kind kind = type.fields()[i].fType->kind();
1005 if ((kind == Type::kArray_Kind || kind == Type::kStruct_Kind) && offset % alignment != 0) {
1006 offset += alignment - offset % alignment;
1007 }
1008 ASSERT(offset % alignment == 0);
1009 }
1010 }
1011
1012 SpvId SPIRVCodeGenerator::getType(const Type& type) {
1013 auto entry = fTypeMap.find(type.name());
1014 if (entry == fTypeMap.end()) {
1015 SpvId result = this->nextId();
1016 switch (type.kind()) {
1017 case Type::kScalar_Kind:
1018 if (type == *kBool_Type) {
1019 this->writeInstruction(SpvOpTypeBool, result, fConstantBuffe r);
1020 } else if (type == *kInt_Type) {
1021 this->writeInstruction(SpvOpTypeInt, result, 32, 1, fConstan tBuffer);
1022 } else if (type == *kUInt_Type) {
1023 this->writeInstruction(SpvOpTypeInt, result, 32, 0, fConstan tBuffer);
1024 } else if (type == *kFloat_Type) {
1025 this->writeInstruction(SpvOpTypeFloat, result, 32, fConstant Buffer);
1026 } else if (type == *kDouble_Type) {
1027 this->writeInstruction(SpvOpTypeFloat, result, 64, fConstant Buffer);
1028 } else {
1029 ASSERT(false);
1030 }
1031 break;
1032 case Type::kVector_Kind:
1033 this->writeInstruction(SpvOpTypeVector, result,
1034 this->getType(*type.componentType()),
1035 type.columns(), fConstantBuffer);
1036 break;
1037 case Type::kMatrix_Kind:
1038 this->writeInstruction(SpvOpTypeMatrix, result, this->getType(*i ndex_type(type)),
1039 type.columns(), fConstantBuffer);
1040 break;
1041 case Type::kStruct_Kind:
1042 this->writeStruct(type, result);
1043 break;
1044 case Type::kArray_Kind: {
1045 if (type.columns() > 0) {
1046 IntLiteral count(Position(), type.columns());
1047 this->writeInstruction(SpvOpTypeArray, result,
1048 this->getType(*type.componentType()),
1049 this->writeIntLiteral(count), fConsta ntBuffer);
1050 this->writeInstruction(SpvOpDecorate, result, SpvDecorationA rrayStride,
1051 (int32_t) type.stride(), fDecorationB uffer);
1052 } else {
1053 ABORT("runtime-sized arrays are not yet supported");
1054 this->writeInstruction(SpvOpTypeRuntimeArray, result,
1055 this->getType(*type.componentType()), fConstantBuffer);
1056 }
1057 break;
1058 }
1059 case Type::kSampler_Kind: {
1060 SpvId image = this->nextId();
1061 this->writeInstruction(SpvOpTypeImage, image, this->getType(*kFl oat_Type),
1062 type.dimensions(), type.isDepth(), type.i sArrayed(),
1063 type.isMultisampled(), type.isSampled(),
1064 SpvImageFormatUnknown, fConstantBuffer);
1065 this->writeInstruction(SpvOpTypeSampledImage, result, image, fCo nstantBuffer);
1066 break;
1067 }
1068 default:
1069 if (type == *kVoid_Type) {
1070 this->writeInstruction(SpvOpTypeVoid, result, fConstantBuffe r);
1071 } else {
1072 ABORT("invalid type: %s", type.description().c_str());
1073 }
1074 }
1075 fTypeMap[type.name()] = result;
1076 return result;
1077 }
1078 return entry->second;
1079 }
1080
1081 SpvId SPIRVCodeGenerator::getFunctionType(std::shared_ptr<FunctionDeclaration> f unction) {
1082 std::string key = function->fReturnType->description() + "(";
1083 std::string separator = "";
1084 for (size_t i = 0; i < function->fParameters.size(); i++) {
1085 key += separator;
1086 separator = ", ";
1087 key += function->fParameters[i]->fType->description();
1088 }
1089 key += ")";
1090 auto entry = fTypeMap.find(key);
1091 if (entry == fTypeMap.end()) {
1092 SpvId result = this->nextId();
1093 int32_t length = 3 + (int32_t) function->fParameters.size();
1094 SpvId returnType = this->getType(*function->fReturnType);
1095 std::vector<SpvId> parameterTypes;
1096 for (size_t i = 0; i < function->fParameters.size(); i++) {
1097 // glslang seems to treat all function arguments as pointers whether they need to be or
1098 // not. I was initially puzzled by this until I ran bizarre failure s with certain
1099 // patterns of function calls and control constructs, as exemplified by this minimal
1100 // failure case:
1101 //
1102 // void sphere(float x) {
1103 // }
1104 //
1105 // void map() {
1106 // sphere(1.0);
1107 // }
1108 //
1109 // void main() {
1110 // for (int i = 0; i < 1; i++) {
1111 // map();
1112 // }
1113 // }
1114 //
1115 // As of this writing, compiling this in the "obvious" way (with sph ere taking a float)
1116 // crashes. Making it take a float* and storing the argument in a te mporary variable,
1117 // as glslang does, fixes it. It's entirely possible I simply missed whichever part of
1118 // the spec makes this make sense.
1119 // if (is_out(function->fParameters[i])) {
1120 parameterTypes.push_back(this->getPointerType(function->fParamet ers[i]->fType,
1121 SpvStorageClassFun ction));
1122 // } else {
1123 // parameterTypes.push_back(this->getType(*function->fParameters[ i]->fType));
1124 // }
1125 }
1126 this->writeOpCode(SpvOpTypeFunction, length, fConstantBuffer);
1127 this->writeWord(result, fConstantBuffer);
1128 this->writeWord(returnType, fConstantBuffer);
1129 for (SpvId id : parameterTypes) {
1130 this->writeWord(id, fConstantBuffer);
1131 }
1132 fTypeMap[key] = result;
1133 return result;
1134 }
1135 return entry->second;
1136 }
1137
1138 SpvId SPIRVCodeGenerator::getPointerType(std::shared_ptr<Type> type,
1139 SpvStorageClass_ storageClass) {
1140 std::string key = type->description() + "*" + to_string(storageClass);
1141 auto entry = fTypeMap.find(key);
1142 if (entry == fTypeMap.end()) {
1143 SpvId result = this->nextId();
1144 this->writeInstruction(SpvOpTypePointer, result, storageClass,
1145 this->getType(*type), fConstantBuffer);
1146 fTypeMap[key] = result;
1147 return result;
1148 }
1149 return entry->second;
1150 }
1151
1152 SpvId SPIRVCodeGenerator::writeExpression(Expression& expr, std::ostream& out) {
1153 switch (expr.fKind) {
1154 case Expression::kBinary_Kind:
1155 return this->writeBinaryExpression((BinaryExpression&) expr, out);
1156 case Expression::kBoolLiteral_Kind:
1157 return this->writeBoolLiteral((BoolLiteral&) expr);
1158 case Expression::kConstructor_Kind:
1159 return this->writeConstructor((Constructor&) expr, out);
1160 case Expression::kIntLiteral_Kind:
1161 return this->writeIntLiteral((IntLiteral&) expr);
1162 case Expression::kFieldAccess_Kind:
1163 return this->writeFieldAccess(((FieldAccess&) expr), out);
1164 case Expression::kFloatLiteral_Kind:
1165 return this->writeFloatLiteral(((FloatLiteral&) expr));
1166 case Expression::kFunctionCall_Kind:
1167 return this->writeFunctionCall((FunctionCall&) expr, out);
1168 case Expression::kPrefix_Kind:
1169 return this->writePrefixExpression((PrefixExpression&) expr, out);
1170 case Expression::kPostfix_Kind:
1171 return this->writePostfixExpression((PostfixExpression&) expr, out);
1172 case Expression::kSwizzle_Kind:
1173 return this->writeSwizzle((Swizzle&) expr, out);
1174 case Expression::kVariableReference_Kind:
1175 return this->writeVariableReference((VariableReference&) expr, out);
1176 case Expression::kTernary_Kind:
1177 return this->writeTernaryExpression((TernaryExpression&) expr, out);
1178 case Expression::kIndex_Kind:
1179 return this->writeIndexExpression((IndexExpression&) expr, out);
1180 default:
1181 ABORT("unsupported expression: %s", expr.description().c_str());
1182 }
1183 return -1;
1184 }
1185
1186 SpvId SPIRVCodeGenerator::writeIntrinsicCall(FunctionCall& c, std::ostream& out) {
1187 auto intrinsic = fIntrinsicMap.find(c.fFunction->fName);
1188 ASSERT(intrinsic != fIntrinsicMap.end());
1189 std::shared_ptr<Type> type = c.fArguments[0]->fType;
1190 int32_t intrinsicId;
1191 if (std::get<0>(intrinsic->second) == kSpecial_IntrinsicKind || is_float(*ty pe)) {
1192 intrinsicId = std::get<1>(intrinsic->second);
1193 } else if (is_signed(*type)) {
1194 intrinsicId = std::get<2>(intrinsic->second);
1195 } else if (is_unsigned(*type)) {
1196 intrinsicId = std::get<3>(intrinsic->second);
1197 } else if (is_bool(*type)) {
1198 intrinsicId = std::get<4>(intrinsic->second);
1199 } else {
1200 ABORT("invalid call %s, cannot operate on '%s'", c.description().c_str() ,
1201 type->description().c_str());
1202 }
1203 switch (std::get<0>(intrinsic->second)) {
1204 case kGLSL_STD_450_IntrinsicKind: {
1205 SpvId result = this->nextId();
1206 std::vector<SpvId> arguments;
1207 for (size_t i = 0; i < c.fArguments.size(); i++) {
1208 arguments.push_back(this->writeExpression(*c.fArguments[i], out) );
1209 }
1210 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) arguments.size(), out) ;
1211 this->writeWord(this->getType(*c.fType), out);
1212 this->writeWord(result, out);
1213 this->writeWord(fGLSLExtendedInstructions, out);
1214 this->writeWord(intrinsicId, out);
1215 for (SpvId id : arguments) {
1216 this->writeWord(id, out);
1217 }
1218 return result;
1219 }
1220 case kSPIRV_IntrinsicKind: {
1221 SpvId result = this->nextId();
1222 std::vector<SpvId> arguments;
1223 for (size_t i = 0; i < c.fArguments.size(); i++) {
1224 arguments.push_back(this->writeExpression(*c.fArguments[i], out) );
1225 }
1226 this->writeOpCode((SpvOp_) intrinsicId, 3 + (int32_t) arguments.size (), out);
1227 this->writeWord(this->getType(*c.fType), out);
1228 this->writeWord(result, out);
1229 for (SpvId id : arguments) {
1230 this->writeWord(id, out);
1231 }
1232 return result;
1233 }
1234 case kSpecial_IntrinsicKind:
1235 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId , out);
1236 default:
1237 ABORT("unsupported intrinsic kind");
1238 }
1239 }
1240
1241 SpvId SPIRVCodeGenerator::writeSpecialIntrinsic(FunctionCall& c, SpecialIntrinsi c kind,
1242 std::ostream& out) {
1243 SpvId result = this->nextId();
1244 switch (kind) {
1245 case kAtan_SpecialIntrinsic: {
1246 std::vector<SpvId> arguments;
1247 for (size_t i = 0; i < c.fArguments.size(); i++) {
1248 arguments.push_back(this->writeExpression(*c.fArguments[i], out) );
1249 }
1250 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) arguments.size(), out) ;
1251 this->writeWord(this->getType(*c.fType), out);
1252 this->writeWord(result, out);
1253 this->writeWord(fGLSLExtendedInstructions, out);
1254 this->writeWord(arguments.size() == 2 ? GLSLstd450Atan2 : GLSLstd450 Atan, out);
1255 for (SpvId id : arguments) {
1256 this->writeWord(id, out);
1257 }
1258 return result;
1259 }
1260 case kTexture_SpecialIntrinsic: {
1261 SpvId type = this->getType(*c.fType);
1262 SpvId sampler = this->writeExpression(*c.fArguments[0], out);
1263 SpvId uv = this->writeExpression(*c.fArguments[1], out);
1264 if (c.fArguments.size() == 3) {
1265 this->writeInstruction(SpvOpImageSampleImplicitLod, type, result , sampler, uv,
1266 SpvImageOperandsBiasMask,
1267 this->writeExpression(*c.fArguments[2], o ut),
1268 out);
1269 } else {
1270 ASSERT(c.fArguments.size() == 2);
1271 this->writeInstruction(SpvOpImageSampleImplicitLod, type, result , sampler, uv, out);
1272 }
1273 break;
1274 }
1275 case kTextureProj_SpecialIntrinsic: {
1276 SpvId type = this->getType(*c.fType);
1277 SpvId sampler = this->writeExpression(*c.fArguments[0], out);
1278 SpvId uv = this->writeExpression(*c.fArguments[1], out);
1279 if (c.fArguments.size() == 3) {
1280 this->writeInstruction(SpvOpImageSampleProjImplicitLod, type, re sult, sampler, uv,
1281 SpvImageOperandsBiasMask,
1282 this->writeExpression(*c.fArguments[2], o ut),
1283 out);
1284 } else {
1285 ASSERT(c.fArguments.size() == 2);
1286 this->writeInstruction(SpvOpImageSampleProjImplicitLod, type, re sult, sampler, uv,
1287 out);
1288 }
1289 break;
1290 }
1291 case kTexture2D_SpecialIntrinsic: {
1292 SpvId img = this->writeExpression(*c.fArguments[0], out);
1293 SpvId coords = this->writeExpression(*c.fArguments[1], out);
1294 this->writeInstruction(SpvOpImageSampleImplicitLod,
1295 this->getType(*c.fType),
1296 result,
1297 img,
1298 coords,
1299 out);
1300 break;
1301 }
1302 }
1303 return result;
1304 }
1305
1306 SpvId SPIRVCodeGenerator::writeFunctionCall(FunctionCall& c, std::ostream& out) {
1307 const auto& entry = fFunctionMap.find(c.fFunction);
1308 if (entry == fFunctionMap.end()) {
1309 return this->writeIntrinsicCall(c, out);
1310 }
1311 // stores (variable, type, lvalue) pairs to extract and save after the funct ion call is complete
1312 std::vector<std::tuple<SpvId, SpvId, std::unique_ptr<LValue>>> lvalues;
1313 std::vector<SpvId> arguments;
1314 for (size_t i = 0; i < c.fArguments.size(); i++) {
1315 // id of temporary variable that we will use to hold this argument, or 0 if it is being
1316 // passed directly
1317 SpvId tmpVar;
1318 // if we need a temporary var to store this argument, this is the value to store in the var
1319 SpvId tmpValueId;
1320 if (is_out(c.fFunction->fParameters[i])) {
1321 std::unique_ptr<LValue> lv = this->getLValue(*c.fArguments[i], out);
1322 SpvId ptr = lv->getPointer();
1323 if (ptr) {
1324 arguments.push_back(ptr);
1325 continue;
1326 } else {
1327 // lvalue cannot simply be read and written via a pointer (e.g. a swizzle). Need to
1328 // copy it into a temp, call the function, read the value out of the temp, and then
1329 // update the lvalue.
1330 tmpValueId = lv->load(out);
1331 tmpVar = this->nextId();
1332 lvalues.push_back(std::make_tuple(tmpVar, this->getType(*c.fArgu ments[i]->fType),
1333 std::move(lv)));
1334 }
1335 } else {
1336 // see getFunctionType for an explanation of why we're always using pointer parameters
1337 tmpValueId = this->writeExpression(*c.fArguments[i], out);
1338 tmpVar = this->nextId();
1339 }
1340 this->writeInstruction(SpvOpVariable,
1341 this->getPointerType(c.fArguments[i]->fType,
1342 SpvStorageClassFunction),
1343 tmpVar,
1344 SpvStorageClassFunction,
1345 out);
1346 this->writeInstruction(SpvOpStore, tmpVar, tmpValueId, out);
1347 arguments.push_back(tmpVar);
1348 }
1349 SpvId result = this->nextId();
1350 this->writeOpCode(SpvOpFunctionCall, 4 + (int32_t) c.fArguments.size(), out) ;
1351 this->writeWord(this->getType(*c.fType), out);
1352 this->writeWord(result, out);
1353 this->writeWord(entry->second, out);
1354 for (SpvId id : arguments) {
1355 this->writeWord(id, out);
1356 }
1357 // now that the call is complete, we may need to update some lvalues with th e new values of out
1358 // arguments
1359 for (const auto& tuple : lvalues) {
1360 SpvId load = this->nextId();
1361 this->writeInstruction(SpvOpLoad, std::get<1>(tuple), load, std::get<0>( tuple), out);
1362 std::get<2>(tuple)->store(load, out);
1363 }
1364 return result;
1365 }
1366
1367 SpvId SPIRVCodeGenerator::writeConstantVector(Constructor& c) {
1368 ASSERT(c.fType->kind() == Type::kVector_Kind && c.isConstant());
1369 SpvId result = this->nextId();
1370 std::vector<SpvId> arguments;
1371 for (size_t i = 0; i < c.fArguments.size(); i++) {
1372 arguments.push_back(this->writeExpression(*c.fArguments[i], fConstantBuf fer));
1373 }
1374 SpvId type = this->getType(*c.fType);
1375 if (c.fArguments.size() == 1) {
1376 // with a single argument, a vector will have all of its entries equal t o the argument
1377 this->writeOpCode(SpvOpConstantComposite, 3 + c.fType->columns(), fConst antBuffer);
1378 this->writeWord(type, fConstantBuffer);
1379 this->writeWord(result, fConstantBuffer);
1380 for (int i = 0; i < c.fType->columns(); i++) {
1381 this->writeWord(arguments[0], fConstantBuffer);
1382 }
1383 } else {
1384 this->writeOpCode(SpvOpConstantComposite, 3 + (int32_t) c.fArguments.siz e(),
1385 fConstantBuffer);
1386 this->writeWord(type, fConstantBuffer);
1387 this->writeWord(result, fConstantBuffer);
1388 for (SpvId id : arguments) {
1389 this->writeWord(id, fConstantBuffer);
1390 }
1391 }
1392 return result;
1393 }
1394
1395 SpvId SPIRVCodeGenerator::writeFloatConstructor(Constructor& c, std::ostream& ou t) {
1396 ASSERT(c.fType == kFloat_Type);
1397 ASSERT(c.fArguments.size() == 1);
1398 ASSERT(c.fArguments[0]->fType->isNumber());
1399 SpvId result = this->nextId();
1400 SpvId parameter = this->writeExpression(*c.fArguments[0], out);
1401 if (c.fArguments[0]->fType == kInt_Type) {
1402 this->writeInstruction(SpvOpConvertSToF, this->getType(*c.fType), result , parameter,
1403 out);
1404 } else if (c.fArguments[0]->fType == kUInt_Type) {
1405 this->writeInstruction(SpvOpConvertUToF, this->getType(*c.fType), result , parameter,
1406 out);
1407 } else if (c.fArguments[0]->fType == kFloat_Type) {
1408 return parameter;
1409 }
1410 return result;
1411 }
1412
1413 SpvId SPIRVCodeGenerator::writeIntConstructor(Constructor& c, std::ostream& out) {
1414 ASSERT(c.fType == kInt_Type);
1415 ASSERT(c.fArguments.size() == 1);
1416 ASSERT(c.fArguments[0]->fType->isNumber());
1417 SpvId result = this->nextId();
1418 SpvId parameter = this->writeExpression(*c.fArguments[0], out);
1419 if (c.fArguments[0]->fType == kFloat_Type) {
1420 this->writeInstruction(SpvOpConvertFToS, this->getType(*c.fType), result , parameter,
1421 out);
1422 } else if (c.fArguments[0]->fType == kUInt_Type) {
1423 this->writeInstruction(SpvOpSatConvertUToS, this->getType(*c.fType), res ult, parameter,
1424 out);
1425 } else if (c.fArguments[0]->fType == kInt_Type) {
1426 return parameter;
1427 }
1428 return result;
1429 }
1430
1431 SpvId SPIRVCodeGenerator::writeMatrixConstructor(Constructor& c, std::ostream& o ut) {
1432 ASSERT(c.fType->kind() == Type::kMatrix_Kind);
1433 // go ahead and write the arguments so we don't try to write new instruction s in the middle of
1434 // an instruction
1435 std::vector<SpvId> arguments;
1436 for (size_t i = 0; i < c.fArguments.size(); i++) {
1437 arguments.push_back(this->writeExpression(*c.fArguments[i], out));
1438 }
1439 SpvId result = this->nextId();
1440 int rows = c.fType->rows();
1441 int columns = c.fType->columns();
1442 // FIXME this won't work to create a matrix from another matrix
1443 if (arguments.size() == 1) {
1444 // with a single argument, a matrix will have all of its diagonal entrie s equal to the
1445 // argument and its other values equal to zero
1446 // FIXME this won't work for int matrices
1447 FloatLiteral zero(Position(), 0);
1448 SpvId zeroId = this->writeFloatLiteral(zero);
1449 std::vector<SpvId> columnIds;
1450 for (int column = 0; column < columns; column++) {
1451 this->writeOpCode(SpvOpCompositeConstruct, 3 + c.fType->rows(),
1452 out);
1453 this->writeWord(this->getType(*c.fType->componentType()->toCompound( rows, 1)), out);
1454 SpvId columnId = this->nextId();
1455 this->writeWord(columnId, out);
1456 columnIds.push_back(columnId);
1457 for (int row = 0; row < c.fType->columns(); row++) {
1458 this->writeWord(row == column ? arguments[0] : zeroId, out);
1459 }
1460 }
1461 this->writeOpCode(SpvOpCompositeConstruct, 3 + columns,
1462 out);
1463 this->writeWord(this->getType(*c.fType), out);
1464 this->writeWord(result, out);
1465 for (SpvId id : columnIds) {
1466 this->writeWord(id, out);
1467 }
1468 } else {
1469 std::vector<SpvId> columnIds;
1470 int currentCount = 0;
1471 for (size_t i = 0; i < arguments.size(); i++) {
1472 if (c.fArguments[i]->fType->kind() == Type::kVector_Kind) {
1473 ASSERT(currentCount == 0);
1474 columnIds.push_back(arguments[i]);
1475 currentCount = 0;
1476 } else {
1477 ASSERT(c.fArguments[i]->fType->kind() == Type::kScalar_Kind);
1478 if (currentCount == 0) {
1479 this->writeOpCode(SpvOpCompositeConstruct, 3 + c.fType->rows (), out);
1480 this->writeWord(this->getType(*c.fType->componentType()->toC ompound(rows, 1)),
1481 out);
1482 SpvId id = this->nextId();
1483 this->writeWord(id, out);
1484 columnIds.push_back(id);
1485 }
1486 this->writeWord(arguments[i], out);
1487 currentCount = (currentCount + 1) % rows;
1488 }
1489 }
1490 ASSERT(columnIds.size() == (size_t) columns);
1491 this->writeOpCode(SpvOpCompositeConstruct, 3 + columns, out);
1492 this->writeWord(this->getType(*c.fType), out);
1493 this->writeWord(result, out);
1494 for (SpvId id : columnIds) {
1495 this->writeWord(id, out);
1496 }
1497 }
1498 return result;
1499 }
1500
1501 SpvId SPIRVCodeGenerator::writeVectorConstructor(Constructor& c, std::ostream& o ut) {
1502 ASSERT(c.fType->kind() == Type::kVector_Kind);
1503 if (c.isConstant()) {
1504 return this->writeConstantVector(c);
1505 }
1506 // go ahead and write the arguments so we don't try to write new instruction s in the middle of
1507 // an instruction
1508 std::vector<SpvId> arguments;
1509 for (size_t i = 0; i < c.fArguments.size(); i++) {
1510 arguments.push_back(this->writeExpression(*c.fArguments[i], out));
1511 }
1512 SpvId result = this->nextId();
1513 if (arguments.size() == 1 && c.fArguments[0]->fType->kind() == Type::kScalar _Kind) {
1514 this->writeOpCode(SpvOpCompositeConstruct, 3 + c.fType->columns(), out);
1515 this->writeWord(this->getType(*c.fType), out);
1516 this->writeWord(result, out);
1517 for (int i = 0; i < c.fType->columns(); i++) {
1518 this->writeWord(arguments[0], out);
1519 }
1520 } else {
1521 this->writeOpCode(SpvOpCompositeConstruct, 3 + (int32_t) c.fArguments.si ze(), out);
1522 this->writeWord(this->getType(*c.fType), out);
1523 this->writeWord(result, out);
1524 for (SpvId id : arguments) {
1525 this->writeWord(id, out);
1526 }
1527 }
1528 return result;
1529 }
1530
1531 SpvId SPIRVCodeGenerator::writeConstructor(Constructor& c, std::ostream& out) {
1532 if (c.fType == kFloat_Type) {
1533 return this->writeFloatConstructor(c, out);
1534 } else if (c.fType == kInt_Type) {
1535 return this->writeIntConstructor(c, out);
1536 }
1537 switch (c.fType->kind()) {
1538 case Type::kVector_Kind:
1539 return this->writeVectorConstructor(c, out);
1540 case Type::kMatrix_Kind:
1541 return this->writeMatrixConstructor(c, out);
1542 default:
1543 ABORT("unsupported constructor: %s", c.description().c_str());
1544 }
1545 }
1546
1547 SpvStorageClass_ get_storage_class(const Modifiers& modifiers) {
1548 if (modifiers.fFlags & Modifiers::kIn_Flag) {
1549 return SpvStorageClassInput;
1550 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
1551 return SpvStorageClassOutput;
1552 } else if (modifiers.fFlags & Modifiers::kUniform_Flag) {
1553 return SpvStorageClassUniform;
1554 } else {
1555 return SpvStorageClassFunction;
1556 }
1557 }
1558
1559 SpvStorageClass_ get_storage_class(Expression& expr) {
1560 switch (expr.fKind) {
1561 case Expression::kVariableReference_Kind:
1562 return get_storage_class(((VariableReference&) expr).fVariable->fMod ifiers);
1563 case Expression::kFieldAccess_Kind:
1564 return get_storage_class(*((FieldAccess&) expr).fBase);
1565 case Expression::kIndex_Kind:
1566 return get_storage_class(*((IndexExpression&) expr).fBase);
1567 default:
1568 return SpvStorageClassFunction;
1569 }
1570 }
1571
1572 std::vector<SpvId> SPIRVCodeGenerator::getAccessChain(Expression& expr, std::ost ream& out) {
1573 std::vector<SpvId> chain;
1574 switch (expr.fKind) {
1575 case Expression::kIndex_Kind: {
1576 IndexExpression& indexExpr = (IndexExpression&) expr;
1577 chain = this->getAccessChain(*indexExpr.fBase, out);
1578 chain.push_back(this->writeExpression(*indexExpr.fIndex, out));
1579 break;
1580 }
1581 case Expression::kFieldAccess_Kind: {
1582 FieldAccess& fieldExpr = (FieldAccess&) expr;
1583 chain = this->getAccessChain(*fieldExpr.fBase, out);
1584 IntLiteral index(Position(), fieldExpr.fFieldIndex);
1585 chain.push_back(this->writeIntLiteral(index));
1586 break;
1587 }
1588 default:
1589 chain.push_back(this->getLValue(expr, out)->getPointer());
1590 }
1591 return chain;
1592 }
1593
1594 class PointerLValue : public SPIRVCodeGenerator::LValue {
1595 public:
1596 PointerLValue(SPIRVCodeGenerator& gen, SpvId pointer, SpvId type)
1597 : fGen(gen)
1598 , fPointer(pointer)
1599 , fType(type) {}
1600
1601 virtual SpvId getPointer() override {
1602 return fPointer;
1603 }
1604
1605 virtual SpvId load(std::ostream& out) override {
1606 SpvId result = fGen.nextId();
1607 fGen.writeInstruction(SpvOpLoad, fType, result, fPointer, out);
1608 return result;
1609 }
1610
1611 virtual void store(SpvId value, std::ostream& out) override {
1612 fGen.writeInstruction(SpvOpStore, fPointer, value, out);
1613 }
1614
1615 private:
1616 SPIRVCodeGenerator& fGen;
1617 const SpvId fPointer;
1618 const SpvId fType;
1619 };
1620
1621 class SwizzleLValue : public SPIRVCodeGenerator::LValue {
1622 public:
1623 SwizzleLValue(SPIRVCodeGenerator& gen, SpvId vecPointer, const std::vector<i nt>& components,
1624 const Type& baseType, const Type& swizzleType)
1625 : fGen(gen)
1626 , fVecPointer(vecPointer)
1627 , fComponents(components)
1628 , fBaseType(baseType)
1629 , fSwizzleType(swizzleType) {}
1630
1631 virtual SpvId getPointer() override {
1632 return 0;
1633 }
1634
1635 virtual SpvId load(std::ostream& out) override {
1636 SpvId base = fGen.nextId();
1637 fGen.writeInstruction(SpvOpLoad, fGen.getType(fBaseType), base, fVecPoin ter, out);
1638 SpvId result = fGen.nextId();
1639 fGen.writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) fComponents.size(), o ut);
1640 fGen.writeWord(fGen.getType(fSwizzleType), out);
1641 fGen.writeWord(result, out);
1642 fGen.writeWord(base, out);
1643 fGen.writeWord(base, out);
1644 for (int component : fComponents) {
1645 fGen.writeWord(component, out);
1646 }
1647 return result;
1648 }
1649
1650 virtual void store(SpvId value, std::ostream& out) override {
1651 // use OpVectorShuffle to mix and match the vector components. We effect ively create
1652 // a virtual vector out of the concatenation of the left and right vecto rs, and then
1653 // select components from this virtual vector to make the result vector. For
1654 // instance, given:
1655 // vec3 L = ...;
1656 // vec3 R = ...;
1657 // L.xz = R.xy;
1658 // we end up with the virtual vector (L.x, L.y, L.z, R.x, R.y, R.z). The n we want
1659 // our result vector to look like (R.x, L.y, R.y), so we need to select indices
1660 // (3, 1, 4).
1661 SpvId base = fGen.nextId();
1662 fGen.writeInstruction(SpvOpLoad, fGen.getType(fBaseType), base, fVecPoin ter, out);
1663 SpvId shuffle = fGen.nextId();
1664 fGen.writeOpCode(SpvOpVectorShuffle, 5 + fBaseType.columns(), out);
1665 fGen.writeWord(fGen.getType(fBaseType), out);
1666 fGen.writeWord(shuffle, out);
1667 fGen.writeWord(base, out);
1668 fGen.writeWord(value, out);
1669 for (int i = 0; i < fBaseType.columns(); i++) {
1670 // current offset into the virtual vector, defaults to pulling the u nmodified
1671 // value from the left side
1672 int offset = i;
1673 // check to see if we are writing this component
1674 for (size_t j = 0; j < fComponents.size(); j++) {
1675 if (fComponents[j] == i) {
1676 // we're writing to this component, so adjust the offset to pull from
1677 // the correct component of the right side instead of preser ving the
1678 // value from the left
1679 offset = (int) (j + fBaseType.columns());
1680 break;
1681 }
1682 }
1683 fGen.writeWord(offset, out);
1684 }
1685 fGen.writeInstruction(SpvOpStore, fVecPointer, shuffle, out);
1686 }
1687
1688 private:
1689 SPIRVCodeGenerator& fGen;
1690 const SpvId fVecPointer;
1691 const std::vector<int>& fComponents;
1692 const Type& fBaseType;
1693 const Type& fSwizzleType;
1694 };
1695
1696 std::unique_ptr<SPIRVCodeGenerator::LValue> SPIRVCodeGenerator::getLValue(Expres sion& expr,
1697 std::o stream& out) {
1698 switch (expr.fKind) {
1699 case Expression::kVariableReference_Kind: {
1700 std::shared_ptr<Variable> var = ((VariableReference&) expr).fVariabl e;
1701 auto entry = fVariableMap.find(var);
1702 ASSERT(entry != fVariableMap.end());
1703 return std::unique_ptr<SPIRVCodeGenerator::LValue>(new PointerLValue (
1704 *this,
1705 entry->se cond,
1706 this->get Type(*expr.fType)));
1707 }
1708 case Expression::kIndex_Kind: // fall through
1709 case Expression::kFieldAccess_Kind: {
1710 std::vector<SpvId> chain = this->getAccessChain(expr, out);
1711 SpvId member = this->nextId();
1712 this->writeOpCode(SpvOpAccessChain, (SpvId) (3 + chain.size()), out) ;
1713 this->writeWord(this->getPointerType(expr.fType, get_storage_class(e xpr)), out);
1714 this->writeWord(member, out);
1715 for (SpvId idx : chain) {
1716 this->writeWord(idx, out);
1717 }
1718 return std::unique_ptr<SPIRVCodeGenerator::LValue>(new PointerLValue (
1719 *this,
1720 member,
1721 this->get Type(*expr.fType)));
1722 }
1723
1724 case Expression::kSwizzle_Kind: {
1725 Swizzle& swizzle = (Swizzle&) expr;
1726 size_t count = swizzle.fComponents.size();
1727 SpvId base = this->getLValue(*swizzle.fBase, out)->getPointer();
1728 ASSERT(base);
1729 if (count == 1) {
1730 IntLiteral index(Position(), swizzle.fComponents[0]);
1731 SpvId member = this->nextId();
1732 this->writeInstruction(SpvOpAccessChain,
1733 this->getPointerType(swizzle.fType,
1734 get_storage_class(*s wizzle.fBase)),
1735 member,
1736 base,
1737 this->writeIntLiteral(index),
1738 out);
1739 return std::unique_ptr<SPIRVCodeGenerator::LValue>(new PointerLV alue(
1740 *this,
1741 member,
1742 this->get Type(*expr.fType)));
1743 } else {
1744 return std::unique_ptr<SPIRVCodeGenerator::LValue>(new SwizzleLV alue(
1745 *t his,
1746 ba se,
1747 sw izzle.fComponents,
1748 *s wizzle.fBase->fType,
1749 *e xpr.fType));
1750 }
1751 }
1752
1753 default:
1754 // expr isn't actually an lvalue, create a dummy variable for it. Th is case happens due
1755 // to the need to store values in temporary variables during functio n calls (see
1756 // comments in getFunctionType); erroneous uses of rvalues as lvalue s should have been
1757 // caught by IRGenerator
1758 SpvId result = this->nextId();
1759 SpvId type = this->getPointerType(expr.fType, SpvStorageClassFunctio n);
1760 this->writeInstruction(SpvOpVariable, type, result, SpvStorageClassF unction, out);
1761 this->writeInstruction(SpvOpStore, result, this->writeExpression(exp r, out), out);
1762 return std::unique_ptr<SPIRVCodeGenerator::LValue>(new PointerLValue (
1763 *this,
1764 result,
1765 this->get Type(*expr.fType)));
1766 }
1767 }
1768
1769 SpvId SPIRVCodeGenerator::writeVariableReference(VariableReference& ref, std::os tream& out) {
1770 auto entry = fVariableMap.find(ref.fVariable);
1771 ASSERT(entry != fVariableMap.end());
1772 SpvId var = entry->second;
1773 SpvId result = this->nextId();
1774 this->writeInstruction(SpvOpLoad, this->getType(*ref.fVariable->fType), resu lt, var, out);
1775 return result;
1776 }
1777
1778 SpvId SPIRVCodeGenerator::writeIndexExpression(IndexExpression& expr, std::ostre am& out) {
1779 return getLValue(expr, out)->load(out);
1780 }
1781
1782 SpvId SPIRVCodeGenerator::writeFieldAccess(FieldAccess& f, std::ostream& out) {
1783 return getLValue(f, out)->load(out);
1784 }
1785
1786 SpvId SPIRVCodeGenerator::writeSwizzle(Swizzle& swizzle, std::ostream& out) {
1787 SpvId base = this->writeExpression(*swizzle.fBase, out);
1788 SpvId result = this->nextId();
1789 size_t count = swizzle.fComponents.size();
1790 if (count == 1) {
1791 this->writeInstruction(SpvOpCompositeExtract, this->getType(*swizzle.fTy pe), result, base,
1792 swizzle.fComponents[0], out);
1793 } else {
1794 this->writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) count, out);
1795 this->writeWord(this->getType(*swizzle.fType), out);
1796 this->writeWord(result, out);
1797 this->writeWord(base, out);
1798 this->writeWord(base, out);
1799 for (int component : swizzle.fComponents) {
1800 this->writeWord(component, out);
1801 }
1802 }
1803 return result;
1804 }
1805
1806 SpvId SPIRVCodeGenerator::writeBinaryOperation(const Type& resultType,
1807 const Type& operandType, SpvId lh s,
1808 SpvId rhs, SpvOp_ ifFloat, SpvOp_ ifInt,
1809 SpvOp_ ifUInt, SpvOp_ ifBool, std ::ostream& out) {
1810 SpvId result = this->nextId();
1811 if (is_float(operandType)) {
1812 this->writeInstruction(ifFloat, this->getType(resultType), result, lhs, rhs, out);
1813 } else if (is_signed(operandType)) {
1814 this->writeInstruction(ifInt, this->getType(resultType), result, lhs, rh s, out);
1815 } else if (is_unsigned(operandType)) {
1816 this->writeInstruction(ifUInt, this->getType(resultType), result, lhs, r hs, out);
1817 } else if (operandType == *kBool_Type) {
1818 this->writeInstruction(ifBool, this->getType(resultType), result, lhs, r hs, out);
1819 } else {
1820 ABORT("invalid operandType: %s", operandType.description().c_str());
1821 }
1822 return result;
1823 }
1824
1825 bool is_assignment(Token::Kind op) {
1826 switch (op) {
1827 case Token::EQ: // fall through
1828 case Token::PLUSEQ: // fall through
1829 case Token::MINUSEQ: // fall through
1830 case Token::STAREQ: // fall through
1831 case Token::SLASHEQ: // fall through
1832 case Token::PERCENTEQ: // fall through
1833 case Token::SHLEQ: // fall through
1834 case Token::SHREQ: // fall through
1835 case Token::BITWISEOREQ: // fall through
1836 case Token::BITWISEXOREQ: // fall through
1837 case Token::BITWISEANDEQ: // fall through
1838 case Token::LOGICALOREQ: // fall through
1839 case Token::LOGICALXOREQ: // fall through
1840 case Token::LOGICALANDEQ:
1841 return true;
1842 default:
1843 return false;
1844 }
1845 }
1846
1847 SpvId SPIRVCodeGenerator::writeBinaryExpression(BinaryExpression& b, std::ostrea m& out) {
1848 // handle cases where we don't necessarily evaluate both LHS and RHS
1849 switch (b.fOperator) {
1850 case Token::EQ: {
1851 SpvId rhs = this->writeExpression(*b.fRight, out);
1852 this->getLValue(*b.fLeft, out)->store(rhs, out);
1853 return rhs;
1854 }
1855 case Token::LOGICALAND:
1856 return this->writeLogicalAnd(b, out);
1857 case Token::LOGICALOR:
1858 return this->writeLogicalOr(b, out);
1859 default:
1860 break;
1861 }
1862
1863 // "normal" operators
1864 const Type& resultType = *b.fType;
1865 std::unique_ptr<LValue> lvalue;
1866 SpvId lhs;
1867 if (is_assignment(b.fOperator)) {
1868 lvalue = this->getLValue(*b.fLeft, out);
1869 lhs = lvalue->load(out);
1870 } else {
1871 lvalue = nullptr;
1872 lhs = this->writeExpression(*b.fLeft, out);
1873 }
1874 SpvId rhs = this->writeExpression(*b.fRight, out);
1875 // component type we are operating on: float, int, uint
1876 const Type* operandType;
1877 // IR allows mismatched types in expressions (e.g. vec2 * float), but they n eed special handling
1878 // in SPIR-V
1879 if (b.fLeft->fType != b.fRight->fType) {
1880 if (b.fLeft->fType->kind() == Type::kVector_Kind &&
1881 b.fRight->fType->isNumber()) {
1882 // promote number to vector
1883 SpvId vec = this->nextId();
1884 this->writeOpCode(SpvOpCompositeConstruct, 3 + b.fType->columns(), o ut);
1885 this->writeWord(this->getType(resultType), out);
1886 this->writeWord(vec, out);
1887 for (int i = 0; i < resultType.columns(); i++) {
1888 this->writeWord(rhs, out);
1889 }
1890 rhs = vec;
1891 operandType = b.fRight->fType.get();
1892 } else if (b.fRight->fType->kind() == Type::kVector_Kind &&
1893 b.fLeft->fType->isNumber()) {
1894 // promote number to vector
1895 SpvId vec = this->nextId();
1896 this->writeOpCode(SpvOpCompositeConstruct, 3 + b.fType->columns(), o ut);
1897 this->writeWord(this->getType(resultType), out);
1898 this->writeWord(vec, out);
1899 for (int i = 0; i < resultType.columns(); i++) {
1900 this->writeWord(lhs, out);
1901 }
1902 lhs = vec;
1903 ASSERT(!lvalue);
1904 operandType = b.fLeft->fType.get();
1905 } else if (b.fLeft->fType->kind() == Type::kMatrix_Kind) {
1906 SpvOp_ op;
1907 if (b.fRight->fType->kind() == Type::kMatrix_Kind) {
1908 op = SpvOpMatrixTimesMatrix;
1909 } else if (b.fRight->fType->kind() == Type::kVector_Kind) {
1910 op = SpvOpMatrixTimesVector;
1911 } else {
1912 ASSERT(b.fRight->fType->kind() == Type::kScalar_Kind);
1913 op = SpvOpMatrixTimesScalar;
1914 }
1915 SpvId result = this->nextId();
1916 this->writeInstruction(op, this->getType(*b.fType), result, lhs, rhs , out);
1917 if (b.fOperator == Token::STAREQ) {
1918 lvalue->store(result, out);
1919 } else {
1920 ASSERT(b.fOperator == Token::STAR);
1921 }
1922 return result;
1923 } else if (b.fRight->fType->kind() == Type::kMatrix_Kind) {
1924 SpvId result = this->nextId();
1925 if (b.fLeft->fType->kind() == Type::kVector_Kind) {
1926 this->writeInstruction(SpvOpVectorTimesMatrix, this->getType(*b. fType), result,
1927 lhs, rhs, out);
1928 } else {
1929 ASSERT(b.fLeft->fType->kind() == Type::kScalar_Kind);
1930 this->writeInstruction(SpvOpMatrixTimesScalar, this->getType(*b. fType), result, rhs,
1931 lhs, out);
1932 }
1933 if (b.fOperator == Token::STAREQ) {
1934 lvalue->store(result, out);
1935 } else {
1936 ASSERT(b.fOperator == Token::STAR);
1937 }
1938 return result;
1939 } else {
1940 ABORT("unsupported binary expression: %s", b.description().c_str());
1941 }
1942 } else {
1943 operandType = b.fLeft->fType.get();
1944 ASSERT(*operandType == *b.fRight->fType);
1945 }
1946 switch (b.fOperator) {
1947 case Token::EQEQ:
1948 ASSERT(resultType == *kBool_Type);
1949 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs , SpvOpFOrdEqual,
1950 SpvOpIEqual, SpvOpIEqual, SpvOpLog icalEqual, out);
1951 case Token::NEQ:
1952 ASSERT(resultType == *kBool_Type);
1953 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs , SpvOpFOrdNotEqual,
1954 SpvOpINotEqual, SpvOpINotEqual, Sp vOpLogicalNotEqual,
1955 out);
1956 case Token::GT:
1957 ASSERT(resultType == *kBool_Type);
1958 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs ,
1959 SpvOpFOrdGreaterThan, SpvOpSGreate rThan,
1960 SpvOpUGreaterThan, SpvOpUndef, out );
1961 case Token::LT:
1962 ASSERT(resultType == *kBool_Type);
1963 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs , SpvOpFOrdLessThan,
1964 SpvOpSLessThan, SpvOpULessThan, Sp vOpUndef, out);
1965 case Token::GTEQ:
1966 ASSERT(resultType == *kBool_Type);
1967 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs ,
1968 SpvOpFOrdGreaterThanEqual, SpvOpSG reaterThanEqual,
1969 SpvOpUGreaterThanEqual, SpvOpUndef , out);
1970 case Token::LTEQ:
1971 ASSERT(resultType == *kBool_Type);
1972 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs ,
1973 SpvOpFOrdLessThanEqual, SpvOpSLess ThanEqual,
1974 SpvOpULessThanEqual, SpvOpUndef, o ut);
1975 case Token::PLUS:
1976 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs , SpvOpFAdd,
1977 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
1978 case Token::MINUS:
1979 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs , SpvOpFSub,
1980 SpvOpISub, SpvOpISub, SpvOpUndef, out);
1981 case Token::STAR:
1982 if (b.fLeft->fType->kind() == Type::kMatrix_Kind &&
1983 b.fRight->fType->kind() == Type::kMatrix_Kind) {
1984 // matrix multiply
1985 SpvId result = this->nextId();
1986 this->writeInstruction(SpvOpMatrixTimesMatrix, this->getType(res ultType), result,
1987 lhs, rhs, out);
1988 return result;
1989 }
1990 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs , SpvOpFMul,
1991 SpvOpIMul, SpvOpIMul, SpvOpUndef, out);
1992 case Token::SLASH:
1993 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs , SpvOpFDiv,
1994 SpvOpSDiv, SpvOpUDiv, SpvOpUndef, out);
1995 case Token::PLUSEQ: {
1996 SpvId result = this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFAdd,
1997 SpvOpIAdd, SpvOpIAdd, SpvO pUndef, out);
1998 ASSERT(lvalue);
1999 lvalue->store(result, out);
2000 return result;
2001 }
2002 case Token::MINUSEQ: {
2003 SpvId result = this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFSub,
2004 SpvOpISub, SpvOpISub, SpvO pUndef, out);
2005 ASSERT(lvalue);
2006 lvalue->store(result, out);
2007 return result;
2008 }
2009 case Token::STAREQ: {
2010 if (b.fLeft->fType->kind() == Type::kMatrix_Kind &&
2011 b.fRight->fType->kind() == Type::kMatrix_Kind) {
2012 // matrix multiply
2013 SpvId result = this->nextId();
2014 this->writeInstruction(SpvOpMatrixTimesMatrix, this->getType(res ultType), result,
2015 lhs, rhs, out);
2016 ASSERT(lvalue);
2017 lvalue->store(result, out);
2018 return result;
2019 }
2020 SpvId result = this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMul,
2021 SpvOpIMul, SpvOpIMul, SpvO pUndef, out);
2022 ASSERT(lvalue);
2023 lvalue->store(result, out);
2024 return result;
2025 }
2026 case Token::SLASHEQ: {
2027 SpvId result = this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFDiv,
2028 SpvOpSDiv, SpvOpUDiv, SpvO pUndef, out);
2029 ASSERT(lvalue);
2030 lvalue->store(result, out);
2031 return result;
2032 }
2033 default:
2034 // FIXME: missing support for some operators (bitwise, &&=, ||=, shi ft...)
2035 ABORT("unsupported binary expression: %s", b.description().c_str());
2036 }
2037 }
2038
2039 SpvId SPIRVCodeGenerator::writeLogicalAnd(BinaryExpression& a, std::ostream& out ) {
2040 ASSERT(a.fOperator == Token::LOGICALAND);
2041 BoolLiteral falseLiteral(Position(), false);
2042 SpvId falseConstant = this->writeBoolLiteral(falseLiteral);
2043 SpvId lhs = this->writeExpression(*a.fLeft, out);
2044 SpvId rhsLabel = this->nextId();
2045 SpvId end = this->nextId();
2046 SpvId lhsBlock = fCurrentBlock;
2047 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone , out);
2048 this->writeInstruction(SpvOpBranchConditional, lhs, rhsLabel, end, out);
2049 this->writeLabel(rhsLabel, out);
2050 SpvId rhs = this->writeExpression(*a.fRight, out);
2051 SpvId rhsBlock = fCurrentBlock;
2052 this->writeInstruction(SpvOpBranch, end, out);
2053 this->writeLabel(end, out);
2054 SpvId result = this->nextId();
2055 this->writeInstruction(SpvOpPhi, this->getType(*kBool_Type), result, falseCo nstant, lhsBlock,
2056 rhs, rhsBlock, out);
2057 return result;
2058 }
2059
2060 SpvId SPIRVCodeGenerator::writeLogicalOr(BinaryExpression& o, std::ostream& out) {
2061 ASSERT(o.fOperator == Token::LOGICALOR);
2062 BoolLiteral trueLiteral(Position(), true);
2063 SpvId trueConstant = this->writeBoolLiteral(trueLiteral);
2064 SpvId lhs = this->writeExpression(*o.fLeft, out);
2065 SpvId rhsLabel = this->nextId();
2066 SpvId end = this->nextId();
2067 SpvId lhsBlock = fCurrentBlock;
2068 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone , out);
2069 this->writeInstruction(SpvOpBranchConditional, lhs, end, rhsLabel, out);
2070 this->writeLabel(rhsLabel, out);
2071 SpvId rhs = this->writeExpression(*o.fRight, out);
2072 SpvId rhsBlock = fCurrentBlock;
2073 this->writeInstruction(SpvOpBranch, end, out);
2074 this->writeLabel(end, out);
2075 SpvId result = this->nextId();
2076 this->writeInstruction(SpvOpPhi, this->getType(*kBool_Type), result, trueCon stant, lhsBlock,
2077 rhs, rhsBlock, out);
2078 return result;
2079 }
2080
2081 SpvId SPIRVCodeGenerator::writeTernaryExpression(TernaryExpression& t, std::ostr eam& out) {
2082 SpvId test = this->writeExpression(*t.fTest, out);
2083 if (t.fIfTrue->isConstant() && t.fIfFalse->isConstant()) {
2084 // both true and false are constants, can just use OpSelect
2085 SpvId result = this->nextId();
2086 SpvId trueId = this->writeExpression(*t.fIfTrue, out);
2087 SpvId falseId = this->writeExpression(*t.fIfFalse, out);
2088 this->writeInstruction(SpvOpSelect, this->getType(*t.fType), result, tes t, trueId, falseId,
2089 out);
2090 return result;
2091 }
2092 // was originally using OpPhi to choose the result, but for some reason that is crashing on
2093 // Adreno. Switched to storing the result in a temp variable as glslang does .
2094 SpvId var = this->nextId();
2095 this->writeInstruction(SpvOpVariable, this->getPointerType(t.fType, SpvStora geClassFunction),
2096 var, SpvStorageClassFunction, out);
2097 SpvId trueLabel = this->nextId();
2098 SpvId falseLabel = this->nextId();
2099 SpvId end = this->nextId();
2100 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone , out);
2101 this->writeInstruction(SpvOpBranchConditional, test, trueLabel, falseLabel, out);
2102 this->writeLabel(trueLabel, out);
2103 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.fIfTrue, ou t), out);
2104 this->writeInstruction(SpvOpBranch, end, out);
2105 this->writeLabel(falseLabel, out);
2106 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.fIfFalse, o ut), out);
2107 this->writeInstruction(SpvOpBranch, end, out);
2108 this->writeLabel(end, out);
2109 SpvId result = this->nextId();
2110 this->writeInstruction(SpvOpLoad, this->getType(*t.fType), result, var, out) ;
2111 return result;
2112 }
2113
2114 Expression* literal_1(const Type& type) {
2115 static IntLiteral int1(Position(), 1);
2116 static FloatLiteral float1(Position(), 1.0);
2117 if (type == *kInt_Type) {
2118 return &int1;
2119 }
2120 else if (type == *kFloat_Type) {
2121 return &float1;
2122 } else {
2123 ABORT("math is unsupported on type '%s'")
2124 }
2125 }
2126
2127 SpvId SPIRVCodeGenerator::writePrefixExpression(PrefixExpression& p, std::ostrea m& out) {
2128 if (p.fOperator == Token::MINUS) {
2129 SpvId result = this->nextId();
2130 SpvId typeId = this->getType(*p.fType);
2131 SpvId expr = this->writeExpression(*p.fOperand, out);
2132 if (is_float(*p.fType)) {
2133 this->writeInstruction(SpvOpFNegate, typeId, result, expr, out);
2134 } else if (is_signed(*p.fType)) {
2135 this->writeInstruction(SpvOpSNegate, typeId, result, expr, out);
2136 } else {
2137 ABORT("unsupported prefix expression %s", p.description().c_str());
2138 };
2139 return result;
2140 }
2141 switch (p.fOperator) {
2142 case Token::PLUS:
2143 return this->writeExpression(*p.fOperand, out);
2144 case Token::PLUSPLUS: {
2145 std::unique_ptr<LValue> lv = this->getLValue(*p.fOperand, out);
2146 SpvId one = this->writeExpression(*literal_1(*p.fType), out);
2147 SpvId result = this->writeBinaryOperation(*p.fType, *p.fType, lv->lo ad(out), one,
2148 SpvOpFAdd, SpvOpIAdd, SpvO pIAdd, SpvOpUndef,
2149 out);
2150 lv->store(result, out);
2151 return result;
2152 }
2153 case Token::MINUSMINUS: {
2154 std::unique_ptr<LValue> lv = this->getLValue(*p.fOperand, out);
2155 SpvId one = this->writeExpression(*literal_1(*p.fType), out);
2156 SpvId result = this->writeBinaryOperation(*p.fType, *p.fType, lv->lo ad(out), one,
2157 SpvOpFSub, SpvOpISub, SpvO pISub, SpvOpUndef,
2158 out);
2159 lv->store(result, out);
2160 return result;
2161 }
2162 case Token::NOT: {
2163 ASSERT(p.fOperand->fType == kBool_Type);
2164 SpvId result = this->nextId();
2165 this->writeInstruction(SpvOpLogicalNot, this->getType(*p.fOperand->f Type), result,
2166 this->writeExpression(*p.fOperand, out), out) ;
2167 return result;
2168 }
2169 default:
2170 ABORT("unsupported prefix expression: %s", p.description().c_str());
2171 }
2172 }
2173
2174 SpvId SPIRVCodeGenerator::writePostfixExpression(PostfixExpression& p, std::ostr eam& out) {
2175 std::unique_ptr<LValue> lv = this->getLValue(*p.fOperand, out);
2176 SpvId result = lv->load(out);
2177 SpvId one = this->writeExpression(*literal_1(*p.fType), out);
2178 switch (p.fOperator) {
2179 case Token::PLUSPLUS: {
2180 SpvId temp = this->writeBinaryOperation(*p.fType, *p.fType, result, one, SpvOpFAdd,
2181 SpvOpIAdd, SpvOpIAdd, SpvOpU ndef, out);
2182 lv->store(temp, out);
2183 return result;
2184 }
2185 case Token::MINUSMINUS: {
2186 SpvId temp = this->writeBinaryOperation(*p.fType, *p.fType, result, one, SpvOpFSub,
2187 SpvOpISub, SpvOpISub, SpvOpU ndef, out);
2188 lv->store(temp, out);
2189 return result;
2190 }
2191 default:
2192 ABORT("unsupported postfix expression %s", p.description().c_str());
2193 }
2194 }
2195
2196 SpvId SPIRVCodeGenerator::writeBoolLiteral(BoolLiteral& b) {
2197 if (b.fValue) {
2198 if (fBoolTrue == 0) {
2199 fBoolTrue = this->nextId();
2200 this->writeInstruction(SpvOpConstantTrue, this->getType(*b.fType), f BoolTrue,
2201 fConstantBuffer);
2202 }
2203 return fBoolTrue;
2204 } else {
2205 if (fBoolFalse == 0) {
2206 fBoolFalse = this->nextId();
2207 this->writeInstruction(SpvOpConstantFalse, this->getType(*b.fType), fBoolFalse,
2208 fConstantBuffer);
2209 }
2210 return fBoolFalse;
2211 }
2212 }
2213
2214 SpvId SPIRVCodeGenerator::writeIntLiteral(IntLiteral& i) {
2215 if (i.fType == kInt_Type) {
2216 auto entry = fIntConstants.find(i.fValue);
2217 if (entry == fIntConstants.end()) {
2218 SpvId result = this->nextId();
2219 this->writeInstruction(SpvOpConstant, this->getType(*i.fType), resul t, (SpvId) i.fValue,
2220 fConstantBuffer);
2221 fIntConstants[i.fValue] = result;
2222 return result;
2223 }
2224 return entry->second;
2225 } else {
2226 ASSERT(i.fType == kUInt_Type);
2227 auto entry = fUIntConstants.find(i.fValue);
2228 if (entry == fUIntConstants.end()) {
2229 SpvId result = this->nextId();
2230 this->writeInstruction(SpvOpConstant, this->getType(*i.fType), resul t, (SpvId) i.fValue,
2231 fConstantBuffer);
2232 fUIntConstants[i.fValue] = result;
2233 return result;
2234 }
2235 return entry->second;
2236 }
2237 }
2238
2239 SpvId SPIRVCodeGenerator::writeFloatLiteral(FloatLiteral& f) {
2240 if (f.fType == kFloat_Type) {
2241 float value = (float) f.fValue;
2242 auto entry = fFloatConstants.find(value);
2243 if (entry == fFloatConstants.end()) {
2244 SpvId result = this->nextId();
2245 uint32_t bits;
2246 ASSERT(sizeof(bits) == sizeof(value));
2247 memcpy(&bits, &value, sizeof(bits));
2248 this->writeInstruction(SpvOpConstant, this->getType(*f.fType), resul t, bits,
2249 fConstantBuffer);
2250 fFloatConstants[value] = result;
2251 return result;
2252 }
2253 return entry->second;
2254 } else {
2255 ASSERT(f.fType == kDouble_Type);
2256 auto entry = fDoubleConstants.find(f.fValue);
2257 if (entry == fDoubleConstants.end()) {
2258 SpvId result = this->nextId();
2259 uint64_t bits;
2260 ASSERT(sizeof(bits) == sizeof(f.fValue));
2261 memcpy(&bits, &f.fValue, sizeof(bits));
2262 this->writeInstruction(SpvOpConstant, this->getType(*f.fType), resul t,
2263 bits & 0xffffffff, bits >> 32, fConstantBuffe r);
2264 fDoubleConstants[f.fValue] = result;
2265 return result;
2266 }
2267 return entry->second;
2268 }
2269 }
2270
2271 SpvId SPIRVCodeGenerator::writeFunctionStart(std::shared_ptr<FunctionDeclaration > f,
2272 std::ostream& out) {
2273 SpvId result = fFunctionMap[f];
2274 this->writeInstruction(SpvOpFunction, this->getType(*f->fReturnType), result ,
2275 SpvFunctionControlMaskNone, this->getFunctionType(f), out);
2276 this->writeInstruction(SpvOpName, result, f->fName.c_str(), fNameBuffer);
2277 for (size_t i = 0; i < f->fParameters.size(); i++) {
2278 SpvId id = this->nextId();
2279 fVariableMap[f->fParameters[i]] = id;
2280 SpvId type;
2281 type = this->getPointerType(f->fParameters[i]->fType, SpvStorageClassFun ction);
2282 this->writeInstruction(SpvOpFunctionParameter, type, id, out);
2283 }
2284 return result;
2285 }
2286
2287 SpvId SPIRVCodeGenerator::writeFunction(FunctionDefinition& f, std::ostream& out ) {
2288 SpvId result = this->writeFunctionStart(f.fDeclaration, out);
2289 this->writeLabel(this->nextId(), out);
2290 if (f.fDeclaration->fName == "main") {
2291 out << fGlobalInitializersBuffer.str();
2292 }
2293 std::stringstream bodyBuffer;
2294 this->writeBlock(*f.fBody, bodyBuffer);
2295 out << fVariableBuffer.str();
2296 fVariableBuffer.str("");
2297 out << bodyBuffer.str();
2298 if (fCurrentBlock) {
2299 this->writeInstruction(SpvOpReturn, out);
2300 }
2301 this->writeInstruction(SpvOpFunctionEnd, out);
2302 return result;
2303 }
2304
2305 void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target) {
2306 if (layout.fLocation >= 0) {
2307 this->writeInstruction(SpvOpDecorate, target, SpvDecorationLocation, lay out.fLocation,
2308 fDecorationBuffer);
2309 }
2310 if (layout.fBinding >= 0) {
2311 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBinding, layo ut.fBinding,
2312 fDecorationBuffer);
2313 }
2314 if (layout.fIndex >= 0) {
2315 this->writeInstruction(SpvOpDecorate, target, SpvDecorationIndex, layout .fIndex,
2316 fDecorationBuffer);
2317 }
2318 if (layout.fSet >= 0) {
2319 this->writeInstruction(SpvOpDecorate, target, SpvDecorationDescriptorSet , layout.fSet,
2320 fDecorationBuffer);
2321 }
2322 if (layout.fBuiltin >= 0) {
2323 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBuiltIn, layo ut.fBuiltin,
2324 fDecorationBuffer);
2325 }
2326 }
2327
2328 void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target, int mem ber) {
2329 if (layout.fLocation >= 0) {
2330 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecoratio nLocation,
2331 layout.fLocation, fDecorationBuffer);
2332 }
2333 if (layout.fBinding >= 0) {
2334 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecoratio nBinding,
2335 layout.fBinding, fDecorationBuffer);
2336 }
2337 if (layout.fIndex >= 0) {
2338 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecoratio nIndex,
2339 layout.fIndex, fDecorationBuffer);
2340 }
2341 if (layout.fSet >= 0) {
2342 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecoratio nDescriptorSet,
2343 layout.fSet, fDecorationBuffer);
2344 }
2345 if (layout.fBuiltin >= 0) {
2346 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecoratio nBuiltIn,
2347 layout.fBuiltin, fDecorationBuffer);
2348 }
2349 }
2350
2351 SpvId SPIRVCodeGenerator::writeInterfaceBlock(InterfaceBlock& intf) {
2352 SpvId type = this->getType(*intf.fVariable->fType);
2353 SpvId result = this->nextId();
2354 this->writeInstruction(SpvOpDecorate, type, SpvDecorationBlock, fDecorationB uffer);
2355 SpvStorageClass_ storageClass = get_storage_class(intf.fVariable->fModifiers );
2356 SpvId ptrType = this->nextId();
2357 this->writeInstruction(SpvOpTypePointer, ptrType, storageClass, type, fConst antBuffer);
2358 this->writeInstruction(SpvOpVariable, ptrType, result, storageClass, fConsta ntBuffer);
2359 this->writeLayout(intf.fVariable->fModifiers.fLayout, result);
2360 fVariableMap[intf.fVariable] = result;
2361 return result;
2362 }
2363
2364 void SPIRVCodeGenerator::writeGlobalVars(VarDeclaration& decl, std::ostream& out ) {
2365 for (size_t i = 0; i < decl.fVars.size(); i++) {
2366 if (!decl.fVars[i]->fIsReadFrom && !decl.fVars[i]->fIsWrittenTo) {
2367 continue;
2368 }
2369 SpvStorageClass_ storageClass;
2370 if (decl.fVars[i]->fModifiers.fFlags & Modifiers::kIn_Flag) {
2371 storageClass = SpvStorageClassInput;
2372 } else if (decl.fVars[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
2373 storageClass = SpvStorageClassOutput;
2374 } else if (decl.fVars[i]->fModifiers.fFlags & Modifiers::kUniform_Flag) {
2375 if (decl.fVars[i]->fType->kind() == Type::kSampler_Kind) {
2376 storageClass = SpvStorageClassUniformConstant;
2377 } else {
2378 storageClass = SpvStorageClassUniform;
2379 }
2380 } else {
2381 storageClass = SpvStorageClassPrivate;
2382 }
2383 SpvId id = this->nextId();
2384 fVariableMap[decl.fVars[i]] = id;
2385 SpvId type = this->getPointerType(decl.fVars[i]->fType, storageClass);
2386 this->writeInstruction(SpvOpVariable, type, id, storageClass, fConstantB uffer);
2387 this->writeInstruction(SpvOpName, id, decl.fVars[i]->fName.c_str(), fNam eBuffer);
2388 if (decl.fVars[i]->fType->kind() == Type::kMatrix_Kind) {
2389 this->writeInstruction(SpvOpMemberDecorate, id, (SpvId) i, SpvDecora tionColMajor,
2390 fDecorationBuffer);
2391 this->writeInstruction(SpvOpMemberDecorate, id, (SpvId) i, SpvDecora tionMatrixStride,
2392 (SpvId) decl.fVars[i]->fType->stride(), fDeco rationBuffer);
2393 }
2394 if (decl.fValues[i]) {
2395 ASSERT(!fCurrentBlock);
2396 fCurrentBlock = -1;
2397 SpvId value = this->writeExpression(*decl.fValues[i], fGlobalInitial izersBuffer);
2398 this->writeInstruction(SpvOpStore, id, value, fGlobalInitializersBuf fer);
2399 fCurrentBlock = 0;
2400 }
2401 this->writeLayout(decl.fVars[i]->fModifiers.fLayout, id);
2402 }
2403 }
2404
2405 void SPIRVCodeGenerator::writeVarDeclaration(VarDeclaration& decl, std::ostream& out) {
2406 for (size_t i = 0; i < decl.fVars.size(); i++) {
2407 SpvId id = this->nextId();
2408 fVariableMap[decl.fVars[i]] = id;
2409 SpvId type = this->getPointerType(decl.fVars[i]->fType, SpvStorageClassF unction);
2410 this->writeInstruction(SpvOpVariable, type, id, SpvStorageClassFunction, fVariableBuffer);
2411 this->writeInstruction(SpvOpName, id, decl.fVars[i]->fName.c_str(), fNam eBuffer);
2412 if (decl.fValues[i]) {
2413 SpvId value = this->writeExpression(*decl.fValues[i], out);
2414 this->writeInstruction(SpvOpStore, id, value, out);
2415 }
2416 }
2417 }
2418
2419 void SPIRVCodeGenerator::writeStatement(Statement& s, std::ostream& out) {
2420 switch (s.fKind) {
2421 case Statement::kBlock_Kind:
2422 this->writeBlock((Block&) s, out);
2423 break;
2424 case Statement::kExpression_Kind:
2425 this->writeExpression(*((ExpressionStatement&) s).fExpression, out);
2426 break;
2427 case Statement::kReturn_Kind:
2428 this->writeReturnStatement((ReturnStatement&) s, out);
2429 break;
2430 case Statement::kVarDeclaration_Kind:
2431 this->writeVarDeclaration(*((VarDeclarationStatement&) s).fDeclarati on, out);
2432 break;
2433 case Statement::kIf_Kind:
2434 this->writeIfStatement((IfStatement&) s, out);
2435 break;
2436 case Statement::kFor_Kind:
2437 this->writeForStatement((ForStatement&) s, out);
2438 break;
2439 case Statement::kBreak_Kind:
2440 this->writeInstruction(SpvOpBranch, fBreakTarget.top(), out);
2441 break;
2442 case Statement::kContinue_Kind:
2443 this->writeInstruction(SpvOpBranch, fContinueTarget.top(), out);
2444 break;
2445 case Statement::kDiscard_Kind:
2446 this->writeInstruction(SpvOpKill, out);
2447 break;
2448 default:
2449 ABORT("unsupported statement: %s", s.description().c_str());
2450 }
2451 }
2452
2453 void SPIRVCodeGenerator::writeBlock(Block& b, std::ostream& out) {
2454 for (size_t i = 0; i < b.fStatements.size(); i++) {
2455 this->writeStatement(*b.fStatements[i], out);
2456 }
2457 }
2458
2459 void SPIRVCodeGenerator::writeIfStatement(IfStatement& stmt, std::ostream& out) {
2460 SpvId test = this->writeExpression(*stmt.fTest, out);
2461 SpvId ifTrue = this->nextId();
2462 SpvId ifFalse = this->nextId();
2463 if (stmt.fIfFalse) {
2464 SpvId end = this->nextId();
2465 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMask None, out);
2466 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, ou t);
2467 this->writeLabel(ifTrue, out);
2468 this->writeStatement(*stmt.fIfTrue, out);
2469 if (fCurrentBlock) {
2470 this->writeInstruction(SpvOpBranch, end, out);
2471 }
2472 this->writeLabel(ifFalse, out);
2473 this->writeStatement(*stmt.fIfFalse, out);
2474 if (fCurrentBlock) {
2475 this->writeInstruction(SpvOpBranch, end, out);
2476 }
2477 this->writeLabel(end, out);
2478 } else {
2479 this->writeInstruction(SpvOpSelectionMerge, ifFalse, SpvSelectionControl MaskNone, out);
2480 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, ou t);
2481 this->writeLabel(ifTrue, out);
2482 this->writeStatement(*stmt.fIfTrue, out);
2483 if (fCurrentBlock) {
2484 this->writeInstruction(SpvOpBranch, ifFalse, out);
2485 }
2486 this->writeLabel(ifFalse, out);
2487 }
2488 }
2489
2490 void SPIRVCodeGenerator::writeForStatement(ForStatement& f, std::ostream& out) {
2491 if (f.fInitializer) {
2492 this->writeStatement(*f.fInitializer, out);
2493 }
2494 SpvId header = this->nextId();
2495 SpvId start = this->nextId();
2496 SpvId body = this->nextId();
2497 SpvId next = this->nextId();
2498 fContinueTarget.push(next);
2499 SpvId end = this->nextId();
2500 fBreakTarget.push(end);
2501 this->writeInstruction(SpvOpBranch, header, out);
2502 this->writeLabel(header, out);
2503 this->writeInstruction(SpvOpLoopMerge, end, next, SpvLoopControlMaskNone, ou t);
2504 this->writeInstruction(SpvOpBranch, start, out);
2505 this->writeLabel(start, out);
2506 SpvId test = this->writeExpression(*f.fTest, out);
2507 this->writeInstruction(SpvOpBranchConditional, test, body, end, out);
2508 this->writeLabel(body, out);
2509 this->writeStatement(*f.fStatement, out);
2510 if (fCurrentBlock) {
2511 this->writeInstruction(SpvOpBranch, next, out);
2512 }
2513 this->writeLabel(next, out);
2514 if (f.fNext) {
2515 this->writeExpression(*f.fNext, out);
2516 }
2517 this->writeInstruction(SpvOpBranch, header, out);
2518 this->writeLabel(end, out);
2519 fBreakTarget.pop();
2520 fContinueTarget.pop();
2521 }
2522
2523 void SPIRVCodeGenerator::writeReturnStatement(ReturnStatement& r, std::ostream& out) {
2524 if (r.fExpression) {
2525 this->writeInstruction(SpvOpReturnValue, this->writeExpression(*r.fExpre ssion, out),
2526 out);
2527 } else {
2528 this->writeInstruction(SpvOpReturn, out);
2529 }
2530 }
2531
2532 void SPIRVCodeGenerator::writeInstructions(Program& program, std::ostream& out) {
2533 fGLSLExtendedInstructions = this->nextId();
2534 std::stringstream body;
2535 std::vector<SpvId> interfaceVars;
2536 // assign IDs to functions
2537 for (size_t i = 0; i < program.fElements.size(); i++) {
2538 if (program.fElements[i]->fKind == ProgramElement::kFunction_Kind) {
2539 FunctionDefinition& f = (FunctionDefinition&) *program.fElements[i];
2540 fFunctionMap[f.fDeclaration] = this->nextId();
2541 }
2542 }
2543 for (size_t i = 0; i < program.fElements.size(); i++) {
2544 if (program.fElements[i]->fKind == ProgramElement::kInterfaceBlock_Kind) {
2545 InterfaceBlock& intf = (InterfaceBlock&) *program.fElements[i];
2546 SpvId id = this->writeInterfaceBlock(intf);
2547 if ((intf.fVariable->fModifiers.fFlags & Modifiers::kIn_Flag) ||
2548 (intf.fVariable->fModifiers.fFlags & Modifiers::kOut_Flag)) {
2549 interfaceVars.push_back(id);
2550 }
2551 }
2552 }
2553 for (size_t i = 0; i < program.fElements.size(); i++) {
2554 if (program.fElements[i]->fKind == ProgramElement::kVar_Kind) {
2555 this->writeGlobalVars(((VarDeclaration&) *program.fElements[i]), bod y);
2556 }
2557 }
2558 for (size_t i = 0; i < program.fElements.size(); i++) {
2559 if (program.fElements[i]->fKind == ProgramElement::kFunction_Kind) {
2560 this->writeFunction(((FunctionDefinition&) *program.fElements[i]), b ody);
2561 }
2562 }
2563 std::shared_ptr<FunctionDeclaration> main = nullptr;
2564 for (auto entry : fFunctionMap) {
2565 if (entry.first->fName == "main") {
2566 main = entry.first;
2567 }
2568 }
2569 ASSERT(main);
2570 for (auto entry : fVariableMap) {
2571 std::shared_ptr<Variable> var = entry.first;
2572 if (var->fStorage == Variable::kGlobal_Storage &&
2573 ((var->fModifiers.fFlags & Modifiers::kIn_Flag) ||
2574 (var->fModifiers.fFlags & Modifiers::kOut_Flag))) {
2575 interfaceVars.push_back(entry.second);
2576 }
2577 }
2578 this->writeCapabilities(out);
2579 this->writeInstruction(SpvOpExtInstImport, fGLSLExtendedInstructions, "GLSL. std.450", out);
2580 this->writeInstruction(SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemor yModelGLSL450, out);
2581 this->writeOpCode(SpvOpEntryPoint, (SpvId) (3 + (strlen(main->fName.c_str()) + 4) / 4) +
2582 (int32_t) interfaceVars.size(), out);
2583 switch (program.fKind) {
2584 case Program::kVertex_Kind:
2585 this->writeWord(SpvExecutionModelVertex, out);
2586 break;
2587 case Program::kFragment_Kind:
2588 this->writeWord(SpvExecutionModelFragment, out);
2589 break;
2590 }
2591 this->writeWord(fFunctionMap[main], out);
2592 this->writeString(main->fName.c_str(), out);
2593 for (int var : interfaceVars) {
2594 this->writeWord(var, out);
2595 }
2596 if (program.fKind == Program::kFragment_Kind) {
2597 this->writeInstruction(SpvOpExecutionMode,
2598 fFunctionMap[main],
2599 SpvExecutionModeOriginUpperLeft,
2600 out);
2601 }
2602 for (size_t i = 0; i < program.fElements.size(); i++) {
2603 if (program.fElements[i]->fKind == ProgramElement::kExtension_Kind) {
2604 this->writeInstruction(SpvOpSourceExtension,
2605 ((Extension&) *program.fElements[i]).fName.c_ str(),
2606 out);
2607 }
2608 }
2609
2610 out << fNameBuffer.str();
2611 out << fDecorationBuffer.str();
2612 out << fConstantBuffer.str();
2613 out << fExternalFunctionsBuffer.str();
2614 out << body.str();
2615 }
2616
2617 void SPIRVCodeGenerator::generateCode(Program& program, std::ostream& out) {
2618 this->writeWord(SpvMagicNumber, out);
2619 this->writeWord(SpvVersion, out);
2620 this->writeWord(SKSL_MAGIC, out);
2621 std::stringstream buffer;
2622 this->writeInstructions(program, buffer);
2623 this->writeWord(fIdCount, out);
2624 this->writeWord(0, out); // reserved, always zero
2625 out << buffer.str();
2626 }
2627
2628 }
OLDNEW
« no previous file with comments | « src/sksl/SkSLSPIRVCodeGenerator.h ('k') | src/sksl/SkSLToken.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698