Blender V5.3
flow_control.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2024 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include "intermediate.hh"
10#include "metadata.hh"
11#include "processor.hh"
12
13namespace blender::gpu::shader {
14using namespace std;
15using namespace shader::parser;
16using namespace metadata;
17
18void SourceProcessor::lower_loop_unroll(Parser &parser)
19{
20 struct ArgParseResult {
21 Scope init, condition, iter;
22 };
23 auto parse_for_args = [&](const Scope loop_args) -> ArgParseResult {
24 ArgParseResult result{Scope(parser), Scope(parser), Scope(parser)};
25 loop_args.foreach_scope(ScopeType::LoopArg, [&](const Scope arg) {
26 if (arg.front().prev() == '(' && arg.back().next() == ';') {
27 result.init = arg;
28 }
29 else if (arg.front().prev() == ';' && arg.back().next() == ';') {
30 result.condition = arg;
31 }
32 else if (arg.front().prev() == ';' && arg.back().next() == ')') {
33 result.iter = arg;
34 }
35 else {
36 report_error(arg.front(), "Invalid loop declaration.");
37 }
38 });
39 return result;
40 };
41
42 auto process_loop = [&](const Token loop_start,
43 const int iter_count,
44 const int iter_init,
45 const int iter_incr,
46 const bool condition_is_trivial,
47 const bool iteration_is_trivial,
48 const Scope init,
49 const Scope cond,
50 const Scope iter,
51 const Scope body,
52 const string body_prefix = "",
53 const string body_suffix = "") {
54 /* Check that there is no unsupported keywords in the loop body. */
55 bool error = false;
56 /* Checks if `continue` exists, even in switch statement inside the unrolled loop. */
57 body.foreach_token(Continue, [&](const Token token) {
58 if (token.scope().first_scope_of_type(ScopeType::LoopBody) == body) {
59 report_error(token, "Unrolled loop cannot contain \"continue\" statement.");
60 error = true;
61 }
62 });
63 /* Checks if `break` exists directly the unrolled loop scope. Switch statements are ok. */
64 body.foreach_token(Break, [&](const Token token) {
65 if (token.scope().first_scope_of_type(ScopeType::LoopBody) == body) {
66 const Scope switch_scope = token.scope().first_scope_of_type(ScopeType::SwitchBody);
67 if (switch_scope.is_invalid() || !body.contains(switch_scope)) {
68 report_error(token, "Unrolled loop cannot contain \"break\" statement.");
69 error = true;
70 }
71 }
72 });
73 if (error) {
74 return;
75 }
76
77 if (!parser.replace_try(loop_start, body.back(), "", true)) {
78 /* This is the case of nested loops. This loop will be processed in another parser pass. */
79 return;
80 }
81
82 string indent_init, indent_cond, indent_iter;
83 if (init.is_valid()) {
84 indent_init = string(init.front().char_number() - 1, ' ');
85 }
86 if (cond.is_valid()) {
87 indent_cond = string(cond.front().char_number() - 3, ' ');
88 }
89 if (iter.is_valid()) {
90 indent_iter = string(iter.front().char_number(), ' ');
91 }
92 string indent_body = string(body.front().char_number(), ' ');
93 string indent_end = string(body.back().char_number(), ' ');
94
95 /* If possible, replaces the index of the loop iteration inside the given string. */
96 auto replace_index = [&](const string &str, int loop_index) {
97 if (iter.is_invalid() || !iteration_is_trivial || str.empty()) {
98 return str;
99 }
100 Parser str_parser(str, error_handler);
101 str_parser().foreach_token(Word, [&](const Token tok) {
102 if (tok.str() == iter[0].str()) {
103 str_parser.replace(tok, to_string(loop_index), true);
104 }
105 });
106 return str_parser.result_get();
107 };
108
109 parser.insert_after(body.back(), "\n");
110 if (init.is_valid() && !iteration_is_trivial) {
111 parser.insert_line_number(body.back(), init.front().line_number());
112 parser.insert_after(body.back(),
113 indent_init + "{" + string(init.str_with_whitespace()) + ";\n");
114 }
115 else {
116 parser.insert_after(body.back(), "{\n");
117 }
118 for (int64_t i = 0, value = iter_init; i < iter_count; i++, value += iter_incr) {
119 if (cond.is_valid() && !condition_is_trivial) {
120 parser.insert_line_number(body.back(), cond.front().line_number());
121 parser.insert_after(body.back(),
122 indent_cond + "if(" + string(cond.str_with_whitespace()) + ")\n");
123 }
124 parser.insert_after(body.back(), replace_index(body_prefix, value));
125 parser.insert_line_number(body.back(), body.front().line_number());
126 parser.insert_after(body.back(),
127 indent_body + replace_index(string(body.str_with_whitespace()), value) +
128 "\n");
129 parser.insert_after(body.back(), body_suffix);
130 if (iter.is_valid() && !iteration_is_trivial) {
131 parser.insert_line_number(body.back(), iter.front().line_number());
132 parser.insert_after(body.back(), indent_iter + string(iter.str_with_whitespace()) + ";\n");
133 }
134 }
135 parser.insert_line_number(body.back(), body.back().line_number());
136 parser.insert_after(body.back(), indent_end + string(body.back().str_with_whitespace()));
137 };
138
139 do {
140 /* WORKAROUND: We need to differentiate for and switch statements apart for proper break and
141 * continue statement usage linting. For this, we modify the body scope types to be able to
142 * detect which loop or switch body the break and continue statements are part of. */
143 parser().foreach_match("f(..)[[..]]{..}", [&](const vector<Token> tokens) {
144 tokens[11].scope().set_type(ScopeType::LoopBody);
145 });
146 parser().foreach_match("f(..){..}", [&](const vector<Token> tokens) {
147 tokens[5].scope().set_type(ScopeType::LoopBody);
148 });
149 parser().foreach_match("h(..){..}", [&](const vector<Token> tokens) {
150 tokens[5].scope().set_type(ScopeType::SwitchBody);
151 });
152
153 /* [[unroll]]. */
154 parser().foreach_match("f(..)[[A]]{..}", [&](const vector<Token> tokens) {
155 if (tokens[6].scope().str_with_whitespace() != "[unroll]") {
156 return;
157 }
158 const Token for_tok = tokens[0];
159 const Scope loop_args = tokens[1].scope();
160 const Scope loop_body = tokens[10].scope();
161
162 auto [init, cond, iter] = parse_for_args(loop_args);
163
164 /* Init statement. */
165 const Token var_type = init[0];
166 const Token var_name = init[1];
167 const Token var_init = init[2];
168 if (var_type.str() != "int" && var_type.str() != "uint") {
169 report_error(var_init, "Can only unroll integer based loop.");
170 return;
171 }
172 if (var_init != '=') {
173 report_error(var_init, "Expecting assignment here.");
174 return;
175 }
176 if (init[3] != Number && init[3] != '-') {
177 report_error(init[3], "Expecting integer literal here.");
178 return;
179 }
180
181 /* Conditional statement. */
182 int t = 0;
183 const Token cond_var = cond[t++];
184 const Token cond_type = cond[t++];
185 const Token cond_sign = (cond[t] == '+' || cond[t] == '-') ? cond[t++] : Token(parser);
186 const Token cond_end = cond[t];
187 if (cond_var.str() != var_name.str()) {
188 report_error(cond_var, "Non matching loop counter variable.");
189 return;
190 }
191 if (cond_end != Number) {
192 report_error(cond_end, "Expecting integer literal here.");
193 return;
194 }
195
196 /* Iteration statement. */
197 const Token iter_var = iter[0];
198 const Token iter_type = iter[1];
199 const Token iter_end = iter[1];
200 int iter_incr = 0;
201 if (iter_var.str() != var_name.str()) {
202 report_error(iter_var, "Non matching loop counter variable.");
203 return;
204 }
205 if (iter_type == Increment) {
206 iter_incr = +1;
207 if (cond_type == GThan || cond_type == GEqual) {
208 report_error(for_tok, "Unsupported condition in unrolled loop.");
209 return;
210 }
211 }
212 else if (iter_type == Decrement) {
213 iter_incr = -1;
214 if (cond_type == LThan || cond_type == LEqual) {
215 report_error(for_tok, "Unsupported condition in unrolled loop.");
216 return;
217 }
218 }
219 else {
220 report_error(iter_type, "Unsupported loop expression. Expecting ++ or --.");
221 return;
222 }
223
224 int64_t init_value = stol(
225 parser.substr_range_inclusive(var_init.next(), var_init.scope().back()));
226 int64_t end_value = stol(
227 parser.substr_range_inclusive(cond_sign.is_valid() ? cond_sign : cond_end, cond_end));
228 /* TODO(fclem): Support arbitrary strides (aka, arbitrary iter statement). */
229 int iter_count = abs(end_value - init_value);
230 if (cond_type == GEqual || cond_type == LEqual) {
231 iter_count += 1;
232 }
233
234 bool condition_is_trivial = (cond_end == cond.back());
235 bool iteration_is_trivial = (iter_end == iter.back());
236
237 process_loop(tokens[0],
238 iter_count,
239 init_value,
240 iter_incr,
241 condition_is_trivial,
242 iteration_is_trivial,
243 init,
244 cond,
245 iter,
246 loop_body);
247 });
248
249 /* [[unroll_n(n)]]. */
250 parser().foreach_match("f(..)[[A(1)]]{..}", [&](const vector<Token> tokens) {
251 if (tokens[7].str() != "unroll_n") {
252 return;
253 }
254 const Scope loop_args = tokens[1].scope();
255 const Scope loop_body = tokens[13].scope();
256
257 auto [init, cond, iter] = parse_for_args(loop_args);
258
259 int iter_count = stol(string(tokens[9].str()));
260
261 process_loop(tokens[0], iter_count, 0, 0, false, false, init, cond, iter, loop_body);
262 });
263 } while (parser.apply_mutations());
264
265 /* Check for remaining keywords. */
266 parser().foreach_match("[[A", [&](const vector<Token> tokens) {
267 if (tokens[2].str().find("unroll") != string::npos) {
268 report_error(tokens[0], "Incompatible loop format for [[unroll]].");
269 }
270 });
271}
272
273void SourceProcessor::lower_static_branch(Parser &parser)
274{
275
276 do {
277 /* Transform `if constexpr (...)` into `if (...) [[static_branch]]`. */
278 parser().foreach_match("iC(..)", [&](const vector<Token> &tokens) {
279 parser.erase(tokens[1]);
280 parser.insert_after(tokens[5], "[[static_branch]]");
281 });
282 } while (parser.apply_mutations());
283
284 do {
285 parser().foreach_match("i(..)[[A]]{..}", [&](const vector<Token> &tokens) {
286 Token if_tok = tokens[0];
287 Scope condition = tokens[1].scope();
288 Token attribute = tokens[7];
289 Scope body = tokens[10].scope();
290
291 if (attribute.str() != "static_branch") {
292 return;
293 }
294
295 if (condition.str().find("&&") != string::npos || condition.str().find("||") != string::npos)
296 {
297 report_error(condition[0], "Expecting single condition.");
298 return;
299 }
300
301 const int i = condition[1].str() == "!" ? 2 : 1;
302 /* TODO(fclem): Make full check of all params. */
303 const bool is_constexpr = condition[i].str() == "true" || condition[i].str() == "false";
304 const bool constexpr_val = is_constexpr ? (condition[i].str() == "true") ^ (i == 2) : false;
305
306 if (condition[i].str() != "srt_access" && !is_constexpr) {
307 report_error(if_tok,
308 "Expecting compilation or specialization constant. Make sure SRT arguments "
309 "have the [[resource_table]] attribute.");
310 return;
311 }
312
313 Token before_body = body.front().prev();
314
315 string test = is_constexpr ? string(constexpr_val ? "1" : "0") :
316 string(i == 2 ? "!" : "") + "SRT_CONSTANT_" +
317 string(condition[4 + i].str()) + " ";
318 if (condition[is_constexpr ? 2 : 7] != condition.back().prev()) {
319 test += parser.substr_range_inclusive(condition[is_constexpr ? 2 : 7],
320 condition.back().prev());
321 }
322 string directive = (if_tok.prev() == Else ? "#elif " : "#if ");
323
324 parser.insert_directive(before_body, directive + test);
325 parser.erase(if_tok, before_body);
326
327 if (body.back().next() == Else) {
328 Token else_tok = body.back().next();
329 parser.erase(else_tok);
330 if (else_tok.next() == If) {
331 /* Will be processed later. */
332 Token next_if = else_tok.next();
333 /* Ensure the rest of the if clauses also have the attribute. */
334 Scope attributes = next_if.next().scope().back().next().scope();
335 if (attributes.type() != ScopeType::Subscript ||
336 attributes.front().next().scope().str_exclusive() != "static_branch")
337 {
338 report_error(next_if, "Expecting next if statement to also be a static branch.");
339 return;
340 }
341 return;
342 }
343 body = else_tok.next().scope();
344
345 parser.insert_directive(else_tok, "#else");
346 }
347 parser.insert_directive(body.back(), "#endif");
348 });
349 } while (parser.apply_mutations());
350}
351
352} // namespace blender::gpu::shader
void init()
parser::IntermediateForm< parser::FullLexer, parser::FullParser > Parser
Definition processor.hh:45
#define str(s)
#define attribute(slot)
#define condition(cond)
#define abs
if(state< num_states)
const char * to_string(ShaderStage stage)
Definition mtl_shader.mm:52
const std::any * find(const AnyDictionary &dictionary, const std::string &key)
__int64 int64_t
Definition BKE_text.h:90
@ GThan
Definition types.hh:149
@ LThan
Definition types.hh:150
@ Else
Definition types.hh:98
@ LEqual
Definition types.hh:104
@ Break
Definition types.hh:83
@ Continue
Definition types.hh:110
@ Decrement
Definition types.hh:88
@ Increment
Definition types.hh:112
@ Number
Definition types.hh:44
@ Word
Definition types.hh:43
@ GEqual
Definition types.hh:94
Scope first_scope_of_type(const ScopeType type) const
Definition scope.hh:228
Token prev(int i=1) const
Definition lexit.hh:376