|
23 | 23 | CallC, |
24 | 24 | Cast, |
25 | 25 | ComparisonOp, |
| 26 | + ControlOp, |
26 | 27 | DecRef, |
27 | 28 | Extend, |
28 | 29 | Float, |
@@ -123,6 +124,28 @@ def generate_native_function( |
123 | 124 | for i, block in enumerate(blocks): |
124 | 125 | block.label = i |
125 | 126 |
|
| 127 | + # Find blocks that are never jumped to or are only jumped to from the |
| 128 | + # block directly above it. This allows for more labels and gotos to be |
| 129 | + # eliminated during code generation. |
| 130 | + for block in fn.blocks: |
| 131 | + terminator = block.terminator |
| 132 | + assert isinstance(terminator, ControlOp) |
| 133 | + |
| 134 | + for target in terminator.targets(): |
| 135 | + is_next_block = target.label == block.label + 1 |
| 136 | + |
| 137 | + # Always emit labels for GetAttr error checks since the emit code that |
| 138 | + # generates them will add instructions between the branch and the |
| 139 | + # next label, causing the label to be wrongly removed. A better |
| 140 | + # solution would be to change the IR so that it adds a basic block |
| 141 | + # inbetween the calls. |
| 142 | + is_problematic_op = isinstance(terminator, Branch) and any( |
| 143 | + isinstance(s, GetAttr) for s in terminator.sources() |
| 144 | + ) |
| 145 | + |
| 146 | + if not is_next_block or is_problematic_op: |
| 147 | + fn.blocks[target.label].referenced = True |
| 148 | + |
126 | 149 | common = frequently_executed_blocks(fn.blocks[0]) |
127 | 150 |
|
128 | 151 | for i in range(len(blocks)): |
@@ -216,17 +239,20 @@ def visit_branch(self, op: Branch) -> None: |
216 | 239 |
|
217 | 240 | if false is self.next_block: |
218 | 241 | if op.traceback_entry is None: |
219 | | - self.emit_line(f"if ({cond}) goto {self.label(true)};") |
| 242 | + if true is not self.next_block: |
| 243 | + self.emit_line(f"if ({cond}) goto {self.label(true)};") |
220 | 244 | else: |
221 | 245 | self.emit_line(f"if ({cond}) {{") |
222 | 246 | self.emit_traceback(op) |
223 | 247 | self.emit_lines("goto %s;" % self.label(true), "}") |
224 | 248 | else: |
225 | 249 | self.emit_line(f"if ({cond}) {{") |
226 | 250 | self.emit_traceback(op) |
227 | | - self.emit_lines( |
228 | | - "goto %s;" % self.label(true), "} else", " goto %s;" % self.label(false) |
229 | | - ) |
| 251 | + |
| 252 | + if true is not self.next_block: |
| 253 | + self.emit_line("goto %s;" % self.label(true)) |
| 254 | + |
| 255 | + self.emit_lines("} else", " goto %s;" % self.label(false)) |
230 | 256 |
|
231 | 257 | def visit_return(self, op: Return) -> None: |
232 | 258 | value_str = self.reg(op.value) |
|
0 commit comments