Blender V5.3
function.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2024 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include "intermediate.hh"
10#include "metadata.hh"
11#include "processor.hh"
12
13namespace blender::gpu::shader {
14using namespace std;
15using namespace shader::parser;
16using namespace metadata;
17
18/* Parse entry point definitions and mutating all parameter usage to global resources. */
19void SourceProcessor::lower_entry_points(Parser &parser)
20{
21 using namespace metadata;
22
23 auto to_uppercase = [](string str) {
24 for (char &c : str) {
25 c = toupper(c);
26 }
27 return str;
28 };
29
30 parser().foreach_function([&](bool, Token type, Token fn_name, Scope args, bool, Scope fn_body) {
31 bool is_entry_point = false;
32 bool is_compute_func = false;
33 bool is_vertex_func = false;
34 bool is_fragment_func = false;
35 bool use_early_frag_test = false;
36 bool use_clip_control = false;
37 bool use_texture_atomic = false;
39 string local_size;
40
41 if (type.prev() == ']' && type.prev().scope().type() == ScopeType::Subscript) {
42 Scope attributes = type.prev().prev().scope();
43 attributes.foreach_attribute([&](Token attr, Scope attr_scope) {
44 const string attr_str(attr.str());
45 if (attr_str == "vertex") {
46 is_vertex_func = true;
47 is_entry_point = true;
48 }
49 else if (attr_str == "fragment") {
50 is_fragment_func = true;
51 is_entry_point = true;
52 }
53 else if (attr_str == "compute") {
54 is_compute_func = true;
55 is_entry_point = true;
56 }
57 else if (attr_str == "early_fragment_tests") {
58 use_early_frag_test = true;
59 }
60 else if (attr_str == "local_size") {
61 local_size = attr_scope.str();
62 }
63 else if (attr_str == "metal_max_total_threads_per_threadgroup") {
65 }
66 else if (attr_str == "clip_control") {
67 use_clip_control = true;
68 }
69 else if (attr_str == "texture_atomic") {
70 use_texture_atomic = true;
71 }
72 });
73 }
74
75 if (is_entry_point && type.str() != "void") {
76 report_error(type, "Entry point function must return void.");
77 return;
78 }
79
80 auto parse_condition = [&](const Scope &attributes) {
81 string cond;
82 attributes.foreach_attribute([&](Token attribute_name, Scope attribute_parameters) {
83 if (attribute_name.str() == "condition") {
84 if (!cond.empty()) {
85 report_error(attribute_name, "Only one condition attribute is allowed.");
86 return;
87 }
88 attribute_parameters[1].scope().foreach_token(Word, [&](const Token tok) {
89 cond += "int " + string(tok.str()) + " = ";
90 cond += "ShaderCreateInfo::find_constant(constants, \"" + string(tok.str()) + "\"); ";
91 });
92 cond += "return " + string(attribute_parameters[1].scope().str()) + ";";
93 }
94 });
95
96 if (!cond.empty()) {
97 cond = ", [](blender::Span<CompilationConstant> constants) { " + cond + "}";
98 }
99 return cond;
100 };
101
102 auto replace_word = [&](const string &replaced, const string &replacement) {
103 fn_body.foreach_token(Word, [&](const Token tok) {
104 if (tok.str() == replaced) {
105 parser.replace(tok, replacement, true);
106 }
107 });
108 };
109
110 auto replace_word_and_accessor = [&](const string &replaced, const string &replacement) {
111 fn_body.foreach_token(Word, [&](const Token tok) {
112 if (tok.next().type() == Dot && tok.str() == replaced) {
113 parser.replace(tok, tok.next(), replacement);
114 }
115 });
116 };
117
118 /* For now, just emit good old create info macros. */
119 string create_info_decl;
120
121 if (!local_size.empty()) {
122 if (!is_compute_func) {
123 report_error(type, "Only compute entry point function can use [[local_size(x,y,z)]].");
124 }
125 else {
126 create_info_decl += "LOCAL_GROUP_SIZE" + local_size + "\n";
127 }
128 }
129
130 if (use_early_frag_test) {
131 if (!is_fragment_func) {
132 report_error(type, "Only fragment entry point function can use [[use_early_frag_test]].");
133 }
134 else {
135 create_info_decl += "EARLY_FRAGMENT_TEST(true)\n";
136 }
137 }
138
139 if (use_clip_control) {
140 if (!is_vertex_func) {
141 report_error(type, "Only vertex entry point function can use [[clip_control]].");
142 }
143 else {
144 create_info_decl += "BUILTINS(BuiltinBits::CLIP_CONTROL)\n";
145 }
146 }
147
148 if (use_texture_atomic) {
149 create_info_decl += "BUILTINS(BuiltinBits::TEXTURE_ATOMIC)\n";
150 }
151
153 if (!is_compute_func) {
154 report_error(type,
155 "Only compute entry point function can use "
156 "[[metal_max_total_threads_per_threadgroup(x)]].");
157 }
158 else {
159 create_info_decl += "MTL_MAX_TOTAL_THREADS_PER_THREADGROUP" +
161 }
162 }
163
164 auto process_argument = [&](Token type, Token var, Scope attributes) {
165 const bool is_const = type.prev() == TokenType::Const;
166 string srt_type(type.str());
167 string srt_var(var.str());
168 string srt_attr(attributes[1].str());
169
170 if (srt_attr == "vertex_id" && is_entry_point) {
171 if (!is_vertex_func) {
172 report_error(attributes[1], "[[vertex_id]] is only supported in vertex functions.");
173 }
174 else if (!is_const || srt_type != "int") {
175 report_error(type, "[[vertex_id]] must be declared as `const int`.");
176 }
177 replace_word(srt_var, "gl_VertexID");
178 metadata_.builtins.emplace_back(Builtin(hash("gl_VertexID")));
179 create_info_decl += "BUILTINS(BuiltinBits::VERTEX_ID)\n";
180 }
181 else if (srt_attr == "instance_id" && is_entry_point) {
182 if (!is_vertex_func) {
183 report_error(attributes[1], "[[instance_id]] is only supported in vertex functions.");
184 }
185 else if (!is_const || srt_type != "int") {
186 report_error(type, "[[instance_id]] must be declared as `const int`.");
187 }
188 replace_word(srt_var, "gl_InstanceID");
189 metadata_.builtins.emplace_back(Builtin(hash("gl_InstanceID")));
190 create_info_decl += "BUILTINS(BuiltinBits::INSTANCE_ID)\n";
191 }
192 else if (srt_attr == "instance_index" && is_entry_point) {
193 if (!is_vertex_func) {
194 report_error(attributes[1], "[[instance_index]] is only supported in vertex functions.");
195 }
196 else if (!is_const || srt_type != "int") {
197 report_error(type, "[[instance_index]] must be declared as `const int`.");
198 }
199 replace_word(srt_var, "gpu_InstanceIndex");
200 metadata_.builtins.emplace_back(Builtin(hash("gpu_InstanceIndex")));
201 create_info_decl += "BUILTINS(BuiltinBits::INSTANCE_ID)\n";
202 }
203 else if (srt_attr == "base_instance" && is_entry_point) {
204 if (!is_vertex_func) {
205 report_error(attributes[1], "[[base_instance]] is only supported in vertex functions.");
206 }
207 else if (!is_const || srt_type != "int") {
208 report_error(type,
209 "[[base_instance]] must be declared as "
210 "`const int`.");
211 }
212 replace_word(srt_var, "gpu_BaseInstance");
213 metadata_.builtins.emplace_back(Builtin(hash("gpu_BaseInstance")));
214 create_info_decl += "BUILTINS(BuiltinBits::INSTANCE_ID)\n";
215 }
216 else if (srt_attr == "point_size" && is_entry_point) {
217 if (!is_vertex_func) {
218 report_error(attributes[1], "[[point_size]] is only supported in vertex functions.");
219 }
220 else if (is_const || srt_type != "float") {
221 report_error(type,
222 "[[point_size]] must be declared as non-const reference (aka `float &`).");
223 }
224 replace_word(srt_var, "gl_PointSize");
225 create_info_decl += "BUILTINS(BuiltinBits::POINT_SIZE)\n";
226 }
227 else if (srt_attr == "clip_distance" && is_entry_point) {
228 if (!is_vertex_func) {
229 report_error(attributes[1], "[[clip_distance]] is only supported in vertex functions.");
230 }
231 else if (is_const || srt_type != "float") {
232 report_error(type,
233 "[[clip_distance]] must be declared as non-const reference "
234 "(aka `float (&)[]`).");
235 }
236 replace_word(srt_var, "gl_ClipDistance");
237 string res_condition_lambda = parse_condition(attributes);
238 create_info_decl += ".builtins(BuiltinBits::CLIP_DISTANCES" + res_condition_lambda + ")\n";
239 }
240 else if (srt_attr == "layer" && is_entry_point) {
241 if (is_compute_func) {
242 report_error(attributes[1],
243 "[[layer]] is only supported in vertex and fragment functions.");
244 }
245 else if (is_vertex_func && (is_const || srt_type != "int")) {
246 report_error(type,
247 "[[layer]] must be declared as non-const reference "
248 "(aka `int &`).");
249 }
250 else if (is_fragment_func && (!is_const || srt_type != "int")) {
251 report_error(type,
252 "[[layer]] must be declared as const reference "
253 "(aka `const int &`).");
254 }
255 replace_word(srt_var, "gl_Layer");
256 string res_condition_lambda = parse_condition(attributes);
257 create_info_decl += ".builtins(BuiltinBits::LAYER" + res_condition_lambda + ")\n";
258 }
259 else if (srt_attr == "viewport_index" && is_entry_point) {
260 if (is_compute_func) {
261 report_error(attributes[1],
262 "[[viewport_index]] is only supported in vertex and "
263 "fragment functions.");
264 }
265 else if (is_vertex_func && (is_const || srt_type != "int")) {
266 report_error(type,
267 "[[viewport_index]] must be declared as non-const reference "
268 "(aka `int &`).");
269 }
270 else if (is_fragment_func && (!is_const || srt_type != "int")) {
271 report_error(type,
272 "[[viewport_index]] must be declared as const reference "
273 "(aka `const int &`).");
274 }
275 replace_word(srt_var, "gpu_ViewportIndex");
276 string res_condition_lambda = parse_condition(attributes);
277 create_info_decl += ".builtins(BuiltinBits::VIEWPORT_INDEX" + res_condition_lambda + ")\n";
278 }
279 else if (srt_attr == "position" && is_entry_point) {
280 if (!is_vertex_func) {
281 report_error(attributes[1], "[[position]] is only supported in vertex functions.");
282 }
283 else if (is_const || srt_type != "float4") {
284 report_error(type,
285 "[[position]] must be declared as non-const reference (aka `float4 &`).");
286 }
287 else {
288 replace_word(srt_var, "gl_Position");
289 }
290 }
291 else if (srt_attr == "frag_coord" && is_entry_point) {
292 if (!is_fragment_func) {
293 report_error(attributes[1], "[[frag_coord]] is only supported in fragment functions.");
294 }
295 else if (!is_const || srt_type != "float4") {
296 report_error(type, "[[frag_coord]] must be declared as `const float4`.");
297 }
298 else {
299 create_info_decl += "BUILTINS(BuiltinBits::FRAG_COORD)\n";
300 replace_word(srt_var, "gl_FragCoord");
301 }
302 }
303 else if (srt_attr == "point_coord" && is_entry_point) {
304 if (!is_fragment_func) {
305 report_error(attributes[1], "[[point_coord]] is only supported in fragment functions.");
306 }
307 else if (!is_const || srt_type != "float2") {
308 report_error(type, "[[point_coord]] must be declared as `const float2`.");
309 }
310 else {
311 create_info_decl += "BUILTINS(BuiltinBits::POINT_COORD)\n";
312 replace_word(srt_var, "gl_PointCoord");
313 }
314 }
315 else if (srt_attr == "front_facing" && is_entry_point) {
316 if (!is_fragment_func) {
317 report_error(attributes[1], "[[front_facing]] is only supported in fragment functions.");
318 }
319 else if (!is_const || srt_type != "bool") {
320 report_error(type, "[[front_facing]] must be declared as `const bool`.");
321 }
322 else {
323 create_info_decl += "BUILTINS(BuiltinBits::FRONT_FACING)\n";
324 replace_word(srt_var, "gl_FrontFacing");
325 }
326 }
327 else if (srt_attr == "global_invocation_id" && is_entry_point) {
328 if (!is_compute_func) {
329 report_error(attributes[1],
330 "[[global_invocation_id]] is only supported in compute functions.");
331 }
332 else if (!is_const || srt_type != "uint3") {
333 report_error(type, "[[global_invocation_id]] must be declared as `const uint3`.");
334 }
335 else {
336 create_info_decl += "BUILTINS(BuiltinBits::GLOBAL_INVOCATION_ID)\n";
337 replace_word(srt_var, "gl_GlobalInvocationID");
338 }
339 }
340 else if (srt_attr == "local_invocation_id" && is_entry_point) {
341 if (!is_compute_func) {
342 report_error(attributes[1],
343 "[[local_invocation_id]] is only supported in compute functions.");
344 }
345 else if (!is_const || srt_type != "uint3") {
346 report_error(type, "[[local_invocation_id]] must be declared as `const uint3`.");
347 }
348 else {
349 create_info_decl += "BUILTINS(BuiltinBits::LOCAL_INVOCATION_ID)\n";
350 replace_word(srt_var, "gl_LocalInvocationID");
351 }
352 }
353 else if (srt_attr == "local_invocation_index" && is_entry_point) {
354 if (!is_compute_func) {
355 report_error(attributes[1],
356 "[[local_invocation_index]] is only supported in compute functions.");
357 }
358 else if (!is_const || srt_type != "uint") {
359 report_error(type, "[[local_invocation_index]] must be declared as `const uint`.");
360 }
361 else {
362 create_info_decl += "BUILTINS(BuiltinBits::LOCAL_INVOCATION_INDEX)\n";
363 replace_word(srt_var, "gl_LocalInvocationIndex");
364 }
365 }
366 else if (srt_attr == "work_group_id" && is_entry_point) {
367 if (!is_compute_func) {
368 report_error(attributes[1], "[[work_group_id]] is only supported in compute functions.");
369 }
370 else if (!is_const || srt_type != "uint3") {
371 report_error(type,
372 "[[work_group_id]] must be declared as "
373 "`const uint3`.");
374 }
375 else {
376 create_info_decl += "BUILTINS(BuiltinBits::WORK_GROUP_ID)\n";
377 replace_word(srt_var, "gl_WorkGroupID");
378 }
379 }
380 else if (srt_attr == "num_work_groups" && is_entry_point) {
381 if (!is_compute_func) {
382 report_error(attributes[1],
383 "[[num_work_groups]] is only supported in compute functions.");
384 }
385 else if (!is_const || srt_type != "uint3") {
386 report_error(type,
387 "[[num_work_groups]] must be declared as "
388 "`const uint3`.");
389 }
390 else {
391 create_info_decl += "BUILTINS(BuiltinBits::NUM_WORK_GROUP)\n";
392 replace_word(srt_var, "gl_NumWorkGroups");
393 }
394 }
395 else if (srt_attr == "in") {
396 if (is_compute_func) {
397 report_error(attributes[1],
398 "[[in]] is only supported in vertex and fragment functions.");
399 }
400 else if (!is_const) {
401 report_error(type, "[[in]] must be declared as const reference.");
402 }
403 else if (is_vertex_func) {
404 replace_word_and_accessor(srt_var, "");
405 create_info_decl += "ADDITIONAL_INFO(" + srt_type + ")\n";
406 }
407 else if (is_fragment_func) {
408 replace_word_and_accessor(srt_var, srt_type + "_");
409 // create_info_decl += "VERTEX_OUT(" + srt_type + ")\n";
410 }
411 }
412 else if (srt_attr == "subpass_in") {
413 if (is_compute_func) {
414 report_error(attributes[1], "[[subpass_in]] is only supported in fragment functions.");
415 }
416 else if (!is_const) {
417 report_error(type, "[[subpass_in]] must be declared as const reference.");
418 }
419 else if (is_fragment_func) {
420 replace_word_and_accessor(srt_var, srt_type + "_");
421 create_info_decl += "ADDITIONAL_INFO(" + srt_type + ")\n";
422 }
423 }
424 else if (srt_attr == "out") {
425 if (is_compute_func) {
426 report_error(attributes[1],
427 "[[out]] is only supported in vertex and fragment functions.");
428 }
429 else if (is_const) {
430 report_error(type, "[[out]] must be declared as non-const reference.");
431 }
432 else if (is_vertex_func) {
433 replace_word_and_accessor(srt_var, srt_type + "_");
434 string res_condition_lambda = parse_condition(attributes);
435 create_info_decl += ".vertex_out(" + srt_type + "_t" + res_condition_lambda + ")\n";
436 }
437 else if (is_fragment_func) {
438 replace_word_and_accessor(srt_var, srt_type + "_");
439 string res_condition_lambda = parse_condition(attributes);
440 create_info_decl += ".additional_info_with_condition(\"" + srt_type + "\"" +
441 res_condition_lambda + ")\n";
442 }
443 }
444 else if (srt_attr == "resource_table") {
445 if (is_entry_point) {
446 /* Add dummy var at start of function body. */
447 parser.insert_after(fn_body.front().str_index_start(),
448 " " + srt_type + " " + srt_var + "{};");
449 string res_condition_lambda = parse_condition(attributes);
450 create_info_decl += ".additional_info_with_condition(\"" + srt_type + "\"" +
451 res_condition_lambda + ")\n";
452 }
453 }
454 else if (srt_attr == "frag_depth") {
455 if (srt_type != "float") {
456 report_error(type, "[[frag_depth]] needs to be declared as float");
457 }
458 const string mode(attributes[3].str());
459
460 if (mode != "any" && mode != "greater" && mode != "less") {
461 report_error(attributes[3], "unrecognized mode, expecting 'any', 'greater' or 'less'");
462 }
463 else {
464 create_info_decl += "DEPTH_WRITE(DepthWrite::" + to_uppercase(mode) + ")\n";
465 replace_word(srt_var, "gl_FragDepth");
466 }
467 }
468 else if (srt_attr == "frag_stencil_ref") {
469 if (srt_type != "int") {
470 report_error(type, "[[frag_stencil_ref]] needs to be declared as int");
471 }
472 else {
473 create_info_decl += "BUILTINS(BuiltinBits::STENCIL_REF)\n";
474 replace_word(srt_var, "gl_FragStencilRefARB");
475 }
476 }
477 else {
478 report_error(attributes[1], "Invalid attribute.");
479 }
480 };
481
482 args.foreach_match("[[..]]c?AA", [&](const vector<Token> toks) {
483 process_argument(toks[8], toks[9], toks[1].scope());
484 });
485 args.foreach_match("[[..]]c?A&A", [&](const vector<Token> toks) {
486 process_argument(toks[8], toks[10], toks[1].scope());
487 });
488
489 args.foreach_match("[[..]]c?A(&A)", [&](const vector<Token> toks) {
490 process_argument(toks[8], toks[11], toks[1].scope());
491 });
492
493 if (is_entry_point) {
494 if (create_info_decl.empty()) {
495 /* Add unused define to avoid warning about unused expression. */
496 create_info_decl += "DEFINE(\"EMPTY_CREATE_INFO\")\n";
497 }
498 create_info_decl = "GPU_SHADER_CREATE_INFO(" + string(fn_name.str()) + "_infos_)\n" +
499 create_info_decl + "GPU_SHADER_CREATE_END()\n";
500 metadata_.create_infos_declarations.emplace_back(create_info_decl);
501 }
502 });
503
504 parser.apply_mutations();
505}
506
507/* Removes entry point arguments to make it compatible with the legacy code.
508 * Has to run after mutation related to function arguments. */
509void SourceProcessor::lower_entry_points_signature(Parser &parser)
510{
511 using namespace metadata;
512
513 parser().foreach_function([&](bool, Token type, Token name, Scope args, bool, Scope fn_body) {
514 bool is_entry_point = false;
515
516 if (type.prev() == ']' && type.prev().scope().type() == ScopeType::Subscript) {
517 Scope attributes = type.prev().prev().scope();
518 attributes.foreach_attribute([&](Token attr, Scope) {
519 const string attr_str(attr.str());
520 if (attr_str == "vertex" || attr_str == "fragment" || attr_str == "compute") {
521 is_entry_point = true;
522 }
523 });
524 }
525
526 if (is_entry_point && args.str() != "()") {
527 parser.erase(args.front().next(), args.back().prev());
528 }
529
530 /* Mute entry points when not enabled.
531 * Could be lifted at some point, but for now required because of stage_in/out parameters. */
532 if (is_entry_point) {
533 /* Take attributes into account. */
534 parser.insert_directive(type.prev().scope().front().prev(),
535 "#if defined(ENTRY_POINT_" + string(name.str()) + ")");
536 parser.insert_directive(fn_body.back(), "#endif");
537 }
538 });
539
540 parser.apply_mutations();
541}
542
543} // namespace blender::gpu::shader
#define str(s)
#define metal_max_total_threads_per_threadgroup(count)
#define local_size(...)
@ Dot
Definition types.hh:48
@ Word
Definition types.hh:43
#define hash
Definition noise_c.cc:156
void foreach_attribute(CallbackFn callback) const
Definition scope.hh:367