|
1 | 1 | from kirin import ir |
2 | 2 | from kirin.analysis import const |
| 3 | +from kirin.dialects import func |
3 | 4 | from kirin.rewrite.abc import RewriteRule |
4 | 5 | from kirin.rewrite.result import RewriteResult |
5 | 6 | from kirin.dialects.py.constant import Constant |
6 | 7 |
|
7 | | -from .stmts import For, Yield |
| 8 | +from .stmts import For, Yield, IfElse |
| 9 | + |
| 10 | + |
| 11 | +class PickIfElse(RewriteRule): |
| 12 | + |
| 13 | + def rewrite_Statement(self, node: ir.Statement) -> RewriteResult: |
| 14 | + if not isinstance(node, IfElse): |
| 15 | + return RewriteResult() |
| 16 | + |
| 17 | + if not isinstance(hint := node.cond.hints.get("const"), const.Value): |
| 18 | + return RewriteResult() |
| 19 | + |
| 20 | + if hint.data: |
| 21 | + return self.insert_body(node, node.then_body) |
| 22 | + else: |
| 23 | + return self.insert_body(node, node.else_body) |
| 24 | + |
| 25 | + def insert_body(self, node: IfElse, body: ir.Region): |
| 26 | + body_block = body.clone().blocks[0] |
| 27 | + body_block.args[0].replace_by(node.cond) |
| 28 | + block_stmt = body_block.first_stmt |
| 29 | + while block_stmt and not block_stmt.has_trait(ir.IsTerminator): |
| 30 | + block_stmt.detach() |
| 31 | + block_stmt.insert_before(node) |
| 32 | + block_stmt = body_block.first_stmt |
| 33 | + |
| 34 | + terminator = body_block.last_stmt |
| 35 | + if isinstance(terminator, Yield): |
| 36 | + for result, output in zip(node.results, terminator.values): |
| 37 | + result.replace_by(output) |
| 38 | + node.delete() |
| 39 | + return RewriteResult(has_done_something=True) |
| 40 | + elif isinstance(terminator, func.Return): |
| 41 | + block = node.parent |
| 42 | + assert block is not None |
| 43 | + stmt = block.last_stmt |
| 44 | + while stmt is not None and stmt is not node: # remove the rest of the block |
| 45 | + delete_stmt = stmt |
| 46 | + stmt = stmt.prev_stmt |
| 47 | + delete_stmt.delete() |
| 48 | + |
| 49 | + terminator.detach() |
| 50 | + node.replace_by(terminator) |
| 51 | + return RewriteResult(has_done_something=True) |
| 52 | + else: |
| 53 | + return RewriteResult() |
8 | 54 |
|
9 | 55 |
|
10 | 56 | class ForLoop(RewriteRule): |
|
0 commit comments