blob: 845c8343dde5f99776b3a035bc72c35b25fcfd22 [file] [log] [blame]
Ethan Nicholas371f6e12021-05-04 14:30:02 -04001/*
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 "src/sksl/SkSLCompiler.h"
11#include "src/sksl/SkSLIRGenerator.h"
12#include "src/sksl/ir/SkSLUnresolvedFunction.h"
13
14namespace SkSL {
15
John Stilesf96cb712021-05-05 22:17:04 -040016static IntrinsicKind identify_intrinsic(const String& functionName) {
17 #define SKSL_INTRINSIC(name) {#name, k_##name##_IntrinsicKind},
18 static const auto* kAllIntrinsics = new std::unordered_map<String, IntrinsicKind>{
19 SKSL_INTRINSIC_LIST
20 };
21 #undef SKSL_INTRINSIC
22
23 auto iter = kAllIntrinsics->find(functionName);
24 if (iter != kAllIntrinsics->end()) {
25 return iter->second;
26 }
27
28 return kNotIntrinsic;
29}
30
Ethan Nicholas371f6e12021-05-04 14:30:02 -040031static bool check_modifiers(const Context& context, int offset, const Modifiers& modifiers) {
32 IRGenerator::CheckModifiers(
33 context,
34 offset,
35 modifiers,
36 Modifiers::kHasSideEffects_Flag | Modifiers::kInline_Flag | Modifiers::kNoInline_Flag,
37 /*permittedLayoutFlags=*/0);
38 if ((modifiers.fFlags & Modifiers::kInline_Flag) &&
39 (modifiers.fFlags & Modifiers::kNoInline_Flag)) {
40 context.fErrors.error(offset, "functions cannot be both 'inline' and 'noinline'");
41 return false;
42 }
43 return true;
44}
45
46static bool check_return_type(const Context& context, int offset, const Type& returnType,
47 bool isBuiltin) {
48 ErrorReporter& errors = context.fErrors;
49 if (returnType.isArray()) {
50 errors.error(offset, "functions may not return type '" + returnType.displayName() + "'");
51 return false;
52 }
53 if (context.fConfig->strictES2Mode() && returnType.isOrContainsArray()) {
54 errors.error(offset, "functions may not return structs containing arrays");
55 return false;
56 }
57 if (!isBuiltin && !returnType.isVoid() && returnType.componentType().isOpaque()) {
58 errors.error(offset, "functions may not return opaque type '" + returnType.displayName() +
59 "'");
60 return false;
61 }
62 return true;
63}
64
John Stiles0b822792021-05-04 17:41:53 -040065static bool check_parameters(const Context& context,
Ethan Nicholas371f6e12021-05-04 14:30:02 -040066 std::vector<std::unique_ptr<Variable>>& parameters, bool isMain,
67 bool isBuiltin) {
68 auto typeIsValidForColor = [&](const Type& type) {
69 return type == *context.fTypes.fHalf4 || type == *context.fTypes.fFloat4;
70 };
71
John Stiles9c19b9f2021-06-10 09:43:35 -040072 // The first color parameter passed to main() is the input color; the second is the dest color.
John Stiles50d0d092021-06-09 17:24:31 -040073 static constexpr int kBuiltinColorIDs[] = {SK_INPUT_COLOR_BUILTIN, SK_DEST_COLOR_BUILTIN};
74 unsigned int builtinColorIndex = 0;
75
John Stiles9c19b9f2021-06-10 09:43:35 -040076 // Check modifiers on each function parameter.
Ethan Nicholas371f6e12021-05-04 14:30:02 -040077 for (auto& param : parameters) {
78 IRGenerator::CheckModifiers(context, param->fOffset, param->modifiers(),
79 Modifiers::kConst_Flag | Modifiers::kIn_Flag |
80 Modifiers::kOut_Flag, /*permittedLayoutFlags=*/0);
81 const Type& type = param->type();
82 // Only the (builtin) declarations of 'sample' are allowed to have shader/colorFilter or FP
83 // parameters. You can pass other opaque types to functions safely; this restriction is
84 // specific to "child" objects.
Brian Osman8c264792021-07-01 16:41:27 -040085 if (type.isEffectChild() && !isBuiltin) {
Ethan Nicholas371f6e12021-05-04 14:30:02 -040086 context.fErrors.error(param->fOffset, "parameters of type '" + type.displayName() +
87 "' not allowed");
88 return false;
89 }
90
91 Modifiers m = param->modifiers();
John Stilesbb2ef922021-07-26 08:32:07 -040092 if (isMain) {
John Stilesaddccaf2021-08-02 19:03:30 -040093 if (ProgramConfig::IsRuntimeEffect(context.fConfig->fKind)) {
John Stilesbb2ef922021-07-26 08:32:07 -040094 // We verify that the signature is fully correct later. For now, if this is a
95 // runtime effect of any flavor, a float2 param is supposed to be the coords, and a
96 // half4/float parameter is supposed to be the input or destination color:
97 if (type == *context.fTypes.fFloat2) {
98 m.fLayout.fBuiltin = SK_MAIN_COORDS_BUILTIN;
99 } else if (typeIsValidForColor(type) &&
100 builtinColorIndex < SK_ARRAY_COUNT(kBuiltinColorIDs)) {
101 m.fLayout.fBuiltin = kBuiltinColorIDs[builtinColorIndex++];
102 }
103 if (m.fLayout.fBuiltin) {
104 param->setModifiers(context.fModifiersPool->add(m));
105 }
106 } else if (context.fConfig->fKind == ProgramKind::kFragment) {
107 // For testing purposes, we have .sksl inputs that are treated as both runtime
108 // effects and fragment shaders. To make that work, fragment shaders are allowed to
109 // have a coords parameter. We turn it into sk_FragCoord.
110 if (type == *context.fTypes.fFloat2) {
111 m.fLayout.fBuiltin = SK_FRAGCOORD_BUILTIN;
112 param->setModifiers(context.fModifiersPool->add(m));
113 }
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400114 }
115 }
116 }
117 return true;
118}
119
120static bool check_main_signature(const Context& context, int offset, const Type& returnType,
121 std::vector<std::unique_ptr<Variable>>& parameters,
122 bool isBuiltin) {
123 ErrorReporter& errors = context.fErrors;
124 ProgramKind kind = context.fConfig->fKind;
125
126 auto typeIsValidForColor = [&](const Type& type) {
127 return type == *context.fTypes.fHalf4 || type == *context.fTypes.fFloat4;
128 };
129
130 auto paramIsCoords = [&](int idx) {
131 const Variable& p = *parameters[idx];
132 return p.type() == *context.fTypes.fFloat2 &&
133 p.modifiers().fFlags == 0 &&
134 p.modifiers().fLayout.fBuiltin == (kind == ProgramKind::kFragment
135 ? SK_FRAGCOORD_BUILTIN
136 : SK_MAIN_COORDS_BUILTIN);
137 };
138
John Stiles50d0d092021-06-09 17:24:31 -0400139 auto paramIsBuiltinColor = [&](int idx, int builtinID) {
140 const Variable& p = *parameters[idx];
141 return typeIsValidForColor(p.type()) &&
142 p.modifiers().fFlags == 0 &&
143 p.modifiers().fLayout.fBuiltin == builtinID;
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400144 };
145
John Stiles50d0d092021-06-09 17:24:31 -0400146 auto paramIsInputColor = [&](int n) { return paramIsBuiltinColor(n, SK_INPUT_COLOR_BUILTIN); };
147 auto paramIsDestColor = [&](int n) { return paramIsBuiltinColor(n, SK_DEST_COLOR_BUILTIN); };
148
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400149 switch (kind) {
150 case ProgramKind::kRuntimeColorFilter: {
151 // (half4|float4) main(half4|float4)
152 if (!typeIsValidForColor(returnType)) {
153 errors.error(offset, "'main' must return: 'vec4', 'float4', or 'half4'");
154 return false;
155 }
156 bool validParams = (parameters.size() == 1 && paramIsInputColor(0));
157 if (!validParams) {
158 errors.error(offset, "'main' parameter must be 'vec4', 'float4', or 'half4'");
159 return false;
160 }
161 break;
162 }
163 case ProgramKind::kRuntimeShader: {
164 // (half4|float4) main(float2) -or- (half4|float4) main(float2, half4|float4)
165 if (!typeIsValidForColor(returnType)) {
166 errors.error(offset, "'main' must return: 'vec4', 'float4', or 'half4'");
167 return false;
168 }
169 bool validParams =
170 (parameters.size() == 1 && paramIsCoords(0)) ||
171 (parameters.size() == 2 && paramIsCoords(0) && paramIsInputColor(1));
172 if (!validParams) {
173 errors.error(offset, "'main' parameters must be (float2, (vec4|float4|half4)?)");
174 return false;
175 }
176 break;
177 }
John Stiles2d8b8352021-06-16 11:33:13 -0400178 case ProgramKind::kRuntimeBlender: {
John Stilesf7f36ae2021-06-08 14:06:22 -0400179 // (half4|float4) main(half4|float4, half4|float4)
180 if (!typeIsValidForColor(returnType)) {
181 errors.error(offset, "'main' must return: 'vec4', 'float4', or 'half4'");
182 return false;
183 }
184 if (!(parameters.size() == 2 &&
185 paramIsInputColor(0) &&
John Stiles50d0d092021-06-09 17:24:31 -0400186 paramIsDestColor(1))) {
John Stilesf7f36ae2021-06-08 14:06:22 -0400187 errors.error(offset, "'main' parameters must be (vec4|float4|half4, "
188 "vec4|float4|half4)");
189 return false;
190 }
191 break;
192 }
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400193 case ProgramKind::kGeneric:
194 // No rules apply here
195 break;
196 case ProgramKind::kFragment: {
197 bool validParams = (parameters.size() == 0) ||
198 (parameters.size() == 1 && paramIsCoords(0));
199 if (!validParams) {
200 errors.error(offset, "shader 'main' must be main() or main(float2)");
201 return false;
202 }
203 break;
204 }
205 case ProgramKind::kVertex:
206 case ProgramKind::kGeometry:
207 if (parameters.size()) {
208 errors.error(offset, "shader 'main' must have zero parameters");
209 return false;
210 }
211 break;
212 }
213 return true;
214}
215
216/**
217 * Checks for a previously existing declaration of this function, reporting errors if there is an
218 * incompatible symbol. Returns true and sets outExistingDecl to point to the existing declaration
219 * (or null if none) on success, returns false on error.
220 */
221static bool find_existing_declaration(const Context& context, SymbolTable& symbols, int offset,
Ethan Nicholas962dec42021-06-10 13:06:39 -0400222 skstd::string_view name,
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400223 std::vector<std::unique_ptr<Variable>>& parameters,
224 const Type* returnType, bool isBuiltin,
225 const FunctionDeclaration** outExistingDecl) {
226 ErrorReporter& errors = context.fErrors;
227 const Symbol* entry = symbols[name];
228 *outExistingDecl = nullptr;
229 if (entry) {
230 std::vector<const FunctionDeclaration*> functions;
231 switch (entry->kind()) {
232 case Symbol::Kind::kUnresolvedFunction:
233 functions = entry->as<UnresolvedFunction>().functions();
234 break;
235 case Symbol::Kind::kFunctionDeclaration:
236 functions.push_back(&entry->as<FunctionDeclaration>());
237 break;
238 default:
239 errors.error(offset, "symbol '" + name + "' was already defined");
240 return false;
241 }
242 for (const FunctionDeclaration* other : functions) {
243 SkASSERT(name == other->name());
244 if (parameters.size() != other->parameters().size()) {
245 continue;
246 }
247 bool match = true;
248 for (size_t i = 0; i < parameters.size(); i++) {
249 if (parameters[i]->type() != other->parameters()[i]->type()) {
250 match = false;
251 break;
252 }
253 }
254 if (!match) {
255 continue;
256 }
257 if (*returnType != other->returnType()) {
258 std::vector<const Variable*> paramPtrs;
259 paramPtrs.reserve(parameters.size());
260 for (std::unique_ptr<Variable>& param : parameters) {
261 paramPtrs.push_back(param.get());
262 }
263 FunctionDeclaration invalidDecl(offset,
264 &other->modifiers(),
265 name,
266 std::move(paramPtrs),
267 returnType,
268 isBuiltin);
269 errors.error(offset,
270 "functions '" + invalidDecl.description() + "' and '" +
271 other->description() + "' differ only in return type");
272 return false;
273 }
274 for (size_t i = 0; i < parameters.size(); i++) {
275 if (parameters[i]->modifiers() != other->parameters()[i]->modifiers()) {
276 errors.error(offset,
277 "modifiers on parameter " + to_string((uint64_t)i + 1) +
278 " differ between declaration and definition");
279 return false;
280 }
281 }
282 if (other->definition() && !other->isBuiltin()) {
283 errors.error(offset, "duplicate definition of " + other->description());
284 return false;
285 }
286 *outExistingDecl = other;
287 break;
288 }
289 }
290 return true;
291}
292
John Stilesf96cb712021-05-05 22:17:04 -0400293FunctionDeclaration::FunctionDeclaration(int offset,
294 const Modifiers* modifiers,
Ethan Nicholas962dec42021-06-10 13:06:39 -0400295 skstd::string_view name,
John Stilesf96cb712021-05-05 22:17:04 -0400296 std::vector<const Variable*> parameters,
297 const Type* returnType,
298 bool builtin)
299 : INHERITED(offset, kSymbolKind, name, /*type=*/nullptr)
300 , fDefinition(nullptr)
301 , fModifiers(modifiers)
302 , fParameters(std::move(parameters))
303 , fReturnType(returnType)
304 , fBuiltin(builtin)
305 , fIsMain(name == "main")
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400306 , fIntrinsicKind(builtin ? identify_intrinsic(String(name)) : kNotIntrinsic) {}
John Stilesf96cb712021-05-05 22:17:04 -0400307
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400308const FunctionDeclaration* FunctionDeclaration::Convert(const Context& context,
John Stiles0b822792021-05-04 17:41:53 -0400309 SymbolTable& symbols, int offset, const Modifiers* modifiers,
Ethan Nicholas962dec42021-06-10 13:06:39 -0400310 skstd::string_view name, std::vector<std::unique_ptr<Variable>> parameters,
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400311 const Type* returnType, bool isBuiltin) {
312 bool isMain = (name == "main");
313
314 const FunctionDeclaration* decl = nullptr;
315 if (!check_modifiers(context, offset, *modifiers) ||
316 !check_return_type(context, offset, *returnType, isBuiltin) ||
John Stiles0b822792021-05-04 17:41:53 -0400317 !check_parameters(context, parameters, isMain, isBuiltin) ||
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400318 (isMain && !check_main_signature(context, offset, *returnType, parameters, isBuiltin)) ||
319 !find_existing_declaration(context, symbols, offset, name, parameters, returnType,
320 isBuiltin, &decl)) {
321 return nullptr;
322 }
323 std::vector<const Variable*> finalParameters;
324 finalParameters.reserve(parameters.size());
John Stilesf96cb712021-05-05 22:17:04 -0400325 for (std::unique_ptr<Variable>& param : parameters) {
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400326 finalParameters.push_back(symbols.takeOwnershipOfSymbol(std::move(param)));
327 }
328 if (decl) {
329 return decl;
330 }
331 auto result = std::make_unique<FunctionDeclaration>(offset, modifiers, name,
332 std::move(finalParameters), returnType,
333 isBuiltin);
334 return symbols.add(std::move(result));
335}
336
John Stilesf96cb712021-05-05 22:17:04 -0400337String FunctionDeclaration::mangledName() const {
338 if ((this->isBuiltin() && !this->definition()) || this->isMain()) {
339 // Builtins without a definition (like `sin` or `sqrt`) must use their real names.
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400340 return String(this->name());
John Stilesf96cb712021-05-05 22:17:04 -0400341 }
342 // GLSL forbids two underscores in a row; add an extra character if necessary to avoid this.
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400343 const char* splitter = this->name().ends_with("_") ? "x_" : "_";
John Stilesf96cb712021-05-05 22:17:04 -0400344 // Rename function to `funcname_returntypeparamtypes`.
345 String result = this->name() + splitter + this->returnType().abbreviatedName();
346 for (const Variable* p : this->parameters()) {
347 result += p->type().abbreviatedName();
348 }
349 return result;
350}
351
352String FunctionDeclaration::description() const {
353 String result = this->returnType().displayName() + " " + this->name() + "(";
354 String separator;
355 for (const Variable* p : this->parameters()) {
356 result += separator;
357 separator = ", ";
358 result += p->type().displayName();
359 result += " ";
360 result += p->name();
361 }
362 result += ")";
363 return result;
364}
365
366bool FunctionDeclaration::matches(const FunctionDeclaration& f) const {
367 if (this->name() != f.name()) {
368 return false;
369 }
370 const std::vector<const Variable*>& parameters = this->parameters();
371 const std::vector<const Variable*>& otherParameters = f.parameters();
372 if (parameters.size() != otherParameters.size()) {
373 return false;
374 }
375 for (size_t i = 0; i < parameters.size(); i++) {
376 if (parameters[i]->type() != otherParameters[i]->type()) {
377 return false;
378 }
379 }
380 return true;
381}
382
383bool FunctionDeclaration::determineFinalTypes(const ExpressionArray& arguments,
384 ParamTypes* outParameterTypes,
385 const Type** outReturnType) const {
386 const std::vector<const Variable*>& parameters = this->parameters();
387 SkASSERT(arguments.size() == parameters.size());
388
389 outParameterTypes->reserve_back(arguments.size());
390 int genericIndex = -1;
391 for (size_t i = 0; i < arguments.size(); i++) {
392 // Non-generic parameters are final as-is.
393 const Type& parameterType = parameters[i]->type();
394 if (parameterType.typeKind() != Type::TypeKind::kGeneric) {
395 outParameterTypes->push_back(&parameterType);
396 continue;
397 }
398 // We use the first generic parameter we find to lock in the generic index;
399 // e.g. if we find `float3` here, all `$genType`s will be assumed to be `float3`.
400 const std::vector<const Type*>& types = parameterType.coercibleTypes();
401 if (genericIndex == -1) {
402 for (size_t j = 0; j < types.size(); j++) {
403 if (arguments[i]->type().canCoerceTo(*types[j], /*allowNarrowing=*/true)) {
404 genericIndex = j;
405 break;
406 }
407 }
408 if (genericIndex == -1) {
409 // The passed-in type wasn't a match for ANY of the generic possibilities.
410 // This function isn't a match at all.
411 return false;
412 }
413 }
414 outParameterTypes->push_back(types[genericIndex]);
415 }
416 // Apply the generic index to our return type.
417 const Type& returnType = this->returnType();
418 if (returnType.typeKind() == Type::TypeKind::kGeneric) {
419 if (genericIndex == -1) {
420 // We don't support functions with a generic return type and no other generics.
421 return false;
422 }
423 *outReturnType = returnType.coercibleTypes()[genericIndex];
424 } else {
425 *outReturnType = &returnType;
426 }
427 return true;
428}
429
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400430} // namespace SkSL