Debian Codegraph @

src/sksl/ir/SkSLType.h

raw
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 #ifndef SKSL_TYPE
9 #define SKSL_TYPE
10
11 #include "include/core/SkSpan.h"
12 #include "include/core/SkTypes.h"
13 #include "include/private/base/SkTArray.h"
14 #include "src/sksl/SkSLDefines.h"
15 #include "src/sksl/SkSLPosition.h"
16 #include "src/sksl/ir/SkSLIRNode.h"
17 #include "src/sksl/ir/SkSLLayout.h"
18 #include "src/sksl/ir/SkSLModifierFlags.h"
19 #include "src/sksl/ir/SkSLSymbol.h"
20 #include "src/sksl/spirv.h"
21
22 #include <cmath>
23 #include <cstddef>
24 #include <cstdint>
25 #include <cstring>
26 #include <memory>
27 #include <string>
28 #include <string_view>
29 #include <tuple>
30
31 // IWYU wants this, but it's C++20 and beyond. We can remove
32 // this guard once C++ core is allowed to use C++20
33 #if __cplusplus >= 202002L
34 #include <compare>
35 #endif
36
37 namespace SkSL {
38
39 class Context;
40 class Expression;
41 class SymbolTable;
42 class Type;
43
44 struct CoercionCost {
45 static CoercionCost Free() { return { 0, 0, false }; }
46 static CoercionCost Normal(int cost) { return { cost, 0, false }; }
47 static CoercionCost Narrowing(int cost) { return { 0, cost, false }; }
48 static CoercionCost Impossible() { return { 0, 0, true }; }
49
50 bool isPossible(bool allowNarrowing) const {
51 return !fImpossible && (fNarrowingCost == 0 || allowNarrowing);
52 }
53
54 // Addition of two costs. Saturates at Impossible().
55 CoercionCost operator+(CoercionCost rhs) const {
56 if (fImpossible || rhs.fImpossible) {
57 return Impossible();
58 }
59 return { fNormalCost + rhs.fNormalCost, fNarrowingCost + rhs.fNarrowingCost, false };
60 }
61
62 bool operator<(CoercionCost rhs) const {
63 return std::tie( fImpossible, fNarrowingCost, fNormalCost) <
64 std::tie(rhs.fImpossible, rhs.fNarrowingCost, rhs.fNormalCost);
65 }
66
67 bool operator<=(CoercionCost rhs) const {
68 return std::tie( fImpossible, fNarrowingCost, fNormalCost) <=
69 std::tie(rhs.fImpossible, rhs.fNarrowingCost, rhs.fNormalCost);
70 }
71
72 int fNormalCost;
73 int fNarrowingCost;
74 bool fImpossible;
75 };
76
77 /**
78 * Represents a single field in a struct type.
79 */
80 struct Field {
81 Field(Position pos, Layout layout, ModifierFlags flags, std::string_view name, const Type* type)
82 : fPosition(pos)
83 , fLayout(layout)
84 , fModifierFlags(flags)
85 , fName(name)
86 , fType(type) {}
87
88 std::string description() const;
89
90 Position fPosition;
91 Layout fLayout;
92 ModifierFlags fModifierFlags;
93 std::string_view fName;
94 const Type* fType;
95 };
96
97 /**
98 * Represents a type, such as int or float4.
99 */
100 class Type : public Symbol {
101 public:
102 inline static constexpr Kind kIRNodeKind = Kind::kType;
103 inline static constexpr int kMaxAbbrevLength = 3;
104 // Represents unspecified array dimensions, as in `int[]`.
105 inline static constexpr int kUnsizedArray = -1;
106
107 enum class TypeKind : int8_t {
108 kArray,
109 kAtomic,
110 kGeneric,
111 kLiteral,
112 kMatrix,
113 kOther,
114 kSampler,
115 kSeparateSampler,
116 kScalar,
117 kStruct,
118 kTexture,
119 kVector,
120 kVoid,
121
122 // Types that represent stages in the Skia pipeline
123 kColorFilter,
124 kShader,
125 kBlender,
126 };
127
128 enum class NumberKind : int8_t {
129 kFloat,
130 kSigned,
131 kUnsigned,
132 kBoolean,
133 kNonnumeric
134 };
135
136 enum class TextureAccess : int8_t {
137 kSample, // `kSample` access level allows both sampling and reading
138 kRead,
139 kWrite,
140 kReadWrite,
141 };
142
143 Type(const Type& other) = delete;
144
145 /** Creates an array type. `columns` may be kUnsizedArray. */
146 static std::unique_ptr<Type> MakeArrayType(const Context& context, std::string_view name,
147 const Type& componentType, int columns);
148
149 /** Converts a component type and a size (float, 10) into an array name ("float[10]"). */
150 std::string getArrayName(int arraySize) const;
151
152 /**
153 * Creates an alias which maps to another type.
154 */
155 static std::unique_ptr<Type> MakeAliasType(std::string_view name, const Type& targetType);
156
157 /**
158 * Create a generic type which maps to the listed types--e.g. $genType is a generic type which
159 * can match float, float2, float3 or float4.
160 */
161 static std::unique_ptr<Type> MakeGenericType(const char* name,
162 SkSpan<const Type* const> types,
163 const Type* slotType);
164
165 /** Create a type for literal scalars. */
166 static std::unique_ptr<Type> MakeLiteralType(const char* name, const Type& scalarType,
167 int8_t priority);
168
169 /** Create a matrix type. */
170 static std::unique_ptr<Type> MakeMatrixType(std::string_view name, const char* abbrev,
171 const Type& componentType, int columns,
172 int8_t rows);
173
174 /** Create a sampler type. */
175 static std::unique_ptr<Type> MakeSamplerType(const char* name, const Type& textureType);
176
177 /** Create a scalar type. */
178 static std::unique_ptr<Type> MakeScalarType(std::string_view name, const char* abbrev,
179 Type::NumberKind numberKind, int8_t priority,
180 int8_t bitWidth);
181
182 /**
183 * Create a "special" type with the given name, abbreviation, and TypeKind.
184 */
185 static std::unique_ptr<Type> MakeSpecialType(const char* name, const char* abbrev,
186 Type::TypeKind typeKind);
187
188 /**
189 * Creates a struct type with the given fields. Reports an error if the struct is not
190 * well-formed.
191 */
192 static std::unique_ptr<Type> MakeStructType(const Context& context,
193 Position pos,
194 std::string_view name,
195 skia_private::TArray<Field> fields,
196 bool interfaceBlock = false);
197
198 /** Create a texture type. */
199 static std::unique_ptr<Type> MakeTextureType(const char* name, SpvDim_ dimensions, bool isDepth,
200 bool isArrayedTexture, bool isMultisampled,
201 TextureAccess textureAccess);
202
203 /** Create a vector type. */
204 static std::unique_ptr<Type> MakeVectorType(std::string_view name, const char* abbrev,
205 const Type& componentType, int columns);
206
207 /** Create an atomic type. */
208 static std::unique_ptr<Type> MakeAtomicType(std::string_view name, const char* abbrev);
209
210 template <typename T>
211 bool is() const {
212 return this->typeKind() == T::kTypeKind;
213 }
214
215 template <typename T>
216 const T& as() const {
217 SkASSERT(this->is<T>());
218 return static_cast<const T&>(*this);
219 }
220
221 template <typename T>
222 T& as() {
223 SkASSERT(this->is<T>());
224 return static_cast<T&>(*this);
225 }
226
227 /** Creates a clone of this Type, if needed, and inserts it into a different symbol table. */
228 const Type* clone(const Context& context, SymbolTable* symbolTable) const;
229
230 /**
231 * Returns true if this type is known to come from BuiltinTypes, or is declared in a module. If
232 * this returns true, the Type will always be available in the root SymbolTable and never needs
233 * to be copied to migrate an Expression from one location to another. If it returns false, the
234 * Type might not exist in a separate SymbolTable and you'll need to consider cloning it.
235 */
236 virtual bool isBuiltin() const {
237 return true;
238 }
239
240 std::string displayName() const {
241 return std::string(this->scalarTypeForLiteral().name());
242 }
243
244 std::string description() const override {
245 return this->displayName();
246 }
247
248 /** Returns true if the program supports this type. Strict ES2 programs can't use ES3 types. */
249 bool isAllowedInES2(const Context& context) const;
250
251 /** Returns true if this type is legal to use in a strict-ES2 program. */
252 virtual bool isAllowedInES2() const {
253 return true;
254 }
255
256 /**
257 * Returns true if this type is legal to use as a uniform. If false is returned, the
258 * `errorPosition` field may be populated; if it is, this position can be used to emit an extra
259 * diagnostic "caused by: <a field>" for nested types.
260 * Note that runtime effects enforce additional, much stricter rules about uniforms; these
261 * limitations are not handled here.
262 */
263 virtual bool isAllowedInUniform(Position* errorPosition = nullptr) const {
264 // We don't allow samplers, textures or atomics to be marked as uniforms.
265 // This rules out all opaque types.
266 return !this->isOpaque();
267 }
268
269 /** If this is an alias, returns the underlying type, otherwise returns this. */
270 virtual const Type& resolve() const {
271 return *this;
272 }
273
274 /** Returns true if these types are equal after alias resolution. */
275 virtual bool matches(const Type& that) const {
276 return &this->resolve() == &that.resolve();
277 }
278
279 /**
280 * Returns an abbreviated name of the type, meant for name-mangling. (e.g. float4x4 -> f44)
281 */
282 const char* abbreviatedName() const {
283 return fAbbreviatedName;
284 }
285
286 /**
287 * Returns the category (scalar, vector, matrix, etc.) of this type.
288 */
289 TypeKind typeKind() const {
290 return fTypeKind;
291 }
292
293 /**
294 * Returns the NumberKind of this type (always kNonnumeric for non-scalar values).
295 */
296 virtual NumberKind numberKind() const {
297 return NumberKind::kNonnumeric;
298 }
299
300 /**
301 * Returns true if this type is a bool.
302 */
303 bool isBoolean() const {
304 return this->numberKind() == NumberKind::kBoolean;
305 }
306
307 /**
308 * Returns true if this is a numeric scalar type.
309 */
310 bool isNumber() const {
311 switch (this->numberKind()) {
312 case NumberKind::kFloat:
313 case NumberKind::kSigned:
314 case NumberKind::kUnsigned:
315 return true;
316 default:
317 return false;
318 }
319 }
320
321 /**
322 * Returns true if this is a floating-point scalar type (float or half).
323 */
324 bool isFloat() const {
325 return this->numberKind() == NumberKind::kFloat;
326 }
327
328 /**
329 * Returns true if this is a signed scalar type (int or short).
330 */
331 bool isSigned() const {
332 return this->numberKind() == NumberKind::kSigned;
333 }
334
335 /**
336 * Returns true if this is an unsigned scalar type (uint or ushort).
337 */
338 bool isUnsigned() const {
339 return this->numberKind() == NumberKind::kUnsigned;
340 }
341
342 /**
343 * Returns true if this is a signed or unsigned integer.
344 */
345 bool isInteger() const {
346 switch (this->numberKind()) {
347 case NumberKind::kSigned:
348 case NumberKind::kUnsigned:
349 return true;
350 default:
351 return false;
352 }
353 }
354
355 /**
356 * Returns true if this is an "opaque type" (an external object which the shader references in
357 * some fashion). https://www.khronos.org/opengl/wiki/Data_Type_(GLSL)#Opaque_types
358 */
359 bool isOpaque() const {
360 switch (fTypeKind) {
361 case TypeKind::kAtomic:
362 case TypeKind::kBlender:
363 case TypeKind::kColorFilter:
364 case TypeKind::kSampler:
365 case TypeKind::kSeparateSampler:
366 case TypeKind::kShader:
367 case TypeKind::kTexture:
368 return true;
369 default:
370 return false;
371 }
372 }
373
374 /**
375 * Returns true if this is a storage texture.
376 */
377 bool isStorageTexture() const {
378 return fTypeKind == TypeKind::kTexture && this->dimensions() != SpvDimSubpassData;
379 }
380
381 /**
382 * Returns the "priority" of a number type, in order of float > half > int > short.
383 * When operating on two number types, the result is the higher-priority type.
384 */
385 virtual int priority() const {
386 SkDEBUGFAIL("not a number type");
387 return -1;
388 }
389
390 /**
391 * Returns true if an instance of this type can be freely coerced (implicitly converted) to
392 * another type.
393 */
394 bool canCoerceTo(const Type& other, bool allowNarrowing) const {
395 return this->coercionCost(other).isPossible(allowNarrowing);
396 }
397
398 /**
399 * Determines the "cost" of coercing (implicitly converting) this type to another type. The cost
400 * is a number with no particular meaning other than that lower costs are preferable to higher
401 * costs. Returns INT_MAX if the coercion is not possible.
402 */
403 CoercionCost coercionCost(const Type& other) const;
404
405 /**
406 * For matrices and vectors, returns the type of individual cells (e.g. mat2 has a component
407 * type of Float). For arrays, returns the base type. For all other types, returns the type
408 * itself.
409 */
410 virtual const Type& componentType() const {
411 return *this;
412 }
413
414 /**
415 * For matrix types, returns the type of a single column (`m[n]`). Asserts for all other types.
416 */
417 const Type& columnType(const Context& context) const {
418 return this->componentType().toCompound(context, this->rows(), /*rows=*/1);
419 }
420
421 /**
422 * For texture samplers, returns the type of texture it samples (e.g., sampler2D has
423 * a texture type of texture2D).
424 */
425 virtual const Type& textureType() const {
426 SkDEBUGFAIL("not a sampler type");
427 return *this;
428 }
429
430 /**
431 * For matrices and vectors, returns the number of columns (e.g. both mat3 and float3 return 3).
432 * For scalars, returns 1. For arrays, returns either the size of the array (if known) or -1.
433 * For all other types, causes an assertion failure.
434 */
435 virtual int columns() const {
436 SkDEBUGFAIL("type does not have columns");
437 return -1;
438 }
439
440 /**
441 * For matrices, returns the number of rows (e.g. mat2x4 returns 4). For vectors and scalars,
442 * returns 1. For all other types, causes an assertion failure.
443 */
444 virtual int rows() const {
445 SkDEBUGFAIL("type does not have rows");
446 return -1;
447 }
448
449 /** Returns the minimum value that can fit in the type. */
450 virtual double minimumValue() const {
451 SkDEBUGFAIL("type does not have a minimum value");
452 return -INFINITY;
453 }
454
455 virtual double maximumValue() const {
456 SkDEBUGFAIL("type does not have a maximum value");
457 return +INFINITY;
458 }
459
460 /**
461 * Returns the number of scalars needed to hold this type.
462 */
463 virtual size_t slotCount() const {
464 return 0;
465 }
466
467 /**
468 * Returns the type of the value in the nth slot. For scalar, vector and matrix types, should
469 * always match `componentType()`.
470 */
471 virtual const Type& slotType(size_t) const {
472 return *this;
473 }
474
475 virtual SkSpan<const Field> fields() const {
476 SK_ABORT("Internal error: not a struct");
477 }
478
479 /**
480 * For generic types, returns the types that this generic type can substitute for.
481 */
482 virtual SkSpan<const Type* const> coercibleTypes() const {
483 SkDEBUGFAIL("Internal error: not a generic type");
484 return {};
485 }
486
487 virtual SpvDim_ dimensions() const {
488 SkDEBUGFAIL("Internal error: not a texture type");
489 return SpvDim1D;
490 }
491
492 virtual bool isDepth() const {
493 SkDEBUGFAIL("Internal error: not a texture type");
494 return false;
495 }
496
497 virtual bool isArrayedTexture() const {
498 SkDEBUGFAIL("Internal error: not a texture type");
499 return false;
500 }
501
502 bool isVoid() const {
503 return fTypeKind == TypeKind::kVoid;
504 }
505
506 bool isGeneric() const {
507 return fTypeKind == TypeKind::kGeneric;
508 }
509
510 bool isSampler() const {
511 return fTypeKind == TypeKind::kSampler;
512 }
513
514 bool isAtomic() const {
515 return this->typeKind() == TypeKind::kAtomic;
516 }
517
518 virtual bool isScalar() const {
519 return false;
520 }
521
522 virtual bool isLiteral() const {
523 return false;
524 }
525
526 virtual const Type& scalarTypeForLiteral() const {
527 return *this;
528 }
529
530 virtual bool isVector() const {
531 return false;
532 }
533
534 virtual bool isMatrix() const {
535 return false;
536 }
537
538 virtual bool isArray() const {
539 return false;
540 }
541
542 virtual bool isUnsizedArray() const {
543 return false;
544 }
545
546 virtual bool isStruct() const {
547 return false;
548 }
549
550 virtual bool isInterfaceBlock() const {
551 return false;
552 }
553
554 // Is this type something that can be bound & sampled from an SkRuntimeEffect?
555 // Includes types that represent stages of the Skia pipeline (colorFilter, shader, blender).
556 bool isEffectChild() const {
557 return fTypeKind == TypeKind::kColorFilter ||
558 fTypeKind == TypeKind::kShader ||
559 fTypeKind == TypeKind::kBlender;
560 }
561
562 virtual bool isMultisampled() const {
563 SkDEBUGFAIL("not a texture type");
564 return false;
565 }
566
567 virtual TextureAccess textureAccess() const {
568 SkDEBUGFAIL("not a texture type");
569 return TextureAccess::kSample;
570 }
571
572 bool hasPrecision() const {
573 return this->componentType().isNumber() || this->isSampler();
574 }
575
576 bool highPrecision() const {
577 return this->bitWidth() >= 32;
578 }
579
580 virtual int bitWidth() const {
581 return 0;
582 }
583
584 virtual bool isOrContainsArray() const {
585 return false;
586 }
587
588 virtual bool isOrContainsUnsizedArray() const {
589 return false;
590 }
591
592 virtual bool isOrContainsAtomic() const {
593 return false;
594 }
595
596 virtual bool isOrContainsBool() const {
597 return false;
598 }
599
600 /**
601 * Returns the corresponding vector or matrix type with the specified number of columns and
602 * rows.
603 */
604 const Type& toCompound(const Context& context, int columns, int rows) const;
605
606 /**
607 * Returns a type which honors the precision and access-level qualifiers set in ModifierFlags.
608 * For example:
609 * - Modifier `mediump` + Type `float2`: Type `half2`
610 * - Modifier `readonly` + Type `texture2D`: Type `readonlyTexture2D`
611 * Generates an error if the qualifiers don't make sense (`highp bool`, `writeonly MyStruct`)
612 */
613 const Type* applyQualifiers(const Context& context,
614 ModifierFlags* modifierFlags,
615 Position pos) const;
616
617 /**
618 * Coerces the passed-in expression to this type. If the types are incompatible, reports an
619 * error and returns null.
620 */
621 std::unique_ptr<Expression> coerceExpression(std::unique_ptr<Expression> expr,
622 const Context& context) const;
623
624 /** Detects any IntLiterals in the expression which can't fit in this type. */
625 bool checkForOutOfRangeLiteral(const Context& context, const Expression& expr) const;
626
627 /** Checks if `value` can fit in this type. The type must be scalar. */
628 bool checkForOutOfRangeLiteral(const Context& context, double value, Position pos) const;
629
630 /**
631 * Reports errors and returns false if this type cannot be used as the base type for an array.
632 */
633 bool checkIfUsableInArray(const Context& context, Position arrayPos) const;
634
635 /**
636 * Verifies that the expression is a valid constant array size for this type. Returns the array
637 * size, or reports errors and returns zero if the expression isn't a valid literal value.
638 */
639 SKSL_INT convertArraySize(const Context& context,
640 Position arrayPos,
641 std::unique_ptr<Expression> size) const;
642
643 SKSL_INT convertArraySize(const Context& context,
644 Position arrayPos,
645 Position sizePos,
646 SKSL_INT size) const;
647
648 protected:
649 Type(std::string_view name, const char* abbrev, TypeKind kind, Position pos = Position())
650 : INHERITED(pos, kIRNodeKind, name)
651 , fTypeKind(kind) {
652 SkASSERT(strlen(abbrev) <= kMaxAbbrevLength);
653 strcpy(fAbbreviatedName, abbrev);
654 }
655
656 const Type* applyPrecisionQualifiers(const Context& context,
657 ModifierFlags* modifierFlags,
658 Position pos) const;
659
660 const Type* applyAccessQualifiers(const Context& context,
661 ModifierFlags* modifierFlags,
662 Position pos) const;
663
664 /** Only structs and arrays can be created in code; all other types exist in the root. */
665 bool isInRootSymbolTable() const {
666 return !(this->isArray() || this->isStruct());
667 }
668
669 /** If the type is a struct, returns the depth of the struct's most deeply-nested field. */
670 virtual int structNestingDepth() const {
671 return 0;
672 }
673
674 private:
675 using INHERITED = Symbol;
676
677 char fAbbreviatedName[kMaxAbbrevLength + 1] = {};
678 TypeKind fTypeKind;
679 };
680
681 } // namespace SkSL
682
683 #endif