cairo-native 0.8.0

A compiler to convert Cairo's IR Sierra code to MLIR and execute it.
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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
//! # Runtime library bindings
//!
//! This metadata ensures that the bindings to the runtime functions exist in the current
//! compilation context.

use crate::{
    error::{Error, Result},
    libfuncs::LibfuncHelper,
};
use itertools::Itertools;
use melior::{
    dialect::{
        arith::{self, CmpiPredicate},
        cf, llvm, ods,
    },
    helpers::{ArithBlockExt, BuiltinBlockExt, LlvmBlockExt},
    ir::{
        attribute::{FlatSymbolRefAttribute, StringAttribute, TypeAttribute},
        operation::OperationBuilder,
        r#type::IntegerType,
        Attribute, Block, BlockLike, Identifier, Location, Module, OperationRef, Region, Type,
        Value,
    },
    Context,
};
use std::{
    alloc::Layout,
    collections::HashSet,
    ffi::{c_int, c_void},
};

#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
enum RuntimeBinding {
    Pedersen,
    HadesPermutation,
    EcStateTryFinalizeNz,
    EcStateAddMul,
    EcStateInit,
    EcStateAdd,
    EcPointTryNewNz,
    EcPointFromXNz,
    DictNew,
    DictGet,
    DictSquash,
    DictDrop,
    DictDup,
    GetCostsBuiltin,
    DebugPrint,
    ExtendedEuclideanAlgorithm,
    CircuitArithOperation,
    #[cfg(feature = "with-cheatcode")]
    VtableCheatcode,
}

impl RuntimeBinding {
    const fn symbol(self) -> &'static str {
        match self {
            RuntimeBinding::DebugPrint => "cairo_native__libfunc__debug__print",
            RuntimeBinding::Pedersen => "cairo_native__libfunc__pedersen",
            RuntimeBinding::HadesPermutation => "cairo_native__libfunc__hades_permutation",
            RuntimeBinding::EcStateTryFinalizeNz => {
                "cairo_native__libfunc__ec__ec_state_try_finalize_nz"
            }
            RuntimeBinding::EcStateAddMul => "cairo_native__libfunc__ec__ec_state_add_mul",
            RuntimeBinding::EcStateInit => "cairo_native__libfunc__ec__ec_state_init",
            RuntimeBinding::EcStateAdd => "cairo_native__libfunc__ec__ec_state_add",
            RuntimeBinding::EcPointTryNewNz => "cairo_native__libfunc__ec__ec_point_try_new_nz",
            RuntimeBinding::EcPointFromXNz => "cairo_native__libfunc__ec__ec_point_from_x_nz",
            RuntimeBinding::DictNew => "cairo_native__dict_new",
            RuntimeBinding::DictGet => "cairo_native__dict_get",
            RuntimeBinding::DictSquash => "cairo_native__dict_squash",
            RuntimeBinding::DictDrop => "cairo_native__dict_drop",
            RuntimeBinding::DictDup => "cairo_native__dict_dup",
            RuntimeBinding::GetCostsBuiltin => "cairo_native__get_costs_builtin",
            RuntimeBinding::ExtendedEuclideanAlgorithm => {
                "cairo_native__extended_euclidean_algorithm"
            }
            RuntimeBinding::CircuitArithOperation => "cairo_native__circuit_arith_operation",
            #[cfg(feature = "with-cheatcode")]
            RuntimeBinding::VtableCheatcode => "cairo_native__vtable_cheatcode",
        }
    }

    /// Returns an `Option` with a function pointer depending on how the binding is implemented.
    ///
    /// - For external bindings (implemented in Rust), it returns `Some`, containing
    ///   a pointer to the corresponding Rust function
    /// - For internal bindings (implemented in MLIR), it returns `None`, since those
    ///   functions are defined within MLIR and invoked by name
    const fn function_ptr(self) -> Option<*const ()> {
        let function_ptr = match self {
            RuntimeBinding::DebugPrint => {
                crate::runtime::cairo_native__libfunc__debug__print as *const ()
            }
            RuntimeBinding::Pedersen => {
                crate::runtime::cairo_native__libfunc__pedersen as *const ()
            }
            RuntimeBinding::HadesPermutation => {
                crate::runtime::cairo_native__libfunc__hades_permutation as *const ()
            }
            RuntimeBinding::EcStateTryFinalizeNz => {
                crate::runtime::cairo_native__libfunc__ec__ec_state_try_finalize_nz as *const ()
            }
            RuntimeBinding::EcStateAddMul => {
                crate::runtime::cairo_native__libfunc__ec__ec_state_add_mul as *const ()
            }
            RuntimeBinding::EcStateInit => {
                crate::runtime::cairo_native__libfunc__ec__ec_state_init as *const ()
            }
            RuntimeBinding::EcStateAdd => {
                crate::runtime::cairo_native__libfunc__ec__ec_state_add as *const ()
            }
            RuntimeBinding::EcPointTryNewNz => {
                crate::runtime::cairo_native__libfunc__ec__ec_point_try_new_nz as *const ()
            }
            RuntimeBinding::EcPointFromXNz => {
                crate::runtime::cairo_native__libfunc__ec__ec_point_from_x_nz as *const ()
            }
            RuntimeBinding::DictNew => crate::runtime::cairo_native__dict_new as *const (),
            RuntimeBinding::DictGet => crate::runtime::cairo_native__dict_get as *const (),
            RuntimeBinding::DictSquash => crate::runtime::cairo_native__dict_squash as *const (),
            RuntimeBinding::DictDrop => crate::runtime::cairo_native__dict_drop as *const (),
            RuntimeBinding::DictDup => crate::runtime::cairo_native__dict_dup as *const (),
            RuntimeBinding::GetCostsBuiltin => {
                crate::runtime::cairo_native__get_costs_builtin as *const ()
            }
            RuntimeBinding::ExtendedEuclideanAlgorithm => return None,
            RuntimeBinding::CircuitArithOperation => return None,
            #[cfg(feature = "with-cheatcode")]
            RuntimeBinding::VtableCheatcode => {
                crate::starknet::cairo_native__vtable_cheatcode as *const ()
            }
        };
        Some(function_ptr)
    }
}

// This enum is used when performing circuit arithmetic operations.
// Inversion is not included because it is handled separately.
#[repr(u8)]
#[derive(Clone, Copy)]
pub enum CircuitArithOperationType {
    Add,
    Sub,
    Mul,
}

/// Runtime library bindings metadata.
#[derive(Debug, Default)]
pub struct RuntimeBindingsMeta {
    active_map: HashSet<RuntimeBinding>,
}

impl RuntimeBindingsMeta {
    /// Register the global for the given binding, if not yet registered, and return
    /// a pointer to the stored function.
    ///
    /// For the function to be available, `setup_runtime` must be called before running the module
    fn build_function<'c, 'a>(
        &mut self,
        context: &'c Context,
        module: &Module,
        block: &'a Block<'c>,
        location: Location<'c>,
        binding: RuntimeBinding,
    ) -> Result<Value<'c, 'a>> {
        if self.active_map.insert(binding) {
            module.body().append_operation(
                ods::llvm::mlir_global(
                    context,
                    Region::new(),
                    TypeAttribute::new(llvm::r#type::pointer(context, 0)),
                    StringAttribute::new(context, binding.symbol()),
                    Attribute::parse(context, "#llvm.linkage<weak>")
                        .ok_or(Error::ParseAttributeError)?,
                    location,
                )
                .into(),
            );
        }

        let global_address = block.append_op_result(
            ods::llvm::mlir_addressof(
                context,
                llvm::r#type::pointer(context, 0),
                FlatSymbolRefAttribute::new(context, binding.symbol()),
                location,
            )
            .into(),
        )?;

        Ok(block.load(
            context,
            location,
            global_address,
            llvm::r#type::pointer(context, 0),
        )?)
    }

    /// Build if necessary the extended euclidean algorithm used in circuit inverse gates.
    ///
    /// After checking, calls the MLIR function with arguments `a` and `b` which are the initial remainders
    /// used in the algorithm and returns a `Value` containing a struct where the first element is the
    /// greatest common divisor of `a` and `b` and the second element is the bezout coefficient x.
    pub fn extended_euclidean_algorithm<'c, 'a>(
        &mut self,
        context: &'c Context,
        module: &Module,
        block: &'a Block<'c>,
        location: Location<'c>,
        a: Value<'c, '_>,
        b: Value<'c, '_>,
    ) -> Result<Value<'c, 'a>>
    where
        'c: 'a,
    {
        let func_symbol = RuntimeBinding::ExtendedEuclideanAlgorithm.symbol();
        if self
            .active_map
            .insert(RuntimeBinding::ExtendedEuclideanAlgorithm)
        {
            build_egcd_function(module, context, location, func_symbol)?;
        }
        let integer_type: Type = IntegerType::new(context, 384).into();
        // The struct returned by the function that contains both of the results
        let return_type = llvm::r#type::r#struct(context, &[integer_type, integer_type], false);
        Ok(block
            .append_operation(
                OperationBuilder::new("llvm.call", location)
                    .add_attributes(&[(
                        Identifier::new(context, "callee"),
                        FlatSymbolRefAttribute::new(context, func_symbol).into(),
                    )])
                    .add_operands(&[a, b])
                    .add_results(&[return_type])
                    .build()?,
            )
            .result(0)?
            .into())
    }

    /// Builds, if necessary, the circuit operation function, used to perform
    /// circuit arithmetic operations.
    ///
    /// ## Operands
    /// - `op`: an enum telling which arithmetic operation to perform.
    /// - `lhs_value`: u384 operand.
    /// - `rhs_value`: u384 operand.
    /// - `circuit_modulus`: u384 circuit modulus.
    ///
    /// This function only handles addition, substraction and multiplication
    /// operations. The inversion operation was excluded as it is already handled
    /// by the [`extended_euclidean_algorithm`]
    #[allow(clippy::too_many_arguments)]
    pub fn circuit_arith_operation<'c, 'a>(
        &mut self,
        context: &'c Context,
        module: &Module,
        block: &'a Block<'c>,
        location: Location<'c>,
        op_type: CircuitArithOperationType,
        lhs_value: Value<'c, '_>,
        rhs_value: Value<'c, '_>,
        circuit_modulus: Value<'c, '_>,
    ) -> Result<Value<'c, 'a>>
    where
        'c: 'a,
    {
        let func_symbol = RuntimeBinding::CircuitArithOperation.symbol();
        if self
            .active_map
            .insert(RuntimeBinding::CircuitArithOperation)
        {
            build_circuit_arith_operation(context, module, location, func_symbol)?;
        }

        let op_tag = block.const_int(context, location, op_type as u8, 2)?;
        let return_type = IntegerType::new(context, 384).into();

        Ok(block.append_op_result(
            OperationBuilder::new("llvm.call", location)
                .add_attributes(&[(
                    Identifier::new(context, "callee"),
                    FlatSymbolRefAttribute::new(context, func_symbol).into(),
                )])
                .add_operands(&[op_tag, lhs_value, rhs_value, circuit_modulus])
                .add_results(&[return_type])
                .build()?,
        )?)
    }

    /// Register if necessary, then invoke the `debug::print()` function.
    #[allow(clippy::too_many_arguments)]
    pub fn libfunc_debug_print<'c, 'a>(
        &mut self,
        context: &'c Context,
        module: &Module,
        block: &'a Block<'c>,
        target_fd: Value<'c, '_>,
        values_ptr: Value<'c, '_>,
        values_len: Value<'c, '_>,
        location: Location<'c>,
    ) -> Result<Value<'c, 'a>>
    where
        'c: 'a,
    {
        let function =
            self.build_function(context, module, block, location, RuntimeBinding::DebugPrint)?;

        Ok(block
            .append_operation(
                OperationBuilder::new("llvm.call", location)
                    .add_operands(&[function])
                    .add_operands(&[target_fd, values_ptr, values_len])
                    .add_results(&[IntegerType::new(context, 32).into()])
                    .build()?,
            )
            .result(0)?
            .into())
    }

    /// Register if necessary, then invoke the `pedersen()` function.
    #[allow(clippy::too_many_arguments)]
    pub fn libfunc_pedersen<'c, 'a>(
        &mut self,
        context: &'c Context,
        module: &Module,
        block: &'a Block<'c>,
        dst_ptr: Value<'c, '_>,
        lhs_ptr: Value<'c, '_>,
        rhs_ptr: Value<'c, '_>,
        location: Location<'c>,
    ) -> Result<OperationRef<'c, 'a>>
    where
        'c: 'a,
    {
        let function =
            self.build_function(context, module, block, location, RuntimeBinding::Pedersen)?;

        Ok(block.append_operation(
            OperationBuilder::new("llvm.call", location)
                .add_operands(&[function])
                .add_operands(&[dst_ptr, lhs_ptr, rhs_ptr])
                .build()?,
        ))
    }

    /// Register if necessary, then invoke the `poseidon()` function.
    /// The passed pointers serve both as in/out pointers. I.E results are stored in the given pointers.
    #[allow(clippy::too_many_arguments)]
    pub fn libfunc_hades_permutation<'c, 'a>(
        &mut self,
        context: &'c Context,
        module: &Module,
        block: &'a Block<'c>,
        op0_ptr: Value<'c, '_>,
        op1_ptr: Value<'c, '_>,
        op2_ptr: Value<'c, '_>,
        location: Location<'c>,
    ) -> Result<OperationRef<'c, 'a>>
    where
        'c: 'a,
    {
        let function = self.build_function(
            context,
            module,
            block,
            location,
            RuntimeBinding::HadesPermutation,
        )?;

        Ok(block.append_operation(
            OperationBuilder::new("llvm.call", location)
                .add_operands(&[function])
                .add_operands(&[op0_ptr, op1_ptr, op2_ptr])
                .build()?,
        ))
    }

    /// Register if necessary, then invoke the `ec_point_from_x_nz()` function.
    pub fn libfunc_ec_point_from_x_nz<'c, 'a>(
        &mut self,
        context: &'c Context,
        module: &Module,
        block: &'a Block<'c>,
        point_ptr: Value<'c, '_>,
        location: Location<'c>,
    ) -> Result<OperationRef<'c, 'a>>
    where
        'c: 'a,
    {
        let function = self.build_function(
            context,
            module,
            block,
            location,
            RuntimeBinding::EcPointFromXNz,
        )?;

        Ok(block.append_operation(
            OperationBuilder::new("llvm.call", location)
                .add_operands(&[function])
                .add_operands(&[point_ptr])
                .add_results(&[IntegerType::new(context, 1).into()])
                .build()?,
        ))
    }

    /// Register if necessary, then invoke the `ec_point_try_new_nz()` function.
    pub fn libfunc_ec_point_try_new_nz<'c, 'a>(
        &mut self,
        context: &'c Context,
        module: &Module,
        block: &'a Block<'c>,
        point_ptr: Value<'c, '_>,
        location: Location<'c>,
    ) -> Result<OperationRef<'c, 'a>>
    where
        'c: 'a,
    {
        let function = self.build_function(
            context,
            module,
            block,
            location,
            RuntimeBinding::EcPointTryNewNz,
        )?;

        Ok(block.append_operation(
            OperationBuilder::new("llvm.call", location)
                .add_operands(&[function])
                .add_operands(&[point_ptr])
                .add_results(&[IntegerType::new(context, 1).into()])
                .build()?,
        ))
    }

    /// Register if necessary, then invoke the `ec_state_init()` function.
    pub fn libfunc_ec_state_init<'c, 'a>(
        &mut self,
        context: &'c Context,
        module: &Module,
        block: &'a Block<'c>,
        state_ptr: Value<'c, '_>,
        location: Location<'c>,
    ) -> Result<OperationRef<'c, 'a>>
    where
        'c: 'a,
    {
        let function = self.build_function(
            context,
            module,
            block,
            location,
            RuntimeBinding::EcStateInit,
        )?;

        Ok(block.append_operation(
            OperationBuilder::new("llvm.call", location)
                .add_operands(&[function])
                .add_operands(&[state_ptr])
                .build()?,
        ))
    }

    /// Register if necessary, then invoke the `ec_state_add()` function.
    pub fn libfunc_ec_state_add<'c, 'a>(
        &mut self,
        context: &'c Context,
        module: &Module,
        block: &'a Block<'c>,
        state_ptr: Value<'c, '_>,
        point_ptr: Value<'c, '_>,
        location: Location<'c>,
    ) -> Result<OperationRef<'c, 'a>>
    where
        'c: 'a,
    {
        let function =
            self.build_function(context, module, block, location, RuntimeBinding::EcStateAdd)?;

        Ok(block.append_operation(
            OperationBuilder::new("llvm.call", location)
                .add_operands(&[function])
                .add_operands(&[state_ptr, point_ptr])
                .build()?,
        ))
    }

    /// Register if necessary, then invoke the `ec_state_add_mul()` function.
    #[allow(clippy::too_many_arguments)]
    pub fn libfunc_ec_state_add_mul<'c, 'a>(
        &mut self,
        context: &'c Context,
        module: &Module,
        block: &'a Block<'c>,
        state_ptr: Value<'c, '_>,
        scalar_ptr: Value<'c, '_>,
        point_ptr: Value<'c, '_>,
        location: Location<'c>,
    ) -> Result<OperationRef<'c, 'a>>
    where
        'c: 'a,
    {
        let function = self.build_function(
            context,
            module,
            block,
            location,
            RuntimeBinding::EcStateAddMul,
        )?;

        Ok(block.append_operation(
            OperationBuilder::new("llvm.call", location)
                .add_operands(&[function])
                .add_operands(&[state_ptr, scalar_ptr, point_ptr])
                .build()?,
        ))
    }

    pub fn libfunc_ec_state_try_finalize_nz<'c, 'a>(
        &mut self,
        context: &'c Context,
        module: &Module,
        block: &'a Block<'c>,
        point_ptr: Value<'c, '_>,
        state_ptr: Value<'c, '_>,
        location: Location<'c>,
    ) -> Result<OperationRef<'c, 'a>>
    where
        'c: 'a,
    {
        let function = self.build_function(
            context,
            module,
            block,
            location,
            RuntimeBinding::EcStateTryFinalizeNz,
        )?;

        Ok(block.append_operation(
            OperationBuilder::new("llvm.call", location)
                .add_operands(&[function])
                .add_operands(&[point_ptr, state_ptr])
                .add_results(&[IntegerType::new(context, 1).into()])
                .build()?,
        ))
    }

    /// Register if necessary, then invoke the `dict_alloc_new()` function.
    ///
    /// Returns a opaque pointer as the result.
    #[allow(clippy::too_many_arguments)]
    pub fn dict_new<'c, 'a>(
        &mut self,
        context: &'c Context,
        module: &Module,
        block: &'a Block<'c>,
        location: Location<'c>,
        drop_fn: Option<Value<'c, 'a>>,
        layout: Layout,
    ) -> Result<Value<'c, 'a>>
    where
        'c: 'a,
    {
        let function =
            self.build_function(context, module, block, location, RuntimeBinding::DictNew)?;

        let i64_ty = IntegerType::new(context, 64).into();
        let size = block.const_int_from_type(context, location, layout.size(), i64_ty)?;
        let align = block.const_int_from_type(context, location, layout.align(), i64_ty)?;

        let drop_fn = match drop_fn {
            Some(x) => x,
            None => {
                block.append_op_result(llvm::zero(llvm::r#type::pointer(context, 0), location))?
            }
        };

        Ok(block.append_op_result(
            OperationBuilder::new("llvm.call", location)
                .add_operands(&[function])
                .add_operands(&[size, align, drop_fn])
                .add_results(&[llvm::r#type::pointer(context, 0)])
                .build()?,
        )?)
    }

    /// Register if necessary, then invoke the `dict_alloc_new()` function.
    ///
    /// Returns a opaque pointer as the result.
    #[allow(clippy::too_many_arguments)]
    pub fn dict_drop<'c, 'a>(
        &mut self,
        context: &'c Context,
        module: &Module,
        block: &'a Block<'c>,
        ptr: Value<'c, 'a>,
        location: Location<'c>,
    ) -> Result<OperationRef<'c, 'a>>
    where
        'c: 'a,
    {
        let function =
            self.build_function(context, module, block, location, RuntimeBinding::DictDrop)?;

        Ok(block.append_operation(
            OperationBuilder::new("llvm.call", location)
                .add_operands(&[function])
                .add_operands(&[ptr])
                .build()?,
        ))
    }

    /// Register if necessary, then invoke the `dict_alloc_new()` function.
    ///
    /// Returns a opaque pointer as the result.
    #[allow(clippy::too_many_arguments)]
    pub fn dict_dup<'c, 'a>(
        &mut self,
        context: &'c Context,
        module: &Module,
        block: &'a Block<'c>,
        ptr: Value<'c, 'a>,
        location: Location<'c>,
    ) -> Result<Value<'c, 'a>>
    where
        'c: 'a,
    {
        let function =
            self.build_function(context, module, block, location, RuntimeBinding::DictDup)?;

        Ok(block.append_op_result(
            OperationBuilder::new("llvm.call", location)
                .add_operands(&[function])
                .add_operands(&[ptr])
                .add_results(&[llvm::r#type::pointer(context, 0)])
                .build()?,
        )?)
    }

    /// Register if necessary, then invoke the `dict_get()` function.
    ///
    /// Gets the value for a given key, the returned pointer is null if not found.
    ///
    /// Returns a opaque pointer as the result.
    #[allow(clippy::too_many_arguments)]
    pub fn dict_get<'c, 'a>(
        &mut self,
        context: &'c Context,
        helper: &LibfuncHelper<'c, 'a>,
        block: &'a Block<'c>,
        dict_ptr: Value<'c, 'a>, // ptr to the dict
        key_ptr: Value<'c, 'a>,  // key must be a ptr to Felt
        location: Location<'c>,
    ) -> Result<(Value<'c, 'a>, Value<'c, 'a>)>
    where
        'c: 'a,
    {
        let function =
            self.build_function(context, helper, block, location, RuntimeBinding::DictGet)?;

        let value_ptr = helper.init_block().alloca1(
            context,
            location,
            llvm::r#type::pointer(context, 0),
            align_of::<*mut ()>(),
        )?;

        let is_present = block.append_op_result(
            OperationBuilder::new("llvm.call", location)
                .add_operands(&[function])
                .add_operands(&[dict_ptr, key_ptr, value_ptr])
                .add_results(&[IntegerType::new(context, c_int::BITS).into()])
                .build()?,
        )?;

        let value_ptr = block.load(
            context,
            location,
            value_ptr,
            llvm::r#type::pointer(context, 0),
        )?;

        Ok((is_present, value_ptr))
    }

    /// Register if necessary, then invoke the `dict_gas_refund()` function.
    ///
    /// Compute the total gas refund for the dictionary.
    ///
    /// Returns a u64 of the result.
    #[allow(clippy::too_many_arguments)]
    pub fn dict_squash<'c, 'a>(
        &mut self,
        context: &'c Context,
        module: &Module,
        block: &'a Block<'c>,
        dict_ptr: Value<'c, 'a>,        // ptr to the dict
        range_check_ptr: Value<'c, 'a>, // ptr to range check
        gas_ptr: Value<'c, 'a>,         // ptr to gas
        location: Location<'c>,
    ) -> Result<OperationRef<'c, 'a>>
    where
        'c: 'a,
    {
        let function =
            self.build_function(context, module, block, location, RuntimeBinding::DictSquash)?;

        Ok(block.append_operation(
            OperationBuilder::new("llvm.call", location)
                .add_operands(&[function])
                .add_operands(&[dict_ptr, range_check_ptr, gas_ptr])
                .add_results(&[IntegerType::new(context, 64).into()])
                .build()?,
        ))
    }

    // Register if necessary, then invoke the `get_costs_builtin()` function.
    #[allow(clippy::too_many_arguments)]
    pub fn get_costs_builtin<'c, 'a>(
        &mut self,
        context: &'c Context,
        module: &Module,
        block: &'a Block<'c>,
        location: Location<'c>,
    ) -> Result<OperationRef<'c, 'a>>
    where
        'c: 'a,
    {
        let function = self.build_function(
            context,
            module,
            block,
            location,
            RuntimeBinding::GetCostsBuiltin,
        )?;

        Ok(block.append_operation(
            OperationBuilder::new("llvm.call", location)
                .add_operands(&[function])
                .add_results(&[llvm::r#type::pointer(context, 0)])
                .build()?,
        ))
    }

    /// Register if necessary, then invoke the `vtable_cheatcode()` runtime function.
    ///
    /// Calls the cheatcode syscall with the given arguments.
    ///
    /// The result is stored in `result_ptr`.
    #[allow(clippy::too_many_arguments)]
    #[cfg(feature = "with-cheatcode")]
    pub fn vtable_cheatcode<'c, 'a>(
        &mut self,
        context: &'c Context,
        module: &Module,
        block: &'a Block<'c>,
        location: Location<'c>,
        result_ptr: Value<'c, 'a>,
        selector_ptr: Value<'c, 'a>,
        args: Value<'c, 'a>,
    ) -> Result<OperationRef<'c, 'a>>
    where
        'c: 'a,
    {
        let function = self.build_function(
            context,
            module,
            block,
            location,
            RuntimeBinding::VtableCheatcode,
        )?;

        Ok(block.append_operation(
            OperationBuilder::new("llvm.call", location)
                .add_operands(&[function])
                .add_operands(&[result_ptr, selector_ptr, args])
                .build()?,
        ))
    }
}

pub fn setup_runtime(find_symbol_ptr: impl Fn(&str) -> Option<*mut c_void>) {
    for binding in [
        RuntimeBinding::DebugPrint,
        RuntimeBinding::Pedersen,
        RuntimeBinding::HadesPermutation,
        RuntimeBinding::EcStateTryFinalizeNz,
        RuntimeBinding::EcStateAddMul,
        RuntimeBinding::EcStateInit,
        RuntimeBinding::EcStateAdd,
        RuntimeBinding::EcPointTryNewNz,
        RuntimeBinding::EcPointFromXNz,
        RuntimeBinding::DictNew,
        RuntimeBinding::DictGet,
        RuntimeBinding::DictSquash,
        RuntimeBinding::DictDrop,
        RuntimeBinding::DictDup,
        RuntimeBinding::GetCostsBuiltin,
        RuntimeBinding::DebugPrint,
        #[cfg(feature = "with-cheatcode")]
        RuntimeBinding::VtableCheatcode,
    ] {
        if let Some(global) = find_symbol_ptr(binding.symbol()) {
            let global = global.cast::<*const ()>();
            unsafe {
                if let Some(function_ptr) = binding.function_ptr() {
                    *global = function_ptr;
                };
            }
        }
    }
}

/// Build the extended euclidean algorithm MLIR function.
///
/// The extended euclidean algorithm calculates the greatest common divisor
/// (gcd) of two integers `a` and `b`, as well as the Bézout coefficients `x`
/// and `y` such that `ax + by = gcd(a,b)`. If `gcd(a,b) = 1`, then `x` is the
/// modular multiplicative inverse of `a` modulo `b`.
///
/// This function declares a MLIR function that given two 384 bit integers `a`
/// and `b`, returns a MLIR struct with `gcd(a,b)` and the Bézout coefficient
/// `x`. The declaration is done in the body of the module.
fn build_egcd_function<'ctx>(
    module: &Module,
    context: &'ctx Context,
    location: Location<'ctx>,
    func_symbol: &str,
) -> Result<()> {
    let integer_width = 384;
    let integer_type = IntegerType::new(context, integer_width).into();

    // Pseudocode for calculating the EGCD of two integers `a` and `b`.
    // https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Pseudocode.
    //
    // ```
    // (old_r, new_r) := (a, b)
    // (old_s, new_s) := (1, 0)
    //
    // while new_r != 0 do
    //     quotient := old_r / new_r
    //     (old_r, new_r) := (new_r, old_r − quotient * new_r)
    //     (old_s, new_s) := (new_s, old_s − quotient * new_s)
    //
    // old_s is equal to Bézout coefficient X
    // old_r is equal to GCD
    // ```
    //
    // Note that when `b > a`, the first iteration inverts the values. Our
    // implementation does it manually as we already know that `b > a`.
    //
    // The core idea of the method is that `gcd(a,b) = gcd(a,b-a)`, and that
    // `gcd(a,b) = gcd(b,a)`. As an optimization, we can actually substract `a`
    // from `b` as many times as possible, so `gcd(a,b) = gcd(b%a,a)`.
    //
    // Take, for example, `a=21` and `b=54`:
    //
    //   gcd(21, 54)
    // = gcd(12, 21)
    // = gcd(9, 12)
    // = gcd(3, 9)
    // = gcd(0, 3)
    // = 3
    //
    // Thus, the algorithm works by calculating a series of remainders `r` which
    // starts with b,a,... being `r[i]` the remainder of dividing `r[i-2]` by
    // `r[i-1]`. At each step, `r[i]` can be calculated as:
    //
    // r[i] = r[i-2] - r[i-1] * quotient
    //
    // The GCD will be the last non-zero remainder.
    //
    // [54; 21; 12; 9; 3; 0]
    //                 ^
    //
    // See Dr. Katherine Stange's Youtube video for a better explanation on how
    // this works: https://www.youtube.com/watch?v=Jwf6ncRmhPg.
    //
    // The extended algorithm also obtains the Bézout coefficients
    // by calculating a series of coefficients `s`. See Dr. Katherine
    // Stange's Youtube video for a better explanation on how this works:
    // https://www.youtube.com/watch?v=IwRtISxAHY4.

    // Define entry block for function. Receives arguments `a` and `b`.
    let region = Region::new();
    let entry_block = region.append_block(Block::new(&[
        (integer_type, location), // a
        (integer_type, location), // b
    ]));

    // Define loop block for function. Each iteration last two values from each series.
    let loop_block = region.append_block(Block::new(&[
        (integer_type, location), // old_r
        (integer_type, location), // new_r
        (integer_type, location), // old_s
        (integer_type, location), // new_s
    ]));

    // Define end block for function.
    let end_block = region.append_block(Block::new(&[
        (integer_type, location), // old_r
        (integer_type, location), // old_s
    ]));

    // Jump to loop block from entry block, with initial values.
    // - old_r = b
    // - new_r = a
    // - old_s = 0
    // - new_s = 1
    entry_block.append_operation(cf::br(
        &loop_block,
        &[
            entry_block.arg(1)?,
            entry_block.arg(0)?,
            entry_block.const_int_from_type(context, location, 0, integer_type)?,
            entry_block.const_int_from_type(context, location, 1, integer_type)?,
        ],
        location,
    ));

    // LOOP BLOCK
    {
        let old_r = loop_block.arg(0)?;
        let new_r = loop_block.arg(1)?;
        let old_s = loop_block.arg(2)?;
        let new_s = loop_block.arg(3)?;

        // First calculate quotient of old_r/new_r.
        let quotient = loop_block.append_op_result(arith::divui(old_r, new_r, location))?;

        // Multiply quotient by new_r and new_s.
        let quotient_by_new_r = loop_block.muli(quotient, new_r, location)?;
        let quotient_by_new_s = loop_block.muli(quotient, new_s, location)?;

        // Calculate new values for next iteration.
        // - next_new_r := old_r − quotient * new_r
        // - next_new_s := old_s − quotient * new_s
        let next_new_r =
            loop_block.append_op_result(arith::subi(old_r, quotient_by_new_r, location))?;
        let next_new_s =
            loop_block.append_op_result(arith::subi(old_s, quotient_by_new_s, location))?;

        // Jump to end block if next_new_r is zero.
        let zero = loop_block.const_int_from_type(context, location, 0, integer_type)?;
        let next_new_r_is_zero =
            loop_block.cmpi(context, CmpiPredicate::Eq, next_new_r, zero, location)?;
        loop_block.append_operation(cf::cond_br(
            context,
            next_new_r_is_zero,
            &end_block,
            &loop_block,
            &[new_r, new_s],
            &[new_r, next_new_r, new_s, next_new_s],
            location,
        ));
    }

    // END BLOCK
    {
        let results = end_block.append_op_result(llvm::undef(
            llvm::r#type::r#struct(context, &[integer_type, integer_type], false),
            location,
        ))?;
        let results = end_block.insert_values(
            context,
            location,
            results,
            &[end_block.arg(0)?, end_block.arg(1)?],
        )?;
        end_block.append_operation(llvm::r#return(Some(results), location));
    }

    let func_name = StringAttribute::new(context, func_symbol);
    module.body().append_operation(llvm::func(
        context,
        func_name,
        TypeAttribute::new(llvm::r#type::function(
            llvm::r#type::r#struct(context, &[integer_type, integer_type], false),
            &[integer_type, integer_type],
            false,
        )),
        region,
        &[(
            Identifier::new(context, "no_inline"), // Adding this attribute significantly improves compilation
            Attribute::unit(context),
        )],
        location,
    ));

    Ok(())
}

/// Builds function for circuit arithmetic operations.
///
/// It builds an mlir function to perform most circuit's arithmetic operations
/// with the exception of the inversion since it is handled separately. This
/// allows us to reduce the amount of inlined operations in the mlir generated,
/// significantly reducing the compilation time of circuits.
///
/// Disclaimer: This function could've been split in three functions, each being
/// responsible of one circuit operation, improving maintainability. It would
/// also avoid having to use a `match` in runtime to select the operation to
/// perform, since its known at compile time. However, it was decided not to go
/// with this approach since it would make compilation time about a 10
/// percent slower in circuit-heavy contracts.
fn build_circuit_arith_operation<'ctx>(
    context: &'ctx Context,
    module: &Module,
    location: Location<'ctx>,
    func_symbol: &str,
) -> Result<()> {
    let func_name = StringAttribute::new(context, func_symbol);
    let u2_ty = IntegerType::new(context, 2).into();
    let u384_ty: Type = IntegerType::new(context, 384).into();
    let u385_ty: Type = IntegerType::new(context, 385).into();
    let u768_ty = IntegerType::new(context, 768).into();

    let region = Region::new();
    let entry_block = region.append_block(Block::new(&[
        (u2_ty, location),
        (u384_ty, location),
        (u384_ty, location),
        (u384_ty, location),
    ]));

    let op_tag = entry_block.arg(0)?;
    let lhs = entry_block.arg(1)?;
    let rhs = entry_block.arg(2)?;
    let modulus = entry_block.arg(3)?;

    let ops = [
        CircuitArithOperationType::Add,
        CircuitArithOperationType::Sub,
        CircuitArithOperationType::Mul,
    ];
    let op_blocks = ops
        .into_iter()
        .map(|op| (op, Block::new(&[])))
        .collect_vec();
    let default_block = region.append_block(Block::new(&[]));
    let cases_values = ops.iter().map(|&op| op as i64).collect_vec();

    // Default block. This should be unreachable as the op_tag is not defined by the user.
    {
        // Arithmetic operations' tag go from 0 to 2 (add, sub, mul)
        default_block.append_operation(llvm::unreachable(location));
    }

    // Switch cases' operation blocks.
    for (tag, block) in op_blocks.iter() {
        let result = match tag {
            // result = lhs_value + rhs_value
            CircuitArithOperationType::Add => {
                // We need to extend the operands to avoid overflows while
                // operating. Since we are performing an addition, we need
                // at least a bit width of 384 + 1.
                let lhs = block.extui(lhs, u385_ty, location)?;
                let rhs = block.extui(rhs, u385_ty, location)?;
                let modulus = block.extui(modulus, u385_ty, location)?;

                let result = block.addi(lhs, rhs, location)?;

                // result % circuit_modulus
                block.append_op_result(arith::remui(result, modulus, location))?
            }
            // result = output_value + circuit_modulus - rhs_value
            CircuitArithOperationType::Sub => {
                // We need to extend the operands to avoid overflows while
                // operating. Since we are performing a subtraction, we
                // need at least a bit width of 384 + 1.
                let lhs = block.extui(lhs, u385_ty, location)?;
                let rhs = block.extui(rhs, u385_ty, location)?;
                let modulus = block.extui(modulus, u385_ty, location)?;

                let partial_result = block.addi(lhs, modulus, location)?;
                let result = block.subi(partial_result, rhs, location)?;

                // result % circuit_modulus
                block.append_op_result(arith::remui(result, modulus, location))?
            }
            // result = lhs_value * rhs_value
            CircuitArithOperationType::Mul => {
                // We need to extend the operands to avoid overflows while
                // operating. Since we are performing a multiplication, we need at least a bit width
                // of 284 * 2.
                let lhs = block.extui(lhs, u768_ty, location)?;
                let rhs = block.extui(rhs, u768_ty, location)?;
                let modulus = block.extui(modulus, u768_ty, location)?;

                let result = block.muli(lhs, rhs, location)?;

                // result % circuit_modulus
                block.append_op_result(arith::remui(result, modulus, location))?
            }
        };

        // Truncate back
        let result = block.trunci(result, u384_ty, location)?;

        block.append_operation(llvm::r#return(Some(result), location));
    }

    entry_block.append_operation(cf::switch(
        context,
        &cases_values,
        op_tag,
        u2_ty,
        (&default_block, &[]),
        &op_blocks
            .iter()
            .map(|(_, block)| (block, [].as_slice()))
            .collect::<Vec<_>>(),
        location,
    )?);

    // We need to append the cases to the region.
    for (_, block) in op_blocks.into_iter() {
        region.append_block(block);
    }

    module.body().append_operation(llvm::func(
        context,
        func_name,
        TypeAttribute::new(llvm::r#type::function(
            u384_ty,
            &[u2_ty, u384_ty, u384_ty, u384_ty],
            false,
        )),
        region,
        &[(
            Identifier::new(context, "no_inline"),
            Attribute::unit(context),
        )],
        location,
    ));

    Ok(())
}