cubecl-ir 0.11.0-pre.3

Intermediate representation for CubeCL
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
use alloc::{
    boxed::Box,
    string::{String, ToString},
};
use cubecl_macros_internal::{cube_op, op_traits};
use pliron::{
    attribute::AttrObj,
    printable::Printable,
    r#type::TypeHandle,
    utils::table::{HMap, SmallSet},
    verify_err,
};
use thiserror::Error;

use crate::{
    CanMaterialize, Pure,
    attributes::IndexAttr,
    interfaces::{
        aliasing::AliasingOp,
        memory_slot::{
            DeletionKind, DestructurableAccessorOpInterface, DestructurableConstructorOpInterface,
            DestructurableTypeInterface, DestructurableValueSlot, ValueSlot,
        },
        *,
    },
    prelude::*,
    try_cast_ty,
    types::{VectorType, aggregate::index_attr, scalar::IndexType},
};

#[pliron_op(
    name = "composite.construct",
    format = "operands(CharSpace(`,`)) ` : ` type($0)"
)]
#[op_interfaces(NResultsInterface<1>, OneResultInterface, AtLeastNOpdsInterface<1>)]
#[op_traits(Pure, CanMaterialize)]
pub struct CompositeConstructOp;

impl CompositeConstructOp {
    pub fn new(ctx: &mut Context, ty: TypeHandle, values: Vec<Value>) -> Self {
        let op = Operation::new(
            ctx,
            Self::get_concrete_op_info(),
            vec![ty],
            values,
            vec![],
            0,
        );
        Self { op }
    }

    pub fn values(&self, ctx: &Context) -> Vec<Value> {
        self.get_operation().deref(ctx).operands().collect()
    }
}

#[op_interface_impl]
impl DestructurableConstructorOpInterface for CompositeConstructOp {
    fn destructurable_values(&self, ctx: &Context) -> Vec<DestructurableValueSlot> {
        let ty = self.result_type(ctx).deref(ctx);
        let Some(destructurable) = type_cast::<dyn DestructurableTypeInterface>(&*ty) else {
            return vec![];
        };
        let Some(subelement_types) = destructurable.subelement_index_map(ctx) else {
            return vec![];
        };
        vec![DestructurableValueSlot {
            slot: ValueSlot::new(self.get_result(ctx), self.result_type(ctx)),
            subelement_types,
        }]
    }

    fn destructure(
        &self,
        ctx: &mut Context,
        _value: &DestructurableValueSlot,
        used_indices: &SmallSet<AttrObj, 8>,
        _rewriter: &mut PassRewriter,
        _new_constructors: &mut Vec<TraitOp<dyn DestructurableConstructorOpInterface>>,
    ) -> HMap<AttrObj, ValueSlot> {
        let op = self.get_operation();
        let mut slot_map = HMap::new();
        for used_index in used_indices {
            let index = used_index.downcast_ref::<IndexAttr>().unwrap().0;
            let opd = op.operand(ctx, index);
            slot_map.insert(used_index.clone(), ValueSlot::new(opd, opd.get_type(ctx)));
        }
        slot_map
    }

    fn handle_destructuring_complete(
        &self,
        ctx: &mut Context,
        value: &DestructurableValueSlot,
        rewriter: &mut PassRewriter,
    ) -> Option<TraitOp<dyn DestructurableConstructorOpInterface>> {
        assert_eq!(value.slot.value, self.get_result(ctx));
        rewriter.erase_operation(ctx, self.get_operation());
        None
    }
}

#[cube_op(
    name = "composite.extract",
    format = "$0 `[` attr($index, $IndexAttr) `] : ` type($0)",
    verifier = "custom"
)]
#[result_ty(from_inputs = composite_extract_type)]
#[op_traits(Pure, CanMaterialize)]
pub struct CompositeExtractOp {
    pub composite: Value,
    pub index: IndexAttr,
}

fn composite_extract_type(ctx: &Context, aggregate: &Value, field: &IndexAttr) -> TypeHandle {
    let aggregate_ty = aggregate.get_type(ctx).deref(ctx);
    let aggregate_ty =
        type_cast::<dyn DestructurableTypeInterface>(&*aggregate_ty).expect("Should be aggregate");
    aggregate_ty.type_at_index(ctx, &index_attr(field.0))
}

#[derive(Error, Debug)]
pub enum CompositeConstructError {
    #[error(
        "[CompositeConstructOp]: Output composite size doesn't match parameter count: Expected {_0} parameters, got {_1}"
    )]
    ParameterCountMismatch(usize, usize),
    #[error(
        "[CompositeConstructOp]: Output field type doesn't match parameter type: Expected {_0}, got {_1}"
    )]
    ParameterTypeMismatch(String, String),
}

#[op_interface_impl]
impl AliasingOp for CompositeExtractOp {
    fn source_ptr(&self, ctx: &Context) -> Option<Value> {
        let aggregate = self.composite(ctx);
        let field = self.index(ctx).0;
        let aggregate_ty = aggregate.get_type(ctx).deref(ctx);
        let destruct = try_cast_ty!(aggregate_ty, ctx, dyn DestructurableTypeInterface);
        if destruct.type_at_index(ctx, &index_attr(field)).is_ptr(ctx) {
            let construct = aggregate.defining_op().expect("Should be construct");
            Some(construct.operand(ctx, field))
        } else {
            None
        }
    }
}

impl Verify for CompositeConstructOp {
    fn verify(&self, ctx: &Context) -> Result<()> {
        let ty = self.result_type(ctx).deref(ctx);
        let opds = self.get_operation().operands(ctx);
        let destructurable = try_cast_ty!(ty, ctx, dyn DestructurableTypeInterface);
        let fields = destructurable.subelement_index_map(ctx).unwrap();

        if opds.len() != fields.len() {
            return verify_err!(
                self.loc(ctx),
                CompositeConstructError::ParameterCountMismatch(fields.len(), opds.len())
            );
        }

        for (i, &opd) in opds.iter().enumerate() {
            let field_ty = fields[&index_attr(i)];
            if opd.get_type(ctx) != field_ty {
                return verify_err!(
                    self.loc(ctx),
                    CompositeConstructError::ParameterTypeMismatch(
                        field_ty.disp(ctx).to_string(),
                        opd.get_type(ctx).disp(ctx).to_string()
                    )
                );
            }
        }

        Ok(())
    }
}

#[derive(Error, Debug)]
pub enum CompositeOpError {
    #[error("[CompositeOp]: Index is out of range: index is {_0} but composite size is {_1}.")]
    IndexOutOfRange(usize, usize),
    #[error(
        "[CompositeOp]: Field type doesn't match the inner type of the composite: expected {_0}, got {_1}"
    )]
    MismatchedFieldType(String, String),
}

impl Verify for CompositeExtractOp {
    fn verify(&self, ctx: &Context) -> Result<()> {
        let ty = self.composite(ctx).get_type(ctx).deref(ctx);
        let destructurable = try_cast_ty!(ty, ctx, dyn DestructurableTypeInterface);
        let fields = destructurable.subelement_index_map(ctx).unwrap();

        let loc = self.loc(ctx);
        let index = self.index(ctx).0;
        if index >= fields.len() {
            return verify_err!(loc, CompositeOpError::IndexOutOfRange(index, fields.len()));
        }
        Ok(())
    }
}

#[op_interface_impl]
impl DestructurableAccessorOpInterface for CompositeExtractOp {
    fn can_rewire(
        &self,
        ctx: &Context,
        value: &DestructurableValueSlot,
        used_indices: &mut SmallSet<AttrObj, 8>,
        _must_be_safely_used: &mut Vec<ValueSlot>,
    ) -> bool {
        if value.slot.value != self.composite(ctx) {
            return false;
        }
        used_indices.insert(Box::new(*self.index(ctx)));
        true
    }

    fn rewire(
        &self,
        ctx: &mut Context,
        _value: &DestructurableValueSlot,
        subvalues: &HMap<AttrObj, ValueSlot>,
        rewriter: &mut PassRewriter,
    ) -> DeletionKind {
        let index: AttrObj = Box::new(*self.index(ctx));
        let slot = &subvalues[&index];
        rewriter.replace_value_uses_with(ctx, self.get_result(ctx), slot.value);
        DeletionKind::Delete
    }
}

#[cube_op(
    name = "composite.insert",
    format = "$1 ` -> ` $0 `[` attr($index, $IndexAttr) `] : ` type($0)",
    verifier = "custom"
)]
#[result_ty(same_as = composite)]
#[op_traits(CanMaterialize, Pure)]
pub struct CompositeInsertOp {
    pub composite: Value,
    pub value: Value,
    pub index: IndexAttr,
}

impl Verify for CompositeInsertOp {
    fn verify(&self, ctx: &Context) -> Result<()> {
        let ty = self.result_type(ctx).deref(ctx);
        let destructurable = try_cast_ty!(ty, ctx, dyn DestructurableTypeInterface);
        let fields = destructurable.subelement_index_map(ctx).unwrap();

        let loc = self.loc(ctx);
        let index = self.index(ctx).0;
        if index >= fields.len() {
            return verify_err!(loc, CompositeOpError::IndexOutOfRange(index, fields.len()));
        }
        let field_ty = fields[&index_attr(index)];
        let value_ty = self.value(ctx).get_type(ctx);
        if field_ty != value_ty {
            return verify_err!(
                loc,
                CompositeOpError::MismatchedFieldType(
                    field_ty.disp(ctx).to_string(),
                    value_ty.disp(ctx).to_string()
                )
            );
        }
        Ok(())
    }
}

#[op_interface_impl]
impl DestructurableConstructorOpInterface for CompositeInsertOp {
    fn destructurable_values(&self, ctx: &Context) -> Vec<DestructurableValueSlot> {
        let ty = self.result_type(ctx).deref(ctx);
        let Some(destructurable) = type_cast::<dyn DestructurableTypeInterface>(&*ty) else {
            return vec![];
        };
        let Some(subelement_types) = destructurable.subelement_index_map(ctx) else {
            return vec![];
        };
        vec![DestructurableValueSlot {
            slot: ValueSlot::new(self.get_result(ctx), self.result_type(ctx)),
            subelement_types,
        }]
    }

    fn destructure(
        &self,
        ctx: &mut Context,
        _value: &DestructurableValueSlot,
        used_indices: &SmallSet<AttrObj, 8>,
        rewriter: &mut PassRewriter,
        _new_constructors: &mut Vec<TraitOp<dyn DestructurableConstructorOpInterface>>,
    ) -> HMap<AttrObj, ValueSlot> {
        let inserted_index = self.index(ctx).0;
        let mut slot_map = HMap::new();
        for used_index in used_indices {
            let index = used_index.downcast_ref::<IndexAttr>().unwrap().0;
            let value = if index == inserted_index {
                ValueSlot::new(self.value(ctx), self.value(ctx).get_type(ctx))
            } else {
                let extract = CompositeExtractOp::new(ctx, self.composite(ctx), index);
                rewriter.append_op(ctx, &extract);
                ValueSlot::new(extract.get_result(ctx), extract.result_type(ctx))
            };
            slot_map.insert(used_index.clone(), value);
        }
        slot_map
    }

    fn handle_destructuring_complete(
        &self,
        ctx: &mut Context,
        value: &DestructurableValueSlot,
        rewriter: &mut PassRewriter,
    ) -> Option<TraitOp<dyn DestructurableConstructorOpInterface>> {
        assert_eq!(value.slot.value, self.get_result(ctx));
        rewriter.erase_operation(ctx, self.get_operation());
        None
    }
}

#[cube_op(
    name = "vector.broadcast",
    format = "$0 ` : ` type($0)",
    verifier = "custom"
)]
#[result_ty(argument)]
#[op_interfaces(ResultNOfType<0, VectorType>, TriviallyUnrollable)]
#[op_traits(CanMaterialize, Pure)]
pub struct VectorBroadcastOp {
    pub input: Value,
}

impl Verify for VectorBroadcastOp {
    fn verify(&self, ctx: &Context) -> Result<()> {
        let loc = self.loc(ctx);
        let value_ty = self.input(ctx).get_type(ctx);
        let scalar_ty = self.get_result(ctx).scalar_ty(ctx);
        if scalar_ty != value_ty {
            return verify_err!(
                loc,
                CompositeOpError::MismatchedFieldType(
                    scalar_ty.disp(ctx).to_string(),
                    value_ty.disp(ctx).to_string()
                )
            );
        }
        Ok(())
    }
}

#[op_interface_impl]
impl DestructurableConstructorOpInterface for VectorBroadcastOp {
    fn destructurable_values(&self, ctx: &Context) -> Vec<DestructurableValueSlot> {
        let ty = self.result_type(ctx).deref(ctx);
        let Some(destructurable) = type_cast::<dyn DestructurableTypeInterface>(&*ty) else {
            return vec![];
        };
        let Some(subelement_types) = destructurable.subelement_index_map(ctx) else {
            return vec![];
        };
        vec![DestructurableValueSlot {
            slot: ValueSlot::new(self.get_result(ctx), self.result_type(ctx)),
            subelement_types,
        }]
    }

    fn destructure(
        &self,
        ctx: &mut Context,
        _value: &DestructurableValueSlot,
        used_indices: &SmallSet<AttrObj, 8>,
        _rewriter: &mut PassRewriter,
        _new_constructors: &mut Vec<TraitOp<dyn DestructurableConstructorOpInterface>>,
    ) -> HMap<AttrObj, ValueSlot> {
        let mut slot_map = HMap::new();
        for used_index in used_indices {
            let slot = ValueSlot::new(self.input(ctx), self.input(ctx).get_type(ctx));
            slot_map.insert(used_index.clone(), slot);
        }
        slot_map
    }

    fn handle_destructuring_complete(
        &self,
        ctx: &mut Context,
        value: &DestructurableValueSlot,
        rewriter: &mut PassRewriter,
    ) -> Option<TraitOp<dyn DestructurableConstructorOpInterface>> {
        assert_eq!(value.slot.value, self.get_result(ctx));
        rewriter.erase_operation(ctx, self.get_operation());
        None
    }
}

#[cube_op(
    name = "vector.insert_dynamic",
    format = "$1 ` -> ` $0 `[` $2 `] : ` type($0)",
    verifier = "custom"
)]
#[result_ty(same_as = vector)]
#[op_interfaces(OperandNOfType<0, VectorType>, OperandNOfType<2, IndexType>)]
#[op_traits(CanMaterialize, Pure)]
pub struct VectorInsertDynamicOp {
    pub vector: Value,
    pub value: Value,
    pub index: Value,
}

impl Verify for VectorInsertDynamicOp {
    fn verify(&self, ctx: &Context) -> Result<()> {
        let loc = self.loc(ctx);
        let scalar_ty = self.vector(ctx).scalar_ty(ctx);
        let value_ty = self.value(ctx).get_type(ctx);
        if scalar_ty != value_ty {
            verify_err!(
                loc,
                CompositeOpError::MismatchedFieldType(
                    scalar_ty.disp(ctx).to_string(),
                    value_ty.disp(ctx).to_string()
                )
            )?;
        }
        Ok(())
    }
}

#[cube_op(name = "vector.extract_dynamic", format = "$0 `[` $1 `] : ` type($0)")]
#[result_ty(from_inputs = |ctx, vector, _| scalar_ty(ctx, vector))]
#[op_interfaces(OperandNOfType<0, VectorType>, OperandNOfType<1, IndexType>)]
#[op_traits(CanMaterialize, Pure)]
pub struct VectorExtractDynamicOp {
    pub vector: Value,
    pub index: Value,
}

#[cube_op(name = "vector.magnitude")]
#[result_ty(from_inputs = scalar_ty)]
#[op_interfaces(OperandNOfType<0, VectorType>)]
#[op_traits(CanMaterialize, Pure)]
pub struct MagnitudeOp {
    pub input: Value,
}

#[cube_op(name = "vector.normalize")]
#[result_ty(same_as = input)]
#[op_interfaces(SameOperandsType, SameOperandsAndResultType, OperandNOfType<0, VectorType>)]
#[op_traits(CanMaterialize, Pure)]
pub struct NormalizeOp {
    pub input: Value,
}

#[cube_op(name = "vector.i_sum")]
#[result_ty(from_inputs = scalar_ty)]
#[op_interfaces(OperandNOfType<0, VectorType>)]
#[op_traits(CanMaterialize, Pure)]
pub struct ISumOp {
    pub input: Value,
}

#[cube_op(name = "vector.f_sum")]
#[result_ty(from_inputs = scalar_ty)]
#[op_interfaces(OperandNOfType<0, VectorType>)]
#[op_traits(CanMaterialize, Pure)]
pub struct FSumOp {
    pub input: Value,
}

#[cube_op(name = "vector.s_dot")]
#[result_ty(from_inputs = |ctx, lhs, _| scalar_ty(ctx, lhs))]
#[op_interfaces(OperandNOfType<0, VectorType>, OperandNOfType<1, VectorType>)]
#[op_traits(CanMaterialize, Pure)]
pub struct SDotOp {
    pub lhs: Value,
    pub rhs: Value,
}

#[cube_op(name = "vector.u_dot")]
#[result_ty(from_inputs = |ctx, lhs, _| scalar_ty(ctx, lhs))]
#[op_interfaces(OperandNOfType<0, VectorType>, OperandNOfType<1, VectorType>)]
#[op_traits(CanMaterialize, Pure)]
pub struct UDotOp {
    pub lhs: Value,
    pub rhs: Value,
}

#[cube_op(name = "vector.f_dot")]
#[result_ty(from_inputs = |ctx, lhs, _| scalar_ty(ctx, lhs))]
#[op_interfaces(OperandNOfType<0, VectorType>, OperandNOfType<1, VectorType>)]
#[op_traits(CanMaterialize, Pure)]
pub struct FDotOp {
    pub lhs: Value,
    pub rhs: Value,
}

fn scalar_ty(ctx: &Context, input: &Value) -> TypeHandle {
    input.scalar_ty(ctx)
}