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
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
//! [Op]s defined in the LLVM dialect

use pliron::{
    arg_err_noloc,
    basic_block::BasicBlock,
    builtin::{
        attr_interfaces::TypedAttrInterface,
        attributes::TypeAttr,
        op_interfaces::{
            BranchOpInterface, IsTerminatorInterface, OneOpdInterface, OneResultInterface,
            SameOperandsAndResultType, SameOperandsType, SameResultsType, ZeroResultInterface,
            ZeroResultVerifyErr,
        },
        types::{IntegerType, Signedness},
    },
    common_traits::Verify,
    context::{Context, Ptr},
    dialect::Dialect,
    error::{Error, ErrorKind, Result},
    identifier::Identifier,
    impl_canonical_syntax, impl_op_interface, impl_verify_succ, input_err,
    irfmt::parsers::ssa_opd_parser,
    location::{Located, Location},
    op::{Op, OpObj},
    operation::Operation,
    parsable::{self, Parsable, ParseResult},
    printable::{self, Printable},
    r#type::{TypeObj, TypePtr},
    use_def_lists::Value,
    vec_exns::VecExtns,
    verify_err,
};

use crate::{
    op_interfaces::{BinArithOp, IntBinArithOp, IntBinArithOpWithOverflowFlag, PointerTypeResult},
    types::{ArrayType, StructType},
};

use combine::parser::Parser;
use pliron_derive::def_op;
use thiserror::Error;

use super::{
    attributes::{GepIndexAttr, GepIndicesAttr, ICmpPredicateAttr},
    types::PointerType,
};

/// Equivalent to LLVM's return opcode.
///
/// Operands:
///
/// | operand | description |
/// |-----|-------|
/// | `arg` | any type |
#[def_op("llvm.return")]
pub struct ReturnOp {}

impl ReturnOp {
    pub fn new(ctx: &mut Context, value: Value) -> Self {
        let op = Operation::new(ctx, Self::get_opid_static(), vec![], vec![value], vec![], 0);
        ReturnOp { op }
    }
}

impl Printable for ReturnOp {
    fn fmt(
        &self,
        ctx: &Context,
        _state: &printable::State,
        f: &mut core::fmt::Formatter<'_>,
    ) -> core::fmt::Result {
        write!(
            f,
            "{} {}",
            self.get_opid().disp(ctx),
            self.get_operation()
                .deref(ctx)
                .get_operand(0)
                .unwrap()
                .disp(ctx)
        )
    }
}

impl_verify_succ!(ReturnOp);

impl Parsable for ReturnOp {
    type Arg = Vec<(Identifier, Location)>;
    type Parsed = OpObj;
    fn parse<'a>(
        state_stream: &mut parsable::StateStream<'a>,
        results: Self::Arg,
    ) -> ParseResult<'a, Self::Parsed> {
        if !results.is_empty() {
            input_err!(
                state_stream.loc(),
                ZeroResultVerifyErr(Self::get_opid_static().to_string())
            )?
        }

        ssa_opd_parser()
            .parse_stream(state_stream)
            .map(|opd| -> OpObj { Box::new(Self::new(state_stream.state.ctx, opd)) })
            .into()
    }
}

impl_op_interface!(IsTerminatorInterface for ReturnOp {});

macro_rules! new_int_bin_op {
    (   $(#[$outer:meta])*
        $op_name:ident, $op_id:literal
    ) => {
        #[def_op($op_id)]
        $(#[$outer])*
        /// ### Operands:
        ///
        /// | operand | description |
        /// |-----|-------|
        /// | `lhs` | Signless integer |
        /// | `rhs` | Signless integer |
        ///
        /// ### Result(s):
        ///
        /// | result | description |
        /// |-----|-------|
        /// | `res` | Signless integer |
        pub struct $op_name {}

        impl_verify_succ!($op_name);
        impl_canonical_syntax!($op_name);
        impl_op_interface!(OneResultInterface for $op_name {});
        impl_op_interface!(SameOperandsType for $op_name {});
        impl_op_interface!(SameResultsType for $op_name {});
        impl_op_interface!(SameOperandsAndResultType for $op_name {});
        impl_op_interface!(BinArithOp for $op_name {});
        impl_op_interface!(IntBinArithOp for $op_name {});
    }
}

macro_rules! new_int_bin_op_with_overflow {
    (   $(#[$outer:meta])*
        $op_name:ident, $op_id:literal
    ) => {
        new_int_bin_op!(
            $(#[$outer])*
            /// ### Attributes:
            ///
            /// | key | value | via Interface |
            /// |-----|-------| --------------
            /// | [ATTR_KEY_INTEGER_OVERFLOW_FLAGS](super::op_interfaces::ATTR_KEY_INTEGER_OVERFLOW_FLAGS) | [StringAttr](pliron::builtin::attributes::StringAttr) | [IntBinArithOpWithOverflowFlag] |
            $op_name,
            $op_id
        );
        impl_op_interface!(IntBinArithOpWithOverflowFlag for $op_name {});
    }
}
new_int_bin_op_with_overflow!(
    /// Equivalent to LLVM's Add opcode.
    AddOp,
    "llvm.add"
);

new_int_bin_op_with_overflow!(
    /// Equivalent to LLVM's Sub opcode.
    SubOp,
    "llvm.sub"
);

new_int_bin_op_with_overflow!(
    /// Equivalent to LLVM's Mul opcode.
    MulOp,
    "llvm.mul"
);

new_int_bin_op_with_overflow!(
    /// Equivalent to LLVM's Shl opcode.
    ShlOp,
    "llvm.shl"
);

new_int_bin_op!(
    /// Equivalent to LLVM's UDiv opcode.
    UDivOp,
    "llvm.udiv"
);

new_int_bin_op!(
    /// Equivalent to LLVM's SDiv opcode.
    SDivOp,
    "llvm.sdiv"
);

new_int_bin_op!(
    /// Equivalent to LLVM's URem opcode.
    URemOp,
    "llvm.urem"
);

new_int_bin_op!(
    /// Equivalent to LLVM's SRem opcode.
    SRemOp,
    "llvm.srem"
);

new_int_bin_op!(
    /// Equivalent to LLVM's And opcode.
    AndOp,
    "llvm.and"
);

new_int_bin_op!(
    /// Equivalent to LLVM's Or opcode.
    OrOp,
    "llvm.or"
);

new_int_bin_op!(
    /// Equivalent to LLVM's Xor opcode.
    XorOp,
    "llvm.xor"
);

new_int_bin_op!(
    /// Equivalent to LLVM's LShr opcode.
    LShrOp,
    "llvm.lshr"
);

new_int_bin_op!(
    /// Equivalent to LLVM's AShr opcode.
    AShrOp,
    "llvm.ashr"
);

#[derive(Error, Debug)]
pub enum ICmpOpVerifyErr {
    #[error("Result must be 1-bit integer (bool)")]
    ResultNotBool,
    #[error("Operand must be integer or pointer types")]
    IncorrectOperandsType,
    #[error("Missing or incorrect predicate attribute")]
    PredAttrErr,
}

/// Equivalent to LLVM's ICmp opcode.
/// ### Operands
/// | operand | description |
/// |-----|-------|
/// | `lhs` | Signless integer or pointer |
/// | `rhs` | Signless integer or pointer |
///
/// ### Result(s):
///
/// | result | description |
/// |-----|-------|
/// | `res` | 1-bit signless integer |
/// ### Attributes:
///
/// | key | value | via Interface |
/// |-----|-------| --------------|
/// | [ATTR_KEY_PREDICATE](ICmpOp::ATTR_KEY_PREDICATE) | [ICmpPredicateAttr](ICmpPredicateAttr) | N/A |
#[def_op("llvm.icmp")]
pub struct ICmpOp {}

impl ICmpOp {
    pub const ATTR_KEY_PREDICATE: &'static str = "llvm.icmp_predicate";
    /// Create a new [ICmpOp]
    pub fn new(ctx: &mut Context, pred: ICmpPredicateAttr, lhs: Value, rhs: Value) -> Self {
        let bool_ty = IntegerType::get(ctx, 1, Signedness::Signless);
        let op = Operation::new(
            ctx,
            Self::get_opid_static(),
            vec![bool_ty.into()],
            vec![lhs, rhs],
            vec![],
            0,
        );
        op.deref_mut(ctx)
            .attributes
            .set(Self::ATTR_KEY_PREDICATE, pred);
        ICmpOp { op }
    }
}

impl Verify for ICmpOp {
    fn verify(&self, ctx: &Context) -> Result<()> {
        let loc = self.get_operation().deref(ctx).loc();
        let op = &*self.op.deref(ctx);

        if op
            .attributes
            .get::<ICmpPredicateAttr>(Self::ATTR_KEY_PREDICATE)
            .is_none()
        {
            verify_err!(op.loc(), ICmpOpVerifyErr::PredAttrErr)?
        }

        let res_ty: TypePtr<IntegerType> =
            TypePtr::from_ptr(self.result_type(ctx), ctx).map_err(|mut err| {
                err.set_loc(loc.clone());
                err
            })?;

        if res_ty.deref(ctx).get_width() != 1 {
            return verify_err!(loc, ICmpOpVerifyErr::ResultNotBool);
        }

        let opd_ty = self.operand_type(ctx).deref(ctx);
        if !(opd_ty.is::<IntegerType>() || opd_ty.is::<PointerType>()) {
            return verify_err!(loc, ICmpOpVerifyErr::IncorrectOperandsType);
        }

        Ok(())
    }
}
impl_canonical_syntax!(ICmpOp);
impl_op_interface!(SameOperandsType for ICmpOp {});
impl_op_interface!(OneResultInterface for ICmpOp {});

#[derive(Error, Debug)]
pub enum AllocaOpVerifyErr {
    #[error("Operand must be a signless integer")]
    OperandType,
    #[error("Missing or incorrect type of attribute for element type")]
    ElemTypeAttr,
}

/// Equivalent to LLVM's Alloca opcode.
/// ### Operands
/// | operand | description |
/// |-----|-------|
/// | `array_size` | Signless integer |
///
/// ### Result(s):
///
/// | result | description |
/// |-----|-------|
/// | `res` | [PointerType] |
///
/// ### Attributes:
///
/// | key | value | via Interface |
/// |-----|-------| --------------|
/// | [ATTR_KEY_ELEM_TYPE](AllocaOp::ATTR_KEY_ELEM_TYPE) | [TypeAttr](pliron::builtin::attributes::TypeAttr) | N/A |
#[def_op("llvm.alloca")]
pub struct AllocaOp {}
impl_canonical_syntax!(AllocaOp);
impl Verify for AllocaOp {
    fn verify(&self, ctx: &Context) -> Result<()> {
        let loc = self.get_operation().deref(ctx).loc();
        // Ensure correctness of operand type.
        if !self.operand_type(ctx).deref(ctx).is::<IntegerType>() {
            return verify_err!(loc, AllocaOpVerifyErr::OperandType);
        }
        let op = &*self.op.deref(ctx);
        // Ensure correctness of element type.
        if op
            .attributes
            .get::<TypeAttr>(Self::ATTR_KEY_ELEM_TYPE)
            .is_none()
        {
            verify_err!(op.loc(), AllocaOpVerifyErr::ElemTypeAttr)?
        }

        Ok(())
    }
}
impl_op_interface!(OneResultInterface for AllocaOp {});
impl_op_interface!(OneOpdInterface for AllocaOp {});
impl_op_interface!(PointerTypeResult for AllocaOp {
    fn result_pointee_type(&self,ctx: &Context) -> Ptr<TypeObj> {
        self.op
        .deref(ctx)
        .attributes
        .get::<TypeAttr>(Self::ATTR_KEY_ELEM_TYPE)
        .expect("AllocaOp missing or incorrect type for elem_type attribute")
        .get_type()
    }
});

impl AllocaOp {
    pub const ATTR_KEY_ELEM_TYPE: &'static str = "llvm.element_type";

    /// Create a new [AllocaOp]
    pub fn new(ctx: &mut Context, elem_type: Ptr<TypeObj>, size: Value) -> Self {
        let ptr_ty = PointerType::get(ctx).into();
        let op = Operation::new(
            ctx,
            Self::get_opid_static(),
            vec![ptr_ty],
            vec![size],
            vec![],
            0,
        );
        op.deref_mut(ctx)
            .attributes
            .set(Self::ATTR_KEY_ELEM_TYPE, TypeAttr::new(elem_type));
        AllocaOp { op }
    }
}

// Equivalent to LLVM's Bitcast opcode.
/// ### Operands
/// | operand | description |
/// |-----|-------|
/// | `arg` | non-aggregate LLVM type |
///
/// ### Result(s):
///
/// | result | description |
/// |-----|-------|
/// | `res` | non-aggregate LLVM type |
#[def_op("llvm.bitcast")]
pub struct BitcastOp {}
impl_canonical_syntax!(BitcastOp);
impl_verify_succ!(BitcastOp);
impl_op_interface!(OneResultInterface for BitcastOp {});
impl_op_interface!(OneOpdInterface for BitcastOp {});

// Equivalent to LLVM's Unconditional Branch.
/// ### Operands
/// | operand | description |
/// |-----|-------|
/// | `dest_opds` | Any number of operands with any LLVM type |
///
/// ### Successors:
///
/// | Successor | description |
/// |-----|-------|
/// | `dest` | Any successor |
#[def_op("llvm.br")]
pub struct BrOp {}
impl_canonical_syntax!(BrOp);
impl_verify_succ!(BrOp);
impl_op_interface!(IsTerminatorInterface for BrOp {});
impl_op_interface!(BranchOpInterface for BrOp {
    fn successor_operands(&self, ctx: &Context, succ_idx: usize) -> Vec<Value> {
        assert!(succ_idx == 0, "BrOp has exactly one successor");
        self.get_operation().deref(ctx).operands().collect()
    }
});
impl BrOp {
    /// Create anew [BrOp].
    pub fn new(ctx: &mut Context, dest: Ptr<BasicBlock>, dest_opds: Vec<Value>) -> Self {
        BrOp {
            op: Operation::new(
                ctx,
                Self::get_opid_static(),
                vec![],
                dest_opds,
                vec![dest],
                0,
            ),
        }
    }
}

// Equivalent to LLVM's Conditional Branch.
/// ### Operands
/// | operand | description |
/// |-----|-------|
/// | `condition` | 1-bit signless integer |
/// | `true_dest_opds` | Any number of operands with any LLVM type |
/// | `false_dest_opds` | Any number of operands with any LLVM type |
///
/// ### Successors:
///
/// | Successor | description |
/// |-----|-------|
/// | `true_dest` | Any successor |
/// | `false_dest` | Any successor |
#[def_op("llvm.cond_br")]
pub struct CondBrOp {}
impl CondBrOp {
    /// Create anew [CondBrOp].
    pub fn new(
        ctx: &mut Context,
        condition: Value,
        true_dest: Ptr<BasicBlock>,
        mut true_dest_opds: Vec<Value>,
        false_dest: Ptr<BasicBlock>,
        mut false_dest_opds: Vec<Value>,
    ) -> Self {
        let mut operands = vec![condition];
        operands.append(&mut true_dest_opds);
        operands.append(&mut false_dest_opds);
        CondBrOp {
            op: Operation::new(
                ctx,
                Self::get_opid_static(),
                vec![],
                operands,
                vec![true_dest, false_dest],
                0,
            ),
        }
    }
}
impl_canonical_syntax!(CondBrOp);
impl_verify_succ!(CondBrOp);
impl_op_interface!(IsTerminatorInterface for CondBrOp {});
impl_op_interface!(BranchOpInterface for CondBrOp {
    fn successor_operands(&self, ctx: &Context, succ_idx: usize) -> Vec<Value> {
        assert!(succ_idx == 0 || succ_idx == 1, "CondBrOp has exactly two successors");
        let num_opds_succ0 = self.get_operation().deref(ctx).get_successor(0).unwrap().deref(ctx).get_num_arguments();
        if succ_idx == 0 {
            // Skip `condition` operand and take num_opds_succ0 operands after that.
            self.get_operation().deref(ctx).operands().skip(1).take(num_opds_succ0).collect()
        } else {
            // Skip `condition` and `true_dest_opds`. Take the remaining.
            self.get_operation().deref(ctx).operands().skip(1 + num_opds_succ0).collect()
        }
    }
});

/// A way to express whether a GEP index is a constant or an SSA value
#[derive(Clone)]
pub enum GepIndex {
    Constant(u32),
    Value(Value),
}

#[derive(Error, Debug)]
pub enum GetElementPtrOpErr {
    #[error("GetElementPtrOp has no or incorrect indices attribute")]
    IndicesAttrErr,
    #[error("The indices on this GEP are invalid for its source element type")]
    IndicesErr,
}

// Equivalent to LLVM's GetElementPtr.
/// ### Attributes:
///
/// | key | value | via Interface |
/// |-----|-------| --------------|
/// | [ATTR_KEY_INDICES](GetElementPtrOp::ATTR_KEY_INDICES) | [GepIndicesAttr](super::attributes::GepIndicesAttr)> | N/A |
/// | [ATTR_KEY_SRC_ELEM_TYPE](GetElementPtrOp::ATTR_KEY_SRC_ELEM_TYPE) | [TypeAttr] | N/A |
///
/// ### Operands
/// | operand | description |
/// |-----|-------|
/// | `base` | LLVM pointer type |
/// | `dynamicIndices` | Any number of signless integers |
///
/// ### Result(s):
///
/// | result | description |
/// |-----|-------|
/// | `res` | LLVM pointer type |
#[def_op("llvm.gep")]
pub struct GetElementPtrOp {}
impl_canonical_syntax!(GetElementPtrOp);
impl_op_interface!(OneResultInterface for GetElementPtrOp {});
impl_op_interface!(PointerTypeResult for GetElementPtrOp {
    fn result_pointee_type(&self, ctx: &Context) -> Ptr<TypeObj> {
        Self::indexed_type(ctx, self.src_elem_type(ctx), &self.indices(ctx)).expect("Invalid indices for GEP")
    }
});
impl Verify for GetElementPtrOp {
    fn verify(&self, ctx: &Context) -> Result<()> {
        let op = &*self.op.deref(ctx);
        // Ensure that we have the indices as an attribute.
        if op
            .attributes
            .get::<GepIndicesAttr>(Self::ATTR_KEY_INDICES)
            .is_none()
        {
            verify_err!(op.loc(), GetElementPtrOpErr::IndicesAttrErr)?
        }

        if let Err(Error { kind: _, err, loc }) =
            Self::indexed_type(ctx, self.src_elem_type(ctx), &self.indices(ctx))
        {
            return Err(Error {
                kind: ErrorKind::VerificationFailed,
                err,
                loc,
            });
        }

        Ok(())
    }
}

impl GetElementPtrOp {
    /// [Attribute](pliron::attribute::Attribute) to get the indices vector.
    pub const ATTR_KEY_INDICES: &'static str = "llvm.gep_indices";
    pub const ATTR_KEY_SRC_ELEM_TYPE: &'static str = "llvm.gep_src_elem_type";
    /// Create a new [GetElementPtrOp]
    pub fn new(
        ctx: &mut Context,
        base: Value,
        indices: Vec<GepIndex>,
        elem_type: TypeAttr,
    ) -> Self {
        let mut attr: Vec<GepIndexAttr> = Vec::new();
        let mut opds: Vec<Value> = vec![base];
        for idx in indices {
            match idx {
                GepIndex::Constant(c) => {
                    attr.push(GepIndexAttr::Constant(c));
                }
                GepIndex::Value(v) => {
                    attr.push(GepIndexAttr::OperandIdx(opds.push_back(v)));
                }
            }
        }
        let op = Operation::new(ctx, Self::get_opid_static(), vec![], opds, vec![], 0);
        op.deref_mut(ctx)
            .attributes
            .set(Self::ATTR_KEY_INDICES, GepIndicesAttr(attr));
        op.deref_mut(ctx)
            .attributes
            .set(Self::ATTR_KEY_SRC_ELEM_TYPE, elem_type);
        GetElementPtrOp { op }
    }

    /// Get the source pointer's element type.
    pub fn src_elem_type(&self, ctx: &Context) -> Ptr<TypeObj> {
        self.op
            .deref(ctx)
            .attributes
            .get::<TypeAttr>(Self::ATTR_KEY_SRC_ELEM_TYPE)
            .expect("GetElementPtrOp missing or has incorrect src_elem_type attribute type")
            .get_type()
    }

    /// Get the base (source) pointer of this GEP.
    pub fn src_ptr(&self, ctx: &Context) -> Value {
        self.get_operation().deref(ctx).get_operand(0).unwrap()
    }

    /// Get the indices of this GEP.
    pub fn indices(&self, ctx: &Context) -> Vec<GepIndex> {
        let op = &*self.op.deref(ctx);
        op.attributes
            .get::<GepIndicesAttr>(Self::ATTR_KEY_INDICES)
            .unwrap()
            .0
            .iter()
            .map(|index| match index {
                GepIndexAttr::Constant(c) => GepIndex::Constant(*c),
                GepIndexAttr::OperandIdx(i) => GepIndex::Value(op.get_operand(*i).unwrap()),
            })
            .collect()
    }

    /// Returns the result element type of a GEP with the given source element type and indexes.
    /// See [getIndexedType](https://llvm.org/doxygen/classllvm_1_1GetElementPtrInst.html#a99d4bfe49182f8d80abb1960f2c12d46)
    pub fn indexed_type(
        ctx: &Context,
        src_elem_type: Ptr<TypeObj>,
        indices: &[GepIndex],
    ) -> Result<Ptr<TypeObj>> {
        fn indexed_type_inner(
            ctx: &Context,
            src_elem_type: Ptr<TypeObj>,
            mut idx_itr: impl Iterator<Item = GepIndex>,
        ) -> Result<Ptr<TypeObj>> {
            let Some(idx) = idx_itr.next() else {
                return Ok(src_elem_type);
            };
            let src_elem_type = &*src_elem_type.deref(ctx);
            if let Some(st) = src_elem_type.downcast_ref::<StructType>() {
                let GepIndex::Constant(i) = idx else {
                    return arg_err_noloc!(GetElementPtrOpErr::IndicesErr);
                };
                if i as usize >= st.num_fields() {
                    return arg_err_noloc!(GetElementPtrOpErr::IndicesErr);
                }
                indexed_type_inner(ctx, st.field_type(i as usize), idx_itr)
            } else if let Some(at) = src_elem_type.downcast_ref::<ArrayType>() {
                indexed_type_inner(ctx, at.elem_type(), idx_itr)
            } else {
                arg_err_noloc!(GetElementPtrOpErr::IndicesErr)
            }
        }
        // The first index is for the base (source) pointer. Skip that.
        indexed_type_inner(ctx, src_elem_type, indices.iter().skip(1).cloned())
    }
}

#[derive(Error, Debug)]
pub enum LoadOpVerifyErr {
    #[error("Load operand must be a pointer")]
    OperandTypeErr,
}

/// Equivalent to LLVM's Load opcode.
/// ### Operands
/// | operand | description |
/// |-----|-------|
/// | `addr` | [PointerType] |
///
/// ### Result(s):
///
/// | result | description |
/// |-----|-------|
/// | `res` | sized LLVM type |
///
/// ### Attributes:
///
#[def_op("llvm.load")]
pub struct LoadOp {}
impl LoadOp {
    /// Create a new [LoadOp]
    pub fn new(ctx: &mut Context, ptr: Value, res_ty: Ptr<TypeObj>) -> Self {
        LoadOp {
            op: Operation::new(
                ctx,
                Self::get_opid_static(),
                vec![res_ty],
                vec![ptr],
                vec![],
                0,
            ),
        }
    }
}
impl_canonical_syntax!(LoadOp);
impl Verify for LoadOp {
    fn verify(&self, ctx: &Context) -> Result<()> {
        let loc = self.get_operation().deref(ctx).loc();
        // Ensure correctness of operand type.
        if !self.operand_type(ctx).deref(ctx).is::<PointerType>() {
            return verify_err!(loc, LoadOpVerifyErr::OperandTypeErr);
        }
        Ok(())
    }
}
impl_op_interface!(OneResultInterface for LoadOp {});
impl_op_interface!(OneOpdInterface for LoadOp {});

#[derive(Error, Debug)]
pub enum StoreOpVerifyErr {
    #[error("Store operand must have two operands")]
    NumOpdsErr,
    #[error("Store operand must have a pointer as its second argument")]
    AddrOpdTypeErr,
}

/// Equivalent to LLVM's Store opcode.
/// ### Operands
/// | operand | description |
/// |-----|-------|
/// | `addr` | [PointerType] |
/// | `value` | Sized type |
///
/// ### Attributes:
///
#[def_op("llvm.store")]
pub struct StoreOp {}
impl StoreOp {
    /// Create a new [LoadOp]
    pub fn new(ctx: &mut Context, value: Value, ptr: Value) -> Self {
        StoreOp {
            op: Operation::new(
                ctx,
                Self::get_opid_static(),
                vec![],
                vec![value, ptr],
                vec![],
                0,
            ),
        }
    }

    /// Get the value operand
    pub fn value_opd(&self, ctx: &Context) -> Value {
        self.op.deref(ctx).get_operand(0).unwrap()
    }

    /// Get the address operand
    pub fn address_opd(&self, ctx: &Context) -> Value {
        self.op.deref(ctx).get_operand(1).unwrap()
    }
}
impl_canonical_syntax!(StoreOp);
impl Verify for StoreOp {
    fn verify(&self, ctx: &Context) -> Result<()> {
        let loc = self.get_operation().deref(ctx).loc();
        let op = &*self.op.deref(ctx);

        if op.get_num_operands() != 2 {
            return verify_err!(loc, StoreOpVerifyErr::NumOpdsErr);
        }

        use pliron::r#type::Typed;
        // Ensure correctness of the address operand.
        if !op
            .get_operand(1)
            .unwrap()
            .get_type(ctx)
            .deref(ctx)
            .is::<PointerType>()
        {
            return verify_err!(loc, StoreOpVerifyErr::AddrOpdTypeErr);
        }
        Ok(())
    }
}
impl_op_interface!(ZeroResultInterface for LoadOp {});

/// Register ops in the LLVM dialect.
pub fn register(ctx: &mut Context, dialect: &mut Dialect) {
    AddOp::register(ctx, dialect, AddOp::parser_fn);
    SubOp::register(ctx, dialect, SubOp::parser_fn);
    MulOp::register(ctx, dialect, MulOp::parser_fn);
    ShlOp::register(ctx, dialect, ShlOp::parser_fn);
    UDivOp::register(ctx, dialect, UDivOp::parser_fn);
    SDivOp::register(ctx, dialect, SDivOp::parser_fn);
    URemOp::register(ctx, dialect, URemOp::parser_fn);
    SRemOp::register(ctx, dialect, SRemOp::parser_fn);
    AndOp::register(ctx, dialect, AndOp::parser_fn);
    OrOp::register(ctx, dialect, OrOp::parser_fn);
    XorOp::register(ctx, dialect, XorOp::parser_fn);
    LShrOp::register(ctx, dialect, LShrOp::parser_fn);
    AShrOp::register(ctx, dialect, AShrOp::parser_fn);
    ICmpOp::register(ctx, dialect, ICmpOp::parser_fn);
    AllocaOp::register(ctx, dialect, AllocaOp::parser_fn);
    BitcastOp::register(ctx, dialect, BitcastOp::parser_fn);
    BrOp::register(ctx, dialect, BrOp::parser_fn);
    CondBrOp::register(ctx, dialect, CondBrOp::parser_fn);
    GetElementPtrOp::register(ctx, dialect, GetElementPtrOp::parser_fn);
    LoadOp::register(ctx, dialect, LoadOp::parser_fn);
    StoreOp::register(ctx, dialect, StoreOp::parser_fn);
    ReturnOp::register(ctx, dialect, ReturnOp::parser_fn);
}