Skip to content

Memref

memref

MemRef = Dialect('memref', [LoadOp, StoreOp, AllocOp, AllocaOp, AllocaScopeOp, AllocaScopeReturnOp, AtomicRMWOp, CopyOp, CollapseShapeOp, ExpandShapeOp, DeallocOp, GetGlobalOp, GlobalOp, DimOp, ExtractStridedMetaDataOp, ExtractAlignedPointerAsIndexOp, SubviewOp, ViewOp, CastOp, MemorySpaceCastOp, ReinterpretCastOp, DmaStartOp, DmaWaitOp, RankOp], []) module-attribute

LoadOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
 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
@irdl_op_definition
class LoadOp(IRDLOperation):
    name = "memref.load"

    T: ClassVar = VarConstraint("T", AnyAttr())

    nontemporal = opt_prop_def(BoolAttr, default_value=BoolAttr.from_bool(False))

    memref = operand_def(MemRefType.constr(T))
    indices = var_operand_def(IndexType())
    res = result_def(T)

    traits = traits_def(MemoryReadEffect())

    irdl_options = (ParsePropInAttrDict(),)
    assembly_format = "$memref `[` $indices `]` attr-dict `:` type($memref)"

    # TODO varargs for indexing, which must match the memref dimensions
    # Problem: memref dimensions require variadic type parameters,
    # which is subject to change

    def verify_(self):
        memref_type = self.memref.type
        if not isinstance(memref_type, MemRefType):
            raise VerifyException("expected a memreftype")

        memref_type = cast(MemRefType, memref_type)

        if memref_type.get_num_dims() != len(self.indices):
            raise Exception("expected an index for each dimension")

    @classmethod
    def get(
        cls, ref: SSAValue | Operation, indices: Sequence[SSAValue | Operation]
    ) -> Self:
        ssa_value = SSAValue.get(ref, type=MemRefType)
        return cls(operands=[ref, indices], result_types=[ssa_value.type.element_type])

name = 'memref.load' class-attribute instance-attribute

T: ClassVar = VarConstraint('T', AnyAttr()) class-attribute instance-attribute

nontemporal = opt_prop_def(BoolAttr, default_value=(BoolAttr.from_bool(False))) class-attribute instance-attribute

memref = operand_def(MemRefType.constr(T)) class-attribute instance-attribute

indices = var_operand_def(IndexType()) class-attribute instance-attribute

res = result_def(T) class-attribute instance-attribute

traits = traits_def(MemoryReadEffect()) class-attribute instance-attribute

irdl_options = (ParsePropInAttrDict(),) class-attribute instance-attribute

assembly_format = '$memref `[` $indices `]` attr-dict `:` type($memref)' class-attribute instance-attribute

verify_()

Source code in xdsl/dialects/memref.py
112
113
114
115
116
117
118
119
120
def verify_(self):
    memref_type = self.memref.type
    if not isinstance(memref_type, MemRefType):
        raise VerifyException("expected a memreftype")

    memref_type = cast(MemRefType, memref_type)

    if memref_type.get_num_dims() != len(self.indices):
        raise Exception("expected an index for each dimension")

get(ref: SSAValue | Operation, indices: Sequence[SSAValue | Operation]) -> Self classmethod

Source code in xdsl/dialects/memref.py
122
123
124
125
126
127
@classmethod
def get(
    cls, ref: SSAValue | Operation, indices: Sequence[SSAValue | Operation]
) -> Self:
    ssa_value = SSAValue.get(ref, type=MemRefType)
    return cls(operands=[ref, indices], result_types=[ssa_value.type.element_type])

StoreOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
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
@irdl_op_definition
class StoreOp(IRDLOperation):
    T: ClassVar = VarConstraint("T", AnyAttr())

    name = "memref.store"

    nontemporal = opt_prop_def(BoolAttr, default_value=BoolAttr.from_bool(False))

    value = operand_def(T)
    memref = operand_def(MemRefType.constr(T))
    indices = var_operand_def(IndexType())

    traits = traits_def(MemoryWriteEffect())

    irdl_options = (ParsePropInAttrDict(),)
    assembly_format = "$value `,` $memref `[` $indices `]` attr-dict `:` type($memref)"

    def verify_(self):
        if not isinstance(memref_type := self.memref.type, MemRefType):
            raise VerifyException("expected a memreftype")

        memref_type = cast(MemRefType, memref_type)

        if memref_type.get_num_dims() != len(self.indices):
            raise Exception("Expected an index for each dimension")

    @classmethod
    def get(
        cls,
        value: Operation | SSAValue,
        ref: Operation | SSAValue,
        indices: Sequence[Operation | SSAValue],
    ) -> Self:
        return cls(operands=[value, ref, indices])

T: ClassVar = VarConstraint('T', AnyAttr()) class-attribute instance-attribute

name = 'memref.store' class-attribute instance-attribute

nontemporal = opt_prop_def(BoolAttr, default_value=(BoolAttr.from_bool(False))) class-attribute instance-attribute

value = operand_def(T) class-attribute instance-attribute

memref = operand_def(MemRefType.constr(T)) class-attribute instance-attribute

indices = var_operand_def(IndexType()) class-attribute instance-attribute

traits = traits_def(MemoryWriteEffect()) class-attribute instance-attribute

irdl_options = (ParsePropInAttrDict(),) class-attribute instance-attribute

assembly_format = '$value `,` $memref `[` $indices `]` attr-dict `:` type($memref)' class-attribute instance-attribute

verify_()

Source code in xdsl/dialects/memref.py
147
148
149
150
151
152
153
154
def verify_(self):
    if not isinstance(memref_type := self.memref.type, MemRefType):
        raise VerifyException("expected a memreftype")

    memref_type = cast(MemRefType, memref_type)

    if memref_type.get_num_dims() != len(self.indices):
        raise Exception("Expected an index for each dimension")

get(value: Operation | SSAValue, ref: Operation | SSAValue, indices: Sequence[Operation | SSAValue]) -> Self classmethod

Source code in xdsl/dialects/memref.py
156
157
158
159
160
161
162
163
@classmethod
def get(
    cls,
    value: Operation | SSAValue,
    ref: Operation | SSAValue,
    indices: Sequence[Operation | SSAValue],
) -> Self:
    return cls(operands=[value, ref, indices])

AllocOpHasCanonicalizationPatterns dataclass

Bases: HasCanonicalizationPatternsTrait

Source code in xdsl/dialects/memref.py
166
167
168
169
170
171
class AllocOpHasCanonicalizationPatterns(HasCanonicalizationPatternsTrait):
    @classmethod
    def get_canonicalization_patterns(cls) -> tuple[RewritePattern, ...]:
        from xdsl.transforms.canonicalization_patterns.memref import ElideUnusedAlloc

        return (ElideUnusedAlloc(),)

get_canonicalization_patterns() -> tuple[RewritePattern, ...] classmethod

Source code in xdsl/dialects/memref.py
167
168
169
170
171
@classmethod
def get_canonicalization_patterns(cls) -> tuple[RewritePattern, ...]:
    from xdsl.transforms.canonicalization_patterns.memref import ElideUnusedAlloc

    return (ElideUnusedAlloc(),)

AllocOp

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
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
248
249
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
287
288
289
290
291
292
293
294
295
296
297
298
@irdl_op_definition
class AllocOp(IRDLOperation):
    name = "memref.alloc"

    dynamic_sizes = var_operand_def(IndexType)
    symbol_operands = var_operand_def(IndexType)

    memref = result_def(MemRefType)

    # TODO how to constraint the IntegerAttr type?
    alignment = opt_prop_def(IntegerAttr)

    irdl_options = (AttrSizedOperandSegments(as_property=True),)

    traits = traits_def(AllocOpHasCanonicalizationPatterns(), MemoryAllocEffect())

    def __init__(
        self,
        dynamic_sizes: Sequence[SSAValue],
        symbol_operands: Sequence[SSAValue],
        result_type: Attribute,
        alignment: Attribute | None = None,
    ):
        super().__init__(
            operands=(dynamic_sizes, symbol_operands),
            result_types=(result_type,),
            properties={"alignment": alignment},
        )

    @classmethod
    def get(
        cls,
        return_type: Attribute,
        alignment: int | IntegerAttr | None = None,
        shape: Iterable[int | IntAttr] | None = None,
        dynamic_sizes: Sequence[SSAValue | Operation] | None = None,
        layout: MemRefLayoutAttr | NoneAttr = NoneAttr(),
        memory_space: Attribute = NoneAttr(),
    ) -> Self:
        if shape is None:
            shape = [1]

        if dynamic_sizes is None:
            dynamic_sizes = []

        if isinstance(alignment, int):
            alignment = IntegerAttr(alignment, 64)

        return cls(
            tuple(SSAValue.get(ds) for ds in dynamic_sizes),
            (),
            MemRefType(return_type, shape, layout, memory_space),
            alignment,
        )

    def verify_(self) -> None:
        memref_type = self.memref.type

        dyn_dims = [x for x in memref_type.shape.data if x.data == DYNAMIC_INDEX]
        if len(dyn_dims) != len(self.dynamic_sizes):
            raise VerifyException(
                "op dimension operand count does not equal memref dynamic dimension count."
            )
        _verify_memref_alloc_alignment(self.alignment)

    def print(self, printer: Printer):
        printer.print_string("(")
        printer.print_list(self.dynamic_sizes, printer.print_ssa_value)
        printer.print_string(")")
        if self.symbol_operands:
            printer.print_string("[")
            printer.print_list(self.symbol_operands, printer.print_ssa_value)
            printer.print_string("]")

        printer.print_op_attributes(
            self.properties | self.attributes,
            print_keyword=False,
            reserved_attr_names="operandSegmentSizes",
        )

        printer.print_string(" : ")
        printer.print_attribute(self.memref.type)

    @classmethod
    def parse(cls, parser: Parser) -> Self:
        #  %alloc = memref.alloc(%a)[%s] {alignment = 64 : i64} : memref<3x2xf32>

        unresolved_dynamic_sizes = parser.parse_comma_separated_list(
            parser.Delimiter.PAREN, parser.parse_unresolved_operand
        )
        unresolved_symbol_operands = parser.parse_optional_comma_separated_list(
            parser.Delimiter.SQUARE, parser.parse_unresolved_operand
        )
        if unresolved_symbol_operands is None:
            unresolved_symbol_operands = []

        attrs = parser.parse_optional_attr_dict()

        parser.parse_punctuation(":")
        res_type = parser.parse_attribute()

        index = IndexType()
        dynamic_sizes = tuple(
            parser.resolve_operand(uop, index) for uop in unresolved_dynamic_sizes
        )
        symbol_operands = tuple(
            parser.resolve_operand(uop, index) for uop in unresolved_symbol_operands
        )

        if "alignment" in attrs:
            alignment = attrs["alignment"]
            del attrs["alignment"]
        else:
            alignment = None

        op = cls(
            dynamic_sizes,
            symbol_operands,
            res_type,
            alignment,
        )

        op.attributes |= attrs

        return op

name = 'memref.alloc' class-attribute instance-attribute

dynamic_sizes = var_operand_def(IndexType) class-attribute instance-attribute

symbol_operands = var_operand_def(IndexType) class-attribute instance-attribute

memref = result_def(MemRefType) class-attribute instance-attribute

alignment = opt_prop_def(IntegerAttr) class-attribute instance-attribute

irdl_options = (AttrSizedOperandSegments(as_property=True),) class-attribute instance-attribute

traits = traits_def(AllocOpHasCanonicalizationPatterns(), MemoryAllocEffect()) class-attribute instance-attribute

__init__(dynamic_sizes: Sequence[SSAValue], symbol_operands: Sequence[SSAValue], result_type: Attribute, alignment: Attribute | None = None)

Source code in xdsl/dialects/memref.py
190
191
192
193
194
195
196
197
198
199
200
201
def __init__(
    self,
    dynamic_sizes: Sequence[SSAValue],
    symbol_operands: Sequence[SSAValue],
    result_type: Attribute,
    alignment: Attribute | None = None,
):
    super().__init__(
        operands=(dynamic_sizes, symbol_operands),
        result_types=(result_type,),
        properties={"alignment": alignment},
    )

get(return_type: Attribute, alignment: int | IntegerAttr | None = None, shape: Iterable[int | IntAttr] | None = None, dynamic_sizes: Sequence[SSAValue | Operation] | None = None, layout: MemRefLayoutAttr | NoneAttr = NoneAttr(), memory_space: Attribute = NoneAttr()) -> Self classmethod

Source code in xdsl/dialects/memref.py
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
@classmethod
def get(
    cls,
    return_type: Attribute,
    alignment: int | IntegerAttr | None = None,
    shape: Iterable[int | IntAttr] | None = None,
    dynamic_sizes: Sequence[SSAValue | Operation] | None = None,
    layout: MemRefLayoutAttr | NoneAttr = NoneAttr(),
    memory_space: Attribute = NoneAttr(),
) -> Self:
    if shape is None:
        shape = [1]

    if dynamic_sizes is None:
        dynamic_sizes = []

    if isinstance(alignment, int):
        alignment = IntegerAttr(alignment, 64)

    return cls(
        tuple(SSAValue.get(ds) for ds in dynamic_sizes),
        (),
        MemRefType(return_type, shape, layout, memory_space),
        alignment,
    )

verify_() -> None

Source code in xdsl/dialects/memref.py
229
230
231
232
233
234
235
236
237
def verify_(self) -> None:
    memref_type = self.memref.type

    dyn_dims = [x for x in memref_type.shape.data if x.data == DYNAMIC_INDEX]
    if len(dyn_dims) != len(self.dynamic_sizes):
        raise VerifyException(
            "op dimension operand count does not equal memref dynamic dimension count."
        )
    _verify_memref_alloc_alignment(self.alignment)

print(printer: Printer)

Source code in xdsl/dialects/memref.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
def print(self, printer: Printer):
    printer.print_string("(")
    printer.print_list(self.dynamic_sizes, printer.print_ssa_value)
    printer.print_string(")")
    if self.symbol_operands:
        printer.print_string("[")
        printer.print_list(self.symbol_operands, printer.print_ssa_value)
        printer.print_string("]")

    printer.print_op_attributes(
        self.properties | self.attributes,
        print_keyword=False,
        reserved_attr_names="operandSegmentSizes",
    )

    printer.print_string(" : ")
    printer.print_attribute(self.memref.type)

parse(parser: Parser) -> Self classmethod

Source code in xdsl/dialects/memref.py
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
287
288
289
290
291
292
293
294
295
296
297
298
@classmethod
def parse(cls, parser: Parser) -> Self:
    #  %alloc = memref.alloc(%a)[%s] {alignment = 64 : i64} : memref<3x2xf32>

    unresolved_dynamic_sizes = parser.parse_comma_separated_list(
        parser.Delimiter.PAREN, parser.parse_unresolved_operand
    )
    unresolved_symbol_operands = parser.parse_optional_comma_separated_list(
        parser.Delimiter.SQUARE, parser.parse_unresolved_operand
    )
    if unresolved_symbol_operands is None:
        unresolved_symbol_operands = []

    attrs = parser.parse_optional_attr_dict()

    parser.parse_punctuation(":")
    res_type = parser.parse_attribute()

    index = IndexType()
    dynamic_sizes = tuple(
        parser.resolve_operand(uop, index) for uop in unresolved_dynamic_sizes
    )
    symbol_operands = tuple(
        parser.resolve_operand(uop, index) for uop in unresolved_symbol_operands
    )

    if "alignment" in attrs:
        alignment = attrs["alignment"]
        del attrs["alignment"]
    else:
        alignment = None

    op = cls(
        dynamic_sizes,
        symbol_operands,
        res_type,
        alignment,
    )

    op.attributes |= attrs

    return op

AllocaScopeOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
301
302
303
304
305
306
307
@irdl_op_definition
class AllocaScopeOp(IRDLOperation):
    name = "memref.alloca_scope"

    res = var_result_def()

    scope = region_def()

name = 'memref.alloca_scope' class-attribute instance-attribute

res = var_result_def() class-attribute instance-attribute

scope = region_def() class-attribute instance-attribute

AllocaScopeReturnOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
310
311
312
313
314
315
316
317
318
319
320
321
322
323
@irdl_op_definition
class AllocaScopeReturnOp(IRDLOperation):
    name = "memref.alloca_scope.return"

    ops = var_operand_def()

    traits = traits_def(IsTerminator(), HasParent(AllocaScopeOp))

    def verify_(self) -> None:
        parent = cast(AllocaScopeOp, self.parent_op())
        if self.ops.types != parent.result_types:
            raise VerifyException(
                "Expected operand types to match parent's return types."
            )

name = 'memref.alloca_scope.return' class-attribute instance-attribute

ops = var_operand_def() class-attribute instance-attribute

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

verify_() -> None

Source code in xdsl/dialects/memref.py
318
319
320
321
322
323
def verify_(self) -> None:
    parent = cast(AllocaScopeOp, self.parent_op())
    if self.ops.types != parent.result_types:
        raise VerifyException(
            "Expected operand types to match parent's return types."
        )

AllocaOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
@irdl_op_definition
class AllocaOp(IRDLOperation):
    name = "memref.alloca"

    dynamic_sizes = var_operand_def(IndexType)
    symbol_operands = var_operand_def(IndexType)

    memref = result_def(MemRefType)

    # TODO how to constraint the IntegerAttr type?
    alignment = opt_prop_def(IntegerAttr)

    traits = traits_def(MemoryAllocEffect())

    irdl_options = (AttrSizedOperandSegments(as_property=True), ParsePropInAttrDict())

    assembly_format = """
    `(`$dynamic_sizes`)` (`` `[` $symbol_operands^ `]`)? attr-dict `:` type($memref)
    """

    @staticmethod
    def get(
        return_type: Attribute,
        alignment: int | IntegerAttr | None = None,
        shape: Iterable[int | IntAttr] | None = None,
        dynamic_sizes: Sequence[SSAValue | Operation] | None = None,
        layout: MemRefLayoutAttr | NoneAttr = NoneAttr(),
        memory_space: Attribute = NoneAttr(),
    ) -> AllocaOp:
        if shape is None:
            shape = [1]

        if dynamic_sizes is None:
            dynamic_sizes = []

        if isinstance(alignment, int):
            alignment = IntegerAttr(alignment, 64)

        return AllocaOp.build(
            operands=[dynamic_sizes, []],
            result_types=[MemRefType(return_type, shape, layout, memory_space)],
            properties={
                "alignment": alignment,
            },
        )

    def verify_(self) -> None:
        memref_type = self.memref.type

        dyn_dims = [x for x in memref_type.shape.data if x.data == DYNAMIC_INDEX]
        if len(dyn_dims) != len(self.dynamic_sizes):
            raise VerifyException(
                "op dimension operand count does not equal memref dynamic dimension count."
            )
        _verify_memref_alloc_alignment(self.alignment)

name = 'memref.alloca' class-attribute instance-attribute

dynamic_sizes = var_operand_def(IndexType) class-attribute instance-attribute

symbol_operands = var_operand_def(IndexType) class-attribute instance-attribute

memref = result_def(MemRefType) class-attribute instance-attribute

alignment = opt_prop_def(IntegerAttr) class-attribute instance-attribute

traits = traits_def(MemoryAllocEffect()) class-attribute instance-attribute

irdl_options = (AttrSizedOperandSegments(as_property=True), ParsePropInAttrDict()) class-attribute instance-attribute

assembly_format = '\n `(`$dynamic_sizes`)` (`` `[` $symbol_operands^ `]`)? attr-dict `:` type($memref)\n ' class-attribute instance-attribute

get(return_type: Attribute, alignment: int | IntegerAttr | None = None, shape: Iterable[int | IntAttr] | None = None, dynamic_sizes: Sequence[SSAValue | Operation] | None = None, layout: MemRefLayoutAttr | NoneAttr = NoneAttr(), memory_space: Attribute = NoneAttr()) -> AllocaOp staticmethod

Source code in xdsl/dialects/memref.py
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
@staticmethod
def get(
    return_type: Attribute,
    alignment: int | IntegerAttr | None = None,
    shape: Iterable[int | IntAttr] | None = None,
    dynamic_sizes: Sequence[SSAValue | Operation] | None = None,
    layout: MemRefLayoutAttr | NoneAttr = NoneAttr(),
    memory_space: Attribute = NoneAttr(),
) -> AllocaOp:
    if shape is None:
        shape = [1]

    if dynamic_sizes is None:
        dynamic_sizes = []

    if isinstance(alignment, int):
        alignment = IntegerAttr(alignment, 64)

    return AllocaOp.build(
        operands=[dynamic_sizes, []],
        result_types=[MemRefType(return_type, shape, layout, memory_space)],
        properties={
            "alignment": alignment,
        },
    )

verify_() -> None

Source code in xdsl/dialects/memref.py
372
373
374
375
376
377
378
379
380
def verify_(self) -> None:
    memref_type = self.memref.type

    dyn_dims = [x for x in memref_type.shape.data if x.data == DYNAMIC_INDEX]
    if len(dyn_dims) != len(self.dynamic_sizes):
        raise VerifyException(
            "op dimension operand count does not equal memref dynamic dimension count."
        )
    _verify_memref_alloc_alignment(self.alignment)

AtomicRMWOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
@irdl_op_definition
class AtomicRMWOp(IRDLOperation):
    name = "memref.atomic_rmw"

    T: ClassVar = VarConstraint("T", AnyFloatConstr | SignlessIntegerConstraint)

    value = operand_def(T)
    memref = operand_def(MemRefType.constr(T))
    indices = var_operand_def(IndexType)

    kind = prop_def(IntegerAttr[I64])

    result = result_def(T)

    traits = traits_def(MemoryWriteEffect(), MemoryReadEffect())

name = 'memref.atomic_rmw' class-attribute instance-attribute

T: ClassVar = VarConstraint('T', AnyFloatConstr | SignlessIntegerConstraint) class-attribute instance-attribute

value = operand_def(T) class-attribute instance-attribute

memref = operand_def(MemRefType.constr(T)) class-attribute instance-attribute

indices = var_operand_def(IndexType) class-attribute instance-attribute

kind = prop_def(IntegerAttr[I64]) class-attribute instance-attribute

result = result_def(T) class-attribute instance-attribute

traits = traits_def(MemoryWriteEffect(), MemoryReadEffect()) class-attribute instance-attribute

DeallocOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
400
401
402
403
404
405
406
407
408
409
410
411
@irdl_op_definition
class DeallocOp(IRDLOperation):
    name = "memref.dealloc"
    memref = operand_def(base(MemRefType) | base(UnrankedMemRefType))

    traits = traits_def(MemoryFreeEffect())

    @staticmethod
    def get(operand: Operation | SSAValue) -> DeallocOp:
        return DeallocOp.build(operands=[operand])

    assembly_format = "$memref attr-dict `:` type($memref)"

name = 'memref.dealloc' class-attribute instance-attribute

memref = operand_def(base(MemRefType) | base(UnrankedMemRefType)) class-attribute instance-attribute

traits = traits_def(MemoryFreeEffect()) class-attribute instance-attribute

assembly_format = '$memref attr-dict `:` type($memref)' class-attribute instance-attribute

get(operand: Operation | SSAValue) -> DeallocOp staticmethod

Source code in xdsl/dialects/memref.py
407
408
409
@staticmethod
def get(operand: Operation | SSAValue) -> DeallocOp:
    return DeallocOp.build(operands=[operand])

GetGlobalOp

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
414
415
416
417
418
419
420
421
422
423
424
425
426
427
@irdl_op_definition
class GetGlobalOp(IRDLOperation):
    name = "memref.get_global"
    memref = result_def(MemRefType)
    name_ = prop_def(SymbolRefAttr, prop_name="name")

    traits = traits_def(NoMemoryEffect())

    assembly_format = "$name `:` type($memref) attr-dict"

    def __init__(self, name: str | SymbolRefAttr, return_type: Attribute):
        if isinstance(name, str):
            name = SymbolRefAttr(name)
        super().__init__(result_types=[return_type], properties={"name": name})

name = 'memref.get_global' class-attribute instance-attribute

memref = result_def(MemRefType) class-attribute instance-attribute

name_ = prop_def(SymbolRefAttr, prop_name='name') class-attribute instance-attribute

traits = traits_def(NoMemoryEffect()) class-attribute instance-attribute

assembly_format = '$name `:` type($memref) attr-dict' class-attribute instance-attribute

__init__(name: str | SymbolRefAttr, return_type: Attribute)

Source code in xdsl/dialects/memref.py
424
425
426
427
def __init__(self, name: str | SymbolRefAttr, return_type: Attribute):
    if isinstance(name, str):
        name = SymbolRefAttr(name)
    super().__init__(result_types=[return_type], properties={"name": name})

GlobalOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
@irdl_op_definition
class GlobalOp(IRDLOperation):
    name = "memref.global"

    sym_name = prop_def(SymbolNameConstraint())
    sym_visibility = prop_def(StringAttr)
    type = prop_def(MemRefType)
    initial_value = prop_def(UnitAttr | DenseIntOrFPElementsAttr)
    constant = opt_prop_def(UnitAttr)
    alignment = opt_prop_def(IntegerAttr[I64])

    traits = traits_def(SymbolOpInterface(), MemoryAllocEffect())

    def verify_(self) -> None:
        if self.alignment is not None:
            alignment_value = self.alignment.value.data
            # Alignment has to be a power of two
            if not (is_power_of_two(alignment_value)):
                raise VerifyException(
                    f"Alignment attribute {alignment_value} is not a power of 2"
                )

    @staticmethod
    def get(
        sym_name: StringAttr,
        sym_type: Attribute,
        initial_value: Attribute,
        sym_visibility: StringAttr = StringAttr("private"),
        constant: UnitAttr | None = None,
        alignment: int | IntegerAttr[IntegerType] | None = None,
    ) -> GlobalOp:
        if isinstance(alignment, int):
            alignment = IntegerAttr(alignment, 64)

        return GlobalOp.build(
            properties={
                "sym_name": sym_name,
                "type": sym_type,
                "initial_value": initial_value,
                "sym_visibility": sym_visibility,
                "constant": constant,
                "alignment": alignment,
            }
        )

name = 'memref.global' class-attribute instance-attribute

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

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

type = prop_def(MemRefType) class-attribute instance-attribute

initial_value = prop_def(UnitAttr | DenseIntOrFPElementsAttr) class-attribute instance-attribute

constant = opt_prop_def(UnitAttr) class-attribute instance-attribute

alignment = opt_prop_def(IntegerAttr[I64]) class-attribute instance-attribute

traits = traits_def(SymbolOpInterface(), MemoryAllocEffect()) class-attribute instance-attribute

verify_() -> None

Source code in xdsl/dialects/memref.py
446
447
448
449
450
451
452
453
def verify_(self) -> None:
    if self.alignment is not None:
        alignment_value = self.alignment.value.data
        # Alignment has to be a power of two
        if not (is_power_of_two(alignment_value)):
            raise VerifyException(
                f"Alignment attribute {alignment_value} is not a power of 2"
            )

get(sym_name: StringAttr, sym_type: Attribute, initial_value: Attribute, sym_visibility: StringAttr = StringAttr('private'), constant: UnitAttr | None = None, alignment: int | IntegerAttr[IntegerType] | None = None) -> GlobalOp staticmethod

Source code in xdsl/dialects/memref.py
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
@staticmethod
def get(
    sym_name: StringAttr,
    sym_type: Attribute,
    initial_value: Attribute,
    sym_visibility: StringAttr = StringAttr("private"),
    constant: UnitAttr | None = None,
    alignment: int | IntegerAttr[IntegerType] | None = None,
) -> GlobalOp:
    if isinstance(alignment, int):
        alignment = IntegerAttr(alignment, 64)

    return GlobalOp.build(
        properties={
            "sym_name": sym_name,
            "type": sym_type,
            "initial_value": initial_value,
            "sym_visibility": sym_visibility,
            "constant": constant,
            "alignment": alignment,
        }
    )

DimOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
@irdl_op_definition
class DimOp(IRDLOperation):
    name = "memref.dim"

    source = operand_def(base(MemRefType) | base(UnrankedMemRefType))
    index = operand_def(IndexType)

    result = result_def(IndexType)

    traits = traits_def(NoMemoryEffect())

    assembly_format = "$source `,` $index attr-dict `:` type($source)"

    @staticmethod
    def from_source_and_index(
        source: SSAValue | Operation, index: SSAValue | Operation
    ):
        return DimOp.build(operands=[source, index], result_types=[IndexType()])

name = 'memref.dim' class-attribute instance-attribute

source = operand_def(base(MemRefType) | base(UnrankedMemRefType)) class-attribute instance-attribute

index = operand_def(IndexType) class-attribute instance-attribute

result = result_def(IndexType) class-attribute instance-attribute

traits = traits_def(NoMemoryEffect()) class-attribute instance-attribute

assembly_format = '$source `,` $index attr-dict `:` type($source)' class-attribute instance-attribute

from_source_and_index(source: SSAValue | Operation, index: SSAValue | Operation) staticmethod

Source code in xdsl/dialects/memref.py
492
493
494
495
496
@staticmethod
def from_source_and_index(
    source: SSAValue | Operation, index: SSAValue | Operation
):
    return DimOp.build(operands=[source, index], result_types=[IndexType()])

RankOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
499
500
501
502
503
504
505
506
507
508
509
510
511
@irdl_op_definition
class RankOp(IRDLOperation):
    name = "memref.rank"

    source = operand_def(MemRefType)

    rank = result_def(IndexType)

    traits = traits_def(NoMemoryEffect())

    @staticmethod
    def from_memref(memref: Operation | SSAValue):
        return RankOp.build(operands=[memref], result_types=[IndexType()])

name = 'memref.rank' class-attribute instance-attribute

source = operand_def(MemRefType) class-attribute instance-attribute

rank = result_def(IndexType) class-attribute instance-attribute

traits = traits_def(NoMemoryEffect()) class-attribute instance-attribute

from_memref(memref: Operation | SSAValue) staticmethod

Source code in xdsl/dialects/memref.py
509
510
511
@staticmethod
def from_memref(memref: Operation | SSAValue):
    return RankOp.build(operands=[memref], result_types=[IndexType()])

AlterShapeOperation dataclass

Bases: IRDLOperation, ABC

Source code in xdsl/dialects/memref.py
514
515
516
517
518
class AlterShapeOperation(IRDLOperation, abc.ABC):
    result = result_def(MemRefType)
    reassociation = prop_def(ContiguousArrayOfIntArray())

    traits = traits_def(NoMemoryEffect())

result = result_def(MemRefType) class-attribute instance-attribute

reassociation = prop_def(ContiguousArrayOfIntArray()) class-attribute instance-attribute

traits = traits_def(NoMemoryEffect()) class-attribute instance-attribute

CollapseShapeOp dataclass

Bases: AlterShapeOperation

https://mlir.llvm.org/docs/Dialects/MemRef/#memrefcollapse_shape-memrefcollapseshapeop

Source code in xdsl/dialects/memref.py
521
522
523
524
525
526
527
528
529
530
531
532
533
@irdl_op_definition
class CollapseShapeOp(AlterShapeOperation):
    """
    https://mlir.llvm.org/docs/Dialects/MemRef/#memrefcollapse_shape-memrefcollapseshapeop
    """

    name = "memref.collapse_shape"

    src = operand_def(MemRefType)

    assembly_format = (
        "$src $reassociation attr-dict `:` type($src) `into` type($result)"
    )

name = 'memref.collapse_shape' class-attribute instance-attribute

src = operand_def(MemRefType) class-attribute instance-attribute

assembly_format = '$src $reassociation attr-dict `:` type($src) `into` type($result)' class-attribute instance-attribute

ExpandShapeOp dataclass

Bases: AlterShapeOperation

https://mlir.llvm.org/docs/Dialects/MemRef/#memrefexpand_shape-memrefexpandshapeop

Source code in xdsl/dialects/memref.py
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
@irdl_op_definition
class ExpandShapeOp(AlterShapeOperation):
    """
    https://mlir.llvm.org/docs/Dialects/MemRef/#memrefexpand_shape-memrefexpandshapeop
    """

    name = "memref.expand_shape"

    src = operand_def(MemRefType)
    output_shape = var_operand_def(IndexType)

    static_output_shape = prop_def(DenseArrayBase.constr(i64))

    assembly_format = (
        "$src $reassociation `output_shape`"
        "custom<DynamicIndexList>($output_shape, $static_output_shape) attr-dict `:`"
        "type($src) `into` type($result)"
    )

    custom_directives = (DynamicIndexList,)

name = 'memref.expand_shape' class-attribute instance-attribute

src = operand_def(MemRefType) class-attribute instance-attribute

output_shape = var_operand_def(IndexType) class-attribute instance-attribute

static_output_shape = prop_def(DenseArrayBase.constr(i64)) class-attribute instance-attribute

assembly_format = '$src $reassociation `output_shape`custom<DynamicIndexList>($output_shape, $static_output_shape) attr-dict `:`type($src) `into` type($result)' class-attribute instance-attribute

custom_directives = (DynamicIndexList,) class-attribute instance-attribute

ExtractStridedMetaDataOp

Bases: IRDLOperation

https://mlir.llvm.org/docs/Dialects/MemRef/#memrefextract_strided_metadata-memrefextractstridedmetadataop

Source code in xdsl/dialects/memref.py
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
@irdl_op_definition
class ExtractStridedMetaDataOp(IRDLOperation):
    """
    https://mlir.llvm.org/docs/Dialects/MemRef/#memrefextract_strided_metadata-memrefextractstridedmetadataop
    """

    name = "memref.extract_strided_metadata"

    source = operand_def(MemRefType)

    base_buffer = result_def(MemRefType)
    offset = result_def(IndexType)
    sizes = var_result_def(IndexType)
    strides = var_result_def(IndexType)

    traits = traits_def(NoMemoryEffect())

    irdl_options = (SameVariadicResultSize(),)

    assembly_format = "$source `:` type($source) `->` type(results) attr-dict"

    def __init__(self, source: SSAValue | Operation):
        """
        Create an ExtractStridedMetaDataOp that extracts the metadata from the
        operation (source) that produces a memref.
        """
        source_type = SSAValue.get(source, type=MemRefType).type
        source_shape = source_type.get_shape()
        # Return a rank zero memref with the memref type
        base_buffer_type = MemRefType(
            source_type.element_type,
            [],
            NoneAttr(),
            source_type.memory_space,
        )
        offset_type = IndexType()
        # There are as many strides/sizes as there are shape dimensions
        strides_type = [IndexType()] * len(source_shape)
        sizes_type = [IndexType()] * len(source_shape)
        return_type = [base_buffer_type, offset_type, strides_type, sizes_type]
        super().__init__(operands=[source], result_types=return_type)

name = 'memref.extract_strided_metadata' class-attribute instance-attribute

source = operand_def(MemRefType) class-attribute instance-attribute

base_buffer = result_def(MemRefType) class-attribute instance-attribute

offset = result_def(IndexType) class-attribute instance-attribute

sizes = var_result_def(IndexType) class-attribute instance-attribute

strides = var_result_def(IndexType) class-attribute instance-attribute

traits = traits_def(NoMemoryEffect()) class-attribute instance-attribute

irdl_options = (SameVariadicResultSize(),) class-attribute instance-attribute

assembly_format = '$source `:` type($source) `->` type(results) attr-dict' class-attribute instance-attribute

__init__(source: SSAValue | Operation)

Create an ExtractStridedMetaDataOp that extracts the metadata from the operation (source) that produces a memref.

Source code in xdsl/dialects/memref.py
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
def __init__(self, source: SSAValue | Operation):
    """
    Create an ExtractStridedMetaDataOp that extracts the metadata from the
    operation (source) that produces a memref.
    """
    source_type = SSAValue.get(source, type=MemRefType).type
    source_shape = source_type.get_shape()
    # Return a rank zero memref with the memref type
    base_buffer_type = MemRefType(
        source_type.element_type,
        [],
        NoneAttr(),
        source_type.memory_space,
    )
    offset_type = IndexType()
    # There are as many strides/sizes as there are shape dimensions
    strides_type = [IndexType()] * len(source_shape)
    sizes_type = [IndexType()] * len(source_shape)
    return_type = [base_buffer_type, offset_type, strides_type, sizes_type]
    super().__init__(operands=[source], result_types=return_type)

ExtractAlignedPointerAsIndexOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
@irdl_op_definition
class ExtractAlignedPointerAsIndexOp(IRDLOperation):
    name = "memref.extract_aligned_pointer_as_index"

    source = operand_def(MemRefType)

    aligned_pointer = result_def(IndexType)

    traits = traits_def(NoMemoryEffect())

    @staticmethod
    def get(source: SSAValue | Operation):
        return ExtractAlignedPointerAsIndexOp.build(
            operands=[source], result_types=[IndexType()]
        )

name = 'memref.extract_aligned_pointer_as_index' class-attribute instance-attribute

source = operand_def(MemRefType) class-attribute instance-attribute

aligned_pointer = result_def(IndexType) class-attribute instance-attribute

traits = traits_def(NoMemoryEffect()) class-attribute instance-attribute

get(source: SSAValue | Operation) staticmethod

Source code in xdsl/dialects/memref.py
611
612
613
614
615
@staticmethod
def get(source: SSAValue | Operation):
    return ExtractAlignedPointerAsIndexOp.build(
        operands=[source], result_types=[IndexType()]
    )

MemRefHasCanonicalizationPatternsTrait dataclass

Bases: HasCanonicalizationPatternsTrait

Source code in xdsl/dialects/memref.py
618
619
620
621
622
623
624
625
class MemRefHasCanonicalizationPatternsTrait(HasCanonicalizationPatternsTrait):
    @classmethod
    def get_canonicalization_patterns(cls) -> tuple[RewritePattern, ...]:
        from xdsl.transforms.canonicalization_patterns.memref import (
            MemRefSubviewOfSubviewFolding,
        )

        return (MemRefSubviewOfSubviewFolding(),)

get_canonicalization_patterns() -> tuple[RewritePattern, ...] classmethod

Source code in xdsl/dialects/memref.py
619
620
621
622
623
624
625
@classmethod
def get_canonicalization_patterns(cls) -> tuple[RewritePattern, ...]:
    from xdsl.transforms.canonicalization_patterns.memref import (
        MemRefSubviewOfSubviewFolding,
    )

    return (MemRefSubviewOfSubviewFolding(),)

SubviewOp

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
@irdl_op_definition
class SubviewOp(IRDLOperation):
    name = "memref.subview"

    source = operand_def(MemRefType)
    offsets = var_operand_def(IndexType)
    sizes = var_operand_def(IndexType)
    strides = var_operand_def(IndexType)
    static_offsets = prop_def(DenseArrayBase.constr(i64))
    static_sizes = prop_def(DenseArrayBase.constr(i64))
    static_strides = prop_def(DenseArrayBase.constr(i64))
    result = result_def(MemRefType)

    irdl_options = (AttrSizedOperandSegments(as_property=True),)

    traits = lazy_traits_def(
        lambda: (MemRefHasCanonicalizationPatternsTrait(), NoMemoryEffect())
    )

    assembly_format = (
        "$source ``"
        "custom<DynamicIndexList>($offsets, $static_offsets)"
        "custom<DynamicIndexList>($sizes, $static_sizes)"
        "custom<DynamicIndexList>($strides, $static_strides)"
        "attr-dict `:` type($source) `to` type($result)"
    )

    custom_directives = (DynamicIndexList,)

    def verify_(self) -> None:
        static_offsets = self.static_offsets.get_values()
        static_sizes = self.static_sizes.get_values()
        static_strides = self.static_strides.get_values()
        verify_dynamic_index_list(
            static_sizes, self.sizes, DYNAMIC_INDEX, " in the size arguments"
        )
        verify_dynamic_index_list(
            static_offsets, self.offsets, DYNAMIC_INDEX, " in the offset arguments"
        )
        verify_dynamic_index_list(
            static_strides, self.strides, DYNAMIC_INDEX, " in the stride arguments"
        )

    def __init__(
        self,
        source: SSAValue | Operation,
        offsets: Sequence[SSAValue],
        sizes: Sequence[SSAValue],
        strides: Sequence[SSAValue],
        static_offsets: Sequence[int] | DenseArrayBase,
        static_sizes: Sequence[int] | DenseArrayBase,
        static_strides: Sequence[int] | DenseArrayBase,
        result_type: Attribute,
    ):
        if not isinstance(static_offsets, DenseArrayBase):
            static_offsets = DenseArrayBase.from_list(i64, static_offsets)
        if not isinstance(static_sizes, DenseArrayBase):
            static_sizes = DenseArrayBase.from_list(i64, static_sizes)
        if not isinstance(static_strides, DenseArrayBase):
            static_strides = DenseArrayBase.from_list(i64, static_strides)
        super().__init__(
            operands=[source, offsets, sizes, strides],
            result_types=[result_type],
            properties={
                "static_offsets": static_offsets,
                "static_sizes": static_sizes,
                "static_strides": static_strides,
            },
        )

    @staticmethod
    def get(
        source: SSAValue,
        offsets: Sequence[SSAValue | int],
        sizes: Sequence[SSAValue | int],
        strides: Sequence[SSAValue | int],
        result_type: Attribute,
    ) -> SubviewOp:
        static_offsets, dyn_offsets = split_dynamic_index_list(offsets, DYNAMIC_INDEX)
        static_sizes, dyn_sizes = split_dynamic_index_list(sizes, DYNAMIC_INDEX)
        static_strides, dyn_strides = split_dynamic_index_list(strides, DYNAMIC_INDEX)

        return SubviewOp(
            source,
            dyn_offsets,
            dyn_sizes,
            dyn_strides,
            static_offsets,
            static_sizes,
            static_strides,
            result_type,
        )

    @staticmethod
    def infer_result_type(
        source_type: MemRefType[Attribute],
        offsets: Sequence[SSAValue | int],
        sizes: Sequence[SSAValue | int],
        strides: Sequence[SSAValue | int],
        *,
        reduce_rank: bool = False,
    ) -> MemRefType[Attribute]:
        """
        Infer the result type of a memref.subview from its source type and
        offsets/sizes/strides.

        Raises:
            ValueError: If offsets, sizes, and strides do not match the source rank,
                if the source layout is not strided-like, or if rank reduction is
                requested with dynamic sizes.
        """
        rank = source_type.get_num_dims()
        if not (len(offsets) == len(sizes) == len(strides) == rank):
            raise ValueError(
                "expected offsets, sizes, and strides to match source rank"
            )

        static_offsets = tuple(
            value if isinstance(value, int) else None for value in offsets
        )
        static_sizes = tuple(
            value if isinstance(value, int) else None for value in sizes
        )
        static_strides = tuple(
            value if isinstance(value, int) else None for value in strides
        )

        source_strides = source_type.get_strides()
        if source_strides is None:
            raise ValueError(
                "cannot infer memref.subview result type from non-strided "
                f"source type {source_type}"
            )
        source_offset = source_type.get_offset()

        result_shape = tuple(
            DYNAMIC_INDEX if size is None else size for size in static_sizes
        )

        result_strides = tuple(
            None
            if source_stride is None or static_stride is None
            else source_stride * static_stride
            for source_stride, static_stride in zip(
                source_strides, static_strides, strict=True
            )
        )

        result_offset = source_offset
        if result_offset is not None:
            for static_offset, source_stride in zip(
                static_offsets, source_strides, strict=True
            ):
                if static_offset == 0:
                    continue
                if static_offset is None or source_stride is None:
                    result_offset = None
                    break
                result_offset += static_offset * source_stride

        if reduce_rank:
            if any(size is None for size in static_sizes):
                raise ValueError(
                    "cannot infer rank-reduced memref.subview result type with "
                    "dynamic sizes"
                )

            reduced_shape: list[int] = []
            reduced_strides: list[int | None] = []
            for size, stride in zip(static_sizes, result_strides, strict=True):
                assert size is not None
                if size == 1:
                    continue
                reduced_shape.append(size)
                reduced_strides.append(stride)
            result_shape = tuple(reduced_shape)
            result_strides = tuple(reduced_strides)

        return MemRefType(
            source_type.element_type,
            result_shape,
            StridedLayoutAttr(result_strides, result_offset),
            source_type.memory_space,
        )

    @staticmethod
    def from_static_parameters(
        source: SSAValue | Operation,
        source_type: MemRefType,
        offsets: Sequence[int],
        sizes: Sequence[int],
        strides: Sequence[int],
        reduce_rank: bool = False,
    ) -> SubviewOp:
        """
        Build a memref.subview from static offsets, sizes, and strides.

        Raises:
            ValueError: If offsets, sizes, and strides do not match the source rank,
                if the source layout is not strided-like, or if rank reduction is
                requested with dynamic sizes.
        """

        source = SSAValue.get(source)

        return_type = SubviewOp.infer_result_type(
            source_type,
            offsets,
            sizes,
            strides,
            reduce_rank=reduce_rank,
        )

        return SubviewOp.get(
            source,
            offsets,
            sizes,
            strides,
            return_type,
        )

name = 'memref.subview' class-attribute instance-attribute

source = operand_def(MemRefType) class-attribute instance-attribute

offsets = var_operand_def(IndexType) class-attribute instance-attribute

sizes = var_operand_def(IndexType) class-attribute instance-attribute

strides = var_operand_def(IndexType) class-attribute instance-attribute

static_offsets = prop_def(DenseArrayBase.constr(i64)) class-attribute instance-attribute

static_sizes = prop_def(DenseArrayBase.constr(i64)) class-attribute instance-attribute

static_strides = prop_def(DenseArrayBase.constr(i64)) class-attribute instance-attribute

result = result_def(MemRefType) class-attribute instance-attribute

irdl_options = (AttrSizedOperandSegments(as_property=True),) class-attribute instance-attribute

traits = lazy_traits_def(lambda: (MemRefHasCanonicalizationPatternsTrait(), NoMemoryEffect())) class-attribute instance-attribute

assembly_format = '$source ``custom<DynamicIndexList>($offsets, $static_offsets)custom<DynamicIndexList>($sizes, $static_sizes)custom<DynamicIndexList>($strides, $static_strides)attr-dict `:` type($source) `to` type($result)' class-attribute instance-attribute

custom_directives = (DynamicIndexList,) class-attribute instance-attribute

verify_() -> None

Source code in xdsl/dialects/memref.py
657
658
659
660
661
662
663
664
665
666
667
668
669
def verify_(self) -> None:
    static_offsets = self.static_offsets.get_values()
    static_sizes = self.static_sizes.get_values()
    static_strides = self.static_strides.get_values()
    verify_dynamic_index_list(
        static_sizes, self.sizes, DYNAMIC_INDEX, " in the size arguments"
    )
    verify_dynamic_index_list(
        static_offsets, self.offsets, DYNAMIC_INDEX, " in the offset arguments"
    )
    verify_dynamic_index_list(
        static_strides, self.strides, DYNAMIC_INDEX, " in the stride arguments"
    )

__init__(source: SSAValue | Operation, offsets: Sequence[SSAValue], sizes: Sequence[SSAValue], strides: Sequence[SSAValue], static_offsets: Sequence[int] | DenseArrayBase, static_sizes: Sequence[int] | DenseArrayBase, static_strides: Sequence[int] | DenseArrayBase, result_type: Attribute)

Source code in xdsl/dialects/memref.py
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
def __init__(
    self,
    source: SSAValue | Operation,
    offsets: Sequence[SSAValue],
    sizes: Sequence[SSAValue],
    strides: Sequence[SSAValue],
    static_offsets: Sequence[int] | DenseArrayBase,
    static_sizes: Sequence[int] | DenseArrayBase,
    static_strides: Sequence[int] | DenseArrayBase,
    result_type: Attribute,
):
    if not isinstance(static_offsets, DenseArrayBase):
        static_offsets = DenseArrayBase.from_list(i64, static_offsets)
    if not isinstance(static_sizes, DenseArrayBase):
        static_sizes = DenseArrayBase.from_list(i64, static_sizes)
    if not isinstance(static_strides, DenseArrayBase):
        static_strides = DenseArrayBase.from_list(i64, static_strides)
    super().__init__(
        operands=[source, offsets, sizes, strides],
        result_types=[result_type],
        properties={
            "static_offsets": static_offsets,
            "static_sizes": static_sizes,
            "static_strides": static_strides,
        },
    )

get(source: SSAValue, offsets: Sequence[SSAValue | int], sizes: Sequence[SSAValue | int], strides: Sequence[SSAValue | int], result_type: Attribute) -> SubviewOp staticmethod

Source code in xdsl/dialects/memref.py
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
@staticmethod
def get(
    source: SSAValue,
    offsets: Sequence[SSAValue | int],
    sizes: Sequence[SSAValue | int],
    strides: Sequence[SSAValue | int],
    result_type: Attribute,
) -> SubviewOp:
    static_offsets, dyn_offsets = split_dynamic_index_list(offsets, DYNAMIC_INDEX)
    static_sizes, dyn_sizes = split_dynamic_index_list(sizes, DYNAMIC_INDEX)
    static_strides, dyn_strides = split_dynamic_index_list(strides, DYNAMIC_INDEX)

    return SubviewOp(
        source,
        dyn_offsets,
        dyn_sizes,
        dyn_strides,
        static_offsets,
        static_sizes,
        static_strides,
        result_type,
    )

infer_result_type(source_type: MemRefType[Attribute], offsets: Sequence[SSAValue | int], sizes: Sequence[SSAValue | int], strides: Sequence[SSAValue | int], *, reduce_rank: bool = False) -> MemRefType[Attribute] staticmethod

Infer the result type of a memref.subview from its source type and offsets/sizes/strides.

Raises:

Type Description
ValueError

If offsets, sizes, and strides do not match the source rank, if the source layout is not strided-like, or if rank reduction is requested with dynamic sizes.

Source code in xdsl/dialects/memref.py
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
@staticmethod
def infer_result_type(
    source_type: MemRefType[Attribute],
    offsets: Sequence[SSAValue | int],
    sizes: Sequence[SSAValue | int],
    strides: Sequence[SSAValue | int],
    *,
    reduce_rank: bool = False,
) -> MemRefType[Attribute]:
    """
    Infer the result type of a memref.subview from its source type and
    offsets/sizes/strides.

    Raises:
        ValueError: If offsets, sizes, and strides do not match the source rank,
            if the source layout is not strided-like, or if rank reduction is
            requested with dynamic sizes.
    """
    rank = source_type.get_num_dims()
    if not (len(offsets) == len(sizes) == len(strides) == rank):
        raise ValueError(
            "expected offsets, sizes, and strides to match source rank"
        )

    static_offsets = tuple(
        value if isinstance(value, int) else None for value in offsets
    )
    static_sizes = tuple(
        value if isinstance(value, int) else None for value in sizes
    )
    static_strides = tuple(
        value if isinstance(value, int) else None for value in strides
    )

    source_strides = source_type.get_strides()
    if source_strides is None:
        raise ValueError(
            "cannot infer memref.subview result type from non-strided "
            f"source type {source_type}"
        )
    source_offset = source_type.get_offset()

    result_shape = tuple(
        DYNAMIC_INDEX if size is None else size for size in static_sizes
    )

    result_strides = tuple(
        None
        if source_stride is None or static_stride is None
        else source_stride * static_stride
        for source_stride, static_stride in zip(
            source_strides, static_strides, strict=True
        )
    )

    result_offset = source_offset
    if result_offset is not None:
        for static_offset, source_stride in zip(
            static_offsets, source_strides, strict=True
        ):
            if static_offset == 0:
                continue
            if static_offset is None or source_stride is None:
                result_offset = None
                break
            result_offset += static_offset * source_stride

    if reduce_rank:
        if any(size is None for size in static_sizes):
            raise ValueError(
                "cannot infer rank-reduced memref.subview result type with "
                "dynamic sizes"
            )

        reduced_shape: list[int] = []
        reduced_strides: list[int | None] = []
        for size, stride in zip(static_sizes, result_strides, strict=True):
            assert size is not None
            if size == 1:
                continue
            reduced_shape.append(size)
            reduced_strides.append(stride)
        result_shape = tuple(reduced_shape)
        result_strides = tuple(reduced_strides)

    return MemRefType(
        source_type.element_type,
        result_shape,
        StridedLayoutAttr(result_strides, result_offset),
        source_type.memory_space,
    )

from_static_parameters(source: SSAValue | Operation, source_type: MemRefType, offsets: Sequence[int], sizes: Sequence[int], strides: Sequence[int], reduce_rank: bool = False) -> SubviewOp staticmethod

Build a memref.subview from static offsets, sizes, and strides.

Raises:

Type Description
ValueError

If offsets, sizes, and strides do not match the source rank, if the source layout is not strided-like, or if rank reduction is requested with dynamic sizes.

Source code in xdsl/dialects/memref.py
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
@staticmethod
def from_static_parameters(
    source: SSAValue | Operation,
    source_type: MemRefType,
    offsets: Sequence[int],
    sizes: Sequence[int],
    strides: Sequence[int],
    reduce_rank: bool = False,
) -> SubviewOp:
    """
    Build a memref.subview from static offsets, sizes, and strides.

    Raises:
        ValueError: If offsets, sizes, and strides do not match the source rank,
            if the source layout is not strided-like, or if rank reduction is
            requested with dynamic sizes.
    """

    source = SSAValue.get(source)

    return_type = SubviewOp.infer_result_type(
        source_type,
        offsets,
        sizes,
        strides,
        reduce_rank=reduce_rank,
    )

    return SubviewOp.get(
        source,
        offsets,
        sizes,
        strides,
        return_type,
    )

CastOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
@irdl_op_definition
class CastOp(IRDLOperation):
    name = "memref.cast"

    source = operand_def(base(MemRefType) | base(UnrankedMemRefType))
    dest = result_def(base(MemRefType) | base(UnrankedMemRefType))

    traits = traits_def(NoMemoryEffect())

    @staticmethod
    def get(
        source: SSAValue | Operation,
        type: MemRefType | UnrankedMemRefType,
    ):
        return CastOp.build(operands=[source], result_types=[type])

name = 'memref.cast' class-attribute instance-attribute

source = operand_def(base(MemRefType) | base(UnrankedMemRefType)) class-attribute instance-attribute

dest = result_def(base(MemRefType) | base(UnrankedMemRefType)) class-attribute instance-attribute

traits = traits_def(NoMemoryEffect()) class-attribute instance-attribute

get(source: SSAValue | Operation, type: MemRefType | UnrankedMemRefType) staticmethod

Source code in xdsl/dialects/memref.py
859
860
861
862
863
864
@staticmethod
def get(
    source: SSAValue | Operation,
    type: MemRefType | UnrankedMemRefType,
):
    return CastOp.build(operands=[source], result_types=[type])

MemorySpaceCastOp

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
@irdl_op_definition
class MemorySpaceCastOp(IRDLOperation):
    name = "memref.memory_space_cast"

    source = operand_def(base(MemRefType) | base(UnrankedMemRefType))
    dest = result_def(base(MemRefType) | base(UnrankedMemRefType))

    traits = traits_def(NoMemoryEffect())

    def __init__(
        self,
        source: SSAValue | Operation,
        dest: MemRefType | UnrankedMemRefType,
    ):
        super().__init__(operands=[source], result_types=[dest])

    @staticmethod
    def from_type_and_target_space(
        source: SSAValue | Operation,
        type: MemRefType,
        dest_memory_space: Attribute,
    ) -> MemorySpaceCastOp:
        dest = MemRefType(
            type.get_element_type(),
            shape=type.get_shape(),
            layout=type.layout,
            memory_space=dest_memory_space,
        )
        return MemorySpaceCastOp(source, dest)

    def verify_(self) -> None:
        source = cast(MemRefType, self.source.type)
        dest = cast(MemRefType, self.dest.type)
        if source.get_shape() != dest.get_shape():
            raise VerifyException(
                "Expected source and destination to have the same shape."
            )
        if source.get_element_type() != dest.get_element_type():
            raise VerifyException(
                "Expected source and destination to have the same element type."
            )

name = 'memref.memory_space_cast' class-attribute instance-attribute

source = operand_def(base(MemRefType) | base(UnrankedMemRefType)) class-attribute instance-attribute

dest = result_def(base(MemRefType) | base(UnrankedMemRefType)) class-attribute instance-attribute

traits = traits_def(NoMemoryEffect()) class-attribute instance-attribute

__init__(source: SSAValue | Operation, dest: MemRefType | UnrankedMemRefType)

Source code in xdsl/dialects/memref.py
876
877
878
879
880
881
def __init__(
    self,
    source: SSAValue | Operation,
    dest: MemRefType | UnrankedMemRefType,
):
    super().__init__(operands=[source], result_types=[dest])

from_type_and_target_space(source: SSAValue | Operation, type: MemRefType, dest_memory_space: Attribute) -> MemorySpaceCastOp staticmethod

Source code in xdsl/dialects/memref.py
883
884
885
886
887
888
889
890
891
892
893
894
895
@staticmethod
def from_type_and_target_space(
    source: SSAValue | Operation,
    type: MemRefType,
    dest_memory_space: Attribute,
) -> MemorySpaceCastOp:
    dest = MemRefType(
        type.get_element_type(),
        shape=type.get_shape(),
        layout=type.layout,
        memory_space=dest_memory_space,
    )
    return MemorySpaceCastOp(source, dest)

verify_() -> None

Source code in xdsl/dialects/memref.py
897
898
899
900
901
902
903
904
905
906
907
def verify_(self) -> None:
    source = cast(MemRefType, self.source.type)
    dest = cast(MemRefType, self.dest.type)
    if source.get_shape() != dest.get_shape():
        raise VerifyException(
            "Expected source and destination to have the same shape."
        )
    if source.get_element_type() != dest.get_element_type():
        raise VerifyException(
            "Expected source and destination to have the same element type."
        )

ReinterpretCastOp

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
@irdl_op_definition
class ReinterpretCastOp(IRDLOperation):
    DYNAMIC_INDEX: ClassVar[int] = -9223372036854775808

    name = "memref.reinterpret_cast"

    source = operand_def(MemRefType)

    offsets = var_operand_def(IndexType)
    sizes = var_operand_def(IndexType)
    strides = var_operand_def(IndexType)

    static_offsets = prop_def(DenseArrayBase.constr(i64))
    static_sizes = prop_def(DenseArrayBase.constr(i64))
    static_strides = prop_def(DenseArrayBase.constr(i64))

    result = result_def(MemRefType)

    traits = traits_def(NoMemoryEffect())

    irdl_options = (AttrSizedOperandSegments(as_property=True),)

    assembly_format = (
        "$source `to` `offset` `` `:`"
        "custom<DynamicIndexList>($offsets, $static_offsets)"
        "`` `,` `sizes` `` `:`"
        "custom<DynamicIndexList>($sizes, $static_sizes)"
        "`` `,` `strides` `` `:`"
        "custom<DynamicIndexList>($strides, $static_strides)"
        "attr-dict `:` type($source) `to` type($result)"
    )

    custom_directives = (DynamicIndexList,)

    def __init__(
        self,
        source: SSAValue | Operation,
        offsets: Sequence[SSAValue],
        sizes: Sequence[SSAValue],
        strides: Sequence[SSAValue],
        static_offsets: Sequence[int] | DenseArrayBase,
        static_sizes: Sequence[int] | DenseArrayBase,
        static_strides: Sequence[int] | DenseArrayBase,
        result_type: Attribute,
    ):
        if not isinstance(static_offsets, DenseArrayBase):
            static_offsets = DenseArrayBase.from_list(i64, static_offsets)
        if not isinstance(static_sizes, DenseArrayBase):
            static_sizes = DenseArrayBase.from_list(i64, static_sizes)
        if not isinstance(static_strides, DenseArrayBase):
            static_strides = DenseArrayBase.from_list(i64, static_strides)
        super().__init__(
            operands=[source, offsets, sizes, strides],
            result_types=[result_type],
            properties={
                "static_offsets": static_offsets,
                "static_sizes": static_sizes,
                "static_strides": static_strides,
            },
        )

    @staticmethod
    def from_dynamic(
        source: SSAValue,
        offsets: Sequence[SSAValue | int],
        sizes: Sequence[SSAValue | int],
        strides: Sequence[SSAValue | int],
        result_type: Attribute,
    ):
        """
        Construct a `ReinterpretCastOp` from dynamic offsets, sizes, and strides.
        """
        static_offsets, dyn_offsets = split_dynamic_index_list(
            offsets, ReinterpretCastOp.DYNAMIC_INDEX
        )
        static_sizes, dyn_sizes = split_dynamic_index_list(
            sizes, ReinterpretCastOp.DYNAMIC_INDEX
        )
        static_strides, dyn_strides = split_dynamic_index_list(
            strides, ReinterpretCastOp.DYNAMIC_INDEX
        )

        return ReinterpretCastOp(
            source,
            dyn_offsets,
            dyn_sizes,
            dyn_strides,
            static_offsets,
            static_sizes,
            static_strides,
            result_type,
        )

    def verify_(self):
        static_offsets = self.static_offsets.get_values()
        static_sizes = self.static_sizes.get_values()
        static_strides = self.static_strides.get_values()

        verify_dynamic_index_list(
            static_sizes, self.sizes, self.DYNAMIC_INDEX, " in the size arguments"
        )
        verify_dynamic_index_list(
            static_offsets, self.offsets, self.DYNAMIC_INDEX, " in the offset arguments"
        )
        verify_dynamic_index_list(
            static_strides, self.strides, self.DYNAMIC_INDEX, " in the stride arguments"
        )

        assert isa(self.source.type, MemRefType)
        assert isa(self.result.type, MemRefType)

        if len(self.result.type.shape) != len(self.static_sizes):
            raise VerifyException(
                f"Expected {len(self.source.type.shape)} size values but got {len(self.static_sizes)}"
            )

        # validate sizes
        for dim, (actual, expected) in enumerate(
            zip(
                self.result.type.get_shape(),
                self.static_sizes.get_values(),
                strict=True,
            )
        ):
            if expected == ReinterpretCastOp.DYNAMIC_INDEX and actual != DYNAMIC_INDEX:
                raise VerifyException(
                    f"Expected result type with dynamic size instead of {actual} in dim = {dim}"
                )
            elif expected != ReinterpretCastOp.DYNAMIC_INDEX and expected != actual:
                raise VerifyException(
                    f"Expected result type with size = {expected} instead of {actual} in dim = {dim}"
                )

DYNAMIC_INDEX: int = -9223372036854775808 class-attribute

name = 'memref.reinterpret_cast' class-attribute instance-attribute

source = operand_def(MemRefType) class-attribute instance-attribute

offsets = var_operand_def(IndexType) class-attribute instance-attribute

sizes = var_operand_def(IndexType) class-attribute instance-attribute

strides = var_operand_def(IndexType) class-attribute instance-attribute

static_offsets = prop_def(DenseArrayBase.constr(i64)) class-attribute instance-attribute

static_sizes = prop_def(DenseArrayBase.constr(i64)) class-attribute instance-attribute

static_strides = prop_def(DenseArrayBase.constr(i64)) class-attribute instance-attribute

result = result_def(MemRefType) class-attribute instance-attribute

traits = traits_def(NoMemoryEffect()) class-attribute instance-attribute

irdl_options = (AttrSizedOperandSegments(as_property=True),) class-attribute instance-attribute

assembly_format = '$source `to` `offset` `` `:`custom<DynamicIndexList>($offsets, $static_offsets)`` `,` `sizes` `` `:`custom<DynamicIndexList>($sizes, $static_sizes)`` `,` `strides` `` `:`custom<DynamicIndexList>($strides, $static_strides)attr-dict `:` type($source) `to` type($result)' class-attribute instance-attribute

custom_directives = (DynamicIndexList,) class-attribute instance-attribute

__init__(source: SSAValue | Operation, offsets: Sequence[SSAValue], sizes: Sequence[SSAValue], strides: Sequence[SSAValue], static_offsets: Sequence[int] | DenseArrayBase, static_sizes: Sequence[int] | DenseArrayBase, static_strides: Sequence[int] | DenseArrayBase, result_type: Attribute)

Source code in xdsl/dialects/memref.py
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
def __init__(
    self,
    source: SSAValue | Operation,
    offsets: Sequence[SSAValue],
    sizes: Sequence[SSAValue],
    strides: Sequence[SSAValue],
    static_offsets: Sequence[int] | DenseArrayBase,
    static_sizes: Sequence[int] | DenseArrayBase,
    static_strides: Sequence[int] | DenseArrayBase,
    result_type: Attribute,
):
    if not isinstance(static_offsets, DenseArrayBase):
        static_offsets = DenseArrayBase.from_list(i64, static_offsets)
    if not isinstance(static_sizes, DenseArrayBase):
        static_sizes = DenseArrayBase.from_list(i64, static_sizes)
    if not isinstance(static_strides, DenseArrayBase):
        static_strides = DenseArrayBase.from_list(i64, static_strides)
    super().__init__(
        operands=[source, offsets, sizes, strides],
        result_types=[result_type],
        properties={
            "static_offsets": static_offsets,
            "static_sizes": static_sizes,
            "static_strides": static_strides,
        },
    )

from_dynamic(source: SSAValue, offsets: Sequence[SSAValue | int], sizes: Sequence[SSAValue | int], strides: Sequence[SSAValue | int], result_type: Attribute) staticmethod

Construct a ReinterpretCastOp from dynamic offsets, sizes, and strides.

Source code in xdsl/dialects/memref.py
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
@staticmethod
def from_dynamic(
    source: SSAValue,
    offsets: Sequence[SSAValue | int],
    sizes: Sequence[SSAValue | int],
    strides: Sequence[SSAValue | int],
    result_type: Attribute,
):
    """
    Construct a `ReinterpretCastOp` from dynamic offsets, sizes, and strides.
    """
    static_offsets, dyn_offsets = split_dynamic_index_list(
        offsets, ReinterpretCastOp.DYNAMIC_INDEX
    )
    static_sizes, dyn_sizes = split_dynamic_index_list(
        sizes, ReinterpretCastOp.DYNAMIC_INDEX
    )
    static_strides, dyn_strides = split_dynamic_index_list(
        strides, ReinterpretCastOp.DYNAMIC_INDEX
    )

    return ReinterpretCastOp(
        source,
        dyn_offsets,
        dyn_sizes,
        dyn_strides,
        static_offsets,
        static_sizes,
        static_strides,
        result_type,
    )

verify_()

Source code in xdsl/dialects/memref.py
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
def verify_(self):
    static_offsets = self.static_offsets.get_values()
    static_sizes = self.static_sizes.get_values()
    static_strides = self.static_strides.get_values()

    verify_dynamic_index_list(
        static_sizes, self.sizes, self.DYNAMIC_INDEX, " in the size arguments"
    )
    verify_dynamic_index_list(
        static_offsets, self.offsets, self.DYNAMIC_INDEX, " in the offset arguments"
    )
    verify_dynamic_index_list(
        static_strides, self.strides, self.DYNAMIC_INDEX, " in the stride arguments"
    )

    assert isa(self.source.type, MemRefType)
    assert isa(self.result.type, MemRefType)

    if len(self.result.type.shape) != len(self.static_sizes):
        raise VerifyException(
            f"Expected {len(self.source.type.shape)} size values but got {len(self.static_sizes)}"
        )

    # validate sizes
    for dim, (actual, expected) in enumerate(
        zip(
            self.result.type.get_shape(),
            self.static_sizes.get_values(),
            strict=True,
        )
    ):
        if expected == ReinterpretCastOp.DYNAMIC_INDEX and actual != DYNAMIC_INDEX:
            raise VerifyException(
                f"Expected result type with dynamic size instead of {actual} in dim = {dim}"
            )
        elif expected != ReinterpretCastOp.DYNAMIC_INDEX and expected != actual:
            raise VerifyException(
                f"Expected result type with size = {expected} instead of {actual} in dim = {dim}"
            )

ViewOp

Bases: IRDLOperation

memref view operation.

See external documentation.

Source code in xdsl/dialects/memref.py
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
@irdl_op_definition
class ViewOp(IRDLOperation):
    """
    memref view operation.

    See external [documentation](https://mlir.llvm.org/docs/Dialects/MemRef/#memrefview-memrefviewop).
    """

    name = "memref.view"

    source = operand_def(MemRefType[i8])
    byte_shift = operand_def(IndexType)
    sizes = var_operand_def(IndexType)

    result = result_def(MemRefType)

    traits = traits_def(NoMemoryEffect())

    assembly_format = (
        "$source `[` $byte_shift `]` `` `[` $sizes `]` attr-dict "
        "`:` type($source) `to` type($result)"
    )

    def __init__(
        self,
        source: SSAValue | Operation,
        byte_shift: SSAValue | Operation,
        sizes: Sequence[SSAValue | Operation],
        result_type: MemRefType,
    ):
        super().__init__(
            operands=[source, byte_shift, sizes], result_types=[result_type]
        )

    def verify_(self) -> None:
        # Source must be a 1-D memref of i8.
        src_type = cast(MemRefType[IntegerType], self.source.type)

        if len(src_type.shape.data) != 1:
            raise VerifyException("memref.view source must be a 1-D memref of i8")

        # Enforce empty layout map on source and result (identity layout, offset 0).
        if not isinstance(src_type.layout, NoneAttr):
            raise VerifyException(
                "memref.view source must have identity layout (no layout map)"
            )

        res_type = cast(MemRefType[IntegerType], self.result.type)

        if not isinstance(res_type.layout, NoneAttr):
            raise VerifyException(
                "memref.view result must have identity layout (no layout map)"
            )

        # Memory spaces must match between source and result.
        if src_type.memory_space != res_type.memory_space:
            raise VerifyException(
                "different memory spaces specified for base memref type "
                f"'{src_type}' and view memref type '{res_type}'"
            )

        # A dynamic size operand must be provided for each dynamic dim in result.
        dyn_dims = sum(1 for d in res_type.shape.data if d.data == DYNAMIC_INDEX)
        if dyn_dims != len(self.sizes):
            raise VerifyException(
                "number of size operands must match number of dynamic dims in result type"
            )

name = 'memref.view' class-attribute instance-attribute

source = operand_def(MemRefType[i8]) class-attribute instance-attribute

byte_shift = operand_def(IndexType) class-attribute instance-attribute

sizes = var_operand_def(IndexType) class-attribute instance-attribute

result = result_def(MemRefType) class-attribute instance-attribute

traits = traits_def(NoMemoryEffect()) class-attribute instance-attribute

assembly_format = '$source `[` $byte_shift `]` `` `[` $sizes `]` attr-dict `:` type($source) `to` type($result)' class-attribute instance-attribute

__init__(source: SSAValue | Operation, byte_shift: SSAValue | Operation, sizes: Sequence[SSAValue | Operation], result_type: MemRefType)

Source code in xdsl/dialects/memref.py
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
def __init__(
    self,
    source: SSAValue | Operation,
    byte_shift: SSAValue | Operation,
    sizes: Sequence[SSAValue | Operation],
    result_type: MemRefType,
):
    super().__init__(
        operands=[source, byte_shift, sizes], result_types=[result_type]
    )

verify_() -> None

Source code in xdsl/dialects/memref.py
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
def verify_(self) -> None:
    # Source must be a 1-D memref of i8.
    src_type = cast(MemRefType[IntegerType], self.source.type)

    if len(src_type.shape.data) != 1:
        raise VerifyException("memref.view source must be a 1-D memref of i8")

    # Enforce empty layout map on source and result (identity layout, offset 0).
    if not isinstance(src_type.layout, NoneAttr):
        raise VerifyException(
            "memref.view source must have identity layout (no layout map)"
        )

    res_type = cast(MemRefType[IntegerType], self.result.type)

    if not isinstance(res_type.layout, NoneAttr):
        raise VerifyException(
            "memref.view result must have identity layout (no layout map)"
        )

    # Memory spaces must match between source and result.
    if src_type.memory_space != res_type.memory_space:
        raise VerifyException(
            "different memory spaces specified for base memref type "
            f"'{src_type}' and view memref type '{res_type}'"
        )

    # A dynamic size operand must be provided for each dynamic dim in result.
    dyn_dims = sum(1 for d in res_type.shape.data if d.data == DYNAMIC_INDEX)
    if dyn_dims != len(self.sizes):
        raise VerifyException(
            "number of size operands must match number of dynamic dims in result type"
        )

DmaStartOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
@irdl_op_definition
class DmaStartOp(IRDLOperation):
    name = "memref.dma_start"

    src = operand_def(MemRefType)
    src_indices = var_operand_def(IndexType)

    dest = operand_def(MemRefType)
    dest_indices = var_operand_def(IndexType)

    num_elements = operand_def(IndexType)

    tag = operand_def(MemRefType[IntegerType])
    tag_indices = var_operand_def(IndexType)

    traits = traits_def(MemoryWriteEffect(), MemoryReadEffect())

    irdl_options = (AttrSizedOperandSegments(),)

    @staticmethod
    def get(
        src: SSAValue | Operation,
        src_indices: Sequence[SSAValue | Operation],
        dest: SSAValue | Operation,
        dest_indices: Sequence[SSAValue | Operation],
        num_elements: SSAValue | Operation,
        tag: SSAValue | Operation,
        tag_indices: Sequence[SSAValue | Operation],
    ):
        return DmaStartOp.build(
            operands=[
                src,
                src_indices,
                dest,
                dest_indices,
                num_elements,
                tag,
                tag_indices,
            ]
        )

    def verify_(self) -> None:
        assert isa(self.src.type, MemRefType)
        assert isa(self.dest.type, MemRefType)
        assert isa(self.tag.type, MemRefType[IntegerType])

        if len(self.src.type.shape) != len(self.src_indices):
            raise VerifyException(
                f"Expected {len(self.src.type.shape)} source indices (because of shape of src memref)"
            )

        if len(self.dest.type.shape) != len(self.dest_indices):
            raise VerifyException(
                f"Expected {len(self.dest.type.shape)} dest indices (because of shape of dest memref)"
            )

        if len(self.tag.type.shape) != len(self.tag_indices):
            raise VerifyException(
                f"Expected {len(self.tag.type.shape)} tag indices (because of shape of tag memref)"
            )

        if self.tag.type.element_type != i32:
            raise VerifyException("Expected tag to be a memref of i32")

        if self.dest.type.memory_space == self.src.type.memory_space:
            raise VerifyException("Source and dest must have different memory spaces!")

name = 'memref.dma_start' class-attribute instance-attribute

src = operand_def(MemRefType) class-attribute instance-attribute

src_indices = var_operand_def(IndexType) class-attribute instance-attribute

dest = operand_def(MemRefType) class-attribute instance-attribute

dest_indices = var_operand_def(IndexType) class-attribute instance-attribute

num_elements = operand_def(IndexType) class-attribute instance-attribute

tag = operand_def(MemRefType[IntegerType]) class-attribute instance-attribute

tag_indices = var_operand_def(IndexType) class-attribute instance-attribute

traits = traits_def(MemoryWriteEffect(), MemoryReadEffect()) class-attribute instance-attribute

irdl_options = (AttrSizedOperandSegments(),) class-attribute instance-attribute

get(src: SSAValue | Operation, src_indices: Sequence[SSAValue | Operation], dest: SSAValue | Operation, dest_indices: Sequence[SSAValue | Operation], num_elements: SSAValue | Operation, tag: SSAValue | Operation, tag_indices: Sequence[SSAValue | Operation]) staticmethod

Source code in xdsl/dialects/memref.py
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
@staticmethod
def get(
    src: SSAValue | Operation,
    src_indices: Sequence[SSAValue | Operation],
    dest: SSAValue | Operation,
    dest_indices: Sequence[SSAValue | Operation],
    num_elements: SSAValue | Operation,
    tag: SSAValue | Operation,
    tag_indices: Sequence[SSAValue | Operation],
):
    return DmaStartOp.build(
        operands=[
            src,
            src_indices,
            dest,
            dest_indices,
            num_elements,
            tag,
            tag_indices,
        ]
    )

verify_() -> None

Source code in xdsl/dialects/memref.py
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
def verify_(self) -> None:
    assert isa(self.src.type, MemRefType)
    assert isa(self.dest.type, MemRefType)
    assert isa(self.tag.type, MemRefType[IntegerType])

    if len(self.src.type.shape) != len(self.src_indices):
        raise VerifyException(
            f"Expected {len(self.src.type.shape)} source indices (because of shape of src memref)"
        )

    if len(self.dest.type.shape) != len(self.dest_indices):
        raise VerifyException(
            f"Expected {len(self.dest.type.shape)} dest indices (because of shape of dest memref)"
        )

    if len(self.tag.type.shape) != len(self.tag_indices):
        raise VerifyException(
            f"Expected {len(self.tag.type.shape)} tag indices (because of shape of tag memref)"
        )

    if self.tag.type.element_type != i32:
        raise VerifyException("Expected tag to be a memref of i32")

    if self.dest.type.memory_space == self.src.type.memory_space:
        raise VerifyException("Source and dest must have different memory spaces!")

DmaWaitOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
@irdl_op_definition
class DmaWaitOp(IRDLOperation):
    name = "memref.dma_wait"

    tag = operand_def(MemRefType)
    tag_indices = var_operand_def(IndexType)

    num_elements = operand_def(IndexType)

    traits = traits_def(MemoryWriteEffect(), MemoryReadEffect())

    @staticmethod
    def get(
        tag: SSAValue | Operation,
        tag_indices: Sequence[SSAValue | Operation],
        num_elements: SSAValue | Operation,
    ):
        return DmaWaitOp.build(
            operands=[
                tag,
                tag_indices,
                num_elements,
            ]
        )

    def verify_(self) -> None:
        assert isa(self.tag.type, MemRefType)

        if len(self.tag.type.shape) != len(self.tag_indices):
            raise VerifyException(
                f"Expected {len(self.tag.type.shape)} tag indices because of shape of tag memref"
            )

        if self.tag.type.element_type != i32:
            raise VerifyException("Expected tag to be a memref of i32")

name = 'memref.dma_wait' class-attribute instance-attribute

tag = operand_def(MemRefType) class-attribute instance-attribute

tag_indices = var_operand_def(IndexType) class-attribute instance-attribute

num_elements = operand_def(IndexType) class-attribute instance-attribute

traits = traits_def(MemoryWriteEffect(), MemoryReadEffect()) class-attribute instance-attribute

get(tag: SSAValue | Operation, tag_indices: Sequence[SSAValue | Operation], num_elements: SSAValue | Operation) staticmethod

Source code in xdsl/dialects/memref.py
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
@staticmethod
def get(
    tag: SSAValue | Operation,
    tag_indices: Sequence[SSAValue | Operation],
    num_elements: SSAValue | Operation,
):
    return DmaWaitOp.build(
        operands=[
            tag,
            tag_indices,
            num_elements,
        ]
    )

verify_() -> None

Source code in xdsl/dialects/memref.py
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
def verify_(self) -> None:
    assert isa(self.tag.type, MemRefType)

    if len(self.tag.type.shape) != len(self.tag_indices):
        raise VerifyException(
            f"Expected {len(self.tag.type.shape)} tag indices because of shape of tag memref"
        )

    if self.tag.type.element_type != i32:
        raise VerifyException("Expected tag to be a memref of i32")

CopyOp

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
@irdl_op_definition
class CopyOp(IRDLOperation):
    name = "memref.copy"
    source = operand_def(MemRefType)
    destination = operand_def(MemRefType)

    traits = traits_def(MemoryWriteEffect(), MemoryReadEffect())

    def __init__(self, source: SSAValue | Operation, destination: SSAValue | Operation):
        super().__init__(operands=[source, destination])

    def verify_(self) -> None:
        source = cast(MemRefType, self.source.type)
        destination = cast(MemRefType, self.destination.type)
        if source.get_shape() != destination.get_shape():
            raise VerifyException(
                "Expected source and destination to have the same shape."
            )
        if source.get_element_type() != destination.get_element_type():
            raise VerifyException(
                "Expected source and destination to have the same element type."
            )

name = 'memref.copy' class-attribute instance-attribute

source = operand_def(MemRefType) class-attribute instance-attribute

destination = operand_def(MemRefType) class-attribute instance-attribute

traits = traits_def(MemoryWriteEffect(), MemoryReadEffect()) class-attribute instance-attribute

__init__(source: SSAValue | Operation, destination: SSAValue | Operation)

Source code in xdsl/dialects/memref.py
1226
1227
def __init__(self, source: SSAValue | Operation, destination: SSAValue | Operation):
    super().__init__(operands=[source, destination])

verify_() -> None

Source code in xdsl/dialects/memref.py
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
def verify_(self) -> None:
    source = cast(MemRefType, self.source.type)
    destination = cast(MemRefType, self.destination.type)
    if source.get_shape() != destination.get_shape():
        raise VerifyException(
            "Expected source and destination to have the same shape."
        )
    if source.get_element_type() != destination.get_element_type():
        raise VerifyException(
            "Expected source and destination to have the same element type."
        )