Blender V5.3
codegen.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2026 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include "diagnostic.hh"
10#include "metadata.hh"
11#include "pratt_parser.hh"
12#include "processor.hh"
13#include "symbol_table.hh"
14
15#include <algorithm>
16#include <sstream>
17
18namespace bsl {
19using namespace std;
20using namespace blender::gpu::shader;
21using namespace blender::gpu::shader::parser;
23
24static string to_uppercase(string str)
25{
26 for (char &c : str) {
27 c = toupper(c);
28 }
29 return str;
30}
31
33{
34 switch (tok) {
35 case AssignAdd:
36 return Plus;
37 case AssignSub:
38 return Minus;
39 case AssignMul:
40 return Multiply;
41 case AssignDiv:
42 return Divide;
43 case AssignLShift:
44 return LShift;
45 case AssignRShift:
46 return RShift;
47 default:
48 return Invalid;
49 }
50}
51
52static const char *to_token_string(TokenType tok)
53{
54 switch (tok) {
55 case Increment:
56 return "+1";
57 case Decrement:
58 return "-1";
59 case Plus:
60 return "+";
61 case Minus:
62 return "-";
63 case Multiply:
64 return "*";
65 case Divide:
66 return "/";
67 case LShift:
68 /* Add spaces to avoid parsing it as template. */
69 return " << ";
70 case RShift:
71 /* Add spaces to avoid parsing it as template. */
72 return " >> ";
73 default:
74 return "";
75 }
76}
77
81
83 string str;
84
86 /* Array dimension of the current temporary. */
88 bool is_bitfield = false;
89
90 CodegenResult(SymbolVariable *var, const string &trivia)
91 : str((var->is_constexpr ? var->value_str() : var->identifier) + trivia),
92 type(var->type),
93 array_dim(var->array_dimensions),
95 {
96 }
97
99 : str(node.str_full()), type(cls), array_dim(array_dim)
100 {
101 }
102
103 CodegenResult(const string &str,
104 SymbolClass *cls,
105 int8_t array_dim = 0,
106 bool is_bitfield = false)
108 {
109 }
110 };
111
117 : public PrattParser<CodegenExpressionParser, CodegenResult, ast::Node> {
120 using BindingPower = Base::BindingPower;
121
122 private:
123 CodegenContext &ctx;
124 const SymbolScope &scope;
125 /* Point of instantiation of the containing function. */
126 optional<SourceLocation> poi;
127 ast::Node node;
128
129 public:
131 : ctx(ctx), scope(scope), node(start_node)
132 {
133 if (const SymbolFunction *fn = scope.parent_function(); fn) {
134 poi = fn->poi;
135 }
136 }
137
139 {
140 if (!node.is_valid()) {
141 return {node, ctx.table.err_cls};
142 }
143 return expr(0);
144 }
145
149
151 {
152 switch (t.type()) {
154 return constructor(t);
156 return function(t, scope);
158 return variable(LocalVar(t).identifier(), scope);
159 default:
160 return {t, ctx.table.err_cls};
161 }
162 return {t, ctx.table.err_cls};
163 }
164
166 {
167 return {t, ctx.table.get_literal_type(t.str())};
168 }
169
171 {
172 return {t, ctx.table.str_cls};
173 }
174
176 {
177 CodegenResult result = ctx.expr(ExprSub(t).expr(), scope);
178 string front(t.front().str_with_whitespace());
179 string back(t.back().str_with_whitespace());
180 return {front + result.str + back, result.type};
181 }
182
184 {
185 ast::Node right = consume();
186 switch (right.type()) {
188 CodegenResult rhs = function(right, *left.type);
189 return {left.str + string(t.str_full()) + rhs.str, rhs.type};
190 }
192 CodegenResult rhs = variable(LocalVar(right).identifier(), *left.type);
193 if (left.type->is_srt()) {
194 /* Remove access to SRT type (makes the resource global). */
195 return {left.str + as_whitespace(t.str_full()) + rhs.str,
196 rhs.type,
197 rhs.array_dim,
198 rhs.is_bitfield};
199 }
200 return {
201 left.str + string(t.str_full()) + rhs.str, rhs.type, rhs.array_dim, rhs.is_bitfield};
202 }
203 default:
204 return {t, ctx.table.err_cls};
205 }
206 }
207
209 {
210 /* Subscript operator. */
211 if (ast::Subscript sub = t; sub.is_valid()) {
212 CodegenResult param = ctx.expr(sub.expr(), scope);
213
214 string_view front = t.front().str_with_whitespace();
215 string_view back = t.back().str_with_whitespace();
216
217 if (left.array_dim > 0) {
218 left.str += string(front) + param.str + string(back);
219 left.array_dim -= 1;
220 return left;
221 }
222 /* Call subscript operator */
223 if (left.type->operator_subscript) {
224#if 0 /* Future operator overloading */
225 if (true) {
226 left.str = SymbolTable::subscript_operator_id + '(' + left.str + ',' + param.str + ')';
227 return {left.str, left.type->operator_subscript->return_type};
228 }
229#endif
230 left.str += string(front) + param.str + string(back);
231 return {left.str, left.type->operator_subscript->return_type};
232 }
233 }
234 ctx.error(t, Diag::InvalidSubscript);
235 return {t, ctx.table.err_cls};
236 }
237
239 {
240 ctx.error(t, Diag::OperatorCalledIsNotFunction, left.type ? left.type->identifier : "");
241 return {t, ctx.table.err_cls};
242 }
243
245 {
246 using namespace builtin;
247 TokenType op_type = t.front().type();
248 CodegenResult rhs = expr(p);
249
250 ClassId type = unary_prefix_operator_return_type(op_type, rhs.type);
251
252 if (rhs.is_bitfield) {
253 if (op_type == Increment || op_type == Decrement) {
254 ctx.error(t, Diag::OperatorBitfieldInvalid);
255 }
256 }
257 return {string(t.str_full()) + rhs.str, ctx.table.to_class(type)};
258 }
259
261 {
262 using namespace builtin;
263 TokenType op_type = t.front().type();
264
265 ClassId type = unary_suffix_operator_return_type(lhs.type, op_type);
266
267 if (lhs.is_bitfield) {
268 if (op_type == Increment || op_type == Decrement) {
269 ctx.error(t, Diag::OperatorBitfieldInvalid);
270 }
271 }
272 return {lhs.str + string(t.str_full()), ctx.table.to_class(type)};
273 }
274
276 {
277 using namespace builtin;
278 CodegenResult rhs = expr(p);
279 return {lhs.str + string(t.str_full()) + rhs.str, rhs.type};
280 }
281
283 {
284 using namespace builtin;
285 TokenType op_type = t.front().type();
286
287 CodegenResult rhs = expr(p);
288
289 ClassId type = binary_operator_return_type(lhs.type, op_type, rhs.type);
290
291 if (lhs.is_bitfield) {
292 if (TokenType sub_op = strip_assignment(op_type); sub_op != TokenType::Invalid) {
293 /* Bitfield need to be manually read and write. */
294 return {lhs.str + "=" + lhs.str + to_token_string(sub_op) + trivia(t) + rhs.str,
295 ctx.table.to_class(type)};
296 }
297 }
298
299#if 0 /* Future operator overloading */
300 if (true) {
301 const string op_name = ctx.table.binary_type_to_id.find(op_type)->second;
302 return {op_name + '(' + lhs.str + ',' + rhs.str + ')', type};
303 }
304#endif
305 return {lhs.str + string(t.str_full()) + rhs.str, ctx.table.to_class(type)};
306 }
307
309 const ast::Node &t,
310 BindingPower /*p_first*/,
311 BindingPower p_second)
312 {
313 ast::Node question = t;
314 CodegenResult tval = ctx.expr(consume(), scope);
315 ast::Node colon = consume();
316 CodegenResult fval = expr(p_second);
317 return {left.str + string(question.str_full()) + tval.str + string(colon.str_full()) +
318 fval.str,
319 tval.type};
320 }
321
323 {
324 return node.is_valid() ? node.front().type() : Invalid;
325 }
326
328 {
329 ast::Node n = node;
330 node = node.next();
331 return n;
332 }
333
335 {
336 ast::NodeType type = t.type();
337 return type != ast::NodeType::Invalid ?
339 Word :
340 t.front().type()) :
341 Invalid;
342 }
343
345 {
346 switch (err) {
347 case ErrorType::ExpectedParenthesis:
348 ctx.error(node, Diag::ExpectedParenthesis);
349 break;
350 case ErrorType::ExpectedColon:
351 ctx.error(node, Diag::ExpectedColon);
352 break;
353 case ErrorType::InvalidOperator:
354 ctx.error(node, Diag::OperatorTokenInvalid, to_str(type));
355 break;
356 case ErrorType::InvalidExpression:
357 ctx.error(node, Diag::InvalidExprTypeCodegen);
358 break;
359 }
360 return {node, ctx.table.err_cls};
361 }
362
363 private:
364 CodegenResult constructor(Constructor construct)
365 {
366 SymbolClass *cls = scope.lookup_class(ctx.table, construct.identifier()).unwrap(&ctx);
367 if (cls->is_srt()) {
369 }
370
371 return ctx.initializer_list(construct.initializer_list(), scope, cls);
372 }
373
374 CodegenResult variable(IdQualified id, const SymbolScope &symbol_scope)
375 {
376 assert(id.is_valid());
377 string whitespace = trivia(id);
378
379 SymbolVariable *var = symbol_scope.lookup_variable(ctx.table, id);
380 if (var->is_error) {
381 ctx.error(id, Diag::UnknownVariable, id.str());
382 return {var, whitespace};
383 }
384
385 if (var->is_constexpr) {
386 return {var, whitespace};
387 }
388
389 if (var->condition.is_valid()) {
390 ctx.check_condition(id, var->condition);
391 }
392
393 if (var->type->is_srt()) {
394 bool followed_by_dot = id.back().next() == '.';
395 bool followed_by_member_call = id.parent().next().next() == NodeType::FuncCall;
396 if (followed_by_dot && !followed_by_member_call) {
397 /* Remove access to SRT type (makes the resource global). */
398 return {as_whitespace(id.str_full()), var->type};
399 }
400 /* SRT type is used in an expression (likely as function argument). Call the ctor. */
401 return {var->type->identifier + "_ctor_()" + whitespace, var->type};
402 }
403
404 if (var->reference_value.is_valid()) {
405 return ctx.expr(var->reference_value, scope);
406 }
407
408 bool preceded_by_dot = id.front().prev() == '.';
409 if (!var->is_static && !preceded_by_dot && var->parent->as_class() != nullptr) {
410 return {"this_." + var->identifier + whitespace, var->type, var->array_dimensions};
411 }
412 return {var, whitespace};
413 }
414
415 CodegenResult function(const ast::FuncCall &call, const SymbolScope &symbol_scope)
416 {
417 assert(call.is_valid());
418
419 IdQualified id = call.identifier();
420
421 /* If accessing a function in a different class, we need to set the location at the point of
422 * instantiation. Otherwise we cannot use CRTP patterns. */
423 SourceLocation loc = (&symbol_scope != &scope) ? poi.value_or(id.front()) : id.front();
424
425 SymbolFunction *sym = ctx.id_func_resolved_lookup(
426 id, call.parameters(), symbol_scope, scope, loc);
427
428 if (sym == nullptr || sym->is_error) {
429 ctx.error(call, Diag::UnknownFunction, string(id.str()));
430 return {"", ctx.table.err_cls};
431 }
432
433 if (sym->is_inline) {
435 }
436
437 FuncParamList list = call.parameters();
438 std::string params_str;
439 if (sym->fn_type == SymbolFunction::MEMBER && list.parent().prev().back() != '.') {
440 params_str += "this_";
441 if (!list.is_empty()) {
442 params_str += ", ";
443 }
444 }
445
446 int param_count = 0;
447 for (Expr param : list.children_of_type<Expr>()) {
448 params_str += ctx.expr(param, scope).str;
449 params_str += ctx.opt_str(param.back().next(), Comma);
450 ++param_count;
451 }
452
453 /* Default arguments. */
454 for (; param_count < sym->arg_defaults.size(); ++param_count) {
455 if (sym->arg_defaults[param_count].is_valid()) {
456 if (param_count != 0) {
457 params_str += ", ";
458 }
459 /* Note: We evaluate the expression from where it was defined, in the function scope. */
460 params_str += ctx.expr(sym->arg_defaults[param_count], *sym).str;
461 }
462 else {
463 ctx.error(list, Diag::MissingParameterForCall, sym->identifier);
464 }
465 }
466
467 params_str = std::string(list.front().str_with_whitespace()) + params_str +
468 std::string(list.back().str_with_whitespace()) + trivia(call);
469
470 return {sym->identifier + trivia(id) + params_str, sym->return_type};
471 }
472 };
473
476 stringstream ss;
477
479 {
480 ss << tok.str_with_whitespace();
481 curr = curr.next();
482 return *this;
483 }
484
486 {
487 ss << str;
488 curr = curr.next();
489 return *this;
490 }
491
492 StringBuilder &operator<<(const string_view &str)
493 {
494 ss << str;
495 curr = curr.next();
496 return *this;
497 }
498
500 {
501 ss << node.front().buf_->substr(node.front(), node.back(), true);
502 curr = node.back().next();
503 return *this;
504 }
505
507 {
508 ss << sb.ss.str();
509 curr = curr.next();
510 return *this;
511 }
513
515 SymbolTable &symbols,
517 SourceProcessor::ErrorHandler &error_handler)
518 : NodeErrorHandler(error_handler),
519 table(symbols),
521 builder(Token::invalid(&parser))
522 {
523 }
524
526 {
527 local_scope(node, symbol);
528 return builder.ss.str();
529 }
530
531 private:
532 static string trivia(Token t)
533 {
534 string_view no_ws = t.str();
535 return string(t.str_with_whitespace().substr(no_ws.size()));
536 }
537
538 static string trivia(Node node)
539 {
540 return trivia(node.back());
541 }
542
543 static string as_whitespace(string_view str)
544 {
545 size_t lines = count(str.begin(), str.end(), '\n');
546 size_t spaces = str.find_last_of("\n");
547 if (spaces != string::npos) {
548 spaces = str.length() - (spaces + 1);
549 }
550 else {
551 spaces = str.length();
552 }
553 return string(lines, '\n') + string(spaces, ' ');
554 }
555
556 void skip_node(Node node)
557 {
558 if (node.is_valid()) {
559 const TokenBuffer *buf = node.front().buf_;
560 string_view str = buf->substr(node.front(), node.back(), true);
561 builder.ss << as_whitespace(str);
562 builder.curr = node.back().next();
563 }
564 }
565
566 /* Only go to next token if matching an optional token. */
567 template<typename... Args> bool skip_if(Args... expected)
568 {
569 if (((builder.curr == TokenType(expected)) || ...)) {
570 string_view str = builder.curr.str_with_whitespace();
571 builder << as_whitespace(str);
572 return true;
573 }
574 return false;
575 }
576
577 void line(Token tok)
578 {
579 builder.ss << "\n#line " + to_string(tok.line_number()) + "\n";
580 }
581
582 void line(Node node)
583 {
584 line(node.front());
585 }
586
587 void jump_to(Token tok)
588 {
589 line(tok);
590 builder.ss << string(tok.char_number(), ' ');
591 builder.curr = tok;
592 }
593
594 /* Only go to next token if matching an optional token. */
595 template<typename... Args> bool match_if(Args... expected)
596 {
597 if (((builder.curr == TokenType(expected)) || ...)) {
599 return true;
600 }
601 return false;
602 }
603
604 void local_scope(LocalScope node, SymbolScope &symbol)
605 {
606 assert(node.is_valid());
607
608 /* Check if scope started with a bracket, otherwise we could emit a contained scope last token
609 * because of the last jump_to. */
610 bool has_bracket = false;
611 if (symbol.parent != nullptr) {
612 if (symbol.type == SymbolScope::NAMESPACE) {
613 skip_if('{');
614 }
615 else {
616 has_bracket = match_if('{');
617 }
618 }
619
620 /* Resource guards for local SRT variables. Can be phased out once we remove the need for
621 * resource_table_get. */
622 string cond = !symbol.as_function() ? condition(&symbol) : "";
623 if (!cond.empty()) {
624 builder.ss << string("\n#if ") + cond + "\n";
625 jump_to(builder.curr);
626 }
627
628 if (node.child_first().is_valid()) {
629 jump_to(node.child_first().front());
630 }
631
632 int local_scope_id = 0;
633 for (Node node : node.children_range()) {
634 switch (node.type()) {
635 case NodeType::Preprocessor:
636 jump_to(node.front());
637 builder << node;
638 break;
639 case NodeType::Namespace:
640 namespace_decl(ast::Namespace(node), symbol);
641 break;
642 case NodeType::VarDecl:
643 var_decl(VarDecl(node), symbol);
644 break;
645 case NodeType::ClassDecl:
646 class_decl(ClassDecl(node), symbol);
647 break;
648 case NodeType::FuncDecl:
649 func_decl(FuncDecl(node), symbol);
650 break;
651 case NodeType::FuncForwardDecl:
652 func_forward_decl(FuncForwardDecl(node), symbol);
653 break;
654 case NodeType::TemplateDecl:
655 skip_node(node);
656 break;
657 case NodeType::TemplateInst:
658 template_inst(TemplateInst(node), symbol);
659 break;
660 case NodeType::TemplateSpec:
661 template_spec(TemplateSpec(node), symbol);
662 break;
663 case NodeType::UsingStmt:
664 skip_node(node);
665 break;
666 case NodeType::ForLoop:
667 for_loop(node, *symbol.child_scope(local_scope_id++));
668 break;
669 case NodeType::WhileLoop:
670 while_loop(node, *symbol.child_scope(local_scope_id++));
671 break;
672 case NodeType::DoWhileLoop:
673 do_while_loop(node, *symbol.child_scope(local_scope_id++));
674 break;
675 case NodeType::SwitchStmt:
676 switch_statement(node, symbol, local_scope_id);
677 break;
678 case NodeType::ReturnStmt:
679 return_statement(node, symbol);
680 break;
681 case NodeType::StructuredBinding:
682 structured_binding(node, symbol);
683 break;
684 case NodeType::IfStmt:
685 if (Condition(node.child_first()).attributes().contains_attr("static_branch")) {
686 static_if_statement(node, symbol, local_scope_id);
687 }
688 else {
689 if_statement(node, symbol, local_scope_id);
690 }
691 break;
692 case NodeType::ElseIfStmt:
693 case NodeType::ElseStmt:
694 /* Should have been processed by the if statement. */
695 break;
696 case NodeType::LocalStmt:
697 local_statement(node, symbol);
698 break;
699 case NodeType::LocalScope:
700 local_scope(LocalScope(node), *symbol.child_scope(local_scope_id++));
701 break;
702 case NodeType::PipelineDecl:
703 pipeline_decl(node, symbol);
704 break;
705 default:
706 builder << node;
707 break;
708 }
709 }
710
711 if (!cond.empty()) {
712 builder.ss << string("\n#endif\n");
713 }
714
715 if (symbol.parent != nullptr) {
716 jump_to(node.back());
717 if (symbol.type == SymbolScope::NAMESPACE) {
718 skip_if('}');
719 }
720 else if (has_bracket) {
721 match_if('}');
722 }
723 }
724 }
725
726 void pipeline_decl(PipelineDecl stmt, SymbolScope &scope)
727 {
728 SymbolVariable *pipeline = scope.lookup_variable(table, stmt.identifier());
729
730 const bool is_graphic = stmt.type().str() == "PipelineGraphic";
731
732 FuncParamList params = stmt.parameters();
733
734 jump_to(stmt.front());
735 builder << stmt.type();
736 builder << pipeline->identifier;
737 builder.curr = params.front();
738 match_if('(');
739
740 Expr constants_init = Node{};
741
742 if (is_graphic) {
743 Expr vert_fn = params.child_first();
744 if (!vert_fn.is_valid() || vert_fn.child_count() != 1) {
746 return;
747 }
748 /* Resolve vertex function. */
749 auto *fn =
750 scope.lookup_function(table, LocalVar(vert_fn.child_first()).identifier()).unwrap(this);
751 if (fn->entry_point_type != SymbolFunction::EntryPointType::VERT) {
753 return;
754 }
755 builder << fn->identifier;
756 builder.curr = vert_fn.back().next();
757 match_if(',');
758
759 Expr frag_fn = vert_fn.next();
760 if (!frag_fn.is_valid() || frag_fn.child_count() != 1) {
762 return;
763 }
764 /* Resolve fragment function. */
765 auto *fn2 =
766 scope.lookup_function(table, LocalVar(frag_fn.child_first()).identifier()).unwrap(this);
767 if (fn2->entry_point_type != SymbolFunction::EntryPointType::FRAG) {
769 return;
770 }
771 builder << fn2->identifier;
772 builder.curr = frag_fn.back().next();
773 match_if(',');
774
775 constants_init = frag_fn.next();
776 }
777 else {
778 Expr comp_fn = params.child_first();
779 if (!comp_fn.is_valid() || comp_fn.child_count() != 1) {
781 return;
782 }
783 /* Resolve compute function. */
784 auto *fn =
785 scope.lookup_function(table, LocalVar(comp_fn.child_first()).identifier()).unwrap(this);
786 if (fn->entry_point_type != SymbolFunction::EntryPointType::COMP) {
788 return;
789 }
790 builder << fn->identifier;
791 builder.curr = comp_fn.back().next();
792 match_if(',');
793
794 constants_init = comp_fn.next();
795 }
796
797 while (constants_init.is_valid()) {
798 if (Constructor ctor(constants_init.child_first()); ctor.is_valid()) {
799 auto *cls = scope.lookup_class(table, ctor.identifier()).unwrap(this);
800 InitializerList list = ctor.initializer_list();
801 builder << cls->identifier;
802 builder << list;
803 if (list.back().next() == ',') {
804 builder << list.back().next();
805 }
806 }
807 else {
809 }
810 constants_init = constants_init.next();
811 }
812
813 builder.curr = params.back();
814 match_if(')');
815 match_if(';');
816 }
817
818 void return_statement(ReturnStmt stmt, SymbolScope &scope)
819 {
820 if (SymbolFunction *fn = scope.parent_function(); fn) {
821 string ret_val;
822 if (auto [r_fn, call] = get_inlined_function(stmt.expression(), scope); r_fn) {
823 ret_val = inline_function(r_fn, call, scope);
824 /* Resume. */
825 jump_to(stmt.front());
826 }
827
828 if (fn->is_inline) {
829 SymbolVariable *var = fn->lookup_variable(SymbolFunction::inline_fn_ret_id);
830 builder.ss << var->identifier << " = ";
831 }
832 else {
833 match_if(Return);
834 }
835
836 if (!ret_val.empty()) {
837 builder.ss << ret_val;
838 }
839 else if (InitializerList list(stmt.expression().child_first()); list.is_valid()) {
840 builder.ss << initializer_list(list, scope, fn->return_type).str;
841 }
842 else {
843 builder.ss << expr(stmt.expression(), scope).str;
844 }
845 builder.curr = stmt.expression().back().next();
846
847 if (fn->is_inline) {
848 builder.ss << "; break";
849 }
850 match_if(';');
851 }
852 else {
854 }
855 }
856
857 void structured_binding(StructuredBinding decl, SymbolScope &scope)
858 {
859 SymbolVariable *tmp_var = scope.lookup_variable(decl.tmp_id());
860
861 AssignStmt assign = decl.assign();
862
863 Token decl_front = decl.front();
864 Token assign_front = assign.front();
865
866 int pad = assign_front.char_number() - decl_front.char_number();
867
868 jump_to(decl_front);
869 /* Replace 'auto [a, b]' by the tmp variable declaration. */
870 string decl_str = tmp_var->type->identifier + " " + tmp_var->identifier;
871 /* Add padding until the assign statement. */
872 builder.ss << decl_str + string(max(0, pad - int(decl_str.size())), ' ');
873
874 builder.curr = assign_front;
875 assignment(assign, scope, tmp_var);
876 match_if(';');
877 }
878
879 void switch_statement(SwitchStmt stmt, SymbolScope &scope, int &local_scope_id)
880 {
881 match_if(Switch);
882 condition(stmt.condition(), scope, false, false);
883 match_if('{');
884
885 for (Node node : stmt.children_range()) {
886 switch (node.type()) {
887 case NodeType::Preprocessor:
888 builder << node;
889 break;
890 case NodeType::SwitchCase: {
891 SwitchCase switch_case(node);
892 jump_to(switch_case.front());
893 match_if(Case, Default);
894 if (!switch_case.is_default_case()) {
895 Node val = switch_case.value();
896 if (val.type() == NodeType::IdQualified) {
897 id_var_resolved(val, scope);
898 }
899 else {
900 builder << val;
901 }
902 builder.curr = val.back().next();
903 }
904 match_if(Colon);
905 local_scope(switch_case.body(), *scope.child_scope(local_scope_id++));
906 break;
907 }
908 case NodeType::Condition:
909 break; /* Already processed. */
910 default:
911 assert(0);
912 }
913 }
914 jump_to(stmt.back());
915 match_if('}');
916 }
917
918 void loop_unroll(ForLoop stmt, SymbolScope &scope)
919 {
920 VarDecl init_stmt = stmt.condition().child_first();
921 LocalStmt cond_stmt = init_stmt.next();
922 LocalStmt end_stmt = cond_stmt.next();
923 Expr cond_expr = cond_stmt.expr();
924 Expr end_expr = end_stmt.expr();
925 if (!init_stmt.is_valid()) {
927 return;
928 }
929 Declarator decl = init_stmt.child_first(NodeType::Declarator);
930 SymbolVariable *var = scope.lookup_variable(table, decl.identifier());
931 if (var->is_error) {
933 return;
934 }
935 /* Check if only a single var is declared. */
936 if (decl.next(NodeType::Declarator).is_valid()) {
938 return;
939 }
940 /* Check if loop variable is of integer type. */
941 SymbolClass *cls = var->type;
942 if (cls != table.int_cls && cls != table.uint_cls) {
944 return;
945 }
946 /* Check if loop variable is init by constexpr. */
947 Expr init_expr = decl.initial_value().expr();
948 if (!init_expr.is_valid()) {
950 return;
951 }
952 auto result = table.expr_type_analysis(scope, init_expr.child_first()).unwrap(this);
953 if (!result.is_constexpr()) {
955 return;
956 }
957 ConstexprValue val = result.value;
958 /* Check if loop statement assign to and only to the loop variable. */
959 for (Node node : end_expr.children_range()) {
960 if (node.type() == NodeType::Op && node.front() == ',') {
962 }
963 }
964 if (this->err_handler.err) {
965 return;
966 }
967
968 /* Replace loop variable resolved value with constexpr value. */
969 var->is_constexpr = true;
970 var->value = val;
971 /* Run a small virtual machine. For each iteration, check the condition, and run the loop
972 * statement. */
973 for (int i = 0;; i++) {
974 auto result = table.expr_type_analysis(scope, cond_expr.child_first()).unwrap(this);
975 if (!result.is_constexpr()) {
977 break;
978 }
979 /* Break if condition is false. */
980 if (result.value.comp_as<int>(0) == 0) {
981 break;
982 }
983 /* Break if too many iterations. */
984 if (i >= 64) {
986 break;
987 }
988 /* Generate the loop body. */
989 jump_to(stmt.body().front());
990 local_scope(stmt.body(), scope);
991
992 /* Evaluate the loop statement. */
993 var->value = eval_constexpr_with_side_effects(var, end_expr, scope);
994 if (err_handler.err) {
995 break;
996 }
997 }
998
999 /* Restore. */
1000 var->is_constexpr = false;
1001
1002 jump_to(stmt.back().next());
1003 }
1004
1005 ConstexprValue eval_constexpr_with_side_effects(SymbolVariable *var,
1006 Expr expr,
1007 SymbolScope &scope)
1008 {
1009 if (expr.child_count() == 2) {
1010 /* ExpressionParser will not evaluate increment and decrement operators.
1011 * We have to handle it ourselves. */
1012 TokenType op_type = Invalid;
1013 LocalVar local_var = expr.child_first();
1014 if (expr.child_last().type() == NodeType::Op) {
1015 local_var = expr.child_first();
1016 op_type = expr.back().type();
1017 }
1018 else if (expr.child_first().type() == NodeType::Op) {
1019 local_var = expr.child_last();
1020 op_type = expr.front().type();
1021 }
1022
1023 if (local_var.is_valid()) {
1024 if (scope.lookup_variable(table, local_var.identifier()) != var) {
1025 error(expr, Diag::UnrolledLoopMustAssignToVar, var->identifier);
1026 return ConstexprError(0);
1027 }
1028 /* Assign with the correct type cast. */
1029 switch (op_type) {
1030 case Decrement:
1031 return --var->value;
1032 case Increment:
1033 return ++var->value;
1034 default:
1035 break;
1036 }
1037 }
1038 }
1039 else {
1040 /* ExpressionParser will not evaluate assignment operator (=,+=,-=, ..)s.
1041 * We have to handle it ourselves. */
1042 LocalVar local_var = expr.child_first();
1043 if (local_var.is_valid()) {
1044 if (scope.lookup_variable(table, local_var.identifier()) != var) {
1045 error(expr, Diag::UnrolledLoopMustAssignToVar, var->identifier);
1046 return ConstexprError(0);
1047 }
1048 Node op = local_var.next();
1049 if (op.type() == NodeType::Op) {
1050 Node node = op.next();
1051
1052 auto result = table.expr_type_analysis(scope, node).unwrap(this);
1053 if (!result.is_constexpr()) {
1054 error(expr, Diag::UnrolledLoopNotConstexpr, var->identifier);
1055 return ConstexprError(0);
1056 }
1057
1058#ifdef _MSC_VER
1059/* Silence warning about bool operand.
1060 * They cannot happen because they are caught by the above check */
1061# pragma warning(push)
1062# pragma warning(disable : 4805)
1063#endif
1064
1065 /* Assign with the correct type cast. */
1066 switch (op.front().type()) {
1067 case Assign:
1068 return var->value = result.value;
1069 case AssignAdd:
1070 return var->value += result.value;
1071 case AssignSub:
1072 return var->value -= result.value;
1073 case AssignMul:
1074 return var->value *= result.value;
1075 case AssignDiv:
1076 if (contains_zero(result.value)) {
1078 return ConstexprError(0);
1079 }
1080 return var->value /= result.value;
1081 default:
1082 break;
1083 }
1084#ifdef _MSC_VER
1085# pragma warning(pop)
1086#endif
1087 }
1088 }
1089 }
1090 error(expr, Diag::UnrolledLoopInvalidExpression, var->identifier);
1091 return ConstexprError(0);
1092 }
1093
1094 void for_loop(ForLoop stmt, SymbolScope &scope)
1095 {
1096 if (stmt.condition().attributes().contains_attr("unroll")) {
1097 loop_unroll(stmt, scope);
1098 return;
1099 }
1100 match_if(For);
1101 condition(stmt.condition(), scope, true, true);
1102 local_scope(stmt.body(), scope);
1103 }
1104
1105 void while_loop(WhileLoop stmt, SymbolScope &scope)
1106 {
1107 match_if(While);
1108 condition(stmt.condition(), scope, false, true);
1109 local_scope(stmt.body(), scope);
1110 }
1111
1112 void do_while_loop(DoWhileLoop stmt, SymbolScope &scope)
1113 {
1114 match_if(Do);
1115 local_scope(stmt.body(), scope);
1116 match_if(While);
1117 condition(stmt.condition(), scope, false, true);
1118 match_if(';');
1119 }
1120
1121 void local_statement(LocalStmt stmt, SymbolScope &scope)
1122 {
1123 skip_node(stmt.attributes());
1124
1125 if (auto [fn, call] = get_inlined_function(stmt.expr(), scope); fn) {
1126 inline_function(fn, call, scope);
1127 jump_to(stmt.back().next());
1128 return;
1129 }
1130
1131 builder.ss << expr(stmt.expr(), scope).str;
1132 builder.curr = stmt.expr().back().next();
1133 match_if(';');
1134 }
1135
1136 void namespace_decl(ast::Namespace ns, SymbolScope &scope)
1137 {
1138 SymbolScope *sym = &scope;
1139 for (Id id : ns.identifier().children_of_type<Id>()) {
1140 sym = sym->scopes[string(id.str())];
1141 }
1142 skip_if(TokenType::Namespace);
1143 skip_node(ns.identifier());
1144 local_scope(ns.body(), *sym);
1145 }
1146
1147 void enum_decl(ClassDecl decl, SymbolScope &scope)
1148 {
1149 /* Default to parent scope for anonymous enums. */
1150 SymbolScope *body_scope = &scope;
1151 const IdQualified id = decl.identifier();
1152 if (id.is_valid()) {
1153 auto it = scope.scopes.find(string(id.str()));
1154 if (it == scope.scopes.end()) {
1156 return;
1157 }
1158 body_scope = it->second;
1159 }
1160 SymbolClass *enum_cls = id.is_valid() ? body_scope->as_class() : nullptr;
1161 LocalScope body = decl.body();
1162
1163 IdQualified type = decl.parent_class();
1164
1165 if (enum_cls && id.is_valid()) {
1166 /* TODO(fclem): Remove. Compatibility with previous BSL version. */
1167 builder.ss << "\n#define " << enum_cls->identifier << " " << type.str() << "\n";
1168 }
1169
1170 jump_to(decl.front());
1171
1172 /* Treat enum values as static variables. */
1173 for (EnumValue val : body.children_of_type<EnumValue>()) {
1174 line(val.front());
1175 string type_str = string("static constexpr ") + string(type.str());
1176 builder << type_str;
1177 /* Pretty align. */
1178 builder.ss << string(
1179 max(int64_t(1), int64_t(val.front().char_number()) - int64_t(type_str.size())), ' ');
1180
1181 SymbolVariable *var = id_var_decl_resolved(val.identifier(), *body_scope);
1182 builder << " = " + var->value_str();
1183 builder << string(";");
1184 }
1185 }
1186
1187 void class_decl(ClassDecl decl,
1188 SymbolScope &scope,
1189 int nested_id = 0,
1190 /* Resolved, templated class instance. */
1191 SymbolClass *inst_cls = nullptr)
1192 {
1193 if (decl.is_enum()) {
1194 enum_decl(decl, scope);
1195 return;
1196 }
1197
1198 SymbolClass *cls_ptr = inst_cls;
1199 if (!cls_ptr) {
1200 if (decl.identifier().is_valid()) {
1201 cls_ptr = scope.lookup_class(table, decl.identifier()).unwrap(this);
1202 }
1203 else {
1204 cls_ptr = scope.lookup_class("a" + to_string(nested_id));
1205 }
1206 }
1207 SymbolClass &cls = *cls_ptr;
1208 if (cls.is_error) {
1210 return;
1211 }
1212
1213 LocalScope body = decl.body();
1214
1215 {
1216 /* First emit nested classes. */
1217 int class_id = 0;
1218 for (ClassDecl decl : body.children_of_type<ClassDecl>()) {
1219 class_decl(decl, cls, class_id);
1220 ++class_id;
1221 }
1222 }
1223
1224 if (cls.is_srt()) {
1225 generate_srt_placeholder_macros(cls);
1226 lint_compilation_constant_redefinition(cls);
1227 }
1228
1229 /* Emit static variables. */
1230 for (VarDecl decl : body.children_of_type<VarDecl>()) {
1231 if (decl.type().is_static()) {
1232 var_decl(decl, cls);
1233 }
1234 }
1235
1236 /* Rollback to front. */
1237 jump_to(decl.front());
1238
1239 /* Then emit the class itself. */
1240 builder << "struct" + trivia(builder.curr);
1241
1242 skip_node(decl.attributes());
1243
1244 if (cls.is_anonymous) {
1245 builder.ss << cls.identifier << " ";
1246 }
1247 else {
1248 builder << cls.identifier + trivia(decl.identifier());
1249 }
1250
1251 builder.curr = body.front();
1252 match_if('{');
1253
1254 if (cls.is_union) {
1255 union_members_decl(cls);
1256 }
1257 else {
1258 class_members_decl(decl, cls);
1259 }
1260
1261 jump_to(body.back());
1262 match_if('}');
1263 match_if(';');
1264
1265 line(body.front());
1266 builder.ss << class_default_constructor(decl, cls) + "\n";
1267
1268 if (cls.is_union) {
1269 builder.ss << "\n";
1270 NOTE(decl, Diag::NoteDeclarationUnionRequested, string(decl.identifier().str()));
1271
1272 /* Emit getter and setters. */
1273 for (SymbolVariable *var : cls.non_static_variables_in_declaration_order()) {
1274 builder.ss << union_getter(cls, *var) + "\n";
1275 builder.ss << union_setter(cls, *var) + "\n";
1276 }
1277 }
1278 else {
1279 /* Emit function prototypes. */
1280 if (body.child_first(NodeType::FuncDecl).is_valid()) {
1281 /* Prototypes are not needed with MSL wrapper class. */
1282 builder.ss << "\n#ifndef GPU_METAL\n";
1283 for (FuncDecl decl : body.children_of_type<FuncDecl>()) {
1284 func_forward_decl(decl, cls);
1285 }
1286 builder.ss << "#endif\n";
1287 }
1288 /* Emit function members. */
1289 for (FuncDecl decl : body.children_of_type<FuncDecl>()) {
1290 func_decl(decl, cls);
1291 }
1292 }
1293 }
1294
1295 void class_members_decl(ClassDecl decl, SymbolClass &cls)
1296 {
1297 LocalScope body = decl.body();
1298 /* Emit member variables. */
1299 int member_count = 0;
1300 int class_id = 0;
1301 for (Node node : body.children_range()) {
1302 switch (node.type()) {
1303 case NodeType::VarDecl: {
1304 VarDecl decl = node;
1305 if (!decl.type().is_static()) {
1306 member_count += var_decl(decl, cls);
1307 }
1308 break;
1309 }
1310 case NodeType::ClassDecl: {
1311 ClassDecl decl = node;
1312 if (decl.is_anonymous() && !decl.is_enum()) {
1313 /* Anonymous class are instantiated as regular members. */
1314 jump_to(decl.front());
1315 string id = "a" + to_string(class_id);
1316 id_type_resolved(id, cls);
1317 builder.ss << " " << id << "_;";
1318 member_count++;
1319 }
1320 ++class_id;
1321 break;
1322 }
1323 default:
1324 break;
1325 }
1326 }
1327
1328 if (member_count == 0) {
1329 /* Add padding member. Empty class are invalid in GLSL. */
1330 builder.ss << "int _pad;";
1331 }
1332
1333 if (cls.is_srt()) {
1334 parse_class_metadata(cls, body);
1335 }
1336 }
1337
1338 void lint_compilation_constant_redefinition(SymbolClass &cls)
1339 {
1340 vector<const SymbolVariable *> compilation_constants;
1341 /* Avoid infinite loops or redundant visit. */
1342 vector<const SymbolClass *> visited_srt;
1343
1344 auto check_class = [&](auto &self, SymbolClass *cls) {
1345 if (std::ranges::find(visited_srt, cls) != visited_srt.end()) {
1346 return;
1347 }
1348 visited_srt.emplace_back(cls);
1349
1350 for (const auto &[k, v] : cls->variables) {
1351 const SymbolVariable &member = *v.second;
1352 if (member.is_compilation_const) {
1353 /* Check for duplicate O(N^2). */
1354 for (const SymbolVariable *other : compilation_constants) {
1355 if (other->original == member.original) {
1356 NOTE(other->loc.tok, Diag::CompilationConstantPreviousDecl, "");
1357 error(member.loc.tok, Diag::CompilationConstantRedefinition, member.original);
1358 }
1359 }
1360 compilation_constants.emplace_back(&member);
1361 }
1362 if (member.type->srt_type == ResourceTableType::RESOURCE_TABLE) {
1363 /* Recurse. */
1364 self(self, member.type);
1365 }
1366 }
1367 };
1368
1369 check_class(check_class, &cls);
1370 }
1371
1372 void generate_srt_placeholder_macros(SymbolClass &cls)
1373 {
1374 string access_macros = "#pragma resource_access ";
1375 for (const auto &[k, v] : cls.variables) {
1376 const SymbolVariable &member = *v.second;
1377 if (member.type->is_srt()) {
1378 access_macros += " access_" + cls.identifier + "_" + member.identifier + "()";
1379 access_macros += " " + member.type->identifier + "_ctor_()";
1380 }
1381 else {
1382 access_macros += " access_" + cls.identifier + "_" + member.identifier + "()";
1383 access_macros += " " + member.identifier + "";
1384 }
1385 }
1386
1387 builder.ss << "\n" + access_macros + "\n";
1388 builder.ss << "\n#pragma resource_defines " + cls.identifier + "\n";
1389 }
1390
1391 string size_to_float_vec_type_str(size_t member_size)
1392 {
1393 if (member_size == 4) {
1394 return "float";
1395 }
1396 if (member_size == 8) {
1397 return "float2";
1398 }
1399 if (member_size == 12) {
1400 return "float3";
1401 }
1402 if (member_size == 16) {
1403 return "float4";
1404 }
1405 return "ERROR";
1406 }
1407
1408 void union_members_decl(SymbolClass &cls)
1409 {
1410 for (int i = 0; i < cls.size; i += 16) {
1411 int member_size = min(16, cls.size - i);
1412 builder.ss << size_to_float_vec_type_str(member_size) << " _" << to_string(i / 16) << "; ";
1413 }
1414 }
1415
1416 string union_ctor(SymbolClass &cls)
1417 {
1418 string members;
1419 for (int i = 0; i < cls.size; i += 16) {
1420 int member_size = min(16, cls.size - i);
1421 SymbolClass *type = table.root->lookup_class(size_to_float_vec_type_str(member_size));
1422 members += "r._" + to_string(i / 16) + "=" + default_value(*type) + ";";
1423 }
1424 return members;
1425 }
1426
1427 string default_value(const SymbolClass &type)
1428 {
1429 if (type.identifier == "float") {
1430 return "0.0f";
1431 }
1432 if (type.identifier == "uint" || type.identifier == "uchar") {
1433 return "0u";
1434 }
1435 if (type.identifier == "int" || type.identifier == "char") {
1436 return "0";
1437 }
1438 if (type.identifier == "bool") {
1439 return "false";
1440 }
1441 if (type.is_builtin()) {
1442 return type.identifier + "(0)";
1443 }
1444 return type.identifier + "_ctor_()";
1445 };
1446
1447 /* Return temp variable name for a given index. */
1448 static string get_temp_name(size_t index)
1449 {
1450 string name;
1451 /* Shift to 1-based for the bijective base-26 math. */
1452 size_t n = index + 1;
1453 while (n > 0) {
1454 n--; /* Map 0-25 to 'a'-'z'. */
1455 name += char('a' + (n % 26));
1456 n /= 26;
1457 }
1458 return name;
1459 }
1460
1461 string class_default_constructor(ClassDecl decl, SymbolClass &cls)
1462 {
1463 const string &cls_id = cls.identifier;
1464
1465 string members;
1466 if (cls.is_union) {
1467 members = union_ctor(cls);
1468 }
1469 else {
1470 int class_id = 0;
1471 for (Node node : decl.body().children_range()) {
1472 switch (node.type()) {
1473 case NodeType::VarDecl: {
1474 VarDecl decl = node;
1475 if (!decl.type().is_static()) {
1476 SymbolClass *type = id_type_lookup_resolved(decl.type().identifier(), cls);
1477 for (Declarator d : decl.children_of_type<Declarator>()) {
1478 SymbolVariable *var = cls.lookup_variable(table, d.identifier());
1479 if (var->is_static || var->bit_offset != 0) {
1480 continue;
1481 }
1482 string access;
1483 string close;
1484 int dim = 0;
1485 Subscript sub = d.array().sub();
1486 while (sub.is_valid()) {
1487 string len = var->capacity_value.is_valid() ?
1488 "SRT_CONSTANT_" + string(var->capacity_value.str()) :
1489 string(sub.expr().str());
1490 string var = get_temp_name(dim++);
1491 members += "for(int " + var + " =0;" + var + " < " + len + ";++" + var + ") {";
1492 close += "}";
1493 access += "[" + var + "]";
1494 sub = sub.next();
1495 }
1496 members += "r." + var->original + access + "=" + default_value(*type) + ";";
1497 members += close;
1498 }
1499 }
1500 break;
1501 }
1502 case NodeType::ClassDecl: {
1503 ClassDecl decl = node;
1504 if (decl.is_anonymous() && !decl.is_enum()) {
1505 /* Anonymous class are instantiated as regular members. */
1506 jump_to(decl.front());
1507 string type_id = "a" + to_string(class_id);
1508 SymbolClass *type = cls.lookup_class(type_id);
1509 string member_id = type_id + "_";
1510
1511 members += "r." + member_id + "=" + default_value(*type) + ";";
1512 }
1513 ++class_id;
1514 break;
1515 }
1516 default:
1517 break;
1518 }
1519 }
1520
1521 if (members.empty()) {
1522 /* Empty struct will have a padding int. */
1523 members += "r._pad=0;";
1524 }
1525 }
1526
1527 return cls_id + " " + cls_id + "_ctor_() {" + cls_id + " r;" + members + "return r;}";
1528 }
1529
1530 string union_data_access(const size_t member_offset,
1531 const size_t member_size,
1532 const size_t union_size)
1533 {
1534 string access = "_" + to_string(member_offset / 16);
1535
1536 if (member_size == 12) {
1537 access += ".xyz";
1538 }
1539 else if (member_size == 8) {
1540 access += ((member_offset % 16) == 0) ? ".xy" : ".zw";
1541 }
1542 else if (member_size == 4) {
1543 switch (member_offset % 16) {
1544 case 0:
1545 /* Special case if last member is a scalar. */
1546 access += ((union_size - member_offset) == 4) ? "" : ".x";
1547 break;
1548 case 4:
1549 access += ".y";
1550 break;
1551 case 8:
1552 access += ".z";
1553 break;
1554 case 12:
1555 access += ".w";
1556 break;
1557 }
1558 }
1559 return access;
1560 }
1561
1562 string member_from_float(const SymbolClass &member_type, const string &access)
1563 {
1564 /* Account for trivial types. */
1565 const string &type = member_type.identifier;
1566
1567 if (type.starts_with("uint")) {
1568 return "floatBitsToUint(" + access + ")";
1569 }
1570 if (type.starts_with("int")) {
1571 return "floatBitsToInt(" + access + ")";
1572 }
1573 if (type == "bool32_t") {
1574 return access + " != 0";
1575 }
1576 return access;
1577 }
1578
1579 string member_to_float(const SymbolClass &member_type, const string &access)
1580 {
1581 /* Account for trivial types. */
1582 const string &type = member_type.identifier;
1583
1584 if (type.starts_with("uint")) {
1585 return "uintBitsToFloat(" + access + ")";
1586 }
1587 if (type.starts_with("int")) {
1588 return "intBitsToFloat(" + access + ")";
1589 }
1590 if (type == "bool32_t") {
1591 return "intBitsToFloat(int(" + access + "))";
1592 }
1593 return access;
1594 }
1595
1596 string union_getter(SymbolClass &union_type, SymbolVariable &member)
1597 {
1598 SymbolClass &member_type = *member.type;
1599 string union_type_id = union_type.identifier;
1600 string fn_type_id = member_type.identifier;
1601 string fn_name = "_" + member.original;
1602 string fn_args = "(" + union_type_id + " this_)";
1603 string fn_body = "{\n";
1604 if (member_type.is_builtin()) {
1605 if (member.array_dimensions > 0) {
1606 error(member.loc.tok, Diag::UnionArrayUnsupported);
1607 }
1608 string access = "this_." +
1609 union_data_access(member.offset, member_type.size, union_type.size);
1610 fn_body += " return " + member_from_float(*member.type, access) + ";\n";
1611 }
1612 else {
1613 /* Declare return variable of the same type as the accessed member. */
1614 fn_body += " " + fn_type_id + " r;\n";
1615 for (const auto &var : member_type.get_all_members_flat().unwrap(this)) {
1616 string to_var = "r." + var.path;
1617 string access = "this_." +
1618 union_data_access(var.absolute_offset, var.type->size, union_type.size);
1619 fn_body += " " + to_var + " = " + member_from_float(*var.type, access) + ";\n";
1620 }
1621 fn_body += " return r;\n";
1622 }
1623 fn_body += "}";
1624 return fn_type_id + " " + fn_name + fn_args + " " + fn_body;
1625 };
1626
1627 string union_setter(SymbolClass &union_type, SymbolVariable &member)
1628 {
1629 SymbolClass &member_type = *member.type;
1630 string union_type_id = union_type.identifier;
1631 string member_type_id = member_type.identifier;
1632 string fn_name = "_" + member.original + "_set_";
1633 string fn_args = "(" + union_type_id + " &this_, " + member_type_id + " v)";
1634 string fn_body = "{\n";
1635 if (member_type.is_builtin()) {
1636 if (member.array_dimensions > 0) {
1637 error(member.loc.tok, Diag::UnionArrayUnsupported);
1638 }
1639 string to_var = "this_." +
1640 union_data_access(member.offset, member_type.size, union_type.size);
1641 string access = "v." + member.original;
1642 fn_body += " " + to_var + " = " + member_to_float(*member.type, access) + ";\n";
1643 }
1644 else {
1645 for (const auto &var : member_type.get_all_members_flat().unwrap(this)) {
1646 string to_var = "this_." +
1647 union_data_access(var.absolute_offset, var.type->size, union_type.size);
1648 string access = "v." + var.path;
1649 fn_body += " " + to_var + " = " + member_to_float(*var.type, access) + ";\n";
1650 }
1651 }
1652 fn_body += "}";
1653 return "void " + fn_name + fn_args + " " + fn_body;
1654 };
1655
1656 void func_forward_decl(FuncDecl decl, SymbolScope &scope)
1657 {
1658 string id(decl.identifier().str());
1659 if (auto it = scope.functions.find(id); it != scope.functions.end()) {
1660 SymbolScope &body_scope = *it->second.second;
1661 // jump_to(decl.front()); /* Adds too many directives. */
1662 builder.curr = decl.front();
1663 skip_node(decl.attributes());
1664 skip_if(Static);
1665 id_type(decl.return_type(), scope);
1666 id_func_resolved(decl.identifier(), decl.arguments(), scope, scope);
1667 func_arg_list(decl.arguments(), body_scope, false, true);
1668 builder << string(";\n");
1669 }
1670 else {
1671 assert(0);
1672 }
1673 }
1674
1675 void func_forward_decl(FuncForwardDecl decl, SymbolScope &scope)
1676 {
1677 /* Prototypes are not needed with MSL wrapper class. */
1678 builder.ss << "\n#ifndef GPU_METAL\n";
1679 string id(decl.identifier().str());
1680 if (auto it = scope.functions.find(id); it != scope.functions.end()) {
1681 SymbolScope &body_scope = *it->second.second;
1682 jump_to(decl.front());
1683 builder.curr = decl.front();
1684 skip_node(decl.attributes());
1685 skip_if(Static);
1686 id_type(decl.return_type(), scope);
1687 id_func_resolved(decl.identifier(), decl.arguments(), scope, scope);
1688 func_arg_list(decl.arguments(), body_scope, false, true);
1689 builder << string(";\n");
1690 }
1691 else {
1692 error(decl, Diag::UnknownFunction, id);
1693 }
1694 builder.ss << "#endif\n";
1695 }
1696
1697 string condition(const SymbolScope *scope)
1698 {
1699 string str;
1700 for (const auto &[k, var] : scope->variables) {
1701 if (var.second->type->is_srt()) {
1702 if (var.second->type->srt_type == ResourceTableType::VERTEX_OUT) {
1703 str += " && defined(IFACE_INFO_" + var.second->type->identifier + "_t)";
1704 }
1705 else {
1706 str += " && defined(CREATE_INFO_" + var.second->type->identifier + ")";
1707 }
1708 }
1709 }
1710 return str.empty() ? str : str.substr(4);
1711 }
1712
1713 string condition(const SymbolFunction *fn)
1714 {
1715 string str;
1716 /* Make functions writing to vertex outputs limited to the vertex shader. */
1717 for (int i = 0; i < fn->arg_types.size(); ++i) {
1718 if (fn->arg_types[i]->srt_type == ResourceTableType::VERTEX_OUT && !fn->arg_const[i]) {
1719 str += " && defined(GPU_VERTEX_SHADER)";
1720 break;
1721 }
1722 }
1723 /* Make functions writing to fragment outputs limited to the fragment shader. */
1724 for (int i = 0; i < fn->arg_types.size(); ++i) {
1725 if (fn->arg_types[i]->srt_type == ResourceTableType::FRAGMENT_OUT && !fn->arg_const[i]) {
1726 str += " && defined(GPU_FRAGMENT_SHADER)";
1727 break;
1728 }
1729 }
1730
1731 if (fn->is_entry_point()) {
1732 str += " && defined(ENTRY_POINT_" + fn->identifier + ")";
1733 switch (fn->entry_point_type) {
1735 str += " && defined(GPU_FRAGMENT_SHADER)";
1736 break;
1738 str += " && defined(GPU_VERTEX_SHADER)";
1739 break;
1741 str += " && defined(GPU_COMPUTE_SHADER)";
1742 break;
1744 break;
1745 }
1746 }
1747 else if (string scope_str = condition(static_cast<const SymbolScope *>(fn));
1748 !scope_str.empty())
1749 {
1750 str += " && " + scope_str;
1751 }
1752
1753 return str.empty() ? str : str.substr(4);
1754 }
1755
1756 void func_decl(FuncDecl decl,
1757 SymbolScope &scope,
1758 /* Resolved, templated function instance. */
1759 SymbolFunction *inst_fn = nullptr)
1760 {
1761 LocalScope body = decl.body();
1762
1763 if (inst_fn == nullptr) {
1764 inst_fn = id_func_resolved_lookup(decl.identifier(), decl.arguments(), scope, scope);
1765 }
1766
1767 if (inst_fn->is_inline) {
1768 /* Do not emit inline function. */
1769 return;
1770 }
1771
1772 if (inst_fn->fn_type == SymbolFunction::MEMBER && decl.is_template()) {
1773 if (SymbolClass *cls = inst_fn->parent_class(); cls) {
1774 /* Leave a breadcrumb for a mutation pass which will move the following forward declaration
1775 * all the way up at the class declaration. This is needed to allow other member functions
1776 * to call the templated function. */
1777 builder.ss << "#pragma member_forward_decl " << inst_fn->parent_class()->identifier
1778 << "\n";
1779 builder.ss << inst_fn->return_type->identifier << " " << inst_fn->identifier;
1780 builder.curr = decl.arguments().front();
1781 func_arg_list(decl.arguments(), *inst_fn, false);
1782 builder.ss << ";\n";
1783 }
1784 else {
1786 }
1787 }
1788
1789 string cond = condition(inst_fn);
1790 if (!cond.empty()) {
1791 builder.ss << string("#if ") + cond + "\n";
1792 }
1793
1794 jump_to(decl.front());
1795 skip_node(decl.attributes());
1796 skip_if(Static);
1797 /* Note that we match the id type from inside the function scope in order to match template
1798 * argument aliases. */
1799 id_type(decl.return_type(), *inst_fn);
1800
1801 builder.curr = decl.identifier().back();
1802 builder << inst_fn->identifier + trivia(decl.identifier());
1803
1804 if (inst_fn->is_entry_point()) {
1805 builder.curr = decl.arguments().back();
1806 builder << string("()\n");
1807 }
1808 else {
1809 func_arg_list(decl.arguments(), *inst_fn);
1810 }
1811
1812 local_scope(body, *inst_fn);
1813
1814 if (!cond.empty()) {
1815 builder.ss << string("#endif\n");
1816 }
1817
1818 if (inst_fn->is_entry_point()) {
1819 entry_point_arg_list_metadata(decl, *inst_fn);
1820 }
1821 }
1822
1823 pair<SymbolFunction *, FuncCall> get_inlined_function(Expr expr, SymbolScope &scope)
1824 {
1825 FuncCall call(expr.child_first());
1826 if (!call.is_valid()) {
1827 return {nullptr, {}};
1828 }
1829 if (!expr.has_single_child() || expr.parent().parent().type() == NodeType::Condition) {
1830 return {nullptr, {}};
1831 }
1832
1833 SymbolFunction *fn = id_func_resolved_lookup(
1834 call.identifier(), call.parameters(), scope, scope);
1835 if (!fn || !fn->is_inline) {
1836 return {nullptr, {}};
1837 }
1838 return {fn, call};
1839 }
1840
1841 vector<SymbolFunction *> inlining_stack;
1842
1843 string inline_function(SymbolFunction *fn, FuncCall call, SymbolScope &scope)
1844 {
1845 string uuid = to_string(call.front().index_);
1846 string ret_val = "_r" + uuid;
1847
1848 if (std::ranges::find(inlining_stack, fn) != inlining_stack.end()) {
1850 return "";
1851 }
1852
1853 inlining_stack.push_back(fn);
1854 NOTE(call, Diag::NoteInInliningOf, fn->original);
1855
1856 jump_to(fn->decl.front());
1857
1858 /* Communicate the name of the return variable to the return statements. */
1859 if (auto it = fn->variables.find(SymbolFunction::inline_fn_ret_id); it != fn->variables.end())
1860 {
1861 SymbolVariable *var = it->second.second;
1862 var->identifier = ret_val;
1863 /* Create return variable if any. */
1864 builder.ss << fn->return_type->identifier << " " << ret_val << ";\n";
1865 }
1866
1867 /* Create local scope. */
1868 builder.ss << "do {\n";
1869 jump_to(fn->decl.front());
1870
1871 /* Declare argument copies. */
1872 int arg_i = 0;
1873 Expr param = call.parameters().child_first();
1874 vector<string> original_identifiers;
1875 for (FuncArg arg : fn->decl.arguments().children_range()) {
1876 SymbolVariable *var = fn->lookup_variable(table, arg.identifier());
1877
1878 if (!param.is_valid() && (arg.is_reference() || !fn->arg_defaults[arg_i].is_valid())) {
1879 error(call, Diag::MissingParameterForCall, var->identifier);
1880 continue;
1881 }
1882
1883 original_identifiers.emplace_back(var->identifier);
1884
1885 if (arg.is_reference() || var->type->is_opaque) {
1886 /* Check if reference has no side effect. */
1887 table.expr_type_analysis(scope, param.child_first(), true).unwrap(this);
1888 var->identifier = expr(param, scope).str;
1889 }
1890 else {
1891 /* Make parameter name unique to avoid shadowing. */
1892 string id = "_" + string(arg.identifier().str()) + uuid;
1893 /* Change the mangled name of the argument. */
1894 var->identifier = id;
1895
1896 Expr init_expr = (param.is_valid()) ? param : fn->arg_defaults[arg_i];
1897 builder.ss << fn->arg_types[arg_i]->identifier << " " << id;
1898 builder.ss << " = " << expr(init_expr, scope).str << "; ";
1899 }
1900 param = param.next();
1901 ++arg_i;
1902 }
1903 builder.ss << "\n";
1904
1905 local_scope(fn->decl.body(), *fn);
1906
1907 /* Create argument assignments. */
1908 builder.ss << "} while (false);\n";
1909
1910 inlining_stack.pop_back();
1911
1912 {
1913 /* Restore argument identifiers. */
1914 int arg_i = 0;
1915 for (FuncArg arg : fn->decl.arguments().children_range()) {
1916 SymbolVariable *var = fn->lookup_variable(table, arg.identifier());
1917 var->identifier = original_identifiers[arg_i++];
1918 }
1919 }
1920
1921 return ret_val;
1922 }
1923
1924 void entry_point_arg_list_metadata(FuncDecl decl, SymbolFunction &fn)
1925 {
1926 /* For now, just emit good old create info macros. */
1927 string create_info_decl;
1928
1929 for (Attr attr : decl.attributes().children_of_type<Attr>()) {
1930 string_view id = attr.identifier().str();
1931 if (id == "clip_control") {
1932 create_info_decl += "BUILTINS(BuiltinBits::CLIP_CONTROL)\n";
1933 }
1934 else if (id == "texture_atomic") {
1935 create_info_decl += "BUILTINS(BuiltinBits::TEXTURE_ATOMIC)\n";
1936 }
1937 else if (id == "early_fragment_tests") {
1938 create_info_decl += "EARLY_FRAGMENT_TEST(true)\n";
1939 }
1940 else if (id == "local_size") {
1941 create_info_decl += "LOCAL_GROUP_SIZE" + string(attr.parameters().str()) + "\n";
1942 }
1943 else if (id == "metal_max_total_threads_per_threadgroup") {
1944 create_info_decl += "MTL_MAX_TOTAL_THREADS_PER_THREADGROUP" +
1945 string(attr.parameters().str()) + "\n";
1946 }
1947 }
1948
1949 for (FuncArg arg : decl.arguments().children_of_type<FuncArg>()) {
1950 auto attr = resource_type_from_attributes(arg.attributes()).unwrap(this);
1951
1952 SymbolVariable *var = fn.lookup_variable(table, arg.identifier());
1953
1954 const string &resolved_type = var->type->identifier;
1955
1956 switch (attr.res_type) {
1974 string res_condition_lambda = parse_condition_as_lambda(fn, arg.attributes());
1975 create_info_decl += ".builtins(BuiltinBits::" + to_str(attr.res_type) +
1976 res_condition_lambda + ")\n";
1977 break;
1978 }
1980 string res_condition_lambda = parse_condition_as_lambda(fn, arg.attributes());
1981 create_info_decl += ".builtins(BuiltinBits::BARYCENTRIC_COORD" + res_condition_lambda +
1982 ")\n";
1983 break;
1984 }
1986 for (Attr attr : arg.attributes().children_of_type<Attr>()) {
1987 string_view id = attr.identifier().str();
1988 if (id == "frag_depth") {
1989 create_info_decl += "DEPTH_WRITE(DepthWrite::" +
1990 to_uppercase(string(attr.parameters().splat_1().arg1.str())) +
1991 ")\n";
1992 }
1993 }
1994 break;
1996 string res_condition_lambda = parse_condition_as_lambda(fn, arg.attributes());
1997 if (res_condition_lambda.empty()) {
1998 create_info_decl += "ADDITIONAL_INFO(" + resolved_type + ")\n";
1999 }
2000 else {
2001 create_info_decl += ".additional_info_with_condition(\"" + resolved_type + "\"" +
2002 res_condition_lambda + ")\n";
2003 }
2004 break;
2005 }
2007 case ResourceType::OUT:
2008 case ResourceType::IN:
2009 if (var->type->srt_type == ResourceTableType::VERTEX_OUT) {
2010 string res_condition_lambda = parse_condition_as_lambda(fn, arg.attributes());
2011 if (res_condition_lambda.empty()) {
2012 create_info_decl += ".vertex_out(" + resolved_type + "_t)\n";
2013 }
2014 else {
2015 create_info_decl += ".vertex_out(" + resolved_type + "_t" + res_condition_lambda +
2016 ")\n";
2017 }
2018 }
2019 else {
2020 create_info_decl += "ADDITIONAL_INFO(" + resolved_type + ")\n";
2021 }
2022 break;
2045 case ResourceType::NONE:
2046 break;
2047 }
2048 }
2049
2050 if (create_info_decl.empty()) {
2051 create_info_decl += "DEFINE(\"EMPTY_CREATE_INFO\")\n";
2052 }
2053
2054 create_info_decl = "GPU_SHADER_CREATE_INFO(" + fn.identifier + "_infos_)\n" +
2055 create_info_decl + "GPU_SHADER_CREATE_END()\n";
2056 metadata.create_infos_declarations.emplace_back(create_info_decl);
2057 }
2058
2059 void func_arg_list(FuncArgList list,
2060 SymbolScope &scope,
2061 bool with_trivia = true,
2062 bool no_arg_name = false)
2063 {
2064 match_if('(');
2065
2066 FuncDecl decl = list.parent();
2067 if (decl.is_method() && !decl.is_static()) {
2068 ClassDecl cls = decl.parent_class();
2069 if (decl.is_const()) {
2070 builder.ss << "const ";
2071 }
2072 SymbolClass *cls_resolved = id_type_resolved(cls.identifier(), scope);
2073 if (cls_resolved->is_srt()) {
2074 /* WORKAROUND: Do not pass SRT by reference otherwise we get a compilation error on metal
2075 * we cannot bind to a temporary when the caller is just calling a constructor as the
2076 * parameter. */
2077 builder.ss << "this_";
2078 }
2079 else {
2080 builder.ss << "&this_";
2081 }
2082
2083 if (!list.is_empty()) {
2084 builder.ss << ", ";
2085 }
2086 builder.curr = list.front().next();
2087 }
2088
2089 if (builder.curr != ')') {
2090 int i = 0;
2091 for (FuncArg arg : list.children_of_type<FuncArg>()) {
2092 skip_node(arg.attributes());
2093 id_type(arg.type(), scope);
2094 declarator(arg.declarator(), scope, true, no_arg_name ? i++ : -1);
2095 match_if(',');
2096 }
2097 }
2098
2099 if (with_trivia) {
2100 match_if(')');
2101 skip_if(TokenType::Const);
2102 }
2103 else {
2104 builder << string(")");
2105 if (builder.curr == TokenType::Const) {
2106 builder.curr.next();
2107 }
2108 }
2109 }
2110
2111 void template_inst(TemplateInst temp_decl, SymbolScope &scope)
2112 {
2113 if (temp_decl.is_class()) {
2114 ClassDecl decl = temp_decl.decl();
2115 auto *base_cls = scope.lookup_class_base(table, decl.identifier());
2116 /* Instantiation should have been checked already. */
2117 auto [temp_cls, full_id, _] = base_cls->template_data->lookup_inst(
2118 temp_decl.parameters(), scope, table);
2120 Node decl_tmp = base_cls->template_data->decl.decl();
2121 class_decl(decl_tmp, scope, 0, temp_cls);
2122 }
2123 else {
2124 FuncForwardDecl decl = temp_decl.decl();
2125 auto *base_fn = scope.lookup_function_base(table, decl.identifier());
2126 /* Instantiation should have been checked already. */
2127 auto [temp_fn, full_id, _] = base_fn->template_data->lookup_inst(
2128 temp_decl.parameters(), scope, table);
2130 Node decl_tmp = base_fn->template_data->decl.decl();
2131 func_decl(decl_tmp, *temp_fn->parent, temp_fn);
2132 }
2133 }
2134
2135 void template_spec(TemplateSpec temp_spec, SymbolScope &scope)
2136 {
2137 if (temp_spec.is_class()) {
2138 ClassDecl decl = temp_spec.decl();
2139 auto *base_cls = scope.lookup_class_base(table, decl.identifier());
2140 /* Instantiation should have been checked already. */
2141 auto [temp_cls, full_id, _] = base_cls->template_data->lookup_inst(
2142 temp_spec.parameters(), scope, table);
2144 class_decl(decl, scope, 0, temp_cls);
2145 }
2146 else {
2147 FuncDecl decl = temp_spec.decl();
2148 auto *base_fn = scope.lookup_function_base(table, decl.identifier());
2149 /* Instantiation should have been checked already. */
2150 auto [temp_fn, full_id, _] = base_fn->template_data->lookup_inst(
2151 temp_spec.parameters(), scope, table);
2153 func_decl(decl, *temp_fn->parent, temp_fn);
2154 }
2155 }
2156
2157 /* Match if/else if/else statements */
2158 void if_statement(Node decl,
2159 SymbolScope &parent_scope,
2160 int &local_scope_id,
2161 bool preceded_by_true_if_constexpr = false,
2162 bool preceded_by_regular_if = false)
2163 {
2164 SymbolScope *scope = parent_scope.child_scope(local_scope_id++);
2165 if (scope == nullptr) {
2167 return;
2168 }
2169
2170 jump_to(decl.front());
2171
2172 Condition cond(decl.child_first());
2173
2174 bool is_constexpr = cond.is_valid() && cond.front().prev() == Constexpr;
2175
2176 bool constexpr_value = true;
2177 if (cond.is_valid()) {
2178 LocalStmt stmt = cond.child_first();
2179 auto result = table.expr_type_analysis(*scope, stmt.expr().child_first()).unwrap(this);
2180
2181 if (is_constexpr && !result.is_constexpr()) {
2182 /* Report error if expression couldn't be evaluated. */
2184 }
2185 else if (result.is_constexpr()) {
2186 /* Expression was evaluated successfully. Treat the statement as constexpr. */
2187 is_constexpr = true;
2188 }
2189
2190 if (result.is_constexpr()) {
2191 constexpr_value = result.value.comp_as<int>(0) != 0;
2192 }
2193
2194 if (cond.attributes().contains_attr("static_branch")) {
2196 }
2197 }
2198
2199 /* Generate a 'else' statement only if there is a non-constexpr if above in the chain,
2200 * and if no 'if constexpr' evaluated to true above in the chain,
2201 * and if not a 'if constexpr' itself. */
2202 if (preceded_by_regular_if && !preceded_by_true_if_constexpr &&
2203 (!is_constexpr || constexpr_value == true))
2204 {
2205 match_if(Else);
2206 }
2207 else {
2208 skip_if(Else);
2209 }
2210
2211 /* Generate a if statement only if this is not a 'if constexpr',
2212 * and if no 'if constexpr' evaluated to true above in the chain. */
2213 if (!is_constexpr && !preceded_by_true_if_constexpr) {
2214 match_if(If);
2215 skip_if(Constexpr);
2216 if (cond.is_valid()) {
2217 condition(cond, *scope, false, true);
2218 }
2219 }
2220 else {
2221 skip_if(If);
2222 skip_if(Constexpr);
2223 skip_node(cond);
2224 }
2225
2226 LocalScope body = decl.child_last(NodeType::LocalScope);
2227
2228 if (!preceded_by_true_if_constexpr && (!is_constexpr || constexpr_value == true)) {
2229 local_scope(body, *scope);
2230 }
2231
2232 /* Process preprocessor directive that can be added between if statements. */
2233 Node node = body.next();
2234 while (node.type() == NodeType::Preprocessor) {
2235 builder << node;
2236 node = node.next();
2237 }
2238
2239 Node next = decl.next();
2240 if (next.type() == NodeType::ElseIfStmt || next.type() == NodeType::ElseStmt) {
2241 if_statement(next,
2242 parent_scope,
2243 local_scope_id,
2244 preceded_by_true_if_constexpr || (is_constexpr && constexpr_value == true),
2245 preceded_by_regular_if || !is_constexpr);
2246 }
2247 else {
2248 jump_to(next.front());
2249 }
2250 }
2251
2252 struct StaticConditionStack {
2253 public:
2256
2257 string_view str()
2258 {
2259 return front.p->substr(front.front(), back.back());
2260 }
2261 };
2262
2263 private:
2264 vector<ast::Expr> pos_conditions;
2265 vector<ast::Expr> neg_conditions;
2266
2267 public:
2268 void push_positive_condition(ast::Condition cond)
2269 {
2270 /* Note: Assumes If statements have only one LocalStmt. */
2271 pos_conditions.emplace_back(cond.child_first().child_first());
2272 }
2273 void pop_positive_condition()
2274 {
2275 pos_conditions.pop_back();
2276 }
2277
2278 void push_negative_condition(ast::Condition cond)
2279 {
2280 /* Note: Assumes If statements have only one LocalStmt. */
2281 neg_conditions.emplace_back(cond.child_first().child_first());
2282 }
2283 void pop_negative_condition()
2284 {
2285 neg_conditions.pop_back();
2286 }
2287
2288 /* Checks if all conditions inside `expr` are already checked inside the active static
2289 * conditions in the stack. */
2290 vector<SubCondition> check_condition(ast::Expr expr)
2291 {
2292 /* Note that an exact implementation would require a SAT Solver since this is a NP-complete
2293 * problem (see https://en.wikipedia.org/wiki/Boolean_satisfiability_problem)
2294 *
2295 * Since most of the conditions are simple we consider a series of non-nested expression
2296 * ANDed together and check for matching token strings for each sub expression.
2297 * This is enough for detecting 99% of the logic issues. */
2298
2299 /* Split the expression to check into subexpressions to test individually. */
2300 vector<SubCondition> expr_split = split_expr(expr, LogicalAnd);
2301
2302 for (ast::Expr cond : pos_conditions) {
2303 remove_included_expr(expr_split, split_expr(cond, LogicalAnd), false);
2304 }
2305 for (ast::Expr cond : neg_conditions) {
2306 /* Because of DeMorgan's law: `!(A || B) <=> !A && !B`
2307 * Split the condition on LogicalOr and negate each expression. */
2308 remove_included_expr(expr_split, split_expr(cond, LogicalOr), true);
2309 }
2310
2311 return expr_split;
2312 }
2313
2314 private:
2315 vector<SubCondition> split_expr(ast::Expr &expr_split, const TokenType split_token)
2316 {
2317 vector<SubCondition> split;
2318
2319 ast::Node front = expr_split.child_first();
2320 ast::Node back = front;
2321
2322 while (back.next().is_valid()) {
2323 back = back.next();
2324 if (back.front() == split_token) {
2325 split.emplace_back(front, back.prev());
2326 /* Advance past the operator. */
2327 front = back.next();
2328 back = front;
2329 }
2330 }
2331 if (front.is_valid()) {
2332 split.emplace_back(front, back);
2333 }
2334 return split;
2335 }
2336
2337 void remove_included_expr(vector<SubCondition> &expr_split,
2338 const vector<SubCondition> &cond_split,
2339 bool negative_cond)
2340 {
2341 std::erase_if(expr_split, [&](const SubCondition &expr) {
2342 return std::ranges::any_of(cond_split, [&](const SubCondition &cond) {
2343 return check_expression_inclusion(expr, cond, negative_cond);
2344 });
2345 });
2346 }
2347
2348 /* Check if `expr` is logically included inside `cond`.
2349 *
2350 * If `negative_cond` is true, checks if `expr` is starting with a negation and compare the
2351 * rest of expression. This have the same effect as negating the condition.
2352 *
2353 * NOTE: This function doesn't aim to be a full inclusion check (NP-complete problem), but it
2354 * should be at least conservative. */
2355 bool check_expression_inclusion(SubCondition expr, SubCondition cond, bool negative_cond)
2356 {
2357 /* Check if both expressions are equivalent. */
2358 ast::Node node_expr = expr.front;
2359 ast::Node node_cond = cond.front;
2360 if (negative_cond) {
2361 if (node_expr.front() == '!' && node_expr.front().str().length() == 1) {
2362 node_expr = node_expr.next();
2363 }
2364 else {
2365 return false;
2366 }
2367 }
2368 bool match = true;
2369 while (match) {
2370 switch (node_expr.type()) {
2371 case NodeType::LocalVar:
2372 /* Go to the last token of an accessor and check the last token. */
2373 /* Don't do that for node_expr since it is not supposed to contain member access. */
2374 while (node_cond.next().front() == '.') {
2375 node_cond = node_cond.next().next();
2376 }
2377 if (node_cond.type() != NodeType::LocalVar) {
2378 /* Invalid condition expression. */
2379 match = false;
2380 break;
2381 }
2382 [[fallthrough]];
2383 case NodeType::Op:
2384 case NodeType::NumConst:
2385 /* Textual comparison. */
2386 match &= node_expr.str() == node_cond.str();
2387 break;
2388 default:
2389 // error(node_expr, Diag::InvalidOp);
2390 match = false;
2391 break;
2392 }
2393
2394 bool end_of_cond = node_cond.front() == cond.back.front();
2395 bool end_of_expr = node_expr.front() == expr.back.front();
2396
2397 if (end_of_cond || end_of_expr) {
2398 /* Only valid match if both are terminated. */
2399 match &= end_of_cond && end_of_expr;
2400 break;
2401 }
2402
2403 node_expr = node_expr.next();
2404 node_cond = node_cond.next();
2405
2406 match = (node_expr.type() == node_cond.type());
2407 }
2408 return match;
2409 }
2410 } static_condition_stack;
2411
2412 void check_condition(ast::IdQualified id, ast::Expr expr)
2413 {
2414 /* Split the expression to check into subexpressions to test individually. */
2415 vector<StaticConditionStack::SubCondition> expr_split = static_condition_stack.check_condition(
2416 expr);
2417
2418 if (!expr_split.empty()) {
2421 }
2422 }
2423
2424 void static_if_statement(Node decl,
2425 SymbolScope &parent_scope,
2426 int &local_scope_id,
2427 bool first = true)
2428 {
2429 SymbolScope *scope = parent_scope.child_scope(local_scope_id++);
2430 if (scope == nullptr) {
2432 return;
2433 }
2434
2435 Condition cond(decl.child_first());
2436
2437 if (cond.is_valid()) {
2438 if (!cond.attributes().contains_attr("static_branch")) {
2440 }
2441 if (cond.front().prev() == Constexpr) {
2443 }
2444 LocalStmt stmt(cond.child_first());
2445 int unused_count = 0;
2446 /* Checks that condition is made of compilation constants or constexpr. */
2447 auto cond_str = table
2449 parent_scope, stmt.expr().child_first(), unused_count, true)
2450 .unwrap(this);
2451 builder.ss << (first ? "#if " : "#elif ") + cond_str + "\n";
2452
2453 static_condition_stack.push_positive_condition(cond);
2454 }
2455 else {
2456 builder.ss << "#else\n";
2457 }
2458
2459 skip_if(If);
2460 skip_if(Constexpr);
2461 skip_node(cond);
2462
2463 LocalScope body = decl.child_last(NodeType::LocalScope);
2464 jump_to(body.front());
2465
2466 local_scope(body, *scope);
2467
2468 if (cond.is_valid()) {
2469 /* Convert the active condition into an inactive one (negated). */
2470 static_condition_stack.pop_positive_condition();
2471 static_condition_stack.push_negative_condition(cond);
2472 }
2473
2474 /* Process preprocessor directive that can be added between if statements. */
2475 Node node = body.next();
2476 while (node.type() == NodeType::Preprocessor) {
2477 builder << node;
2478 node = node.next();
2479 }
2480
2481 jump_to(body.back().next());
2482
2483 Node next = decl.next();
2484 if (next.type() == NodeType::ElseIfStmt || next.type() == NodeType::ElseStmt) {
2485 static_if_statement(next, parent_scope, local_scope_id, false);
2486 }
2487 else {
2488 /* Pretty align. */
2489 builder.ss << string(decl.front().char_number(), ' ') + "#endif\n";
2490 jump_to(next.front());
2491 }
2492
2493 if (cond.is_valid()) {
2494 /* Remove the negated condition. */
2495 static_condition_stack.pop_negative_condition();
2496 }
2497 }
2498
2499 void condition(Condition cond, SymbolScope &scope, bool is_for_loop, bool do_implicit_conversion)
2500 {
2501 match_if('(');
2502 for (Node child : cond.children_range()) {
2503 if (child.type() == NodeType::VarDecl) {
2504 var_decl(child, scope, false);
2505 }
2506 else if (child.type() == NodeType::LocalStmt) {
2507 local_statement(child, scope);
2508
2509 /* In for loops, only the center statement is a condition. */
2510 if (do_implicit_conversion &&
2511 (!is_for_loop || (child.prev().is_valid() && child.next().is_valid())))
2512 {
2513 Node start = LocalStmt(child).expr().child_first();
2514 auto *type = table.expr_type_analysis(scope, start).unwrap(this).type;
2515 if (type == table.int_cls) {
2516 builder.ss << "!=0";
2517 }
2518 else if (type == table.uint_cls) {
2519 builder.ss << "!=0u";
2520 }
2521 else if (type != table.bool_cls && type != table.bool32_t_cls) {
2522 error(child, Diag::TypeNotConvertibleToBool, type->original);
2523 }
2524 }
2525 }
2526 else {
2527 /* TODO: structured bindings. */
2528 assert(0);
2529 }
2530 match_if(';');
2531 }
2532 match_if(')');
2533 skip_node(AttrList(cond.next()));
2534 }
2535
2536 CodegenResult expr(Expr node, const SymbolScope &scope)
2537 {
2538 assert(node.is_valid());
2539 return CodegenExpressionParser(*this, scope, node.child_first()).eval();
2540 }
2541
2542 /* Return true if declaration was issued. */
2543 bool var_decl(VarDecl decl, SymbolScope &scope, bool jump = true)
2544 {
2545 auto attr = resource_type_from_attributes(decl.attributes()).unwrap(this);
2546
2547 if (attr.res_type != ResourceType::NONE) {
2548 /* Resources are defined in global space at runtime. */
2549 skip_node(decl);
2550 return false;
2551 }
2552
2553 if (scope.as_class() == nullptr && decl.is_reference()) {
2554 /* Local references are simply pasted. */
2555 skip_node(decl);
2556 return false;
2557 }
2558
2559 if (decl.has_single_declarator()) {
2560 Declarator d = decl.child_first(NodeType::Declarator);
2561 SymbolVariable *var = scope.lookup_variable(table, d.identifier());
2562 if (var->is_bitfield && var->bit_offset != 0) {
2563 /* Only declare the first member of each field. */
2564 skip_node(decl);
2565 return false;
2566 }
2567 }
2568
2569 if (jump) {
2570 jump_to(decl.front());
2571 }
2572
2573 skip_node(decl.attributes());
2574
2575 if (decl.type().identifier().str() == "auto") {
2576 Declarator d = decl.child_first(NodeType::Declarator);
2577 auto *cls = table.resolve_auto_type(scope, d).unwrap(this);
2578 builder << cls->identifier + trivia(decl.type().identifier());
2579 }
2580 else {
2581 id_type(decl.type(), scope);
2582 }
2583 for (Declarator d : decl.children_of_type<Declarator>()) {
2584 declarator(d, scope);
2585 match_if(',');
2586 }
2587 match_if(';');
2588 return true;
2589 }
2590
2591 void id_type(IdType type, SymbolScope &scope)
2592 {
2593 match_if(Static);
2594 match_if(TokenType::Const, Constexpr);
2595 skip_if(Struct, Class, Enum);
2596 id_type_resolved(type.identifier(), scope);
2597 }
2598
2599 void array_decl(SymbolVariable &var, ArrayDecl array, Declarator decl, SymbolScope &scope)
2600 {
2601 if (!array.is_valid()) {
2602 return;
2603 }
2604
2605 if (array.dimensions() == 1) {
2606 if (array.sub().is_empty()) {
2607 AssignStmt stmt = decl.initial_value();
2608 InitializerList list = stmt.initializer_list();
2609 if (!list.is_valid()) {
2611 }
2612 int size = list.child_count();
2613 builder << builder.curr;
2614 builder.ss << to_string(size);
2615 builder << builder.curr;
2616 if (size == 0) {
2618 }
2619 if (var.capacity_value.is_valid()) {
2621 }
2622 return;
2623 }
2624 if (var.capacity_value.is_valid()) {
2625 builder << builder.curr;
2626 builder << "SRT_CONSTANT_" + string(var.capacity_value.str());
2627 /* Replace the whole expression. */
2628 builder.curr = array.sub().back();
2629 builder << array.sub().back();
2630 return;
2631 }
2632 }
2633
2634 for (Subscript sub : array.children_of_type<Subscript>()) {
2635 if (sub.is_empty()) {
2637 }
2638 else {
2639 auto [result, err] = table.expr_type_analysis(scope, sub.expr().child_first());
2640 /* Note: Do not report error. The size might be defined by compilation constant. */
2641 if (!err && result.is_constexpr()) {
2642 if (result.value.comp_as<int>(0) <= 0) {
2644 }
2645 }
2646 }
2647 builder << sub;
2648 }
2649 }
2650
2651 /* If skip_name_match_index is not -1, will not try to match the declared argument name and
2652 * declare empty . */
2653 void declarator(Declarator decl,
2654 SymbolScope &scope,
2655 bool skip_value = false,
2656 int skip_name_match_index = -1)
2657 {
2658 ArrayDecl array = decl.array();
2659 SymbolVariable *var = scope.lookup_variable(table, decl.identifier());
2660
2661 if (var->is_bitfield && var->bit_offset != 0) {
2662 /* Single declarators are skipped by #var_decl. Reaching this point means the declarator is
2663 * part of a sequence, where omitting it would create invalid codegen. */
2665 }
2666
2667 const bool par = match_if('(');
2668
2669 /* Lookup the type from the declaration as var might be ERROR_SYMBOL for forward declared
2670 * functions (because of name mismatch). */
2671 SymbolClass *type = scope.lookup_class(table, decl.type().identifier()).unwrap(this);
2672 if (type->is_srt()) {
2673 /* WORKAROUND: Do not pass SRT by reference because it causes issue on metal when the caller
2674 * is just calling the constructor in place. */
2675 skip_if('&');
2676 }
2677 else {
2678 match_if('&');
2679 }
2680
2681 if (skip_name_match_index != -1) {
2682 /* Do not try to match the identifier for forward declarations. */
2683 builder << "_" + to_string(skip_name_match_index);
2684 }
2685 else {
2686 id_var_decl_resolved(decl.identifier(), scope);
2687 }
2688
2689 if (par) {
2690 match_if(')');
2691 }
2692
2693 array_decl(*var, array, decl, scope);
2694
2695 skip_node(decl.bitfield());
2696
2697 if (!var->is_error && var->is_constexpr) {
2698 builder.curr = decl.back();
2699 builder << "= " + var->value_str();
2700 return;
2701 }
2702
2703 if (skip_value) {
2704 skip_node(decl.initial_value());
2705 }
2706 else if (decl.initial_value().is_valid()) {
2707 assignment(decl.initial_value(), scope, var);
2708 }
2709 else if (decl.initializer_list().is_valid()) {
2710 builder.ss << "=" + initializer_list(
2711 decl.initializer_list(), scope, var->type, array.dimensions())
2712 .str;
2713 builder.curr = decl.back().next();
2714 }
2715 }
2716
2717 void assignment(AssignStmt stmt, SymbolScope &scope, SymbolVariable *var)
2718 {
2719
2720 if (auto [fn, call] = get_inlined_function(stmt.expr(), scope); fn) {
2721 /* Check if this part of a declarator sequence before inlining. */
2722 if (Declarator d(stmt.parent()), d_next(d.next()); d_next.is_valid()) {
2723 /* Could be supported, but keep it simple for now. Continuing will trigger an error. */
2724 }
2725 else {
2726 /* Need to stop the declaration here. */
2727 builder.ss << ";";
2728 string val = inline_function(fn, call, scope);
2729 /* Resume. */
2730 jump_to(var->loc.tok);
2731 builder.ss << var->identifier << " = " << val;
2732 builder.curr = stmt.back().next();
2733 return;
2734 }
2735 }
2736
2737 match_if('=');
2738 builder.ss << init_expression_or_initializer_list(
2739 stmt.child_first(), scope, var->type, var->array_dimensions)
2740 .str;
2741 builder.curr = stmt.back().next();
2742 }
2743
2744 CodegenResult init_expression_or_initializer_list(Node node,
2745 const SymbolScope &scope,
2746 SymbolClass *cls,
2747 int array_dim = 0)
2748 {
2749 if (node == NodeType::InitializerList) {
2750 return initializer_list(node, scope, cls, array_dim);
2751 }
2752 if (node == NodeType::Expr) {
2753 return expr(node, scope);
2754 }
2755 assert(0);
2756 return {"", cls};
2757 }
2758
2759 CodegenResult initializer_list(InitializerList list,
2760 const SymbolScope &scope,
2761 SymbolClass *cls,
2762 int array_dim = 0)
2763 {
2764 const bool is_empty = list.is_empty();
2765 if (array_dim > 0) {
2766 /* Array initializer is the only place where we don't need to prepend the type. */
2767 }
2768 else if (cls == nullptr || cls->is_error) {
2769 /* TODO(fclem): Long term, we can lookup what is the expected type of the expression and pass
2770 * it down the initializer tree. */
2772 return {"", cls};
2773 }
2774
2775 string open, close;
2776 if (array_dim > 0) {
2777 /* Only use aggregate syntax for arrays. */
2778 open = '{', close = '}';
2779 }
2780 else if (cls->is_builtin()) {
2781 /* Use constructor syntax for builtin types. */
2782 open = cls->identifier + "(", close = ')';
2783 }
2784 else if (is_empty) {
2785 /* Call default constructor. */
2786 if (cls->is_builtin()) {
2787 open = cls->identifier + "(0", close = ')';
2788 }
2789 else {
2790 open = cls->identifier + "_ctor_(", close = ')';
2791 }
2792 }
2793 else {
2794 /* NOTE: Converting to `_ctor(id) param _rotc()` messes with the core syntax and prevent
2795 * using AST for the next lowering passes. Instead convert to _ctor(id, params) and lower it
2796 * to final macro later. */
2797 open = "_ctor(" + cls->identifier + ",";
2798 close = ")";
2799 }
2800 open += trivia(list.front());
2801 close += trivia(list.back());
2802
2803 string content;
2804 DesignatedInitializer designated(list.child_first());
2805 if (designated.is_valid()) {
2806 if (array_dim > 0) {
2808 }
2809 /* Iterate over the list of members, zero initializing the omitted members, until we find
2810 * the given initializer. If member is out of order or not existing, raise an error. */
2811 for (SymbolVariable *var : cls->non_static_variables_in_declaration_order()) {
2812 if (designated.is_valid() && var->identifier == designated.identifier().str()) {
2813 AssignStmt stmt = designated.assign();
2814 content += init_expression_or_initializer_list(stmt.child_first(), scope, var->type).str;
2815 string_view comma = opt_str(designated.back().next(), Comma);
2816 content += comma.empty() ? "," : comma;
2817 designated = designated.next();
2818 }
2819 else {
2820 content += default_value(*var->type) + ",";
2821 }
2822 }
2823
2824 content = content.substr(0, content.rfind(","));
2825
2826 if (designated.is_valid()) {
2827 if (auto *var = cls->lookup_variable(string(designated.identifier().str()));
2828 var && !var->is_error)
2829 {
2830 error(designated, Diag::FieldDesignatorOutOfOrder, designated.identifier().str());
2831 }
2832 else {
2833 error(designated,
2835 designated.identifier().str(),
2836 cls->identifier);
2837 }
2838 }
2839 }
2840 else {
2841 for (Node child : list.children_range()) {
2842 content += init_expression_or_initializer_list(child.child_last(),
2843 scope,
2844 array_dim > 0 ? cls : nullptr /* TODO */,
2845 array_dim - 1)
2846 .str;
2847 content += opt_str(child.back().next(), Comma);
2848 }
2849 }
2850 return {open + content + close, cls};
2851 }
2852
2853 string_view opt_str(Token tok, TokenType type)
2854 {
2855 return tok == type ? tok.str_with_whitespace() : string_view();
2856 }
2857
2858 SymbolClass *id_type_lookup_resolved(IdQualified id, const SymbolScope &scope)
2859 {
2860 assert(id.is_valid());
2861 auto *cls = scope.lookup_class(table, id).unwrap(this);
2862 if (cls->template_data && !id.template_params().is_valid()) {
2864 }
2865 else if (cls->is_error) {
2867 }
2868 return cls;
2869 }
2870
2871 SymbolClass *id_type_resolved(IdQualified id, const SymbolScope &scope)
2872 {
2873 auto *cls_resolved = id_type_lookup_resolved(id, scope);
2874 builder.curr = id.back();
2875 builder << cls_resolved->identifier + trivia(id);
2876 return cls_resolved;
2877 }
2878
2879 /* Lookup only in the give scope. */
2880 SymbolClass *id_type_resolved(string id, const SymbolScope &scope)
2881 {
2882 auto it = scope.classes.find(id);
2883 SymbolClass *cls = it->second.second;
2884 builder.ss << cls->identifier;
2885 return cls;
2886 }
2887
2888 template<typename ArgOrParamList>
2889 SymbolFunction *id_func_resolved_lookup(IdQualified id,
2890 ArgOrParamList params,
2891 const SymbolScope &scope,
2892 const SymbolScope &param_scope,
2893 optional<SourceLocation> loc = nullopt)
2894 {
2895 assert(id.is_valid());
2896 return scope.lookup_function(table, id, params, param_scope, loc).unwrap(this);
2897 }
2898
2899 template<typename ArgOrParamList>
2900 SymbolFunction *id_func_resolved(IdQualified id,
2901 ArgOrParamList params,
2902 const SymbolScope &scope,
2903 const SymbolScope &param_scope,
2904 optional<SourceLocation> loc = nullopt)
2905 {
2906 SymbolFunction *func = id_func_resolved_lookup(id, params, scope, param_scope, loc);
2907 builder.curr = id.back();
2908 builder << func->identifier + trivia(id);
2909 return func;
2910 }
2911
2912 /* Resolve a variable in an expression. */
2913 SymbolVariable *id_var_resolved(IdQualified id, const SymbolScope &scope)
2914 {
2915 assert(id.is_valid());
2916 SymbolVariable *var = scope.lookup_variable(table, id);
2917 if (var->is_error) {
2918 error(id, Diag::UnknownVariable, string(id.str()));
2919 builder << id;
2920 return var;
2921 }
2922
2923 if (var->is_constexpr) {
2924 builder.ss << var->value_str() + trivia(id);
2925 return var;
2926 }
2927
2928 if (var->type->is_srt()) {
2929 if (id.back().next() == TokenType::Dot && id.parent().next().next() != NodeType::FuncCall) {
2930 /* Remove access to SRT type (makes the resource global). */
2931 skip_node(id);
2932 }
2933 else {
2934 /* SRT type is used in an expression (likely as function argument). Call the ctor. */
2935 builder << var->type->identifier + "_ctor_()" + trivia(id);
2936 }
2937 return var;
2938 }
2939
2940 if (var->reference_value.is_valid()) {
2941 builder << string(var->reference_value.str()) + trivia(id);
2942 return var;
2943 }
2944
2945 bool preceded_by_dot = id.front().prev() == '.';
2946 if (!var->is_static && !preceded_by_dot && var->parent->as_class() != nullptr) {
2947 builder.ss << "this_.";
2948 }
2949
2950 builder.curr = id.back();
2951 builder << var->identifier + trivia(id);
2952 return var;
2953 }
2954
2955 /* Resolve a variable in a declaration. */
2956 SymbolVariable *id_var_decl_resolved(IdQualified id, const SymbolScope &scope)
2957 {
2958 assert(id.is_valid());
2959 SymbolVariable *var = scope.lookup_variable(table, id);
2960 if (var->is_error) {
2961 error(id, Diag::UnknownVariable, string(id.str()));
2962 builder << id;
2963 return var;
2964 }
2965
2966 /* Note we only resolve static variable. */
2967 if (var->is_static) {
2968 builder.curr = id.back();
2969 builder << var->identifier + trivia(id);
2970 }
2971 else {
2972 builder << id;
2973 }
2974 return var;
2975 }
2976
2977 /* -------------------------------------------------------------------- */
2981
2982 void parse_class_metadata(SymbolClass &cls, LocalScope body)
2983 {
2984 string &cls_id = cls.identifier;
2985 metadata::ResourceTable srt;
2986 metadata::VertexInputs vertex_in;
2987 metadata::StageInterface vertex_out;
2988 metadata::FragmentOutputs fragment_out;
2989 metadata::FragmentInputs fragment_in;
2990 srt.name = cls_id;
2991 vertex_in.name = cls_id;
2992 vertex_out.name = cls_id;
2993 fragment_out.name = cls_id;
2994 fragment_in.name = cls_id;
2995
2996 for (VarDecl decl : body.children_of_type<VarDecl>()) {
2997 Declarator d = decl.child_first(NodeType::Declarator);
2998 SymbolVariable *var = cls.lookup_variable(table, d.identifier());
2999 const string &type_name = var->type->identifier;
3000 const string &var_name = var->identifier;
3001 switch (cls.srt_type) {
3003 srt.emplace_back(parse_resource(decl.attributes(), type_name, var_name, d.array(), cls));
3004 break;
3006 vertex_in.emplace_back(parse_vertex_input(decl.attributes(), type_name, var_name, cls));
3007 break;
3009 vertex_out.emplace_back(parse_vertex_output(decl.attributes(), type_name, var_name));
3010 break;
3012 fragment_out.emplace_back(parse_fragment_output(decl.attributes(), type_name, var_name));
3013 break;
3015 fragment_in.emplace_back(parse_fragment_input(decl.attributes(), type_name, var_name));
3016 break;
3017 default:
3018 break;
3019 }
3020 }
3021
3022 switch (cls.srt_type) {
3024 metadata.resource_tables.emplace_back(srt);
3025 break;
3027 metadata.vertex_inputs.emplace_back(vertex_in);
3028 break;
3030 metadata.stage_interfaces.emplace_back(vertex_out);
3031 break;
3033 metadata.fragment_outputs.emplace_back(fragment_out);
3034 break;
3036 metadata.fragment_inputs.emplace_back(fragment_in);
3037 break;
3040 break;
3041 }
3042 }
3043
3044 metadata::ParsedVertInput parse_vertex_input(AttrList attributes,
3045 const string &type,
3046 const string &name,
3047 const SymbolClass &cls)
3048 {
3049 auto attr = resource_type_from_attributes(attributes).unwrap(this);
3050 return {
3051 .line = 0,
3052 .var_type = type,
3053 .var_name = name,
3054 .slot = string(attr.param1.str()),
3055 .res_condition = parse_condition(cls, attr.condition),
3056 };
3057 }
3058
3059 metadata::ParsedAttribute parse_vertex_output(AttrList attributes,
3060 const string &type,
3061 const string &name)
3062 {
3063 auto attr = resource_type_from_attributes(attributes).unwrap(this);
3064 return {
3065 .line = 0,
3066 .var_type = type,
3067 .var_name = name,
3068 .interpolation_mode = string(attr.attr.str()),
3069 };
3070 }
3071
3072 metadata::ParsedFragOuput parse_fragment_output(AttrList attributes,
3073 const string &type,
3074 const string &name)
3075 {
3076 auto attr = resource_type_from_attributes(attributes).unwrap(this);
3077 return {
3078 .line = 0,
3079 .var_type = type,
3080 .var_name = name,
3081 .slot = string(attr.param1.str()),
3082 .dual_source = string(attr.dual_source_index.str()),
3083 .raster_order_group = string(attr.raster_order_group.str()),
3084 };
3085 }
3086
3087 metadata::ParsedFragInput parse_fragment_input(AttrList attributes,
3088 const string &type,
3089 const string &name)
3090 {
3091 auto attr = resource_type_from_attributes(attributes).unwrap(this);
3092 return {
3093 .line = 0,
3094 .var_type = type,
3095 .var_name = name,
3096 .slot = string(attr.param1.str()),
3097 .image_type = string(attr.param2.str()),
3098 .raster_order_group = string(attr.raster_order_group.str()),
3099 };
3100 }
3101
3102 string parse_image_format(SymbolClass &cls, Expr expr)
3103 {
3104 Node node = expr.child_first();
3105 if (LocalVar var = node; var.is_valid()) {
3106 SymbolVariable *sym = cls.lookup_variable(table, var.identifier());
3107 if (sym->is_macro) {
3108 /* This could be a macro. Don't make an error. */
3109 return string(expr.str());
3110 }
3111 if (sym->is_constexpr) {
3112 int enum_val = sym->value.comp_as<int>(0);
3113 if (auto it = table.image_formats.find(enum_val); it != table.image_formats.end()) {
3114 return it->second;
3115 }
3116 }
3117 }
3119 return "0";
3120 }
3121
3122 string parse_frequency(Expr frequency)
3123 {
3124 return frequency.is_valid() ? string(frequency.str()) : string("PASS");
3125 }
3126
3127 string array_size_to_string(ast::ArrayDecl array, const SymbolScope &scope)
3128 {
3129 if (!array.is_valid()) {
3130 return "";
3131 }
3132
3133 string str;
3134 for (Subscript sub : array.children_of_type<ast::Subscript>()) {
3135 if (sub.expr().is_valid()) {
3136 auto [result, err] = table.expr_type_analysis(scope, sub.expr().child_first());
3137 if (result.is_constexpr()) {
3138 if (result.type == table.int_cls || result.type == table.uint_cls) {
3139 str += '[' + to_string(result.value.comp_as<int>(0)) + ']';
3140 }
3141 else {
3143 }
3144 }
3145 else {
3147 }
3148 }
3149 else {
3150 str += string(sub.str());
3151 }
3152 }
3153 return str;
3154 }
3155
3156 metadata::ParsedResource parse_resource(AttrList attributes,
3157 const string &type,
3158 const string &name,
3159 ArrayDecl array,
3160 SymbolClass &cls)
3161 {
3162 auto attr = resource_type_from_attributes(attributes).unwrap(this);
3163 switch (attr.res_type) {
3169 return {.line = 0,
3170 .var_type = type,
3171 .var_name = name,
3172 .var_array = array_size_to_string(array, cls),
3173 .res_type = string(attr.attr.identifier().str()),
3174 .res_condition = parse_condition(cls, attr.condition)};
3176 return {.line = 0,
3177 .var_type = type,
3178 .var_name = name,
3179 .var_array = array_size_to_string(array, cls),
3180 .res_type = string(attr.attr.identifier().str()),
3181 .res_value = string(attr.param1.str()),
3182 .res_condition = parse_condition(cls, attr.condition)};
3184 return {.line = 0,
3185 .var_type = type,
3186 .var_name = name,
3187 .var_array = array_size_to_string(array, cls),
3188 .res_type = string(attr.attr.identifier().str()),
3189 .res_slot = string(attr.param1.str()),
3190 .res_condition = parse_condition(cls, attr.condition),
3191 .res_frequency = parse_frequency(attr.frequency)};
3193 return {.line = 0,
3194 .var_type = type,
3195 .var_name = name,
3196 .var_array = array_size_to_string(array, cls),
3197 .res_type = string(attr.attr.identifier().str()),
3198 .res_slot = string(attr.param1.str()),
3199 .res_condition = parse_condition(cls, attr.condition),
3200 .res_frequency = parse_frequency(attr.frequency)};
3202 return {.line = 0,
3203 .var_type = type,
3204 .var_name = name,
3205 .var_array = array_size_to_string(array, cls),
3206 .res_type = string(attr.attr.identifier().str()),
3207 .res_slot = string(attr.param1.str()),
3208 .res_condition = parse_condition(cls, attr.condition),
3209 .res_frequency = parse_frequency(attr.frequency)};
3211 return {.line = 0,
3212 .var_type = type,
3213 .var_name = name,
3214 .var_array = array_size_to_string(array, cls),
3215 .res_type = string(attr.attr.identifier().str()),
3216 .res_slot = string(attr.param1.str()),
3217 .res_qualifier = string(attr.param2.str()),
3218 .res_condition = parse_condition(cls, attr.condition),
3219 .res_frequency = parse_frequency(attr.frequency)};
3221 return {.line = 0,
3222 .var_type = type,
3223 .var_name = name,
3224 .var_array = array_size_to_string(array, cls),
3225 .res_type = string(attr.attr.identifier().str()),
3226 .res_slot = string(attr.param1.str()),
3227 .res_qualifier = string(attr.param2.str()),
3228 .res_format = parse_image_format(cls, attr.param3),
3229 .res_condition = parse_condition(cls, attr.condition),
3230 .res_frequency = parse_frequency(attr.frequency)};
3231 break;
3232 default:
3233 assert(0);
3234 break;
3235 }
3236 return {};
3237 }
3238
3239 string parse_condition(const SymbolScope &scope, ast::Expr condition) const
3240 {
3241 if (!condition.is_valid()) {
3242 return "";
3243 }
3244 string str;
3245 for (LocalVar node : condition.children_of_type<LocalVar>()) {
3246 if (SymbolVariable *var = scope.lookup_variable(table, node.identifier());
3247 !var->is_error && var->is_constexpr)
3248 {
3249 str += "int " + string(node.str()) + " = " + var->value_str() + "; ";
3250 }
3251 else {
3252 /* TODO(fclem): Check constant validity. */
3253 str += "int " + string(node.str()) + " = ";
3254 str += "ShaderCreateInfo::find_constant(constants, \"" + string(node.str()) + "\"); ";
3255 }
3256 }
3257 str += "return " + string(condition.str()) + ";";
3258 return str;
3259 }
3260
3261 string parse_condition_as_lambda(const SymbolScope &scope, AttrList attributes)
3262 {
3263 string cond;
3264 for (Attr attr : attributes.children_of_type<Attr>()) {
3265 if (attr.identifier().str() == "condition") {
3266 if (!cond.empty()) {
3267 error(attr.identifier(), Diag::ConditionAttributeMultiple);
3268 break;
3269 }
3270 cond = parse_condition(scope, attr.parameters().splat_1().arg1);
3271 }
3272 }
3273 if (!cond.empty()) {
3274 cond = ", [](blender::Span<CompilationConstant> constants) { " + cond + "}";
3275 }
3276 return cond;
3277 }
3278
3280};
3281
3282} // namespace bsl
3283
3284namespace blender::gpu::shader {
3285
3286/* Lower namespaces by adding namespace prefix to all the contained structs and functions. */
3287void SourceProcessor::lower_bsl_to_il(Parser &parser, bsl::SymbolTable &symbols)
3288{
3289 using namespace parser;
3290 bsl::CodegenContext ctx(parser, symbols, metadata_, error_handler);
3291 std::string str = ctx.process(*symbols.root, parser.root());
3292
3293 if (error_handler.err.has_value()) {
3294 throw ParserException();
3295 }
3296
3297 parser.set_str(str);
3298}
3299} // namespace blender::gpu::shader
int pad[32 - sizeof(int)]
long long int int64_t
btScalar max
void jump(const btVector3 &v=btVector3(0, 0, 0))
parser::IntermediateForm< parser::FullLexer, parser::FullParser > Parser
Definition processor.hh:45
parser::ErrorHandler ErrorHandler
Definition processor.hh:44
#define NOTE(node, diag, id)
#define str(s)
#define assert(assertion)
#define index(i)
#define frequency(freq)
ccl_device_inline dual1 len(const ccl_private dual< T > &a)
Definition math_dual.h:263
int size(const AssetLibraryReference *library_reference)
void split(const std::string &s, const char delim, std::vector< std::string > &tokens)
Definition abc_util.cc:68
SymEdge< T > * sym(const SymEdge< T > *se)
ATTR_WARN_UNUSED_RESULT const BMVert * v
signed char int8_t
Definition BKE_text.h:76
Definition codegen.cc:18
static string to_uppercase(string str)
Definition codegen.cc:24
static const char * to_token_string(TokenType tok)
Definition codegen.cc:52
bool contains_zero(const ConstexprValue &v)
Definition constexpr.hh:547
ConstexprValue ConstexprError
static TokenType strip_assignment(TokenType tok)
Definition codegen.cc:32
Result< ParsedAttribute > resource_type_from_attributes(AttrList list)
Definition resource.cc:17
@ CompilationConstantPreviousDecl
@ ConditionAttributeNotChecked
@ UnrolledLoopMissingAssignment
@ InvalidExprTypeCodegen
@ StaticBranchConstexprIfNotAllowed
@ InliningRecursive
@ CompilerErrorMemberFuncNoClass
Definition diagnostic.hh:98
@ TypeNotConvertibleToBool
@ CapacityArrayImplicitSize
@ OperatorBitfieldInvalid
@ OperatorCalledIsNotFunction
@ CompilerErrorChildScopeNotFound
Definition diagnostic.hh:99
@ UnrolledLoopTooManyIterations
@ ExpectedResourceTableInitializer
@ ResourceTableConstructorNotAllowed
@ OperatorTokenInvalid
@ ArraySizeMustBeGreaterThanZero
@ ConditionAttributeMultiple
@ ConditionAttributeDeclaredHere
@ UnrolledLoopInvalidExpression
@ UnionArrayUnsupported
@ ExpectedImageFormat
@ MissingParameterForCall
@ UnrolledLoopNonIntVar
@ UnrolledLoopMissingInit
@ BitFieldNotSingleDeclarator
@ CompilationConstantRedefinition
@ UnknownClassInstantiation
@ ExpectedFragmentShaderEntryPoint
@ ArrayMultidimensionalImplicitSize
@ NoteDeclarationUnionRequested
@ NoteInstantiationClassTemplateRequested
@ ReturnOutsideFunction
@ UnknownTypeNameWithArg
@ UnrolledLoopMustAssignToVar
@ TemplateMissingExplicitArguments
@ ConstexprIfConditionNotConstexpr
@ ConstexprDivisionByZero
@ UnrolledLoopCommaOperator
@ ArrayNeedsSizeOrInitializer
@ StaticBranchRequiredByPrevious
@ ExpectedVertexShaderEntryPoint
@ InitializerListRequiresExplicitType
@ NoteInstantiationFuncTemplateRequested
@ StaticBranchMissingPrevious
@ UnrolledLoopMultipleVariables
@ ExpectedArrayMemberInitializer
@ InvalidInlinedFunctionLocation
@ ArraySizeNotConstantExpression
@ FieldDesignatorNotFound
@ ExpectedComputeShaderEntryPoint
@ FieldDesignatorOutOfOrder
@ UnrolledLoopNotConstexpr
@ ExpectedParenthesis
TokenType
Definition types.hh:41
@ RShift
Definition types.hh:126
@ Default
Definition types.hh:129
@ While
Definition types.hh:92
@ AssignSub
Definition types.hh:135
@ For
Definition types.hh:91
@ LogicalOr
Definition types.hh:93
@ Return
Definition types.hh:115
@ Do
Definition types.hh:87
@ Static
Definition types.hh:105
@ Enum
Definition types.hh:106
@ Struct
Definition types.hh:117
@ AssignAdd
Definition types.hh:133
@ LogicalAnd
Definition types.hh:81
@ Multiply
Definition types.hh:145
@ Switch
Definition types.hh:95
@ AssignLShift
Definition types.hh:138
@ Case
Definition types.hh:96
@ Else
Definition types.hh:98
@ AssignRShift
Definition types.hh:139
@ Plus
Definition types.hh:68
@ Colon
Definition types.hh:65
@ Decrement
Definition types.hh:88
@ Increment
Definition types.hh:112
@ Constexpr
Definition types.hh:86
@ AssignDiv
Definition types.hh:137
@ If
Definition types.hh:97
@ Divide
Definition types.hh:70
@ LShift
Definition types.hh:125
@ Assign
Definition types.hh:61
@ Minus
Definition types.hh:69
@ Word
Definition types.hh:43
@ AssignMul
Definition types.hh:136
@ Invalid
Definition types.hh:42
@ Class
Definition types.hh:118
@ Comma
Definition types.hh:66
PipelineGraphic pipeline(vert_main, frag_main)
PipelineCompute lines(lines_main)
#define min(a, b)
Definition sort.cc:38
string to_string(const char *str)
Definition string.cpp:202
const NodeType * type
Definition graph/node.h:179
std::vector< ResourceTable > resource_tables
Definition metadata.hh:282
std::vector< FragmentOutputs > fragment_outputs
Definition metadata.hh:284
std::vector< StageInterface > stage_interfaces
Definition metadata.hh:283
std::vector< FragmentInputs > fragment_inputs
Definition metadata.hh:285
std::vector< VertexInputs > vertex_inputs
Definition metadata.hh:286
std::vector< std::string > create_infos_declarations
Definition metadata.hh:279
InitializerList initializer_list() const
Definition ast.hh:791
bool contains_attr(std::string_view attr_name) const
Definition ast.hh:759
InitializerList initializer_list() const
Definition ast.hh:739
InitializerList initializer_list() const
Definition ast.hh:875
ChildRange children_range() const
Definition ast.hh:334
TypedChildRange< NodeT > children_of_type() const
Definition ast.hh:379
std::string_view str_full() const
Definition ast.cc:118
std::string_view str() const
Definition ast.cc:113
TemplateParamList parameters() const
Definition ast.hh:1345
TemplateParamList parameters() const
Definition ast.hh:1330
CodegenResult identifier(const ast::Node &t)
Definition codegen.cc:150
CodegenResult string_literal(const ast::Node &t)
Definition codegen.cc:170
CodegenResult number_literal(const ast::Node &t)
Definition codegen.cc:165
CodegenResult subscript(CodegenResult left, const ast::Node &t)
Definition codegen.cc:208
CodegenResult function_call(CodegenResult left, const ast::Node &t)
Definition codegen.cc:238
CodegenResult parenthesis(const ast::Node &t, BindingPower)
Definition codegen.cc:175
PrattParser< CodegenExpressionParser, CodegenResult, ast::Node > Base
Definition codegen.cc:118
CodegenExpressionParser(CodegenContext &ctx, const SymbolScope &scope, ast::Node start_node)
Definition codegen.cc:130
CodegenResult comma(CodegenResult lhs, const ast::Node &t, BindingPower p)
Definition codegen.cc:275
CodegenResult error(ErrorType err, lexit::TokenType type)
Definition codegen.cc:344
TokenType to_type(const ast::Node &t) const
Definition codegen.cc:334
CodegenResult suffix(CodegenResult lhs, const ast::Node &t)
Definition codegen.cc:260
CodegenResult member(CodegenResult left, const ast::Node &t)
Definition codegen.cc:183
CodegenResult prefix(const ast::Node &t, BindingPower p)
Definition codegen.cc:244
CodegenResult binary(CodegenResult lhs, const ast::Node &t, BindingPower p)
Definition codegen.cc:282
CodegenResult ternary(CodegenResult left, const ast::Node &t, BindingPower, BindingPower p_second)
Definition codegen.cc:308
CodegenResult(SymbolVariable *var, const string &trivia)
Definition codegen.cc:90
CodegenResult(const ast::Node &node, SymbolClass *cls, int8_t array_dim=0)
Definition codegen.cc:98
CodegenResult(const string &str, SymbolClass *cls, int8_t array_dim=0, bool is_bitfield=false)
Definition codegen.cc:103
StringBuilder & operator<<(Token tok)
Definition codegen.cc:478
StringBuilder & operator<<(const string &str)
Definition codegen.cc:485
StringBuilder & operator<<(const StringBuilder &sb)
Definition codegen.cc:506
StringBuilder & operator<<(const string_view &str)
Definition codegen.cc:492
StringBuilder & operator<<(const Node &node)
Definition codegen.cc:499
string process(SymbolScope &symbol, LocalScope node)
Definition codegen.cc:525
metadata::Source & metadata
Definition codegen.cc:80
SymbolTable & table
Definition codegen.cc:79
CodegenContext(SourceProcessor::Parser &parser, SymbolTable &symbols, metadata::Source &metadata, SourceProcessor::ErrorHandler &error_handler)
Definition codegen.cc:514
struct bsl::CodegenContext::StringBuilder builder
void error(Token tok, const string &msg)
ErrorHandler & err_handler
NodeErrorHandler(ErrorHandler &handler)
SymbolFunction * operator_subscript
bool is_srt() const
SymbolClass * return_type
static constexpr const char * inline_fn_ret_id
enum bsl::SymbolScope::Type type
Result< SymbolClass * > lookup_class(const SymbolTable &table, ast::IdQualified id, optional< SourceLocation > loc=nullopt) const
SymbolScope * root
SymbolClass * uint_cls
Result< string > expr_to_string(const SymbolScope &scope, ast::Node start, int &node_count, bool allow_compilation_constant=false) const
SymbolClass * bool_cls
Result< SymbolClass * > resolve_auto_type(SymbolScope &scope, ast::Declarator decl) const
static constexpr const char * subscript_operator_id
SymbolClass * bool32_t_cls
Result< ExpressionResult > expr_type_analysis(const SymbolScope &scope, ast::Node start_node, bool is_reference=false) const
SymbolClass * int_cls
unordered_map< int, string > image_formats
std::string_view substr(const Token &start, const Token &end, const bool with_trailing_whitespaces=false) const
Return the substring between the start and end tokens (included).
Definition lexit.hh:224
std::string_view str() const
Definition lexit.hh:381
int32_t index_
Definition lexit.hh:51
const TokenType & type() const
Definition lexit.hh:354
std::string_view str_with_whitespace() const
Definition lexit.hh:388
Token next(int i=1) const
Definition lexit.hh:372