mlir/dialects/
func.rs

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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
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
// Copyright 2024-2025, Giordano Salvador
// SPDX-License-Identifier: BSD-3-Clause

#![allow(dead_code)]

use mlir_sys::MlirAttribute;
use mlir_sys::MlirOperation;

use std::cmp;
use std::fmt;

use crate::attributes;
use crate::dialects;
use crate::effects;
use crate::exit_code;
use crate::interfaces;
use crate::ir;
use crate::traits;
use crate::types;

use attributes::IAttribute;
use attributes::IAttributeNamed;
use attributes::named::Named;
use attributes::specialized::NamedArrayOfDictionaries;
use attributes::specialized::NamedFunction;
use attributes::specialized::NamedString;
use attributes::specialized::NamedSymbolRef;
use attributes::specialized::SpecializedAttribute;
use attributes::symbol_ref::SymbolRef;
use dialects::IOp;
use dialects::IOperation;
use dialects::OpRef;
use dialects::common::SymbolName;
use dialects::common::SymbolVisibility;
use dialects::common::SymbolVisibilityKind;
use effects::MEFF_NO_MEMORY_EFFECT;
use effects::MemoryEffectList;
use exit_code::ExitCode;
use exit_code::exit;
use interfaces::Interface;
use interfaces::MemoryEffectOpInterface;
use ir::Block;
use ir::Context;
use ir::Dialect;
use ir::Location;
use ir::OperationState;
use ir::Region;
use ir::StringBacked;
use ir::StringRef;
use ir::Type;
use ir::Value;
use traits::Trait;
use types::IType;
use types::function::Function as FunctionType;

///////////////////////////////
//  Attributes
///////////////////////////////

#[derive(Clone)]
pub struct Arguments(MlirAttribute);

#[derive(Clone)]
pub struct Callee(MlirAttribute);

#[derive(Clone)]
pub struct FunctionAttr(MlirAttribute);

#[derive(Clone)]
pub struct Referee(MlirAttribute);

#[derive(Clone)]
pub struct Results(MlirAttribute);

///////////////////////////////
//  Enums
///////////////////////////////

#[derive(Clone, Copy, PartialEq)]
pub enum Op {
    Call,
    CallIndirect,
    Constant,
    Func,
    Return,
}

///////////////////////////////
//  Operations
///////////////////////////////

#[derive(Clone)]
pub struct Call(MlirOperation);

#[derive(Clone)]
pub struct CallIndirect(MlirOperation);

#[derive(Clone)]
pub struct Constant(MlirOperation);

#[derive(Clone)]
pub struct Func(MlirOperation);

#[derive(Clone)]
pub struct Return(MlirOperation, SymbolRef);

///////////////////////////////
//  Attribute Implementation
///////////////////////////////

impl Arguments {
    pub fn get(&self) -> &MlirAttribute {
        &self.0
    }

    pub fn get_mut(&mut self) -> &mut MlirAttribute {
        &mut self.0
    }
}

impl Callee {
    pub fn get(&self) -> &MlirAttribute {
        &self.0
    }

    pub fn get_mut(&mut self) -> &mut MlirAttribute {
        &mut self.0
    }
}

impl FunctionAttr {
    pub fn get(&self) -> &MlirAttribute {
        &self.0
    }

    pub fn get_mut(&mut self) -> &mut MlirAttribute {
        &mut self.0
    }
}

impl Referee {
    pub fn get(&self) -> &MlirAttribute {
        &self.0
    }

    pub fn get_mut(&mut self) -> &mut MlirAttribute {
        &mut self.0
    }
}

impl Results {
    pub fn get(&self) -> &MlirAttribute {
        &self.0
    }

    pub fn get_mut(&mut self) -> &mut MlirAttribute {
        &mut self.0
    }
}

///////////////////////////////
//  Enum Implementation
///////////////////////////////

impl Op {
    pub fn get_name(&self) -> &'static str {
        match self {
            Op::Call => "call",
            Op::CallIndirect => "call_indirect",
            Op::Constant => "constant",
            Op::Func => "func",
            Op::Return => "return",
        }
    }
}

///////////////////////////////
//  Operation Implementation
///////////////////////////////

impl Call {
    /// Currently does not check that the signature of `callee` matches the operands to this
    /// operation since the `callee` argument is just a symbol reference.
    /// This symbol reference may not yet be owned by any parent operation/region at the time this
    /// constructor is called.
    /// To check the call signature, try the `CallIndirect` operation.
    pub fn new(callee: &Callee, t: &[Type], args: &[Value], loc: &Location) -> Self {
        let context = callee.get_context();
        let dialect = context.get_dialect_func();
        let name = dialect.get_op_name(&Op::Call);
        let mut op_state = OperationState::new(&name.as_string_ref(), loc);
        op_state.add_attributes(&[callee.as_named_attribute()]);
        op_state.add_operands(args);
        op_state.add_results(t);
        Self::from(*op_state.create_operation().get())
    }

    pub fn from(op: MlirOperation) -> Self {
        Call(op)
    }

    pub fn get(&self) -> &MlirOperation {
        &self.0
    }

    pub fn get_callee(&self) -> Callee {
        let attr_name = StringBacked::from(Callee::get_name());
        let attr = self
            .as_operation()
            .get_attribute_inherent(&attr_name.as_string_ref());
        Callee::from(*attr.get())
    }

    pub fn get_context(&self) -> Context {
        self.as_operation().get_context()
    }

    pub fn get_mut(&mut self) -> &mut MlirOperation {
        &mut self.0
    }
}

impl CallIndirect {
    pub fn new(f: &Value, args: &[Value], loc: &Location) -> Self {
        if !f.is_result() || !f.get_type().is_function() {
            eprintln!("Expected function value type for indirect callee");
            exit(ExitCode::DialectError);
        }
        let t_f = FunctionType::from(*f.get_type().get());
        if t_f.num_inputs() != args.len() as isize {
            eprintln!("Expected number of inputs to match for callee and arguments provided");
            exit(ExitCode::DialectError);
        }
        for (i, arg) in args.iter().enumerate() {
            if t_f.get_input(i as isize) != arg.get_type() {
                eprintln!(
                    "Expected matching types for callee type anad argument type at position {}",
                    i
                );
                exit(ExitCode::DialectError);
            }
        }
        let mut args_: Vec<Value> = vec![f.clone()];
        args_.append(&mut args.to_vec());
        let t: Vec<Type> = (0..t_f.num_results()).map(|i| t_f.get_result(i)).collect();
        let context = f.get_type().get_context();
        let dialect = context.get_dialect_func();
        let name = dialect.get_op_name(&Op::CallIndirect);
        let mut op_state = OperationState::new(&name.as_string_ref(), loc);
        op_state.add_operands(&args_);
        op_state.add_results(&t);
        Self::from(*op_state.create_operation().get())
    }

    pub fn from(op: MlirOperation) -> Self {
        CallIndirect(op)
    }

    pub fn get(&self) -> &MlirOperation {
        &self.0
    }

    pub fn get_callee(&self) -> Value {
        self.as_operation().get_operand(0)
    }

    pub fn get_context(&self) -> Context {
        self.as_operation().get_context()
    }

    pub fn get_mut(&mut self) -> &mut MlirOperation {
        &mut self.0
    }
}

impl Constant {
    pub fn new(op: &Func, loc: &Location) -> Self {
        let context = op.get_context();
        let dialect = context.get_dialect_func();
        let name = dialect.get_op_name(&Op::Constant);
        let attr = Referee::new(&context, op.get_symbol_ref().get_value().as_ref().unwrap());
        let mut op_state = OperationState::new(&name.as_string_ref(), loc);
        op_state.add_attributes(&[attr.as_named_attribute()]);
        op_state.add_results(&[op.get_function_type().as_type()]);
        Self::from(*op_state.create_operation().get())
    }

    pub fn from(op: MlirOperation) -> Self {
        Constant(op)
    }

    pub fn get(&self) -> &MlirOperation {
        &self.0
    }

    pub fn get_context(&self) -> Context {
        self.as_operation().get_context()
    }

    pub fn get_mut(&mut self) -> &mut MlirOperation {
        &mut self.0
    }

    pub fn get_result(&self) -> Value {
        self.as_operation().get_result(0)
    }

    pub fn get_value(&self) -> Referee {
        let attr_name = StringBacked::from(Referee::get_name());
        let attr = self
            .as_operation()
            .get_attribute_inherent(&attr_name.as_string_ref());
        Referee::from(*attr.get())
    }
}

impl Func {
    pub fn new(
        t: &FunctionType,
        f_name: &StringRef,
        visibility: SymbolVisibilityKind,
        attr_args: Option<&Arguments>,
        attr_results: Option<&Results>,
        loc: &Location,
    ) -> Self {
        let context = t.as_type().get_context();
        let dialect = context.get_dialect_func();
        let name = dialect.get_op_name(&Op::Func);
        let mut op_state = OperationState::new(&name.as_string_ref(), loc);
        let mut block = Block::default();
        let _operands: Vec<Value> = (0..t.num_inputs())
            .map(|i| block.add_arg(&t.get_input(i), loc))
            .collect();
        let sym_name_attr = SymbolName::new(&context, f_name);
        let function_type_attr = FunctionAttr::new(t);
        let mut attrs: Vec<Named> = Vec::new();
        attrs.push(sym_name_attr.as_named_attribute());
        attrs.push(function_type_attr.as_named_attribute());
        if let Some(attr_args_) = attr_args {
            attrs.push(attr_args_.as_named_attribute());
        }
        if let Some(attr_results_) = attr_results {
            attrs.push(attr_results_.as_named_attribute());
        }
        let mut region = Region::new();
        if let Some(sym) = SymbolVisibility::new(&context, visibility) {
            attrs.push(sym.as_named_attribute());
        } else {
            region.append_block(&mut block);
        }
        op_state.add_attributes(&attrs);
        op_state.add_regions(&[region]);
        Self::from(*op_state.create_operation().get())
    }

    pub fn from(op: MlirOperation) -> Self {
        Func(op)
    }

    pub fn get(&self) -> &MlirOperation {
        &self.0
    }

    pub fn get_arguments(&self) -> Option<Arguments> {
        let op = self.as_operation();
        let attr_name = StringBacked::from(Arguments::get_name());
        let s_ref = attr_name.as_string_ref();
        if op.has_attribute_inherent(&s_ref) {
            let attr = op.get_attribute_inherent(&s_ref);
            Some(Arguments::from(*attr.get()))
        } else {
            None
        }
    }

    pub fn get_context(&self) -> Context {
        self.as_operation().get_context()
    }

    pub fn get_mut(&mut self) -> &mut MlirOperation {
        &mut self.0
    }

    pub fn get_function_attribute(&self) -> FunctionAttr {
        let attr_name = StringBacked::from(FunctionAttr::get_name());
        let attr = self
            .as_operation()
            .get_attribute_inherent(&attr_name.as_string_ref());
        FunctionAttr::from(*attr.get())
    }

    pub fn get_function_type(&self) -> FunctionType {
        self.get_function_attribute().get_function()
    }

    pub fn get_symbol_name(&self) -> SymbolName {
        let attr_name = StringBacked::from(SymbolName::get_name());
        let attr = self
            .as_operation()
            .get_attribute_inherent(&attr_name.as_string_ref());
        SymbolName::from(*attr.get())
    }

    pub fn get_symbol_ref(&self) -> SymbolRef {
        SymbolRef::new_flat(
            &self.get_context(),
            &self.get_symbol_name().as_string().get_string(),
        )
    }

    pub fn get_result_attributes(&self) -> Option<Results> {
        let op = self.as_operation();
        let attr_name = StringBacked::from(Results::get_name());
        let s_ref = attr_name.as_string_ref();
        if op.has_attribute_inherent(&s_ref) {
            let attr = op.get_attribute_inherent(&s_ref);
            Some(Results::from(*attr.get()))
        } else {
            None
        }
    }

    pub fn get_visibility(&self) -> Option<SymbolVisibility> {
        let op = self.as_operation();
        let attr_name = StringBacked::from(SymbolVisibility::get_name());
        let s_ref = attr_name.as_string_ref();
        if op.has_attribute_inherent(&s_ref) {
            let attr = op.get_attribute_inherent(&s_ref);
            Some(SymbolVisibility::from(*attr.get()))
        } else {
            None
        }
    }
}

impl Return {
    pub fn new(parent: &Func, args: &[Value], loc: &Location) -> Self {
        let t_f = parent.get_function_type();
        let num_results = t_f.num_results() as usize;
        let symbol_ref = parent.get_symbol_ref();
        if num_results != args.len() {
            eprintln!(
                "Expected '{}' results for func.func '@{}'",
                num_results, symbol_ref
            );
            exit(ExitCode::DialectError);
        }
        for i in 0..num_results {
            let t = t_f.get_result(i as isize);
            if t != args.get(i).unwrap().get_type() {
                eprintln!(
                    "Expected matching type for func.func '@{}' result at position '{}'",
                    symbol_ref, i,
                );
                exit(ExitCode::DialectError);
            }
        }
        let context = parent.get_context();
        let dialect = context.get_dialect_func();
        let name = dialect.get_op_name(&Op::Return);
        let mut op_state = OperationState::new(&name.as_string_ref(), loc);
        op_state.add_operands(args);
        Self::from(*op_state.create_operation().get(), symbol_ref)
    }

    pub fn from(op: MlirOperation, parent: SymbolRef) -> Self {
        Return(op, parent)
    }

    pub fn get(&self) -> &MlirOperation {
        &self.0
    }

    pub fn get_mut(&mut self) -> &mut MlirOperation {
        &mut self.0
    }

    pub fn get_parent(&self) -> &SymbolRef {
        &self.1
    }
}

///////////////////////////////
//  Trait Implementation
///////////////////////////////

SpecializedAttribute!("arg_attrs" = impl NamedArrayOfDictionaries for Arguments {});

impl IOperation for Call {
    fn get(&self) -> &MlirOperation {
        self.get()
    }

    fn get_dialect(&self) -> Dialect {
        self.as_operation().get_context().get_dialect_func()
    }

    fn get_effects(&self) -> MemoryEffectList {
        &[MEFF_NO_MEMORY_EFFECT]
    }

    fn get_interfaces(&self) -> &'static [Interface] {
        &[Interface::CallOpInterface, Interface::SymbolUserOpInterface]
    }

    fn get_mut(&mut self) -> &mut MlirOperation {
        self.get_mut()
    }

    fn get_name(&self) -> &'static str {
        Op::Call.get_name()
    }

    fn get_op(&self) -> OpRef {
        &Op::Call
    }

    fn get_traits(&self) -> &'static [Trait] {
        &[Trait::MemRefsNormalizable]
    }
}

SpecializedAttribute!("callee" = impl NamedSymbolRef for Callee {});

impl IOperation for CallIndirect {
    fn get(&self) -> &MlirOperation {
        self.get()
    }

    fn get_dialect(&self) -> Dialect {
        self.as_operation().get_context().get_dialect_func()
    }

    fn get_effects(&self) -> MemoryEffectList {
        &[MEFF_NO_MEMORY_EFFECT]
    }

    fn get_interfaces(&self) -> &'static [Interface] {
        &[Interface::CallOpInterface]
    }

    fn get_mut(&mut self) -> &mut MlirOperation {
        self.get_mut()
    }

    fn get_name(&self) -> &'static str {
        Op::CallIndirect.get_name()
    }

    fn get_op(&self) -> OpRef {
        &Op::CallIndirect
    }

    fn get_traits(&self) -> &'static [Trait] {
        &[]
    }
}

impl IOperation for Constant {
    fn get(&self) -> &MlirOperation {
        self.get()
    }

    fn get_dialect(&self) -> Dialect {
        self.as_operation().get_context().get_dialect_func()
    }

    fn get_effects(&self) -> MemoryEffectList {
        &[MEFF_NO_MEMORY_EFFECT]
    }

    fn get_interfaces(&self) -> &'static [Interface] {
        &[
            Interface::ConditionallySpeculatable,
            Interface::MemoryEffect(MemoryEffectOpInterface::NoMemoryEffect),
            Interface::OpAsmOpInterface,
            Interface::SymbolUserOpInterface,
        ]
    }

    fn get_mut(&mut self) -> &mut MlirOperation {
        self.get_mut()
    }

    fn get_name(&self) -> &'static str {
        Op::Constant.get_name()
    }

    fn get_op(&self) -> OpRef {
        &Op::Constant
    }

    fn get_traits(&self) -> &'static [Trait] {
        &[Trait::AlwaysSpeculatableImplTrait, Trait::ConstantLike]
    }
}

impl IOperation for Func {
    fn get(&self) -> &MlirOperation {
        self.get()
    }

    fn get_dialect(&self) -> Dialect {
        self.as_operation().get_context().get_dialect_func()
    }

    fn get_effects(&self) -> MemoryEffectList {
        &[MEFF_NO_MEMORY_EFFECT]
    }

    fn get_interfaces(&self) -> &'static [Interface] {
        &[
            Interface::CallableOpInterface,
            Interface::FunctionOpInterface,
            Interface::OpAsmOpInterface,
            Interface::Symbol,
        ]
    }

    fn get_mut(&mut self) -> &mut MlirOperation {
        self.get_mut()
    }

    fn get_name(&self) -> &'static str {
        Op::Func.get_name()
    }

    fn get_op(&self) -> OpRef {
        &Op::Func
    }

    fn get_traits(&self) -> &'static [Trait] {
        &[
            Trait::AffineScope,
            Trait::AutomaticAllocationScope,
            Trait::IsolatedFromAbove,
        ]
    }
}

SpecializedAttribute!("function_type" = impl NamedFunction for FunctionAttr {});

impl IOp for Op {
    fn get_name(&self) -> &'static str {
        self.get_name()
    }
}

SpecializedAttribute!("value" = impl NamedSymbolRef for Referee {});

SpecializedAttribute!("res_attrs" = impl NamedArrayOfDictionaries for Results {});

impl IOperation for Return {
    fn get(&self) -> &MlirOperation {
        self.get()
    }

    fn get_dialect(&self) -> Dialect {
        self.as_operation().get_context().get_dialect_func()
    }

    fn get_effects(&self) -> MemoryEffectList {
        &[MEFF_NO_MEMORY_EFFECT]
    }

    fn get_interfaces(&self) -> &'static [Interface] {
        &[
            Interface::ConditionallySpeculatable,
            Interface::MemoryEffect(MemoryEffectOpInterface::NoMemoryEffect),
            Interface::RegionBranchTerminatorOpInterface,
        ]
    }

    fn get_mut(&mut self) -> &mut MlirOperation {
        self.get_mut()
    }

    fn get_name(&self) -> &'static str {
        Op::Return.get_name()
    }

    fn get_op(&self) -> OpRef {
        &Op::Return
    }

    fn get_traits(&self) -> &'static [Trait] {
        &[
            Trait::AlwaysSpeculatableImplTrait,
            Trait::HasParent(&[&Op::Func]),
            Trait::MemRefsNormalizable,
            Trait::ReturnLike,
            Trait::Terminator,
        ]
    }
}

impl cmp::PartialEq for Return {
    fn eq(&self, rhs: &Self) -> bool {
        self.as_operation() == rhs.as_operation() && self.get_parent() == rhs.get_parent()
    }
}

///////////////////////////////
//  Display
///////////////////////////////

impl fmt::Display for Op {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", match self {
            Op::CallIndirect => "CallIndirectOp",
            Op::Call => "CallOp",
            Op::Constant => "ConstantOp",
            Op::Func => "FuncOp",
            Op::Return => "ReturnOp",
        })
    }
}