Blender V4.3
multi_function_procedure_optimization.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
6
8
9void move_destructs_up(Procedure &procedure, Instruction &block_end_instr)
10{
11 /* A mapping from a variable to its destruct instruction. */
12 Map<Variable *, DestructInstruction *> destruct_instructions;
13 Instruction *current_instr = &block_end_instr;
14 while (true) {
15 InstructionType instr_type = current_instr->type();
16 switch (instr_type) {
18 DestructInstruction &destruct_instr = static_cast<DestructInstruction &>(*current_instr);
19 Variable *variable = destruct_instr.variable();
20 if (variable == nullptr) {
21 continue;
22 }
23 /* Remember this destruct instruction so that it can be moved up later on when the last use
24 * of the variable is found. */
25 destruct_instructions.add(variable, &destruct_instr);
26 break;
27 }
29 CallInstruction &call_instr = static_cast<CallInstruction &>(*current_instr);
30 /* For each variable, place the corresponding remembered destruct instruction right after
31 * this call instruction. */
32 for (Variable *variable : call_instr.params()) {
33 if (variable == nullptr) {
34 continue;
35 }
36 DestructInstruction *destruct_instr = destruct_instructions.pop_default(variable,
37 nullptr);
38 if (destruct_instr == nullptr) {
39 continue;
40 }
41
42 /* Unlink destruct instruction from previous position. */
43 Instruction *after_destruct_instr = destruct_instr->next();
44 while (!destruct_instr->prev().is_empty()) {
45 /* Do a copy of the cursor here, because `destruct_instr->prev()` changes when
46 * #set_next is called below. */
47 const InstructionCursor cursor = destruct_instr->prev()[0];
48 cursor.set_next(procedure, after_destruct_instr);
49 }
50
51 /* Insert destruct instruction in new position. */
52 Instruction *next_instr = call_instr.next();
53 call_instr.set_next(destruct_instr);
54 destruct_instr->set_next(next_instr);
55 }
56 break;
57 }
58 default: {
59 break;
60 }
61 }
62
63 const Span<InstructionCursor> prev_cursors = current_instr->prev();
64 if (prev_cursors.size() != 1) {
65 /* Stop when there is some branching before this instruction. */
66 break;
67 }
68 const InstructionCursor &prev_cursor = prev_cursors[0];
69 current_instr = prev_cursor.instruction();
70 if (current_instr == nullptr) {
71 /* Stop when there is no previous instruction. E.g. when this is the first instruction. */
72 break;
73 }
74 }
75}
76
77} // namespace blender::fn::multi_function::procedure_optimization
bool add(const Key &key, const Value &value)
Definition BLI_map.hh:271
Value pop_default(const Key &key, const Value &default_value)
Definition BLI_map.hh:415
constexpr int64_t size() const
Definition BLI_span.hh:253
void move_destructs_up(Procedure &procedure, Instruction &block_end_instr)