Skip to content

Block

Block dataclass

Block(
    stmts: Sequence[Statement] = (),
    argtypes: Iterable[TypeAttribute] = (),
    *,
    source: SourceInfo | None = None
)

Bases: IRNode['Region']

Block consist of a list of Statements and optionally input arguments.

Pretty Printing

This object is pretty printable via .print() method.

argtypes (Iterable[TypeAttribute], optional): The type of the block arguments. Defaults to ().
Source code in src/kirin/ir/nodes/block.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
def __init__(
    self,
    stmts: Sequence[Statement] = (),
    argtypes: Iterable[TypeAttribute] = (),
    *,
    source: SourceInfo | None = None,
):
    """
    Args:
        stmts (Sequence[Statement], optional): A list of statements. Defaults to ().
        argtypes (Iterable[TypeAttribute], optional): The type of the block arguments. Defaults to ().
    """
    super().__init__()
    self.source = source
    self._args = tuple(
        BlockArgument(self, i, argtype) for i, argtype in enumerate(argtypes)
    )

    self._first_stmt = None
    self._last_stmt = None
    self._first_branch = None
    self._last_branch = None
    self._stmt_len = 0
    self.stmts.extend(stmts)

args property

args: BlockArguments

Get the arguments of the Block.

Returns:

Name Type Description
BlockArguments BlockArguments

The arguments view of the Block.

first_stmt property

first_stmt: Statement | None

Get the first Statement of the Block.

Returns:

Type Description
Statement | None

Statement | None: The first Statement of the Block.

last_stmt property

last_stmt: Statement | None

Get the last Statement of the Block.

Returns:

Type Description
Statement | None

Statement | None: The last Statement of the Block.

parent class-attribute instance-attribute

parent: Region | None = field(default=None, repr=False)

Parent Region of the Block.

parent_node property writable

parent_node: Region | None

Get parent Region of the Block.

parent_stmt property

parent_stmt: Statement | None

parent statement of the Block.

stmts property

stmts: BlockStmts

Get the list of Statements of the Block.

Returns:

Name Type Description
BlockStmts BlockStmts

The Statements of the Block.

delete

delete(safe: bool = True) -> None

Delete the Block completely from the IR.

Note

This method will detach + remove references of the block.

Parameters:

Name Type Description Default
safe bool

If True, raise error if there is anything that still reference components in the block. Defaults to True.

True
Source code in src/kirin/ir/nodes/block.py
358
359
360
361
362
363
364
365
366
367
368
369
370
def delete(self, safe: bool = True) -> None:
    """Delete the Block completely from the IR.

    Note:
        This method will detach + remove references of the block.

    Args:
        safe (bool, optional): If True, raise error if there is anything that still reference components in the block. Defaults to True.
    """
    self.detach()
    self.drop_all_references()
    for stmt in self.stmts:
        stmt.delete(safe=safe)

detach

detach() -> None

Detach this Block from the IR.

Note

Detach only detach the Block from the IR graph. It does not remove uses that reference the Block.

Source code in src/kirin/ir/nodes/block.py
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
def detach(self) -> None:
    """Detach this Block from the IR.

    Note:
        Detach only detach the Block from the IR graph. It does not remove uses that reference the Block.
    """
    if self.parent is None:
        return

    idx = self.parent[self]
    del self.parent._blocks[idx]
    del self.parent._block_idx[self]
    for block in self.parent._blocks[idx:]:
        self.parent._block_idx[block] -= 1
    self.parent = None

drop_all_references

drop_all_references() -> None

Remove all the dependency that reference/uses this Block.

Source code in src/kirin/ir/nodes/block.py
336
337
338
339
340
def drop_all_references(self) -> None:
    """Remove all the dependency that reference/uses this Block."""
    self.parent = None
    for stmt in self.stmts:
        stmt.drop_all_references()

is_structurally_equal

is_structurally_equal(
    other: Self,
    context: (
        dict[IRNode | SSAValue, IRNode | SSAValue] | None
    ) = None,
) -> bool

Check if the Block is structurally equal to another Block.

Parameters:

Name Type Description Default
other Self

The other Block to compare with.

required
context dict[IRNode | SSAValue, IRNode | SSAValue] | None

A map of IRNode/SSAValue to hint that they are equivalent so the check will treat them as equivalent. Defaults to None.

None

Returns:

Name Type Description
bool bool

True if the Block is structurally equal to the other Block.

Source code in src/kirin/ir/nodes/block.py
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
def is_structurally_equal(
    self,
    other: Self,
    context: dict[IRNode | SSAValue, IRNode | SSAValue] | None = None,
) -> bool:
    """Check if the Block is structurally equal to another Block.

    Args:
        other (Self): The other Block to compare with.
        context (dict[IRNode  |  SSAValue, IRNode  |  SSAValue] | None, optional): A map of IRNode/SSAValue to hint that they are equivalent so the check will treat them as equivalent. Defaults to None.

    Returns:
        bool: True if the Block is structurally equal to the other Block.
    """
    if context is None:
        context = {}

    if len(self._args) != len(other._args) or len(self.stmts) != len(other.stmts):
        return False

    for arg, other_arg in zip(self._args, other._args):
        if arg.type != other_arg.type:
            return False
        context[arg] = other_arg

    context[self] = other
    if not all(
        stmt.is_structurally_equal(other_stmt, context)
        for stmt, other_stmt in zip(self.stmts, other.stmts)
    ):
        return False

    return True

verify

verify() -> None

Verify the correctness of the Block.

Raises:

Type Description
ValidationError

If the Block is not correct.

Source code in src/kirin/ir/nodes/block.py
448
449
450
451
452
453
454
455
456
457
458
459
460
def verify(self) -> None:
    """Verify the correctness of the Block.

    Raises:
        ValidationError: If the Block is not correct.
    """
    from kirin.ir.nodes.stmt import Region

    if not isinstance(self.parent, Region):
        raise ValidationError(self, "Parent is not a region")

    for stmt in self.stmts:
        stmt.verify()

verify_type

verify_type() -> None

Verify the types of the Block.

Raises:

Type Description
ValidationError

If the Block is not correct.

Source code in src/kirin/ir/nodes/block.py
462
463
464
465
466
467
468
469
def verify_type(self) -> None:
    """Verify the types of the Block.

    Raises:
        ValidationError: If the Block is not correct.
    """
    for stmt in self.stmts:
        stmt.verify_type()

walk

walk(
    *, reverse: bool = False, region_first: bool = False
) -> Iterator[Statement]

Traversal the Statements in a Block.

Parameters:

Name Type Description Default
reverse bool

If walk in the reversed manner. Defaults to False.

False
region_first bool

If the walk should go through the Statement first or the Region of a Statement first. Defaults to False.

False

Yields:

Type Description
Statement

Iterator[Statement]: An iterator that yield Statements in the Block in the specified order.

Source code in src/kirin/ir/nodes/block.py
409
410
411
412
413
414
415
416
417
418
419
420
421
422
def walk(
    self, *, reverse: bool = False, region_first: bool = False
) -> Iterator[Statement]:
    """Traversal the Statements in a Block.

    Args:
        reverse (bool, optional): If walk in the reversed manner. Defaults to False.
        region_first (bool, optional): If the walk should go through the Statement first or the Region of a Statement first. Defaults to False.

    Yields:
        Iterator[Statement]: An iterator that yield Statements in the Block in the specified order.
    """
    for stmt in reversed(self.stmts) if reverse else self.stmts:
        yield from stmt.walk(reverse=reverse, region_first=region_first)

BlockArguments dataclass

BlockArguments(node: NodeType, field: FieldType)

Bases: MutableSequenceView[tuple, 'Block', BlockArgument]

A View object that contains a list of BlockArgument.

Description

This is a proxy object that provide safe API to manipulate the arguments of a Block.

append_from

append_from(
    typ: TypeAttribute, name: str | None = None
) -> BlockArgument

Append a new argument to the Block that this View reference to.

Description

This method will create a new BlockArgument and append it to the argument list of the reference Block.

Parameters:

Name Type Description Default
typ TypeAttribute

The type of the argument.

required
name str | None

name of the argument. Defaults to None.

None

Returns:

Name Type Description
BlockArgument BlockArgument

The newly created BlockArgument.

Source code in src/kirin/ir/nodes/block.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def append_from(self, typ: TypeAttribute, name: str | None = None) -> BlockArgument:
    """Append a new argument to the Block that this View reference to.

    Description:
        This method will create a new [`BlockArgument`][kirin.ir.BlockArgument] and append it to the argument list
        of the reference `Block`.

    Args:
        typ (TypeAttribute): The type of the argument.
        name (str | None, optional): name of the argument. Defaults to `None`.

    Returns:
        BlockArgument: The newly created [`BlockArgument`][kirin.ir.BlockArgument].

    """
    new_arg = BlockArgument(self.node, len(self.node._args), typ)
    if name:
        new_arg.name = name

    self.node._args += (new_arg,)
    return new_arg

delete

delete(arg: BlockArgument, safe: bool = True) -> None

Delete a BlockArgument from the Block that this View reference to.

Parameters:

Name Type Description Default
arg BlockArgument

description

required
safe bool

If True, error will be raised if the BlockArgument has any Use by others. Defaults to True.

True

Raises:

Type Description
ValueError

If the argument does not belong to the reference block.

Source code in src/kirin/ir/nodes/block.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def delete(self, arg: BlockArgument, safe: bool = True) -> None:
    """Delete a BlockArgument from the Block that this View reference to.


    Args:
        arg (BlockArgument): _description_
        safe (bool, optional): If True, error will be raised if the BlockArgument has any Use by others.  Defaults to True.

    Raises:
        ValueError: If the argument does not belong to the reference block.
    """
    if safe and len(arg.uses) > 0:
        raise ValueError("Cannot delete SSA value with uses")

    if arg.block is not self.node:
        raise ValueError("Attempt to delete an argument that is not in the block")

    for block_arg in self.field[arg.index + 1 :]:
        block_arg.index -= 1
    self.node._args = (*self.field[: arg.index], *self.field[arg.index + 1 :])
    arg.replace_by(DeletedSSAValue(arg))

insert_from

insert_from(
    idx: int, typ: TypeAttribute, name: str | None = None
) -> BlockArgument

Insert a new argument to the Block that this View reference to.

Description

This method will create a new BlockArgument and insert it to the argument list of the reference Block at the specified index

Parameters:

Name Type Description Default
idx int

Insert location index.

required
typ TypeAttribute

The type of the argument.

required
name str | None

Name of the argument. Defaults to None.

None

Returns:

Name Type Description
BlockArgument BlockArgument

The newly created BlockArgument.

Source code in src/kirin/ir/nodes/block.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def insert_from(
    self, idx: int, typ: TypeAttribute, name: str | None = None
) -> BlockArgument:
    """Insert a new argument to the Block that this View reference to.

    Description:
        This method will create a new `BlockArgument` and insert it to the argument list
        of the reference Block at the specified index

    Args:
        idx (int): Insert location index.
        typ (TypeAttribute): The type of the argument.
        name (str | None, optional): Name of the argument. Defaults to `None`.

    Returns:
        BlockArgument: The newly created BlockArgument.
    """
    if idx < 0 or idx > len(self.node._args):
        raise ValueError("Invalid index")

    new_arg = BlockArgument(self.node, idx, typ)
    if name:
        new_arg.name = name

    for arg in self.node._args[idx:]:
        arg.index += 1
    self.node._args = self.node._args[:idx] + (new_arg,) + self.node._args[idx:]
    return new_arg

BlockStmtIterator dataclass

BlockStmtIterator(next_stmt: Statement | None)

Proxy object to iterate over the Statements in a Block.

BlockStmts dataclass

BlockStmts(node: NodeType)

Bases: View['Block', 'Statement']

A View object that contains a list of Statements.

Description

This is a proxy object that provide safe API to manipulate the statements of a Block.

append

append(value: Statement) -> None

Append a Statement to the reference Block.

Parameters:

Name Type Description Default
value Statement

A Statement to be appended.

required
Source code in src/kirin/ir/nodes/block.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
def append(self, value: Statement) -> None:
    """Append a Statement to the reference Block.

    Args:
        value (Statement): A Statement to be appended.
    """
    from kirin.ir.nodes.stmt import Statement

    if not isinstance(value, Statement):
        raise ValueError(f"Expected Statement, got {type(value).__name__}")

    if self.node._stmt_len == 0:  # empty block
        value.attach(self.node)
        self.node._first_stmt = value
        self.node._last_stmt = value
        self.node._stmt_len += 1
    elif self.node._last_stmt:
        value.insert_after(self.node._last_stmt)
    else:
        raise ValueError("Invalid block, last_stmt is None")

at

at(index: int) -> Statement

This is similar to getitem but due to the nature of the linked list, it is less efficient than getitem.

Parameters:

Name Type Description Default
index int

Index of the Statement.

required

Returns:

Name Type Description
Statement Statement

The Statement at the specified index.

Source code in src/kirin/ir/nodes/block.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def at(self, index: int) -> Statement:
    """This is similar to __getitem__ but due to the nature of the linked list,
    it is less efficient than __getitem__.

    Args:
        index (int): Index of the Statement.

    Returns:
        Statement: The Statement at the specified index.
    """
    if index >= len(self):
        raise IndexError("Index out of range")

    if index < 0:
        return self._at_reverse(-index - 1)

    return self._at_forward(index)

BlockStmtsReverseIterator dataclass

BlockStmtsReverseIterator(next_stmt: Statement | None)

Proxy object to iterate over the Statements in a Block in reverse order.