pliron-llvm 0.18.0

LLVM dialect for pliron
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
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) The pliron contributors

//! [Op] Interfaces defined in the LLVM dialect.

use alloc::{
    string::{String, ToString},
    vec,
};

use pliron::{
    builtin::{
        attributes::BoolAttr,
        op_interfaces::{
            NOpdsInterface, OneOpdInterface, ResultNOfType, SymbolOpInterface,
            verify_get_operand_n, verify_get_result_n,
        },
        type_interfaces::FloatTypeInterface,
    },
    derive::op_interface,
    dict_key,
    printable::Printable,
    r#type::{Type, TypeInterfaceHandle, TypeInterfaceMarker, TypedHandle, type_impls},
    utils::const_bound_n::I,
};
use thiserror::Error;

use pliron::{
    builtin::{
        op_interfaces::{OneResultInterface, SameOperandsAndResultType},
        types::{IntegerType, Signedness},
    },
    context::Context,
    location::{Located, Location},
    op::{Op, op_cast},
    operation::Operation,
    result::Result,
    r#type::{TypeHandle, Typed},
    value::Value,
    verify_err,
};

use crate::{
    attributes::{AlignmentAttr, FastmathFlagsAttr, SyncScopeAttr},
    types::{VectorType, VectorTypeKind},
};

use super::{attributes::IntegerOverflowFlagsAttr, types::PointerType};

/// Binary arithmetic [Op].
#[op_interface]
pub trait BinArithOp: SameOperandsAndResultType + OneResultInterface + NOpdsInterface<2> {
    /// Create a new binary arithmetic operation given the operands.
    fn new(ctx: &mut Context, lhs: Value, rhs: Value) -> Self
    where
        Self: Sized,
    {
        let op = Operation::new(
            ctx,
            Self::get_concrete_op_info(),
            vec![lhs.get_type(ctx)],
            vec![lhs, rhs],
            vec![],
            0,
        );
        Self::from_operation(op)
    }

    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }

    /// Get the left-hand side operand of this binary arithmetic [Op].
    fn lhs(&self, ctx: &Context) -> Value
    where
        Self: Sized,
    {
        self.get_operand_i(ctx, I::<0>.into())
    }

    /// Get the right-hand side operand of this binary arithmetic [Op].
    fn rhs(&self, ctx: &Context) -> Value
    where
        Self: Sized,
    {
        self.get_operand_i(ctx, I::<1>.into())
    }
}

#[derive(Error, Debug)]
#[error("Integer binary arithmetic Op can only have signless integer result/operand type")]
pub struct IntBinArithOpErr;

/// Integer binary arithmetic [Op]
#[op_interface]
pub trait IntBinArithOp: BinArithOp + ScalarOrVectorOpd<IntegerType, 0> {
    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let int_ty = op_cast::<dyn ScalarOrVectorOpd<IntegerType, 0>>(op)
            .expect("Op must impl ScalarOrVectorOpd<IntegerType, 0>")
            .scalar_or_vector_elem_ty(ctx);
        let int_ty = int_ty.deref(ctx);
        if int_ty.signedness() != Signedness::Signless {
            return verify_err!(op.loc(ctx), IntBinArithOpErr);
        }

        Ok(())
    }
}

dict_key!(
    /// Attribute key for integer overflow flags.
    ATTR_KEY_INTEGER_OVERFLOW_FLAGS,
    "llvm_integer_overflow_flags"
);

#[derive(Error, Debug)]
#[error("IntegerOverflowFlag missing on Op")]
pub struct IntBinArithOpWithOverflowFlagErr;

/// Integer binary arithmetic [Op] with [IntegerOverflowFlagsAttr]
#[op_interface]
pub trait IntBinArithOpWithOverflowFlag: IntBinArithOp {
    /// Create a new integer binary op with overflow flags set.
    fn new_with_overflow_flag(
        ctx: &mut Context,
        lhs: Value,
        rhs: Value,
        flag: IntegerOverflowFlagsAttr,
    ) -> Self
    where
        Self: Sized,
    {
        let op = Self::new(ctx, lhs, rhs);
        op.set_integer_overflow_flag(ctx, flag);
        op
    }

    /// Get the integer overflow flag on this [Op].
    fn integer_overflow_flag(&self, ctx: &Context) -> IntegerOverflowFlagsAttr
    where
        Self: Sized,
    {
        self.get_operation()
            .deref(ctx)
            .attributes
            .get::<IntegerOverflowFlagsAttr>(&ATTR_KEY_INTEGER_OVERFLOW_FLAGS)
            .expect("Integer overflow flag missing or is of incorrect type")
            .clone()
    }

    /// Set the integer overflow flag for this [Op].
    fn set_integer_overflow_flag(&self, ctx: &Context, flag: IntegerOverflowFlagsAttr)
    where
        Self: Sized,
    {
        self.get_operation()
            .deref_mut(ctx)
            .attributes
            .set(ATTR_KEY_INTEGER_OVERFLOW_FLAGS.clone(), flag);
    }

    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let op = op.get_operation().deref(ctx);
        if op
            .attributes
            .get::<IntegerOverflowFlagsAttr>(&ATTR_KEY_INTEGER_OVERFLOW_FLAGS)
            .is_none()
        {
            return verify_err!(op.loc(), IntBinArithOpWithOverflowFlagErr);
        }

        Ok(())
    }
}

/// Floating point binary arithmetic [Op]
#[op_interface]
pub trait FloatBinArithOp: BinArithOp + ScalarOrVectorOpdImpls<dyn FloatTypeInterface, 0> {
    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }
}

dict_key!(
    /// Attribute key for fastmath flags.
    ATTR_KEY_FAST_MATH_FLAGS,
    "llvm_fast_math_flags"
);

#[derive(Error, Debug)]
#[error("Fastmath flag missing on Op")]
pub struct FastMathFlagMissingErr;

/// Ops that have fast math flags.
#[op_interface]
pub trait FastMathFlags {
    /// Get the fast math flags on this [Op].
    fn fast_math_flags(&self, ctx: &Context) -> FastmathFlagsAttr
    where
        Self: Sized,
    {
        *self
            .get_operation()
            .deref(ctx)
            .attributes
            .get::<FastmathFlagsAttr>(&ATTR_KEY_FAST_MATH_FLAGS)
            .expect("Fast math flags missing or is of incorrect type")
    }

    /// Set the fast math flags for this [Op].
    fn set_fast_math_flags(&self, ctx: &Context, flag: FastmathFlagsAttr)
    where
        Self: Sized,
    {
        self.get_operation()
            .deref_mut(ctx)
            .attributes
            .set(ATTR_KEY_FAST_MATH_FLAGS.clone(), flag);
    }

    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let op = op.get_operation().deref(ctx);
        if op
            .attributes
            .get::<FastmathFlagsAttr>(&ATTR_KEY_FAST_MATH_FLAGS)
            .is_none()
        {
            return verify_err!(op.loc(), FastmathFlagMissingErr);
        }

        Ok(())
    }
}

dict_key!(
    /// Attribute key for the synchronization scope of an atomic [Op].
    ATTR_KEY_SYNC_SCOPE,
    "llvm_syncscope"
);

#[derive(Error, Debug)]
#[error("Synchronization scope missing on Op")]
pub struct SyncScopeMissingErr;

/// Atomic [Op]s that have a synchronization scope.
#[op_interface]
pub trait SyncScopeInterface {
    /// Get the synchronization scope of this [Op].
    fn syncscope(&self, ctx: &Context) -> SyncScopeAttr
    where
        Self: Sized,
    {
        self.get_operation()
            .deref(ctx)
            .attributes
            .get::<SyncScopeAttr>(&ATTR_KEY_SYNC_SCOPE)
            .expect("Synchronization scope missing or is of incorrect type")
            .clone()
    }

    /// Set the synchronization scope of this [Op].
    fn set_syncscope(&self, ctx: &Context, syncscope: SyncScopeAttr)
    where
        Self: Sized,
    {
        self.get_operation()
            .deref_mut(ctx)
            .attributes
            .set(ATTR_KEY_SYNC_SCOPE.clone(), syncscope);
    }

    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let op = op.get_operation().deref(ctx);
        if op
            .attributes
            .get::<SyncScopeAttr>(&ATTR_KEY_SYNC_SCOPE)
            .is_none()
        {
            return verify_err!(op.loc(), SyncScopeMissingErr);
        }

        Ok(())
    }
}

/// Floating point binary arithmetic [Op] with [FastmathFlagsAttr]
#[op_interface]
pub trait FloatBinArithOpWithFastMathFlags: FloatBinArithOp + FastMathFlags {
    /// Create a new floating point binary op with fast math flags set.
    fn new_with_fast_math_flags(
        ctx: &mut Context,
        lhs: Value,
        rhs: Value,
        flag: FastmathFlagsAttr,
    ) -> Self
    where
        Self: Sized,
    {
        let op = Self::new(ctx, lhs, rhs);
        op.set_fast_math_flags(ctx, flag);
        op
    }

    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }
}

#[derive(Error, Debug)]
#[error("Fastmath flag missing on Op")]
pub struct FastmathFlagMissingErr;

dict_key!(
    /// Attribute key for nneg flag.
    ATTR_KEY_NNEG_FLAG,
    "llvm_nneg_flag"
);

#[op_interface]
pub trait NNegFlag {
    // Get the current NNEG flag value.
    fn nneg(&self, ctx: &Context) -> bool {
        self.get_operation()
            .deref(ctx)
            .attributes
            .get::<BoolAttr>(&ATTR_KEY_NNEG_FLAG)
            .expect("NNEG flag missing or is of incorrect type")
            .clone()
            .into()
    }
    // Set the current NNEG flag value.
    fn set_nneg(&self, ctx: &Context, flag: bool) {
        self.get_operation()
            .deref_mut(ctx)
            .attributes
            .set(ATTR_KEY_NNEG_FLAG.clone(), BoolAttr::new(flag));
    }
    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let op = op.get_operation().deref(ctx);
        if op.attributes.get::<BoolAttr>(&ATTR_KEY_NNEG_FLAG).is_none() {
            return verify_err!(op.loc(), NNegFlagMissingErr);
        }

        Ok(())
    }
}

#[derive(Error, Debug)]
#[error("NNEG flag missing on Op")]
pub struct NNegFlagMissingErr;

#[derive(Error, Debug)]
#[error("Result must be a pointer type, but is not")]
pub struct PointerTypeResultVerifyErr;

/// An [Op] with a single result whose type is [PointerType]
#[op_interface]
pub trait PointerTypeResult: OneResultInterface + ResultNOfType<0, PointerType> {
    /// Get the pointee type of the result pointer.
    fn result_pointee_type(&self, ctx: &Context) -> TypeHandle;

    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        if !op_cast::<dyn OneResultInterface>(op)
            .expect("An Op here must impl OneResultInterface")
            .result_type(ctx)
            .deref(ctx)
            .is::<PointerType>()
        {
            return verify_err!(op.loc(ctx), PointerTypeResultVerifyErr);
        }

        Ok(())
    }
}

/// A Cast [Op] has one argument and one result.
#[op_interface]
pub trait CastOpInterface: OneResultInterface + OneOpdInterface {
    /// Create a new cast operation given the operand.
    fn new(ctx: &mut Context, operand: Value, res_type: TypeHandle) -> Self
    where
        Self: Sized,
    {
        let op = Operation::new(
            ctx,
            Self::get_concrete_op_info(),
            vec![res_type],
            vec![operand],
            vec![],
            0,
        );
        Self::from_operation(op)
    }

    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }
}

/// A Cast [Op] with NNEG flag.
#[op_interface]
pub trait CastOpWithNNegInterface: CastOpInterface + NNegFlag {
    /// Create a new cast operation with nneg flag
    fn new_with_nneg(ctx: &mut Context, operand: Value, res_type: TypeHandle, nneg: bool) -> Self
    where
        Self: Sized,
    {
        let op = Self::new(ctx, operand, res_type);
        op.set_nneg(ctx, nneg);
        op
    }

    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }
}

/// Is a global value (variable or function) declaration.
#[op_interface]
pub trait IsDeclaration {
    /// Check if this global value (variable or function) is a declaration.
    fn is_declaration(&self, ctx: &Context) -> bool
    where
        Self: Sized;

    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }
}

dict_key!(
    /// Attribute key for LLVM symbol name.
    ATTR_KEY_LLVM_SYMBOL_NAME,
    "llvm_symbol_name"
);

/// Since LLVM symbols can have characters that are illegal in pliron,
/// this interface provides a way to get the original LLVM symbol name.
#[op_interface]
pub trait LlvmSymbolName: SymbolOpInterface {
    /// Get the original LLVM symbol name, if it's different from the pliron symbol name.
    fn llvm_symbol_name(&self, ctx: &Context) -> Option<String> {
        self.get_operation()
            .deref(ctx)
            .attributes
            .get::<pliron::builtin::attributes::StringAttr>(&ATTR_KEY_LLVM_SYMBOL_NAME)
            .map(|attr| attr.clone().into())
    }

    /// Set the original LLVM symbol name.
    fn set_llvm_symbol_name(&self, ctx: &Context, name: String) {
        self.get_operation().deref_mut(ctx).attributes.set(
            ATTR_KEY_LLVM_SYMBOL_NAME.clone(),
            pliron::builtin::attributes::StringAttr::new(name),
        );
    }

    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }
}

dict_key!(
    /// Attribute key for alignment.
    ATTR_KEY_LLVM_ALIGNMENT,
    "llvm_alignment"
);

/// Ops that can have an alignment set.
#[op_interface]
pub trait AlignableOpInterface {
    /// Get the alignment of this [Op], if set.
    fn alignment(&self, ctx: &Context) -> Option<u32>
    where
        Self: Sized,
    {
        self.get_operation()
            .deref(ctx)
            .attributes
            .get::<AlignmentAttr>(&ATTR_KEY_LLVM_ALIGNMENT)
            .map(|attr| attr.0)
    }

    /// Set the alignment of this [Op].
    fn set_alignment(&self, ctx: &Context, alignment: u32)
    where
        Self: Sized,
    {
        self.get_operation()
            .deref_mut(ctx)
            .attributes
            .set(ATTR_KEY_LLVM_ALIGNMENT.clone(), AlignmentAttr(alignment));
    }

    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }
}

dict_key!(
    /// Attribute key for volatile memory operations.
    ATTR_KEY_LLVM_VOLATILE,
    "llvm_volatile"
);

/// Ops that can be marked volatile.
#[op_interface]
pub trait VolatilityOpInterface {
    /// Return whether this [Op] is volatile.
    fn is_volatile(&self, ctx: &Context) -> bool
    where
        Self: Sized,
    {
        self.get_operation()
            .deref(ctx)
            .attributes
            .get::<BoolAttr>(&ATTR_KEY_LLVM_VOLATILE)
            .map(|attr| attr.clone().into())
            .unwrap_or(false)
    }

    /// Set whether this [Op] is volatile.
    fn set_volatile(&self, ctx: &Context, is_volatile: bool)
    where
        Self: Sized,
    {
        self.get_operation()
            .deref_mut(ctx)
            .attributes
            .set(ATTR_KEY_LLVM_VOLATILE.clone(), BoolAttr::new(is_volatile));
    }

    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }
}

#[derive(Debug, Error)]
pub enum ScalarOrVectorErr {
    #[error("{0} is not {1} or a vector of it")]
    NotTOrVectorOfT(String, String),
    #[error("{0} or its vector element type does not implement interface")]
    TyOrElemNotImplsI(String),
}

/// Get the vector shape of `ty`, or `None` if it is not a [VectorType].
fn vector_shape_of(ty: TypeHandle, ctx: &Context) -> Option<(u32, VectorTypeKind)> {
    ty.deref(ctx)
        .downcast_ref::<VectorType>()
        .map(|vec_ty| (vec_ty.num_elements(), vec_ty.kind()))
}

/// Get `ty`, or its element type if it is a [VectorType], typed as `T`.
///
/// Only valid to call once `verify_t_or_vec_of_t::<T>` has passed for `ty`.
fn elem_ty_of<T: Type>(ty: TypeHandle, ctx: &Context) -> TypedHandle<T> {
    if let Ok(typed_handle) = TypedHandle::from_handle(ty, ctx) {
        return typed_handle;
    }
    let ty_ref = &*ty.deref(ctx);
    let elem_ty = ty_ref
        .downcast_ref::<VectorType>()
        .expect("verify() guarantees type is T or a vector of T")
        .elem_type();
    TypedHandle::from_handle(elem_ty, ctx).expect("verify() guarantees element type is T")
}

/// Verify that `ty` is `T`, or a [VectorType] of `T`.
fn verify_t_or_vec_of_t<T: Type>(loc: Location, ty: &dyn Type, ctx: &Context) -> Result<()> {
    if ty.is::<T>() {
        // ty is equal to `T`, we're good.
        return Ok(());
    }
    // See if `ty` is a vector of `T`.
    let Some(vec_ty) = ty.downcast_ref::<VectorType>() else {
        return verify_err!(
            loc,
            ScalarOrVectorErr::NotTOrVectorOfT(
                ty.get_type_id().disp(ctx).to_string(),
                T::get_type_id_static().disp(ctx).to_string()
            )
        );
    };
    let elem_ty = &*vec_ty.elem_type().deref(ctx);
    if !elem_ty.is::<T>() {
        return verify_err!(
            loc,
            ScalarOrVectorErr::NotTOrVectorOfT(
                ty.get_type_id().disp(ctx).to_string(),
                T::get_type_id_static().disp(ctx).to_string()
            )
        );
    }
    Ok(())
}

/// Get `ty`, or its element type if it is a [VectorType], whichever implements `I`.
///
/// Only valid to call once `verify_impls_i_or_vec_of_impls_i::<I>` has passed for `ty`.
fn elem_ty_of_impls<I: ?Sized + TypeInterfaceMarker + 'static>(
    ty: TypeHandle,
    ctx: &Context,
) -> TypeInterfaceHandle<I> {
    if let Ok(interface_handle) = TypeInterfaceHandle::from_handle(ty, ctx) {
        return interface_handle;
    }
    let ty_ref = &*ty.deref(ctx);
    let elem_ty = ty_ref
        .downcast_ref::<VectorType>()
        .expect("verify() guarantees type impls I or is a vector whose elem impls I")
        .elem_type();
    TypeInterfaceHandle::from_handle(elem_ty, ctx)
        .expect("verify() guarantees element type impls I")
}

/// Verify that `ty` implements `I`, or is a [VectorType] whose element type implements `I`.
fn verify_impls_i_or_vec_of_impls_i<I: ?Sized + TypeInterfaceMarker + 'static>(
    loc: Location,
    ty: &dyn Type,
    ctx: &Context,
) -> Result<()> {
    if type_impls::<I>(ty) {
        // ty implements `I`, we're good.
        return Ok(());
    }
    // See if `ty` is a vector whose element type implements `I`.
    let Some(vec_ty) = ty.downcast_ref::<VectorType>() else {
        return verify_err!(
            loc,
            ScalarOrVectorErr::TyOrElemNotImplsI(ty.get_type_id().disp(ctx).to_string())
        );
    };
    let elem_ty = &*vec_ty.elem_type().deref(ctx);
    if !type_impls::<I>(elem_ty) {
        return verify_err!(
            loc,
            ScalarOrVectorErr::TyOrElemNotImplsI(ty.get_type_id().disp(ctx).to_string())
        );
    }
    Ok(())
}

/// An operand whose type is either `T` or [`VectorType<T>`](VectorType).
#[op_interface]
pub trait ScalarOrVectorOpd<T: Type, const N: usize> {
    /// Get the type of operand N, or its element type if its [VectorType].
    fn scalar_or_vector_elem_ty(&self, ctx: &Context) -> TypedHandle<T> {
        let op = &*self.get_operation().deref(ctx);
        elem_ty_of(op.get_operand(N).get_type(ctx), ctx)
    }

    /// Get the vector shape of operand N, or `None` if it is not a [VectorType].
    fn vector_shape(&self, ctx: &Context) -> Option<(u32, VectorTypeKind)> {
        let op = &*self.get_operation().deref(ctx);
        vector_shape_of(op.get_operand(N).get_type(ctx), ctx)
    }

    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let opd = verify_get_operand_n::<N>(op.get_operation(), ctx)?;
        verify_t_or_vec_of_t::<T>(op.loc(ctx), &*opd.get_type(ctx).deref(ctx), ctx)
    }
}

/// An operand whose type either impls `I` or is [`VectorType<T: I>`](VectorType).
#[op_interface]
pub trait ScalarOrVectorOpdImpls<I: ?Sized + TypeInterfaceMarker + 'static, const N: usize> {
    /// Get the type of operand N, or its element type if its [VectorType].
    fn scalar_or_vector_elem_ty(&self, ctx: &Context) -> TypeInterfaceHandle<I> {
        let op = &*self.get_operation().deref(ctx);
        elem_ty_of_impls::<I>(op.get_operand(N).get_type(ctx), ctx)
    }

    /// Get the vector shape of operand N, or `None` if it is not a [VectorType].
    fn vector_shape(&self, ctx: &Context) -> Option<(u32, VectorTypeKind)> {
        let op = &*self.get_operation().deref(ctx);
        vector_shape_of(op.get_operand(N).get_type(ctx), ctx)
    }

    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let opd = verify_get_operand_n::<N>(op.get_operation(), ctx)?;
        verify_impls_i_or_vec_of_impls_i::<I>(op.loc(ctx), &*opd.get_type(ctx).deref(ctx), ctx)
    }
}

/// A result whose type is either `T` or [`VectorType<T>`](VectorType).
#[op_interface]
pub trait ScalarOrVectorRes<T: Type, const N: usize> {
    /// Get the type of result N, or its element type if its [VectorType].
    fn scalar_or_vector_elem_ty(&self, ctx: &Context) -> TypedHandle<T> {
        let op = &*self.get_operation().deref(ctx);
        elem_ty_of(op.get_result(N).get_type(ctx), ctx)
    }

    /// Get the vector shape of result N, or `None` if it is not a [VectorType].
    fn vector_shape(&self, ctx: &Context) -> Option<(u32, VectorTypeKind)> {
        let op = &*self.get_operation().deref(ctx);
        vector_shape_of(op.get_result(N).get_type(ctx), ctx)
    }

    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let res = verify_get_result_n::<N>(op.get_operation(), ctx)?;
        verify_t_or_vec_of_t::<T>(op.loc(ctx), &*res.get_type(ctx).deref(ctx), ctx)
    }
}

/// A result whose type either impls `I` or is [`VectorType<T: I>`](VectorType).
#[op_interface]
pub trait ScalarOrVectorResImpls<I: ?Sized + TypeInterfaceMarker + 'static, const N: usize> {
    /// Get the type of result N, or its element type if its [VectorType].
    fn scalar_or_vector_elem_ty(&self, ctx: &Context) -> TypeInterfaceHandle<I> {
        let op = &*self.get_operation().deref(ctx);
        elem_ty_of_impls::<I>(op.get_result(N).get_type(ctx), ctx)
    }

    /// Get the vector shape of result N, or `None` if it is not a [VectorType].
    fn vector_shape(&self, ctx: &Context) -> Option<(u32, VectorTypeKind)> {
        let op = &*self.get_operation().deref(ctx);
        vector_shape_of(op.get_result(N).get_type(ctx), ctx)
    }

    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let res = verify_get_result_n::<N>(op.get_operation(), ctx)?;
        verify_impls_i_or_vec_of_impls_i::<I>(op.loc(ctx), &*res.get_type(ctx).deref(ctx), ctx)
    }
}