Debian Codegraph @

src/sksl/ir/SkSLFunctionDeclaration.cpp

raw
1 /*
2 * Copyright 2021 Google LLC.
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 "src/sksl/ir/SkSLFunctionDeclaration.h"
9
10 #include "include/core/SkSpan.h"
11 #include "include/core/SkTypes.h"
12 #include "include/private/base/SkTo.h"
13 #include "src/base/SkEnumBitMask.h"
14 #include "src/base/SkStringView.h"
15 #include "src/sksl/SkSLBuiltinTypes.h"
16 #include "src/sksl/SkSLContext.h"
17 #include "src/sksl/SkSLDefines.h"
18 #include "src/sksl/SkSLErrorReporter.h"
19 #include "src/sksl/SkSLPosition.h"
20 #include "src/sksl/SkSLProgramKind.h"
21 #include "src/sksl/SkSLProgramSettings.h"
22 #include "src/sksl/SkSLString.h"
23 #include "src/sksl/ir/SkSLExpression.h"
24 #include "src/sksl/ir/SkSLLayout.h"
25 #include "src/sksl/ir/SkSLModifierFlags.h"
26 #include "src/sksl/ir/SkSLModifiers.h"
27 #include "src/sksl/ir/SkSLSymbolTable.h"
28 #include "src/sksl/ir/SkSLType.h"
29 #include "src/sksl/ir/SkSLVariable.h"
30
31 #include <cstddef>
32 #include <utility>
33
34 using namespace skia_private;
35
36 namespace SkSL {
37
38 static bool check_modifiers(const Context& context, Position pos, ModifierFlags modifierFlags) {
39 const ModifierFlags permitted = ModifierFlag::kInline |
40 ModifierFlag::kNoInline |
41 (context.fConfig->isBuiltinCode() ? ModifierFlag::kES3 |
42 ModifierFlag::kPure |
43 ModifierFlag::kExport
44 : ModifierFlag::kNone);
45 modifierFlags.checkPermittedFlags(context, pos, permitted);
46 if (modifierFlags.isInline() && modifierFlags.isNoInline()) {
47 context.fErrors->error(pos, "functions cannot be both 'inline' and 'noinline'");
48 return false;
49 }
50 return true;
51 }
52
53 static bool check_return_type(const Context& context, Position pos, const Type& returnType) {
54 ErrorReporter& errors = *context.fErrors;
55 if (returnType.isArray()) {
56 errors.error(pos, "functions may not return type '" + returnType.displayName() + "'");
57 return false;
58 }
59 if (context.fConfig->strictES2Mode() && returnType.isOrContainsArray()) {
60 errors.error(pos, "functions may not return structs containing arrays");
61 return false;
62 }
63 if (!context.fConfig->isBuiltinCode() && returnType.componentType().isOpaque()) {
64 errors.error(pos, "functions may not return opaque type '" + returnType.displayName() +
65 "'");
66 return false;
67 }
68 return true;
69 }
70
71 static bool check_parameters(const Context& context,
72 TArray<std::unique_ptr<Variable>>& parameters,
73 ModifierFlags modifierFlags,
74 IntrinsicKind intrinsicKind) {
75 // Check modifiers on each function parameter.
76 for (auto& param : parameters) {
77 const Type& type = param->type();
78 ModifierFlags permittedFlags = ModifierFlag::kConst | ModifierFlag::kIn;
79 LayoutFlags permittedLayoutFlags = LayoutFlag::kNone;
80 if (!type.isOpaque()) {
81 permittedFlags |= ModifierFlag::kOut;
82 }
83 if (type.isStorageTexture()) {
84 // We allow `readonly`, `writeonly` and `layout(pixel-format)` on storage textures.
85 permittedFlags |= ModifierFlag::kReadOnly | ModifierFlag::kWriteOnly;
86 permittedLayoutFlags |= LayoutFlag::kAllPixelFormats;
87
88 // Intrinsics are allowed to accept any pixel format, but user code must explicitly
89 // specify a pixel format like `layout(rgba32f)`.
90 if (intrinsicKind == kNotIntrinsic &&
91 !(param->layout().fFlags & LayoutFlag::kAllPixelFormats)) {
92 context.fErrors->error(param->fPosition, "storage texture parameters must specify "
93 "a pixel format layout-qualifier");
94 return false;
95 }
96 }
97 param->modifierFlags().checkPermittedFlags(context, param->modifiersPosition(),
98 permittedFlags);
99 param->layout().checkPermittedLayout(context, param->modifiersPosition(),
100 permittedLayoutFlags);
101
102 // Public Runtime Effects aren't allowed to pass shader/colorFilter/blender types to
103 // function calls. You can pass other opaque types to functions safely; this restriction is
104 // specific to "child" objects.
105 if (!ProgramConfig::AllowsPrivateIdentifiers(context.fConfig->fKind) &&
106 type.isEffectChild()) {
107 context.fErrors->error(param->fPosition, "parameters of type '" + type.displayName() +
108 "' not allowed");
109 return false;
110 }
111
112 // Pure functions should not change any state, and should be safe to eliminate if their
113 // result is not used; this is incompatible with out-parameters, so we forbid it here.
114 // (We don't exhaustively guard against pure functions changing global state in other ways,
115 // though, since they aren't allowed in user code.)
116 if (modifierFlags.isPure() && (param->modifierFlags() & ModifierFlag::kOut)) {
117 context.fErrors->error(param->modifiersPosition(),
118 "pure functions cannot have out parameters");
119 return false;
120 }
121 }
122 return true;
123 }
124
125 static bool type_is_valid_for_color(const Type& type) {
126 return type.isVector() && type.columns() == 4 && type.componentType().isFloat();
127 }
128
129 static bool type_is_valid_for_coords(const Type& type) {
130 return type.isVector() && type.highPrecision() && type.columns() == 2 &&
131 type.componentType().isFloat();
132 }
133
134 static bool check_main_signature(const Context& context, Position pos, const Type& returnType,
135 TArray<std::unique_ptr<Variable>>& parameters) {
136 ErrorReporter& errors = *context.fErrors;
137 ProgramKind kind = context.fConfig->fKind;
138
139 auto typeIsValidForAttributes = [](const Type& type) {
140 return type.isStruct() && type.name() == "Attributes";
141 };
142
143 auto typeIsValidForVaryings = [](const Type& type) {
144 return type.isStruct() && type.name() == "Varyings";
145 };
146
147 auto paramIsCoords = [&](int idx) {
148 const Variable& p = *parameters[idx];
149 return type_is_valid_for_coords(p.type()) && p.modifierFlags() == ModifierFlag::kNone;
150 };
151
152 auto paramIsColor = [&](int idx) {
153 const Variable& p = *parameters[idx];
154 return type_is_valid_for_color(p.type()) && p.modifierFlags() == ModifierFlag::kNone;
155 };
156
157 auto paramIsConstInAttributes = [&](int idx) {
158 const Variable& p = *parameters[idx];
159 return typeIsValidForAttributes(p.type()) && p.modifierFlags() == ModifierFlag::kConst;
160 };
161
162 auto paramIsConstInVaryings = [&](int idx) {
163 const Variable& p = *parameters[idx];
164 return typeIsValidForVaryings(p.type()) && p.modifierFlags() == ModifierFlag::kConst;
165 };
166
167 auto paramIsOutColor = [&](int idx) {
168 const Variable& p = *parameters[idx];
169 return type_is_valid_for_color(p.type()) && p.modifierFlags() == ModifierFlag::kOut;
170 };
171
172 switch (kind) {
173 case ProgramKind::kRuntimeColorFilter:
174 case ProgramKind::kPrivateRuntimeColorFilter: {
175 // (half4|float4) main(half4|float4)
176 if (!type_is_valid_for_color(returnType)) {
177 errors.error(pos, "'main' must return: 'vec4', 'float4', or 'half4'");
178 return false;
179 }
180 bool validParams = (parameters.size() == 1 && paramIsColor(0));
181 if (!validParams) {
182 errors.error(pos, "'main' parameter must be 'vec4', 'float4', or 'half4'");
183 return false;
184 }
185 break;
186 }
187 case ProgramKind::kRuntimeShader:
188 case ProgramKind::kPrivateRuntimeShader: {
189 // (half4|float4) main(float2)
190 if (!type_is_valid_for_color(returnType)) {
191 errors.error(pos, "'main' must return: 'vec4', 'float4', or 'half4'");
192 return false;
193 }
194 if (!(parameters.size() == 1 && paramIsCoords(0))) {
195 errors.error(pos, "'main' parameter must be 'float2' or 'vec2'");
196 return false;
197 }
198 break;
199 }
200 case ProgramKind::kRuntimeBlender:
201 case ProgramKind::kPrivateRuntimeBlender: {
202 // (half4|float4) main(half4|float4, half4|float4)
203 if (!type_is_valid_for_color(returnType)) {
204 errors.error(pos, "'main' must return: 'vec4', 'float4', or 'half4'");
205 return false;
206 }
207 if (!(parameters.size() == 2 && paramIsColor(0) && paramIsColor(1))) {
208 errors.error(pos, "'main' parameters must be (vec4|float4|half4, "
209 "vec4|float4|half4)");
210 return false;
211 }
212 break;
213 }
214 case ProgramKind::kMeshVertex: {
215 // Varyings main(const Attributes)
216 if (!typeIsValidForVaryings(returnType)) {
217 errors.error(pos, "'main' must return 'Varyings'.");
218 return false;
219 }
220 if (!(parameters.size() == 1 && paramIsConstInAttributes(0))) {
221 errors.error(pos, "'main' parameter must be 'const Attributes'.");
222 return false;
223 }
224 break;
225 }
226 case ProgramKind::kMeshFragment: {
227 // float2 main(const Varyings) -or- float2 main(const Varyings, out half4|float4)
228 if (!type_is_valid_for_coords(returnType)) {
229 errors.error(pos, "'main' must return: 'vec2' or 'float2'");
230 return false;
231 }
232 if (!((parameters.size() == 1 && paramIsConstInVaryings(0)) ||
233 (parameters.size() == 2 && paramIsConstInVaryings(0) && paramIsOutColor(1)))) {
234 errors.error(pos,
235 "'main' parameters must be (const Varyings, (out (half4|float4))?)");
236 return false;
237 }
238 break;
239 }
240 case ProgramKind::kFragment:
241 case ProgramKind::kGraphiteFragment: {
242 bool validParams = (parameters.size() == 0) ||
243 (parameters.size() == 1 && paramIsCoords(0));
244 if (!validParams) {
245 errors.error(pos, "shader 'main' must be main() or main(float2)");
246 return false;
247 }
248 break;
249 }
250 case ProgramKind::kVertex:
251 case ProgramKind::kGraphiteVertex:
252 case ProgramKind::kCompute:
253 if (!returnType.matches(*context.fTypes.fVoid)) {
254 errors.error(pos, "'main' must return 'void'");
255 return false;
256 }
257 if (parameters.size()) {
258 errors.error(pos, "shader 'main' must have zero parameters");
259 return false;
260 }
261 break;
262 }
263 return true;
264 }
265
266 /**
267 * Given a concrete type (`float3`) and a generic type (`$genType`), returns the index of the
268 * concrete type within the generic type's typelist. Returns -1 if there is no match.
269 */
270 static int find_generic_index(const Type& concreteType,
271 const Type& genericType,
272 bool allowNarrowing) {
273 SkSpan<const Type* const> genericTypes = genericType.coercibleTypes();
274 for (size_t index = 0; index < genericTypes.size(); ++index) {
275 if (concreteType.canCoerceTo(*genericTypes[index], allowNarrowing)) {
276 return index;
277 }
278 }
279 return -1;
280 }
281
282 /** Returns true if the types match, or if `concreteType` can be found in `maybeGenericType`. */
283 static bool type_generically_matches(const Type& concreteType, const Type& maybeGenericType) {
284 return maybeGenericType.isGeneric()
285 ? find_generic_index(concreteType, maybeGenericType, /*allowNarrowing=*/false) != -1
286 : concreteType.matches(maybeGenericType);
287 }
288
289 /**
290 * Checks a parameter list (params) against the parameters of a function that was declared earlier
291 * (otherParams). Returns true if they match, even if the parameters in `otherParams` contain
292 * generic types.
293 */
294 static bool parameters_match(SkSpan<const std::unique_ptr<Variable>> params,
295 SkSpan<Variable* const> otherParams) {
296 // If the param lists are different lengths, they're definitely not a match.
297 if (params.size() != otherParams.size()) {
298 return false;
299 }
300
301 // Figure out a consistent generic index (or bail if we find a contradiction).
302 int genericIndex = -1;
303 for (size_t i = 0; i < params.size(); ++i) {
304 const Type* paramType = &params[i]->type();
305 const Type* otherParamType = &otherParams[i]->type();
306
307 if (otherParamType->isGeneric()) {
308 int genericIndexForThisParam = find_generic_index(*paramType, *otherParamType,
309 /*allowNarrowing=*/false);
310 if (genericIndexForThisParam == -1) {
311 // The type wasn't a match for this generic at all; these params can't be a match.
312 return false;
313 }
314 if (genericIndex != -1 && genericIndex != genericIndexForThisParam) {
315 // The generic index mismatches from what we determined on a previous parameter.
316 return false;
317 }
318 genericIndex = genericIndexForThisParam;
319 }
320 }
321
322 // Now that we've determined a generic index (if we needed one), do a parameter check.
323 for (size_t i = 0; i < params.size(); i++) {
324 const Type* paramType = &params[i]->type();
325 const Type* otherParamType = &otherParams[i]->type();
326
327 // Make generic types concrete.
328 if (otherParamType->isGeneric()) {
329 SkASSERT(genericIndex != -1);
330 SkASSERT(genericIndex < (int)otherParamType->coercibleTypes().size());
331 otherParamType = otherParamType->coercibleTypes()[genericIndex];
332 }
333 // Detect type mismatches.
334 if (!paramType->matches(*otherParamType)) {
335 return false;
336 }
337 }
338 return true;
339 }
340
341 /**
342 * Checks for a previously existing declaration of this function, reporting errors if there is an
343 * incompatible symbol. Returns true and sets outExistingDecl to point to the existing declaration
344 * (or null if none) on success, returns false on error.
345 */
346 static bool find_existing_declaration(const Context& context,
347 Position pos,
348 ModifierFlags modifierFlags,
349 IntrinsicKind intrinsicKind,
350 std::string_view name,
351 TArray<std::unique_ptr<Variable>>& parameters,
352 Position returnTypePos,
353 const Type* returnType,
354 FunctionDeclaration** outExistingDecl) {
355 auto invalidDeclDescription = [&]() -> std::string {
356 TArray<Variable*> paramPtrs;
357 paramPtrs.reserve_exact(parameters.size());
358 for (std::unique_ptr<Variable>& param : parameters) {
359 paramPtrs.push_back(param.get());
360 }
361 return FunctionDeclaration(context,
362 pos,
363 modifierFlags,
364 name,
365 std::move(paramPtrs),
366 returnType,
367 intrinsicKind)
368 .description();
369 };
370
371 ErrorReporter& errors = *context.fErrors;
372 Symbol* entry = context.fSymbolTable->findMutable(name);
373 *outExistingDecl = nullptr;
374 if (entry) {
375 if (!entry->is<FunctionDeclaration>()) {
376 errors.error(pos, "symbol '" + std::string(name) + "' was already defined");
377 return false;
378 }
379 for (FunctionDeclaration* other = &entry->as<FunctionDeclaration>(); other;
380 other = other->mutableNextOverload()) {
381 SkASSERT(name == other->name());
382 if (!parameters_match(parameters, other->parameters())) {
383 continue;
384 }
385 if (!type_generically_matches(*returnType, other->returnType())) {
386 errors.error(returnTypePos, "functions '" + invalidDeclDescription() + "' and '" +
387 other->description() + "' differ only in return type");
388 return false;
389 }
390 for (int i = 0; i < parameters.size(); i++) {
391 if (parameters[i]->modifierFlags() != other->parameters()[i]->modifierFlags() ||
392 parameters[i]->layout() != other->parameters()[i]->layout()) {
393 errors.error(parameters[i]->fPosition,
394 "modifiers on parameter " + std::to_string(i + 1) +
395 " differ between declaration and definition");
396 return false;
397 }
398 }
399 if (other->isIntrinsic()) {
400 errors.error(pos, "duplicate definition of intrinsic function '" +
401 std::string(name) + "'");
402 return false;
403 }
404 if (modifierFlags != other->modifierFlags()) {
405 errors.error(pos, "functions '" + invalidDeclDescription() + "' and '" +
406 other->description() + "' differ only in modifiers");
407 return false;
408 }
409 *outExistingDecl = other;
410 break;
411 }
412 if (!*outExistingDecl && entry->as<FunctionDeclaration>().isMain()) {
413 errors.error(pos, "duplicate definition of 'main'");
414 return false;
415 }
416 }
417 return true;
418 }
419
420 FunctionDeclaration::FunctionDeclaration(const Context& context,
421 Position pos,
422 ModifierFlags modifierFlags,
423 std::string_view name,
424 TArray<Variable*> parameters,
425 const Type* returnType,
426 IntrinsicKind intrinsicKind)
427 : INHERITED(pos, kIRNodeKind, name, /*type=*/nullptr)
428 , fDefinition(nullptr)
429 , fParameters(std::move(parameters))
430 , fReturnType(returnType)
431 , fModifierFlags(modifierFlags)
432 , fIntrinsicKind(intrinsicKind)
433 , fModuleType(context.fConfig->fModuleType)
434 , fIsMain(name == "main") {
435 int builtinColorIndex = 0;
436 for (const Variable* param : fParameters) {
437 // None of the parameters are allowed to be be null.
438 SkASSERT(param);
439
440 // Keep track of arguments to main for runtime effects.
441 if (fIsMain) {
442 if (ProgramConfig::IsRuntimeShader(context.fConfig->fKind) ||
443 ProgramConfig::IsFragment(context.fConfig->fKind)) {
444 // If this is a runtime shader, a float2 param is supposed to be the coords.
445 // For testing purposes, we have .sksl inputs that are treated as both runtime
446 // effects and fragment shaders. To make that work, fragment shaders are allowed to
447 // have a coords parameter as well.
448 if (type_is_valid_for_coords(param->type())) {
449 fHasMainCoordsParameter = true;
450 }
451 } else if (ProgramConfig::IsRuntimeColorFilter(context.fConfig->fKind) ||
452 ProgramConfig::IsRuntimeBlender(context.fConfig->fKind)) {
453 // If this is a runtime color filter or blender, the params are an input color,
454 // followed by a destination color for blenders.
455 if (type_is_valid_for_color(param->type())) {
456 switch (builtinColorIndex++) {
457 case 0: fHasMainInputColorParameter = true; break;
458 case 1: fHasMainDestColorParameter = true; break;
459 default: /* unknown color parameter */ break;
460 }
461 }
462 }
463 }
464 }
465 }
466
467 FunctionDeclaration* FunctionDeclaration::Convert(const Context& context,
468 Position pos,
469 const Modifiers& modifiers,
470 std::string_view name,
471 TArray<std::unique_ptr<Variable>> parameters,
472 Position returnTypePos,
473 const Type* returnType) {
474 // No layout flag is permissible on a function.
475 modifiers.fLayout.checkPermittedLayout(context, pos,
476 /*permittedLayoutFlags=*/LayoutFlag::kNone);
477
478 // If requested, apply the `noinline` modifier to every function. This allows us to test Runtime
479 // Effects without any inlining, even when the code is later added to a paint.
480 ModifierFlags modifierFlags = modifiers.fFlags;
481 if (context.fConfig->fSettings.fForceNoInline) {
482 modifierFlags &= ~ModifierFlag::kInline;
483 modifierFlags |= ModifierFlag::kNoInline;
484 }
485
486 bool isMain = (name == "main");
487 IntrinsicKind intrinsicKind = context.fConfig->isBuiltinCode() ? FindIntrinsicKind(name)
488 : kNotIntrinsic;
489 FunctionDeclaration* decl = nullptr;
490 if (!check_modifiers(context, modifiers.fPosition, modifierFlags) ||
491 !check_return_type(context, returnTypePos, *returnType) ||
492 !check_parameters(context, parameters, modifierFlags, intrinsicKind) ||
493 (isMain && !check_main_signature(context, pos, *returnType, parameters)) ||
494 !find_existing_declaration(context, pos, modifierFlags, intrinsicKind, name, parameters,
495 returnTypePos, returnType, &decl)) {
496 return nullptr;
497 }
498 TArray<Variable*> finalParameters;
499 finalParameters.reserve_exact(parameters.size());
500 for (std::unique_ptr<Variable>& param : parameters) {
501 finalParameters.push_back(context.fSymbolTable->takeOwnershipOfSymbol(std::move(param)));
502 }
503 if (decl) {
504 return decl;
505 }
506 return context.fSymbolTable->add(
507 context,
508 std::make_unique<FunctionDeclaration>(context,
509 pos,
510 modifierFlags,
511 name,
512 std::move(finalParameters),
513 returnType,
514 intrinsicKind));
515 }
516
517 std::string FunctionDeclaration::mangledName() const {
518 if ((this->isBuiltin() && !this->definition()) || this->isMain()) {
519 // Builtins without a definition (like `sin` or `sqrt`) must use their real names.
520 return std::string(this->name());
521 }
522 // Built-in functions can have a $ prefix, which will fail to compile in GLSL. Remove the
523 // $ and add a unique mangling specifier, so user code can't conflict with the name.
524 std::string_view name = this->name();
525 const char* builtinMarker = "";
526 if (skstd::starts_with(name, '$')) {
527 name.remove_prefix(1);
528 builtinMarker = "Q"; // a unique, otherwise-unused mangle character
529 }
530 // Rename function to `funcname_returntypeparamtypes`.
531 std::string result = std::string(name) + "_" + builtinMarker +
532 this->returnType().abbreviatedName();
533 for (const Variable* p : this->parameters()) {
534 result += p->type().abbreviatedName();
535 }
536 return result;
537 }
538
539 std::string FunctionDeclaration::description() const {
540 std::string result = (fModifierFlags ? fModifierFlags.description() + " " : std::string()) +
541 this->returnType().displayName() + " " + std::string(this->name()) + "(";
542 auto separator = SkSL::String::Separator();
543 for (const Variable* p : this->parameters()) {
544 result += separator();
545 result += p->description();
546 }
547 result += ")";
548 return result;
549 }
550
551 bool FunctionDeclaration::matches(const FunctionDeclaration& f) const {
552 if (this->name() != f.name()) {
553 return false;
554 }
555 SkSpan<Variable* const> parameters = this->parameters();
556 SkSpan<Variable* const> otherParameters = f.parameters();
557 if (parameters.size() != otherParameters.size()) {
558 return false;
559 }
560 for (size_t i = 0; i < parameters.size(); i++) {
561 if (!parameters[i]->type().matches(otherParameters[i]->type())) {
562 return false;
563 }
564 }
565 return true;
566 }
567
568 bool FunctionDeclaration::determineFinalTypes(const ExpressionArray& arguments,
569 ParamTypes* outParameterTypes,
570 const Type** outReturnType) const {
571 SkSpan<Variable* const> parameters = this->parameters();
572 SkASSERT(SkToSizeT(arguments.size()) == parameters.size());
573
574 outParameterTypes->reserve_exact(arguments.size());
575 int genericIndex = -1;
576 for (int i = 0; i < arguments.size(); i++) {
577 // Non-generic parameters are final as-is.
578 const Type& parameterType = parameters[i]->type();
579 if (!parameterType.isGeneric()) {
580 outParameterTypes->push_back(&parameterType);
581 continue;
582 }
583 // We use the first generic parameter we find to lock in the generic index;
584 // e.g. if we find `float3` here, all `$genType`s will be assumed to be `float3`.
585 if (genericIndex == -1) {
586 genericIndex = find_generic_index(arguments[i]->type(), parameterType,
587 /*allowNarrowing=*/true);
588 if (genericIndex == -1) {
589 // The passed-in type wasn't a match for ANY of the generic possibilities.
590 // This function isn't a match at all.
591 return false;
592 }
593 }
594 outParameterTypes->push_back(parameterType.coercibleTypes()[genericIndex]);
595 }
596 // Apply the generic index to our return type.
597 const Type& returnType = this->returnType();
598 if (returnType.isGeneric()) {
599 if (genericIndex == -1) {
600 // We don't support functions with a generic return type and no other generics.
601 return false;
602 }
603 *outReturnType = returnType.coercibleTypes()[genericIndex];
604 } else {
605 *outReturnType = &returnType;
606 }
607 return true;
608 }
609
610 } // namespace SkSL