Skip to content

Riscv func

riscv_func

RISCV_Func = Dialect('riscv_func', [SyscallOp, CallOp, FuncOp, ReturnOp], []) module-attribute

SyscallOp

Bases: IRDLOperation

Source code in xdsl/dialects/riscv_func.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
@irdl_op_definition
class SyscallOp(IRDLOperation):
    name = "riscv_func.syscall"
    args = var_operand_def(riscv.IntRegisterType)
    syscall_num = attr_def(IntegerAttr[I32])
    result = opt_result_def(riscv.IntRegisterType)

    def __init__(
        self,
        num: int | IntegerAttr[I32],
        has_result: bool = False,
        operands: list[SSAValue | Operation] = [],
    ):
        if isinstance(num, int):
            num = IntegerAttr(num, i32)
        super().__init__(
            operands=[operands],
            attributes={"syscall_num": num},
            result_types=[riscv.Registers.UNALLOCATED_INT if has_result else None],
        )

    def verify_(self):
        if len(self.args) >= 7:
            raise VerifyException(
                f"Syscall op has too many operands ({len(self.args)}), expected fewer than 7"
            )
        if len(self.results) >= 3:
            raise VerifyException(
                f"Syscall op has too many results ({len(self.results)}), expected fewer than 3"
            )

name = 'riscv_func.syscall' class-attribute instance-attribute

args = var_operand_def(riscv.IntRegisterType) class-attribute instance-attribute

syscall_num = attr_def(IntegerAttr[I32]) class-attribute instance-attribute

result = opt_result_def(riscv.IntRegisterType) class-attribute instance-attribute

__init__(num: int | IntegerAttr[I32], has_result: bool = False, operands: list[SSAValue | Operation] = [])

Source code in xdsl/dialects/riscv_func.py
55
56
57
58
59
60
61
62
63
64
65
66
67
def __init__(
    self,
    num: int | IntegerAttr[I32],
    has_result: bool = False,
    operands: list[SSAValue | Operation] = [],
):
    if isinstance(num, int):
        num = IntegerAttr(num, i32)
    super().__init__(
        operands=[operands],
        attributes={"syscall_num": num},
        result_types=[riscv.Registers.UNALLOCATED_INT if has_result else None],
    )

verify_()

Source code in xdsl/dialects/riscv_func.py
69
70
71
72
73
74
75
76
77
def verify_(self):
    if len(self.args) >= 7:
        raise VerifyException(
            f"Syscall op has too many operands ({len(self.args)}), expected fewer than 7"
        )
    if len(self.results) >= 3:
        raise VerifyException(
            f"Syscall op has too many results ({len(self.results)}), expected fewer than 3"
        )

CallOp

Bases: RISCVInstruction

RISC-V function call operation

Source code in xdsl/dialects/riscv_func.py
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
@irdl_op_definition
class CallOp(riscv.RISCVInstruction):
    """RISC-V function call operation"""

    name = "riscv_func.call"
    args = var_operand_def(riscv.RISCVRegisterType)
    callee = attr_def(SymbolRefAttr)
    ress = var_result_def(riscv.RISCVRegisterType)

    assembly_format = (
        "$callee `(` $args `)` attr-dict `:` functional-type($args, $ress)"
    )

    def __init__(
        self,
        callee: SymbolRefAttr,
        args: Sequence[Operation | SSAValue],
        result_types: Sequence[riscv.RISCVRegisterType],
        comment: StringAttr | None = None,
    ):
        super().__init__(
            operands=[args],
            result_types=[result_types],
            attributes={
                "callee": callee,
                "comment": comment,
            },
        )

    def verify_(self):
        if len(self.args) >= 9:
            raise VerifyException(
                f"Function op has too many operands ({len(self.args)}), expected fewer than 9"
            )

        if len(self.results) >= 3:
            raise VerifyException(
                f"Function op has too many results ({len(self.results)}), expected fewer than 3"
            )

    def assembly_instruction_name(self) -> str:
        return "jal"

    def assembly_line_args(self) -> tuple[riscv.AssemblyInstructionArg | None, ...]:
        return (self.callee.string_value(),)

    def iter_used_registers(self) -> Generator[RegisterType, None, None]:
        # These registers are not guaranteed to hold the same values when the callee
        # returns, according to the RISC-V calling convention.
        # https://riscv.org/wp-content/uploads/2015/01/riscv-calling.pdf
        yield from riscv.Registers.A
        yield from riscv.Registers.T
        yield from riscv.Registers.FA
        yield from riscv.Registers.FT

name = 'riscv_func.call' class-attribute instance-attribute

args = var_operand_def(riscv.RISCVRegisterType) class-attribute instance-attribute

callee = attr_def(SymbolRefAttr) class-attribute instance-attribute

ress = var_result_def(riscv.RISCVRegisterType) class-attribute instance-attribute

assembly_format = '$callee `(` $args `)` attr-dict `:` functional-type($args, $ress)' class-attribute instance-attribute

__init__(callee: SymbolRefAttr, args: Sequence[Operation | SSAValue], result_types: Sequence[riscv.RISCVRegisterType], comment: StringAttr | None = None)

Source code in xdsl/dialects/riscv_func.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def __init__(
    self,
    callee: SymbolRefAttr,
    args: Sequence[Operation | SSAValue],
    result_types: Sequence[riscv.RISCVRegisterType],
    comment: StringAttr | None = None,
):
    super().__init__(
        operands=[args],
        result_types=[result_types],
        attributes={
            "callee": callee,
            "comment": comment,
        },
    )

verify_()

Source code in xdsl/dialects/riscv_func.py
109
110
111
112
113
114
115
116
117
118
def verify_(self):
    if len(self.args) >= 9:
        raise VerifyException(
            f"Function op has too many operands ({len(self.args)}), expected fewer than 9"
        )

    if len(self.results) >= 3:
        raise VerifyException(
            f"Function op has too many results ({len(self.results)}), expected fewer than 3"
        )

assembly_instruction_name() -> str

Source code in xdsl/dialects/riscv_func.py
120
121
def assembly_instruction_name(self) -> str:
    return "jal"

assembly_line_args() -> tuple[riscv.AssemblyInstructionArg | None, ...]

Source code in xdsl/dialects/riscv_func.py
123
124
def assembly_line_args(self) -> tuple[riscv.AssemblyInstructionArg | None, ...]:
    return (self.callee.string_value(),)

iter_used_registers() -> Generator[RegisterType, None, None]

Source code in xdsl/dialects/riscv_func.py
126
127
128
129
130
131
132
133
def iter_used_registers(self) -> Generator[RegisterType, None, None]:
    # These registers are not guaranteed to hold the same values when the callee
    # returns, according to the RISC-V calling convention.
    # https://riscv.org/wp-content/uploads/2015/01/riscv-calling.pdf
    yield from riscv.Registers.A
    yield from riscv.Registers.T
    yield from riscv.Registers.FA
    yield from riscv.Registers.FT

FuncOpCallableInterface dataclass

Bases: CallableOpInterface

Source code in xdsl/dialects/riscv_func.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
class FuncOpCallableInterface(CallableOpInterface):
    @classmethod
    def get_callable_region(cls, op: Operation) -> Region:
        assert isinstance(op, FuncOp)
        return op.body

    @classmethod
    def get_argument_types(cls, op: Operation) -> tuple[Attribute, ...]:
        assert isinstance(op, FuncOp)
        return op.function_type.inputs.data

    @classmethod
    def get_result_types(cls, op: Operation) -> tuple[Attribute, ...]:
        assert isinstance(op, FuncOp)
        return op.function_type.outputs.data

get_callable_region(op: Operation) -> Region classmethod

Source code in xdsl/dialects/riscv_func.py
137
138
139
140
@classmethod
def get_callable_region(cls, op: Operation) -> Region:
    assert isinstance(op, FuncOp)
    return op.body

get_argument_types(op: Operation) -> tuple[Attribute, ...] classmethod

Source code in xdsl/dialects/riscv_func.py
142
143
144
145
@classmethod
def get_argument_types(cls, op: Operation) -> tuple[Attribute, ...]:
    assert isinstance(op, FuncOp)
    return op.function_type.inputs.data

get_result_types(op: Operation) -> tuple[Attribute, ...] classmethod

Source code in xdsl/dialects/riscv_func.py
147
148
149
150
@classmethod
def get_result_types(cls, op: Operation) -> tuple[Attribute, ...]:
    assert isinstance(op, FuncOp)
    return op.function_type.outputs.data

FuncOp

Bases: IRDLOperation, AssemblyPrintable

RISC-V function definition operation

Source code in xdsl/dialects/riscv_func.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
@irdl_op_definition
class FuncOp(IRDLOperation, AssemblyPrintable):
    """RISC-V function definition operation"""

    name = "riscv_func.func"
    sym_name = attr_def(SymbolNameConstraint())
    body = region_def()
    function_type = attr_def(FunctionType)
    sym_visibility = opt_attr_def(StringAttr)
    p2align = opt_attr_def(IntegerAttr[I8])

    traits = traits_def(
        SymbolOpInterface(),
        FuncOpCallableInterface(),
        IsolatedFromAbove(),
    )

    def __init__(
        self,
        name: str,
        region: Region,
        function_type: FunctionType | tuple[Sequence[Attribute], Sequence[Attribute]],
        visibility: StringAttr | str | None = None,
        p2align: int | IntegerAttr[I8] | None = None,
    ):
        if isinstance(function_type, tuple):
            inputs, outputs = function_type
            function_type = FunctionType.from_lists(inputs, outputs)
        if isinstance(visibility, str):
            visibility = StringAttr(visibility)
        if isinstance(p2align, int):
            p2align = IntegerAttr(p2align, i8)
        attributes: dict[str, Attribute | None] = {
            "sym_name": StringAttr(name),
            "function_type": function_type,
            "sym_visibility": visibility,
            "p2align": p2align,
        }

        super().__init__(attributes=attributes, regions=[region])

    @classmethod
    def parse(cls, parser: Parser) -> FuncOp:
        visibility = parser.parse_optional_visibility_keyword()
        (name, input_types, return_types, region, extra_attrs, arg_attrs, res_attrs) = (
            parse_func_op_like(
                parser,
                reserved_attr_names=("sym_name", "function_type", "sym_visibility"),
            )
        )
        if arg_attrs:
            raise NotImplementedError("arg_attrs not implemented in riscv_func")
        if res_attrs:
            raise NotImplementedError("res_attrs not implemented in riscv_func")
        func = FuncOp(name, region, (input_types, return_types), visibility)
        if extra_attrs is not None:
            func.attributes |= extra_attrs.data
        return func

    def print(self, printer: Printer):
        if self.sym_visibility:
            visibility = self.sym_visibility.data
            printer.print_string(" ")
            printer.print_string(visibility)

        print_func_op_like(
            printer,
            self.sym_name,
            self.function_type,
            self.body,
            self.attributes,
            reserved_attr_names=("sym_name", "function_type", "sym_visibility"),
        )

    def print_assembly(self, printer: AssemblyPrinter) -> None:
        if not self.body.blocks:
            # Print nothing for function declaration
            return

        printer.emit_section(".text")

        if self.sym_visibility is not None:
            match self.sym_visibility.data:
                case "public":
                    printer.print_string(f".globl {self.sym_name.data}\n", indent=0)
                case "private":
                    printer.print_string(f".local {self.sym_name.data}\n", indent=0)
                case _:
                    raise DiagnosticException(
                        f"Unexpected visibility {self.sym_visibility.data} for function {self.sym_name}"
                    )

        if self.p2align is not None:
            printer.print_string(f".p2align {self.p2align.value.data}\n", indent=0)
        printer.print_string(f"{self.sym_name.data}:\n")

name = 'riscv_func.func' class-attribute instance-attribute

sym_name = attr_def(SymbolNameConstraint()) class-attribute instance-attribute

body = region_def() class-attribute instance-attribute

function_type = attr_def(FunctionType) class-attribute instance-attribute

sym_visibility = opt_attr_def(StringAttr) class-attribute instance-attribute

p2align = opt_attr_def(IntegerAttr[I8]) class-attribute instance-attribute

traits = traits_def(SymbolOpInterface(), FuncOpCallableInterface(), IsolatedFromAbove()) class-attribute instance-attribute

__init__(name: str, region: Region, function_type: FunctionType | tuple[Sequence[Attribute], Sequence[Attribute]], visibility: StringAttr | str | None = None, p2align: int | IntegerAttr[I8] | None = None)

Source code in xdsl/dialects/riscv_func.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
def __init__(
    self,
    name: str,
    region: Region,
    function_type: FunctionType | tuple[Sequence[Attribute], Sequence[Attribute]],
    visibility: StringAttr | str | None = None,
    p2align: int | IntegerAttr[I8] | None = None,
):
    if isinstance(function_type, tuple):
        inputs, outputs = function_type
        function_type = FunctionType.from_lists(inputs, outputs)
    if isinstance(visibility, str):
        visibility = StringAttr(visibility)
    if isinstance(p2align, int):
        p2align = IntegerAttr(p2align, i8)
    attributes: dict[str, Attribute | None] = {
        "sym_name": StringAttr(name),
        "function_type": function_type,
        "sym_visibility": visibility,
        "p2align": p2align,
    }

    super().__init__(attributes=attributes, regions=[region])

parse(parser: Parser) -> FuncOp classmethod

Source code in xdsl/dialects/riscv_func.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
@classmethod
def parse(cls, parser: Parser) -> FuncOp:
    visibility = parser.parse_optional_visibility_keyword()
    (name, input_types, return_types, region, extra_attrs, arg_attrs, res_attrs) = (
        parse_func_op_like(
            parser,
            reserved_attr_names=("sym_name", "function_type", "sym_visibility"),
        )
    )
    if arg_attrs:
        raise NotImplementedError("arg_attrs not implemented in riscv_func")
    if res_attrs:
        raise NotImplementedError("res_attrs not implemented in riscv_func")
    func = FuncOp(name, region, (input_types, return_types), visibility)
    if extra_attrs is not None:
        func.attributes |= extra_attrs.data
    return func

print(printer: Printer)

Source code in xdsl/dialects/riscv_func.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
def print(self, printer: Printer):
    if self.sym_visibility:
        visibility = self.sym_visibility.data
        printer.print_string(" ")
        printer.print_string(visibility)

    print_func_op_like(
        printer,
        self.sym_name,
        self.function_type,
        self.body,
        self.attributes,
        reserved_attr_names=("sym_name", "function_type", "sym_visibility"),
    )

print_assembly(printer: AssemblyPrinter) -> None

Source code in xdsl/dialects/riscv_func.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
def print_assembly(self, printer: AssemblyPrinter) -> None:
    if not self.body.blocks:
        # Print nothing for function declaration
        return

    printer.emit_section(".text")

    if self.sym_visibility is not None:
        match self.sym_visibility.data:
            case "public":
                printer.print_string(f".globl {self.sym_name.data}\n", indent=0)
            case "private":
                printer.print_string(f".local {self.sym_name.data}\n", indent=0)
            case _:
                raise DiagnosticException(
                    f"Unexpected visibility {self.sym_visibility.data} for function {self.sym_name}"
                )

    if self.p2align is not None:
        printer.print_string(f".p2align {self.p2align.value.data}\n", indent=0)
    printer.print_string(f"{self.sym_name.data}:\n")

ReturnOp

Bases: RISCVInstruction

RISC-V function return operation

Source code in xdsl/dialects/riscv_func.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
@irdl_op_definition
class ReturnOp(riscv.RISCVInstruction):
    """RISC-V function return operation"""

    name = "riscv_func.return"
    values = var_operand_def(riscv.RISCVRegisterType)
    comment = opt_attr_def(StringAttr)

    traits = traits_def(IsTerminator(), HasParent(FuncOp), ReturnLike())

    assembly_format = "attr-dict ($values^ `:` type($values))?"

    def __init__(
        self,
        *values: Operation | SSAValue,
        comment: str | StringAttr | None = None,
    ):
        if isinstance(comment, str):
            comment = StringAttr(comment)
        super().__init__(
            operands=[values],
            attributes={
                "comment": comment,
            },
        )

    def verify_(self):
        if len(self.results) >= 3:
            raise VerifyException(
                f"Function op has too many results ({len(self.results)}), expected fewer than 3"
            )

    def assembly_instruction_name(self) -> str:
        return "ret"

    def assembly_line_args(self) -> tuple[riscv.AssemblyInstructionArg | None, ...]:
        return ()

name = 'riscv_func.return' class-attribute instance-attribute

values = var_operand_def(riscv.RISCVRegisterType) class-attribute instance-attribute

comment = opt_attr_def(StringAttr) class-attribute instance-attribute

traits = traits_def(IsTerminator(), HasParent(FuncOp), ReturnLike()) class-attribute instance-attribute

assembly_format = 'attr-dict ($values^ `:` type($values))?' class-attribute instance-attribute

__init__(*values: Operation | SSAValue, comment: str | StringAttr | None = None)

Source code in xdsl/dialects/riscv_func.py
262
263
264
265
266
267
268
269
270
271
272
273
274
def __init__(
    self,
    *values: Operation | SSAValue,
    comment: str | StringAttr | None = None,
):
    if isinstance(comment, str):
        comment = StringAttr(comment)
    super().__init__(
        operands=[values],
        attributes={
            "comment": comment,
        },
    )

verify_()

Source code in xdsl/dialects/riscv_func.py
276
277
278
279
280
def verify_(self):
    if len(self.results) >= 3:
        raise VerifyException(
            f"Function op has too many results ({len(self.results)}), expected fewer than 3"
        )

assembly_instruction_name() -> str

Source code in xdsl/dialects/riscv_func.py
282
283
def assembly_instruction_name(self) -> str:
    return "ret"

assembly_line_args() -> tuple[riscv.AssemblyInstructionArg | None, ...]

Source code in xdsl/dialects/riscv_func.py
285
286
def assembly_line_args(self) -> tuple[riscv.AssemblyInstructionArg | None, ...]:
    return ()