Skip to content

Register type

register_type

RegisterType dataclass

Bases: ParametrizedAttribute, TypeAttribute, ABC

An abstract register type for target ISA-specific dialects.

Source code in xdsl/backend/register_type.py
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 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
 78
 79
 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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
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
@dataclass(frozen=True)
class RegisterType(ParametrizedAttribute, TypeAttribute, ABC):
    """
    An abstract register type for target ISA-specific dialects.
    """

    index: IntAttr | NoneAttr
    register_name: StringAttr

    @classmethod
    def unallocated(cls) -> Self:
        """
        Returns an unallocated register of this type.
        """
        return cls(NoneAttr(), StringAttr(""))

    @classmethod
    def _parameters_from_name(
        cls, register_name: StringAttr
    ) -> tuple[IntAttr | NoneAttr, StringAttr]:
        """
        Returns the parameter list required to construct a register instance from the given register_name.
        """
        if not register_name.data:
            return NoneAttr(), register_name
        index = cls.index_by_name().get(register_name.data)
        if index is None:
            # Try to decode as infinite register
            prefix = cls.infinite_register_prefix()
            if register_name.data.startswith(prefix):
                suffix = register_name.data[len(prefix) :]
                # infinite registers go from -1 to -inf
                try:
                    index = ~int(suffix)
                except ValueError:
                    index = None
            else:
                index = None

        # Raise verification error instead
        index_attr = NoneAttr() if index is None else IntAttr(index)
        return index_attr, register_name

    @classmethod
    def from_name(cls, register_name: StringAttr | str) -> Self:
        if not isinstance(register_name, StringAttr):
            register_name = StringAttr(register_name)
        return cls(*cls._parameters_from_name(register_name))

    @classmethod
    def from_index(cls, index: int) -> Self:
        if index < 0:
            return cls.infinite_register(~index)
        name = cls.abi_name_by_index()[index]
        return cls(IntAttr(index), StringAttr(name))

    @property
    def is_allocated(self) -> bool:
        """Returns true if the register is allocated, otherwise false"""
        return bool(self.register_name.data)

    @classmethod
    def parse_parameters(cls, parser: AttrParser) -> Sequence[Attribute]:
        if parser.parse_optional_punctuation("<"):
            name = parser.parse_identifier()
            parser.parse_punctuation(">")
            params = cls._parameters_from_name(StringAttr(name))
        else:
            params = (NoneAttr(), StringAttr(""))

        return params

    def print_parameters(self, printer: Printer) -> None:
        if self.register_name.data:
            with printer.in_angle_brackets():
                printer.print_string(self.register_name.data)

    def verify(self) -> None:
        name = self.register_name.data
        expected_index = type(self).index_by_name().get(name)

        if isinstance(self.index, NoneAttr):
            if not name:
                # Unallocated, expect NoneAttr
                return

            if expected_index is None:
                raise VerifyException(
                    f"Invalid register name {name} for register type {self.name}."
                )
            else:
                raise VerifyException(
                    f"Missing index for register {name}, expected {expected_index}."
                )

        if not name:
            raise VerifyException(
                f"Invalid index {self.index.data} for unallocated register."
            )

        if expected_index is not None:
            # Normal registers
            if expected_index == self.index.data:
                return

            raise VerifyException(
                f"Invalid index {self.index.data} for register {name}, expected {expected_index}."
            )

        infinite_register_name = self.infinite_register_prefix() + str(~self.index.data)
        if name == infinite_register_name:
            return

        raise VerifyException(f"Invalid index {self.index.data} for register {name}.")

    @classmethod
    def allocatable_registers(cls) -> Sequence[Self]:
        """
        Registers of this type that can be used for register allocation.
        """
        return ()

    @classmethod
    @abstractmethod
    def index_by_name(cls) -> dict[str, int]:
        raise NotImplementedError()

    # This class variable is created and exclusively accessed in `abi_name_by_index`.
    # _ABI_NAME_BY_INDEX: ClassVar[dict[int, str]]

    @classmethod
    def abi_name_by_index(cls) -> dict[int, str]:
        """
        Returns a mapping from ABI register indices to their names.
        """
        if hasattr(cls, "_ABI_NAME_BY_INDEX"):
            return cls._ABI_NAME_BY_INDEX

        result = {i: n for n, i in cls.index_by_name().items()}
        cls._ABI_NAME_BY_INDEX = result
        return result

    @classmethod
    @abstractmethod
    def infinite_register_prefix(cls) -> str:
        """
        Provide the prefix for the name for a register at the given index in the
        "infinite" register set.
        For a prefix `x`, the name of the first infinite register will be `x0`.
        """
        raise NotImplementedError()

    @classmethod
    def infinite_register(cls, index: int) -> Self:
        """
        Provide the register at the given index in the "infinite" register set.
        Index must be positive.
        """
        assert index >= 0, f"Infinite index must be positive, got {index}."
        register_name = cls.infinite_register_prefix() + str(index)
        assert register_name not in cls.index_by_name(), (
            f"Invalid 'infinite' register name: {register_name} clashes with finite register set"
        )
        index_attr = IntAttr(~index)
        res = cls(index_attr, StringAttr(register_name))
        return res

index: IntAttr | NoneAttr instance-attribute

register_name: StringAttr instance-attribute

is_allocated: bool property

Returns true if the register is allocated, otherwise false

__init__(index: IntAttr | NoneAttr, register_name: StringAttr) -> None

unallocated() -> Self classmethod

Returns an unallocated register of this type.

Source code in xdsl/backend/register_type.py
35
36
37
38
39
40
@classmethod
def unallocated(cls) -> Self:
    """
    Returns an unallocated register of this type.
    """
    return cls(NoneAttr(), StringAttr(""))

from_name(register_name: StringAttr | str) -> Self classmethod

Source code in xdsl/backend/register_type.py
69
70
71
72
73
@classmethod
def from_name(cls, register_name: StringAttr | str) -> Self:
    if not isinstance(register_name, StringAttr):
        register_name = StringAttr(register_name)
    return cls(*cls._parameters_from_name(register_name))

from_index(index: int) -> Self classmethod

Source code in xdsl/backend/register_type.py
75
76
77
78
79
80
@classmethod
def from_index(cls, index: int) -> Self:
    if index < 0:
        return cls.infinite_register(~index)
    name = cls.abi_name_by_index()[index]
    return cls(IntAttr(index), StringAttr(name))

parse_parameters(parser: AttrParser) -> Sequence[Attribute] classmethod

Source code in xdsl/backend/register_type.py
87
88
89
90
91
92
93
94
95
96
@classmethod
def parse_parameters(cls, parser: AttrParser) -> Sequence[Attribute]:
    if parser.parse_optional_punctuation("<"):
        name = parser.parse_identifier()
        parser.parse_punctuation(">")
        params = cls._parameters_from_name(StringAttr(name))
    else:
        params = (NoneAttr(), StringAttr(""))

    return params

print_parameters(printer: Printer) -> None

Source code in xdsl/backend/register_type.py
 98
 99
100
101
def print_parameters(self, printer: Printer) -> None:
    if self.register_name.data:
        with printer.in_angle_brackets():
            printer.print_string(self.register_name.data)

verify() -> None

Source code in xdsl/backend/register_type.py
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
134
135
136
137
138
139
def verify(self) -> None:
    name = self.register_name.data
    expected_index = type(self).index_by_name().get(name)

    if isinstance(self.index, NoneAttr):
        if not name:
            # Unallocated, expect NoneAttr
            return

        if expected_index is None:
            raise VerifyException(
                f"Invalid register name {name} for register type {self.name}."
            )
        else:
            raise VerifyException(
                f"Missing index for register {name}, expected {expected_index}."
            )

    if not name:
        raise VerifyException(
            f"Invalid index {self.index.data} for unallocated register."
        )

    if expected_index is not None:
        # Normal registers
        if expected_index == self.index.data:
            return

        raise VerifyException(
            f"Invalid index {self.index.data} for register {name}, expected {expected_index}."
        )

    infinite_register_name = self.infinite_register_prefix() + str(~self.index.data)
    if name == infinite_register_name:
        return

    raise VerifyException(f"Invalid index {self.index.data} for register {name}.")

allocatable_registers() -> Sequence[Self] classmethod

Registers of this type that can be used for register allocation.

Source code in xdsl/backend/register_type.py
141
142
143
144
145
146
@classmethod
def allocatable_registers(cls) -> Sequence[Self]:
    """
    Registers of this type that can be used for register allocation.
    """
    return ()

index_by_name() -> dict[str, int] abstractmethod classmethod

Source code in xdsl/backend/register_type.py
148
149
150
151
@classmethod
@abstractmethod
def index_by_name(cls) -> dict[str, int]:
    raise NotImplementedError()

abi_name_by_index() -> dict[int, str] classmethod

Returns a mapping from ABI register indices to their names.

Source code in xdsl/backend/register_type.py
156
157
158
159
160
161
162
163
164
165
166
@classmethod
def abi_name_by_index(cls) -> dict[int, str]:
    """
    Returns a mapping from ABI register indices to their names.
    """
    if hasattr(cls, "_ABI_NAME_BY_INDEX"):
        return cls._ABI_NAME_BY_INDEX

    result = {i: n for n, i in cls.index_by_name().items()}
    cls._ABI_NAME_BY_INDEX = result
    return result

infinite_register_prefix() -> str abstractmethod classmethod

Provide the prefix for the name for a register at the given index in the "infinite" register set. For a prefix x, the name of the first infinite register will be x0.

Source code in xdsl/backend/register_type.py
168
169
170
171
172
173
174
175
176
@classmethod
@abstractmethod
def infinite_register_prefix(cls) -> str:
    """
    Provide the prefix for the name for a register at the given index in the
    "infinite" register set.
    For a prefix `x`, the name of the first infinite register will be `x0`.
    """
    raise NotImplementedError()

infinite_register(index: int) -> Self classmethod

Provide the register at the given index in the "infinite" register set. Index must be positive.

Source code in xdsl/backend/register_type.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
@classmethod
def infinite_register(cls, index: int) -> Self:
    """
    Provide the register at the given index in the "infinite" register set.
    Index must be positive.
    """
    assert index >= 0, f"Infinite index must be positive, got {index}."
    register_name = cls.infinite_register_prefix() + str(index)
    assert register_name not in cls.index_by_name(), (
        f"Invalid 'infinite' register name: {register_name} clashes with finite register set"
    )
    index_attr = IntAttr(~index)
    res = cls(index_attr, StringAttr(register_name))
    return res

RegisterResource dataclass

Bases: Resource

Source code in xdsl/backend/register_type.py
194
195
196
197
198
199
@dataclass(frozen=True)
class RegisterResource(Resource):
    register: RegisterType

    def name(self) -> str:
        return f"<Register {self.register}>"

register: RegisterType instance-attribute

__init__(register: RegisterType) -> None

name() -> str

Source code in xdsl/backend/register_type.py
198
199
def name(self) -> str:
    return f"<Register {self.register}>"

RegisterAllocatedMemoryEffect dataclass

Bases: MemoryEffect

An assembly operation that only has side-effect if some registers are allocated to it.

Source code in xdsl/backend/register_type.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
class RegisterAllocatedMemoryEffect(MemoryEffect):
    """
    An assembly operation that only has side-effect if some registers are allocated to
    it.
    """

    @classmethod
    def get_effects(cls, op: Operation) -> set[EffectInstance]:
        effects = set[EffectInstance]()
        for result in op.results:
            if isinstance(r := result.type, RegisterType) and r.is_allocated:
                effects.add(
                    EffectInstance(MemoryEffectKind.WRITE, resource=RegisterResource(r))
                )
        for operand in op.operands:
            if isinstance(r := operand.type, RegisterType) and r.is_allocated:
                effects.add(
                    EffectInstance(MemoryEffectKind.READ, resource=RegisterResource(r))
                )
        return effects

get_effects(op: Operation) -> set[EffectInstance] classmethod

Source code in xdsl/backend/register_type.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
@classmethod
def get_effects(cls, op: Operation) -> set[EffectInstance]:
    effects = set[EffectInstance]()
    for result in op.results:
        if isinstance(r := result.type, RegisterType) and r.is_allocated:
            effects.add(
                EffectInstance(MemoryEffectKind.WRITE, resource=RegisterResource(r))
            )
    for operand in op.operands:
        if isinstance(r := operand.type, RegisterType) and r.is_allocated:
            effects.add(
                EffectInstance(MemoryEffectKind.READ, resource=RegisterResource(r))
            )
    return effects