solar-codegen 0.2.0

Solidity MIR and EVM code generation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
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
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
//! HIR to MIR lowering.
//!
//! This module transforms the high-level IR from solar-sema into MIR.

mod abi_encode;
mod abi_packed;
mod bytes;
mod call;
mod checked_arith;
mod expr;
mod index;
mod stmt;
mod storage;
mod type_query;

use crate::{
    IMMUTABLE_SCRATCH_BASE,
    mir::{
        BlockId, Function, FunctionAttributes, FunctionBuilder, FunctionId, IMMUTABLE_WORD_SIZE,
        ImmutableSlot, MirType, Module, StorageSlot, ValueId,
    },
};
use alloy_primitives::U256;
use solar_data_structures::{
    Never,
    map::{FxHashMap, FxHashSet},
};
use solar_interface::{Ident, Span, diagnostics::DiagMsg, kw, sym};
use solar_sema::{
    hir::{self, ContractId, ElementaryType, FunctionId as HirFunctionId, VariableId, Visit},
    ty::{Gcx, Ty, TyKind},
};
use std::ops::ControlFlow;

use self::storage::StorageLocation;

/// Context for a loop (tracks break/continue targets).
#[derive(Clone, Copy)]
pub struct LoopContext {
    /// Block to jump to on `break`.
    pub break_target: BlockId,
    /// Block to jump to on `continue`.
    pub continue_target: BlockId,
}

#[derive(Clone, Copy)]
enum AbiParamSource {
    ExternalCalldata,
    ConstructorMemory,
}

/// Lowering context for converting HIR to MIR.
pub struct Lowerer<'gcx> {
    /// The global context.
    gcx: Gcx<'gcx>,
    /// The current module being built.
    module: Module,
    /// The current contract being lowered.
    current_contract_id: Option<ContractId>,
    /// Mapping from HIR variable IDs to storage slots.
    storage_slots: FxHashMap<VariableId, u64>,
    /// Mapping from HIR variable IDs to full storage locations.
    storage_locations: FxHashMap<VariableId, StorageLocation>,
    /// Next available storage slot.
    next_storage_slot: u64,
    /// Next available byte offset in `next_storage_slot` for packed variables.
    next_storage_offset: u8,
    /// Mapping from HIR immutable variable IDs to runtime immutable byte offsets.
    immutable_slots: FxHashMap<VariableId, u32>,
    /// Next available immutable byte offset.
    next_immutable_offset: u32,
    /// Mapping from HIR variable IDs to MIR values (for local variables).
    /// For SSA-style immutable variables (function params and non-mutated locals).
    locals: FxHashMap<VariableId, ValueId>,
    /// Mapping from HIR variable IDs to memory offsets (for mutable locals).
    /// Memory layout: starts at offset 0x80 (after scratch space).
    local_memory_slots: FxHashMap<VariableId, u64>,
    /// Next available memory offset for locals.
    next_local_memory_offset: u64,
    /// Bytecodes of other contracts (for `new` expressions).
    /// Maps contract ID to (deployment_bytecode, data_segment_index).
    contract_bytecodes: FxHashMap<ContractId, (Vec<u8>, usize)>,
    /// Stack of loop contexts for nested loops.
    loop_stack: Vec<LoopContext>,
    /// Variables that are assigned after declaration (need memory storage).
    /// Variables not in this set can be kept as SSA values.
    assigned_vars: FxHashSet<VariableId>,
    /// Local variables that are storage references (pointers). Their value in
    /// `locals` is a storage *slot*, so `r.field` reads `sload(slot + offset)`
    /// and `r.field = v` writes `sstore(slot + offset, v)`, rather than treating
    /// the value as a memory pointer.
    storage_ref_locals: FxHashSet<VariableId>,
    /// Stack of function IDs currently being inlined (for cycle detection).
    inline_stack: Vec<HirFunctionId>,
    /// HIR functions already lowered into this MIR module.
    hir_to_mir_functions: FxHashMap<HirFunctionId, FunctionId>,
    /// Internal-convention copies of public functions, lowered on demand so that
    /// public functions can be called internally/recursively via `internal_call`.
    hir_to_internal_mir_functions: FxHashMap<HirFunctionId, FunctionId>,
    /// Cache of whether a function is (directly) self-recursive.
    recursive_functions: FxHashMap<HirFunctionId, bool>,
    /// Functions currently being lowered on demand.
    lowering_functions: FxHashSet<HirFunctionId>,
    /// Whether the current function body is constructor code.
    lowering_constructor: bool,
    /// Whether local memory slots should be addressed through the internal-call frame.
    lowering_internal_function: bool,
    /// Whether arithmetic should use wrapping Solidity `unchecked` semantics.
    in_unchecked_block: bool,
    /// Sema return types of the function currently being lowered (one per declared
    /// return), used to ABI-encode external returns.
    current_return_tys: Vec<Ty<'gcx>>,
    /// Mapping from struct state variable ID to base storage slot.
    pub struct_storage_base_slots: FxHashMap<VariableId, u64>,
    /// Cached struct field slot offsets: (struct_type_id, field_index) -> slot offset from base.
    pub struct_field_offsets: FxHashMap<(hir::StructId, usize), u64>,
    /// Cached struct field memory offsets: (struct_type_id, field_index) -> byte offset from base.
    pub struct_field_memory_offsets: FxHashMap<(hir::StructId, usize), u64>,
}

impl<'gcx> Lowerer<'gcx> {
    /// Reports a lowering error and returns the error sentinel value carrying
    /// the emitted diagnostic's guarantee, mirroring HIR's error types.
    pub(super) fn err_value(
        &self,
        builder: &mut FunctionBuilder<'_>,
        span: Span,
        msg: impl Into<DiagMsg>,
    ) -> ValueId {
        let guar = self.gcx.dcx().err(msg).span(span).emit();
        builder.error_value(guar)
    }

    /// Creates a new lowerer.
    pub fn new(gcx: Gcx<'gcx>, name: Ident) -> Self {
        if !gcx.has_typeck_results() {
            gcx.dcx().emit_err(
                name.span,
                "tried to lower contract without typeck results; likely missing -Zcodegen",
            );
        }
        Self {
            gcx,
            module: Module::new(name),
            current_contract_id: None,
            storage_slots: FxHashMap::default(),
            storage_locations: FxHashMap::default(),
            next_storage_slot: 0,
            next_storage_offset: 0,
            immutable_slots: FxHashMap::default(),
            next_immutable_offset: 0,
            locals: FxHashMap::default(),
            local_memory_slots: FxHashMap::default(),
            next_local_memory_offset: 0x80, // Start after Solidity's scratch space
            contract_bytecodes: FxHashMap::default(),
            loop_stack: Vec::new(),
            assigned_vars: FxHashSet::default(),
            storage_ref_locals: FxHashSet::default(),
            inline_stack: Vec::new(),
            hir_to_mir_functions: FxHashMap::default(),
            hir_to_internal_mir_functions: FxHashMap::default(),
            recursive_functions: FxHashMap::default(),
            lowering_functions: FxHashSet::default(),
            lowering_constructor: false,
            lowering_internal_function: false,
            in_unchecked_block: false,
            current_return_tys: Vec::new(),
            struct_storage_base_slots: FxHashMap::default(),
            struct_field_offsets: FxHashMap::default(),
            struct_field_memory_offsets: FxHashMap::default(),
        }
    }

    /// Pushes a loop context onto the stack.
    pub fn push_loop(&mut self, ctx: LoopContext) {
        self.loop_stack.push(ctx);
    }

    /// Pops a loop context from the stack.
    pub fn pop_loop(&mut self) {
        self.loop_stack.pop();
    }

    /// Gets the current loop context, if any.
    pub fn current_loop(&self) -> Option<&LoopContext> {
        self.loop_stack.last()
    }

    /// Maximum inline depth to prevent excessive recursion.
    const MAX_INLINE_DEPTH: usize = 32;
    /// Historical base used by local memory slots in external function bodies.
    const LOCAL_MEMORY_BASE: u64 = 0x80;
    /// Attempts to enter inlining for a function. Returns false if a cycle is detected
    /// or the max inline depth is exceeded.
    fn try_enter_inline(&mut self, func_id: HirFunctionId) -> bool {
        // Check for cycle
        if self.inline_stack.contains(&func_id) {
            return false;
        }
        // Check depth limit
        if self.inline_stack.len() >= Self::MAX_INLINE_DEPTH {
            return false;
        }
        self.inline_stack.push(func_id);
        true
    }

    /// Exits inlining for a function.
    fn exit_inline(&mut self) {
        self.inline_stack.pop();
    }

    /// Allocates a memory slot for a local variable.
    /// Returns the memory offset.
    pub fn alloc_local_memory(&mut self, var_id: VariableId) -> u64 {
        let offset = self.next_local_memory_offset;
        self.next_local_memory_offset += 32; // Each slot is 32 bytes
        self.local_memory_slots.insert(var_id, offset);
        offset
    }

    /// Gets the memory offset for a local variable, if it's stored in memory.
    pub fn get_local_memory_offset(&self, var_id: &VariableId) -> Option<u64> {
        self.local_memory_slots.get(var_id).copied()
    }

    /// Returns the address for a local memory slot in the current lowering context.
    pub fn local_memory_addr(&self, builder: &mut FunctionBuilder<'_>, offset: u64) -> ValueId {
        if self.lowering_internal_function {
            let header_size = 64;
            let arg_size = (builder.func().params.len() as u64) * 32;
            let return_size = (builder.func().returns.len() as u64) * 32;
            let local_offset = offset.saturating_sub(Self::LOCAL_MEMORY_BASE);
            builder.internal_frame_addr(header_size + arg_size + return_size + local_offset)
        } else {
            builder.imm_u64(offset)
        }
    }

    /// Returns the constructor scratch address for an immutable word.
    pub fn immutable_scratch_addr(offset: u32) -> u64 {
        IMMUTABLE_SCRATCH_BASE + u64::from(offset)
    }

    /// Stages an immutable word in constructor memory.
    pub fn store_immutable_value(
        &self,
        builder: &mut FunctionBuilder<'_>,
        offset: u32,
        value: ValueId,
    ) {
        let addr = builder.imm_u64(Self::immutable_scratch_addr(offset));
        builder.mstore(addr, value);
    }

    /// Loads an immutable word.
    ///
    /// Runtime code reads a `PUSH32` placeholder that the constructor patches
    /// with the staged value before returning the runtime code. The running
    /// constructor's own placeholders are never patched, so constructor-context
    /// reads load the staged scratch word instead.
    pub fn load_immutable_value(&self, builder: &mut FunctionBuilder<'_>, offset: u32) -> ValueId {
        if self.lowering_constructor {
            let addr = builder.imm_u64(Self::immutable_scratch_addr(offset));
            builder.mload(addr)
        } else {
            builder.load_immutable(offset)
        }
    }

    /// Registers a contract's bytecode for use in `new` expressions.
    pub fn register_contract_bytecode(&mut self, contract_id: ContractId, bytecode: Vec<u8>) {
        let segment_idx = self.module.add_data_segment(bytecode.clone());
        self.contract_bytecodes.insert(contract_id, (bytecode, segment_idx));
    }

    /// Gets the bytecode for a contract, if registered.
    pub fn get_contract_bytecode(&self, contract_id: ContractId) -> Option<&(Vec<u8>, usize)> {
        self.contract_bytecodes.get(&contract_id)
    }

    /// Lowers a contract to MIR.
    pub fn lower_contract(&mut self, contract_id: ContractId) {
        let contract = self.gcx.hir.contract(contract_id);

        // Track the current contract for using directive resolution.
        self.current_contract_id = Some(contract_id);

        // Mark interfaces - they don't generate deployable bytecode.
        if contract.kind == hir::ContractKind::Interface {
            self.module.is_interface = true;
        }

        self.allocate_storage(contract_id);

        // Collect all functions from the inheritance chain, handling overrides.
        // Functions are collected from most-derived to most-base, so if a function
        // with the same selector already exists, we skip the base version.
        let functions = self.collect_inherited_functions(contract_id);

        // Generate a constructor for inherited construction/state-variable
        // initialization when the current contract does not declare one.
        if contract.ctor.is_none() {
            self.generate_synthetic_constructor(contract_id);
        }

        for func_id in functions {
            self.ensure_function_lowered(func_id);
        }

        self.current_contract_id = None;
    }

    /// Collects all functions from the inheritance chain, handling overrides.
    ///
    /// Functions from more-derived contracts take precedence over base contracts.
    /// For regular functions, we use the selector to determine uniqueness.
    /// For constructor/fallback/receive, we use the function kind.
    fn collect_inherited_functions(&self, contract_id: ContractId) -> Vec<HirFunctionId> {
        let contract = self.gcx.hir.contract(contract_id);
        let linearized_bases = contract.linearized_bases;

        let mut seen_selectors: FxHashSet<[u8; 4]> = FxHashSet::default();
        let mut has_constructor = false;
        let mut has_fallback = false;
        let mut has_receive = false;
        let mut functions = Vec::new();

        // Iterate from most-derived (index 0) to most-base (last index).
        // The first function with a given selector wins (override behavior).
        for &base_id in linearized_bases.iter() {
            let base_contract = self.gcx.hir.contract(base_id);

            for func_id in base_contract.all_functions() {
                let func = self.gcx.hir.function(func_id);

                // Handle special functions by kind
                match func.kind {
                    hir::FunctionKind::Constructor => {
                        // Constructors are not inherited. Base constructors
                        // are called from the current contract's constructor
                        // prelude instead.
                        if base_id == contract_id && !has_constructor {
                            has_constructor = true;
                            functions.push(func_id);
                        }
                    }
                    hir::FunctionKind::Fallback => {
                        if !has_fallback {
                            has_fallback = true;
                            functions.push(func_id);
                        }
                    }
                    hir::FunctionKind::Receive => {
                        if !has_receive {
                            has_receive = true;
                            functions.push(func_id);
                        }
                    }
                    hir::FunctionKind::Function | hir::FunctionKind::Modifier => {
                        // Skip private functions from base contracts - they're not inherited
                        if base_id != contract_id && func.visibility == hir::Visibility::Private {
                            continue;
                        }

                        // For regular functions, use selector to determine uniqueness.
                        // Only external/public functions have selectors.
                        let is_external_abi = matches!(
                            func.visibility,
                            hir::Visibility::External | hir::Visibility::Public
                        );
                        if is_external_abi {
                            let selector = self.function_selector(func_id);
                            if seen_selectors.insert(selector) {
                                functions.push(func_id);
                            }
                        } else {
                            // Internal functions: use function identity
                            // For simplicity, we include internal functions from all bases
                            // (they won't have selectors in the dispatcher anyway)
                            functions.push(func_id);
                        }
                    }
                }
            }
        }

        functions
    }

    /// Generates a synthetic constructor to initialize state variables and run
    /// inherited constructors when the current contract does not declare one.
    fn generate_synthetic_constructor(&mut self, contract_id: ContractId) {
        let contract = self.gcx.hir.contract(contract_id);
        let linearized_bases = contract.linearized_bases;

        let has_state_initializers = linearized_bases.iter().any(|&base_id| {
            self.gcx.hir.contract(base_id).variables().any(|var_id| {
                let var = self.gcx.hir.variable(var_id);
                var.is_state_variable() && !var.is_constant() && var.initializer.is_some()
            })
        });
        let has_base_constructors = linearized_bases.iter().any(|&base_id| {
            base_id != contract_id && self.gcx.hir.contract(base_id).ctor.is_some()
        });

        if !has_state_initializers && !has_base_constructors {
            return;
        }

        // Create constructor function
        let ctor_name = Ident::new(kw::Constructor, Span::DUMMY);
        let mut mir_func = Function::new(ctor_name);
        mir_func.attributes = FunctionAttributes {
            visibility: hir::Visibility::Public,
            state_mutability: hir::StateMutability::NonPayable,
            is_constructor: true,
            is_fallback: false,
            is_receive: false,
        };

        {
            let mut builder = FunctionBuilder::new(&mut mir_func);
            let saved_lowering_constructor = self.lowering_constructor;
            let saved_lowering_internal_function = self.lowering_internal_function;
            let saved_in_unchecked_block = self.in_unchecked_block;
            let saved_current_return_tys = std::mem::take(&mut self.current_return_tys);
            self.lowering_constructor = true;
            self.lowering_internal_function = false;
            self.in_unchecked_block = false;

            self.lower_constructor_prelude(&mut builder, contract_id);
            builder.stop();
            self.lowering_constructor = saved_lowering_constructor;
            self.lowering_internal_function = saved_lowering_internal_function;
            self.in_unchecked_block = saved_in_unchecked_block;
            self.current_return_tys = saved_current_return_tys;
        }

        self.module.add_function(mir_func);
    }

    /// Allocates storage slots for state variables.
    ///
    /// For inheritance, state variables are allocated starting from the most base contract
    /// (last in linearized_bases) to the most derived (first in linearized_bases).
    /// This ensures parent storage comes before child storage in the layout.
    fn allocate_storage(&mut self, contract_id: ContractId) {
        let contract = self.gcx.hir.contract(contract_id);
        let linearized_bases = contract.linearized_bases;

        // Iterate in reverse order (most base first) to get correct storage layout.
        // Skip index 0 since that's the contract itself - we handle it last.
        for &base_id in linearized_bases.iter().rev() {
            let base_contract = self.gcx.hir.contract(base_id);
            for var_id in base_contract.variables() {
                // Skip if we already allocated this variable (shouldn't happen, but safety check)
                if self.storage_slots.contains_key(&var_id) {
                    continue;
                }

                let var = self.gcx.hir.variable(var_id);
                // Constants are inlined. Immutables are patched into the
                // runtime code's `PUSH32` placeholders at deploy time.
                if var.is_state_variable() && var.is_immutable() {
                    let offset = self.next_immutable_offset;
                    self.next_immutable_offset = self
                        .next_immutable_offset
                        .checked_add(IMMUTABLE_WORD_SIZE as u32)
                        .expect("immutable offset overflow");
                    self.immutable_slots.insert(var_id, offset);

                    let mir_ty = self.lower_type_from_var(var);
                    self.module.add_immutable_slot(ImmutableSlot {
                        offset,
                        ty: mir_ty,
                        name: var.name,
                    });
                } else if var.is_state_variable() && !var.is_constant() {
                    let var_ty = self.gcx.type_of_hir_ty(&var.ty);
                    let location = self.allocate_storage_location(var_ty, var.ty.span);
                    let base_slot = location.slot;

                    // Track struct base slots for field access
                    if matches!(var_ty.peel_refs().kind, TyKind::Struct(_)) {
                        self.struct_storage_base_slots.insert(var_id, base_slot);
                    }

                    self.storage_slots.insert(var_id, base_slot);
                    self.storage_locations.insert(var_id, location);

                    let mir_ty = self.lower_type_from_var(var);
                    self.module.add_storage_slot(StorageSlot {
                        slot: base_slot,
                        offset: location.offset,
                        ty: mir_ty,
                        name: var.name,
                    });
                }
            }
        }
    }

    /// Returns the constant length of a fixed-size array parameter whose elements are single
    /// ABI words, for prologue decoding. Other parameter shapes return `None`.
    fn fixed_word_array_param_len(&self, param: &hir::Variable<'_>) -> Option<u64> {
        let TyKind::Array(elem, len) = self.gcx.type_of_hir_ty(&param.ty).peel_refs().kind else {
            return None;
        };
        (self.abi_is_word_element(elem) && len <= U256::from(u16::MAX)).then(|| len.to::<u64>())
    }

    /// Whether a parameter is a memory-located dynamic array of single-word elements, which
    /// the prologue decodes from calldata into Solidity's `[length][data...]` memory layout.
    fn is_dyn_word_array_memory_param(&self, param: &hir::Variable<'_>) -> bool {
        if param.data_location != Some(solar_ast::DataLocation::Memory) {
            return false;
        }
        match self.gcx.type_of_hir_ty(&param.ty).peel_refs().kind {
            TyKind::DynArray(elem) => self.abi_is_word_element(elem),
            _ => false,
        }
    }

    /// Lowers a function to MIR.
    pub(super) fn ensure_function_lowered(&mut self, func_id: hir::FunctionId) -> FunctionId {
        if let Some(&mir_id) = self.hir_to_mir_functions.get(&func_id) {
            return mir_id;
        }

        if self.lowering_functions.contains(&func_id) {
            return self
                .module
                .add_function(Function::new(Ident::new(sym::_recursive_internal, Span::DUMMY)));
        }

        let saved_locals = std::mem::take(&mut self.locals);
        let saved_local_memory_slots = std::mem::take(&mut self.local_memory_slots);
        let saved_next_local_memory_offset = self.next_local_memory_offset;
        let saved_assigned_vars = std::mem::take(&mut self.assigned_vars);
        let saved_current_contract_id = self.current_contract_id;
        let saved_lowering_constructor = self.lowering_constructor;
        let saved_lowering_internal_function = self.lowering_internal_function;
        let saved_in_unchecked_block = self.in_unchecked_block;
        let saved_current_return_tys = std::mem::take(&mut self.current_return_tys);

        self.lowering_functions.insert(func_id);
        self.current_contract_id = self.gcx.hir.function(func_id).contract;
        self.in_unchecked_block = false;
        let mir_id = self.lower_function(func_id, false);
        self.lowering_functions.remove(&func_id);

        self.locals = saved_locals;
        self.local_memory_slots = saved_local_memory_slots;
        self.next_local_memory_offset = saved_next_local_memory_offset;
        self.assigned_vars = saved_assigned_vars;
        self.current_contract_id = saved_current_contract_id;
        self.lowering_constructor = saved_lowering_constructor;
        self.lowering_internal_function = saved_lowering_internal_function;
        self.in_unchecked_block = saved_in_unchecked_block;
        self.current_return_tys = saved_current_return_tys;

        mir_id
    }

    /// Lowers a public function with the internal-frame calling convention so it
    /// can be called via `internal_call` (e.g. recursion). The result is cached
    /// separately from the external entry; the id is registered before the body
    /// is lowered so the copy's own recursive call resolves to itself.
    pub(super) fn ensure_internal_mir_function(&mut self, func_id: hir::FunctionId) -> FunctionId {
        if let Some(&mir_id) = self.hir_to_internal_mir_functions.get(&func_id) {
            return mir_id;
        }

        let saved_locals = std::mem::take(&mut self.locals);
        let saved_local_memory_slots = std::mem::take(&mut self.local_memory_slots);
        let saved_next_local_memory_offset = self.next_local_memory_offset;
        let saved_assigned_vars = std::mem::take(&mut self.assigned_vars);
        let saved_current_contract_id = self.current_contract_id;
        let saved_lowering_constructor = self.lowering_constructor;
        let saved_lowering_internal_function = self.lowering_internal_function;
        let saved_in_unchecked_block = self.in_unchecked_block;
        let saved_current_return_tys = std::mem::take(&mut self.current_return_tys);

        self.current_contract_id = self.gcx.hir.function(func_id).contract;
        self.in_unchecked_block = false;
        let mir_id = self.lower_function(func_id, true);

        self.locals = saved_locals;
        self.local_memory_slots = saved_local_memory_slots;
        self.next_local_memory_offset = saved_next_local_memory_offset;
        self.assigned_vars = saved_assigned_vars;
        self.current_contract_id = saved_current_contract_id;
        self.lowering_constructor = saved_lowering_constructor;
        self.lowering_internal_function = saved_lowering_internal_function;
        self.in_unchecked_block = saved_in_unchecked_block;
        self.current_return_tys = saved_current_return_tys;

        mir_id
    }

    /// Lowers a function to MIR. When `force_internal` is set, the function is
    /// lowered with the internal-frame convention (no selector) regardless of its
    /// visibility, and registered in `hir_to_internal_mir_functions`.
    fn lower_function(&mut self, func_id: hir::FunctionId, force_internal: bool) -> FunctionId {
        let hir_func = self.gcx.hir.function(func_id);

        let func_name = hir_func.name.unwrap_or_else(|| Ident::new(sym::_anonymous, Span::DUMMY));

        // Reserve and register the MIR id before lowering the body so recursive
        // self-calls can resolve to this function.
        let mir_id = self.module.add_function(Function::new(func_name));
        if force_internal {
            self.hir_to_internal_mir_functions.insert(func_id, mir_id);
        } else {
            self.hir_to_mir_functions.insert(func_id, mir_id);
        }

        let mut mir_func = Function::new(func_name);

        mir_func.attributes = FunctionAttributes {
            visibility: hir_func.visibility,
            state_mutability: hir_func.state_mutability,
            is_constructor: hir_func.kind == hir::FunctionKind::Constructor,
            is_fallback: hir_func.kind == hir::FunctionKind::Fallback,
            is_receive: hir_func.kind == hir::FunctionKind::Receive,
        };

        // Only regular public/external functions get selectors. An internal copy
        // (force_internal) uses the internal-frame convention with no selector.
        // Constructor, receive, and fallback don't have selectors.
        let is_special = mir_func.attributes.is_constructor
            || mir_func.attributes.is_receive
            || mir_func.attributes.is_fallback;
        let uses_external_abi = mir_func.is_public() && !is_special && !force_internal;
        let decodes_abi_params = uses_external_abi || mir_func.attributes.is_constructor;
        if uses_external_abi {
            mir_func.selector = Some(self.function_selector(func_id));
        }
        let uses_internal_frame = !uses_external_abi && !is_special;

        self.locals.clear();
        self.local_memory_slots.clear();
        self.next_local_memory_offset = 0x80;
        self.assigned_vars.clear();
        self.lowering_constructor = hir_func.kind == hir::FunctionKind::Constructor;
        self.lowering_internal_function = uses_internal_frame;
        self.in_unchecked_block = false;
        self.current_return_tys = hir_func
            .returns
            .iter()
            .map(|&id| self.gcx.type_of_hir_ty(&self.gcx.hir.variable(id).ty))
            .collect();

        // Pre-analyze function body to find variables that are assigned after declaration.
        // Variables that are only initialized (never reassigned) can stay as SSA values.
        if let Some(body) = &hir_func.body {
            self.collect_assigned_vars_block(body);
        }

        let external_arg_head_size = if uses_external_abi {
            hir_func
                .parameters
                .iter()
                .map(|&id| {
                    let param = self.gcx.hir.variable(id);
                    let ty = self.gcx.type_of_hir_ty(&param.ty);
                    self.abi_head_size(ty)
                })
                .sum()
        } else {
            0
        };

        {
            let mut builder = FunctionBuilder::new(&mut mir_func);

            if uses_external_abi {
                Self::emit_external_calldata_head_size_check(&mut builder, external_arg_head_size);
            }

            for &param_id in hir_func.parameters {
                let param = self.gcx.hir.variable(param_id);
                let param_ty = self.gcx.type_of_hir_ty(&param.ty);
                let ty = self.lower_type_from_var(param);

                // Check if this is a struct parameter that needs special handling
                let abi_param_source = if self.lowering_constructor {
                    AbiParamSource::ConstructorMemory
                } else {
                    AbiParamSource::ExternalCalldata
                };

                if decodes_abi_params && let TyKind::Struct(struct_id) = param_ty.peel_refs().kind {
                    // Struct parameters: copy fields from calldata to memory
                    let strukt = self.gcx.hir.strukt(struct_id);
                    let field_ids = strukt.fields;
                    let num_fields = field_ids.len();

                    // Allocate memory for the struct
                    let struct_size = (num_fields as u64) * 32;
                    let struct_ptr = self.allocate_memory(&mut builder, struct_size);

                    // Add MIR params for each struct field (they come from calldata)
                    for (field_idx, &field_id) in field_ids.iter().enumerate() {
                        let arg_index = builder.func().params.len() as u64;
                        let field_ty = MirType::uint256();
                        let field_val = builder.add_param(field_ty);
                        let field_var = self.gcx.hir.variable(field_id);
                        self.emit_abi_param_validation(
                            &mut builder,
                            arg_index,
                            &field_var.ty,
                            abi_param_source,
                        );

                        // Store the field value into the struct memory
                        let field_offset = (field_idx as u64) * 32;
                        if field_offset == 0 {
                            builder.mstore(struct_ptr, field_val);
                        } else {
                            let offset_val = builder.imm_u64(field_offset);
                            let field_addr = builder.add(struct_ptr, offset_val);
                            builder.mstore(field_addr, field_val);
                        }
                    }

                    // Store the memory pointer as the local (not the Arg value)
                    self.locals.insert(param_id, struct_ptr);
                } else if decodes_abi_params
                    && let Some(len) = self.fixed_word_array_param_len(param)
                {
                    // Fixed-size array of word elements (memory or calldata):
                    // the ABI head is `len` inline words. Add one MIR param per
                    // element and copy them to memory, like struct params.
                    let array_ptr = self.allocate_memory(&mut builder, len * 32);
                    let elem_hir_ty = match &param.ty.kind {
                        hir::TypeKind::Array(array) => &array.element,
                        _ => &param.ty,
                    };
                    for elem_idx in 0..len {
                        let arg_index = builder.func().params.len() as u64;
                        let elem_val = builder.add_param(MirType::uint256());
                        self.emit_abi_param_validation(
                            &mut builder,
                            arg_index,
                            elem_hir_ty,
                            abi_param_source,
                        );
                        if elem_idx == 0 {
                            builder.mstore(array_ptr, elem_val);
                        } else {
                            let offset_val = builder.imm_u64(elem_idx * 32);
                            let elem_addr = builder.add(array_ptr, offset_val);
                            builder.mstore(elem_addr, elem_val);
                        }
                    }
                    self.locals.insert(param_id, array_ptr);
                } else if decodes_abi_params && self.is_dyn_word_array_memory_param(param) {
                    // Dynamic array of word elements in memory: the ABI head is
                    // an offset to `[length][elements...]` in the ABI argument
                    // blob. Runtime calls read it from calldata after the
                    // selector; constructors read it from the copied argument
                    // blob at memory 0x80.
                    let head = builder.add_param(ty);
                    let abi_base =
                        builder.imm_u64(if self.lowering_constructor { 0x80 } else { 4 });
                    let len_pos = builder.add(abi_base, head);
                    let len = if self.lowering_constructor {
                        builder.mload(len_pos)
                    } else {
                        builder.calldataload(len_pos)
                    };
                    let word = builder.imm_u64(32);
                    let data_bytes = builder.mul(len, word);
                    let total_bytes = builder.add(data_bytes, word);
                    let free_ptr_addr = builder.imm_u64(0x40);
                    let array_ptr = builder.mload(free_ptr_addr);
                    let new_free_ptr = builder.add(array_ptr, total_bytes);
                    let free_ptr_addr = builder.imm_u64(0x40);
                    builder.mstore(free_ptr_addr, new_free_ptr);
                    builder.mstore(array_ptr, len);
                    let dst = builder.add(array_ptr, word);
                    let src = builder.add(len_pos, word);
                    if self.lowering_constructor {
                        self.mcopy(&mut builder, dst, src, data_bytes, None);
                    } else {
                        builder.calldatacopy(dst, src, data_bytes);
                    }
                    self.locals.insert(param_id, array_ptr);
                } else if decodes_abi_params
                    && param.data_location == Some(solar_ast::DataLocation::Memory)
                    && matches!(
                        param_ty.peel_refs().kind,
                        TyKind::Elementary(ElementaryType::Bytes | ElementaryType::String)
                    )
                {
                    // `bytes`/`string` memory parameter: the ABI head word is
                    // the payload's offset relative to the start of the ABI
                    // arguments. Runtime calls read it from calldata after the
                    // selector; constructors read it from the copied argument
                    // blob at memory 0x80.
                    let head = builder.add_param(ty);
                    let abi_base =
                        builder.imm_u64(if self.lowering_constructor { 0x80 } else { 4 });
                    let len_pos = builder.add(abi_base, head);
                    let len = if self.lowering_constructor {
                        builder.mload(len_pos)
                    } else {
                        builder.calldataload(len_pos)
                    };
                    let thirty_one = builder.imm_u64(31);
                    let rounded = builder.add(len, thirty_one);
                    let mask = builder.not(thirty_one);
                    let padded = builder.and(rounded, mask);
                    let word = builder.imm_u64(32);
                    let total = builder.add(padded, word);
                    let ptr = self.allocate_memory_dynamic(&mut builder, total);
                    builder.mstore(ptr, len);
                    let data_ptr = builder.add(ptr, word);
                    let src = builder.add(len_pos, word);
                    if self.lowering_constructor {
                        self.mcopy(&mut builder, data_ptr, src, len, None);
                    } else {
                        builder.calldatacopy(data_ptr, src, len);
                    }
                    self.locals.insert(param_id, ptr);
                } else {
                    // Non-struct parameters: use normal Arg handling
                    let arg_index = builder.func().params.len() as u64;
                    let val = builder.add_param(ty);
                    if decodes_abi_params {
                        self.emit_abi_param_validation(
                            &mut builder,
                            arg_index,
                            &param.ty,
                            abi_param_source,
                        );
                    }
                    self.locals.insert(param_id, val);
                }
            }

            for &ret_id in hir_func.returns {
                let ret_var = self.gcx.hir.variable(ret_id);
                let ret_ty = self.gcx.type_of_hir_ty(&ret_var.ty);
                let ty = self.lower_type_from_var(ret_var);
                builder.add_return(ty);
                // Allocate memory for return variables so they can be assigned to
                // within the function body (e.g., `liquidity = 1` in if/else branches)
                let offset = self.alloc_local_memory(ret_id);
                let offset_val = self.local_memory_addr(&mut builder, offset);
                if matches!(ret_ty.peel_refs().kind, TyKind::Struct(_)) {
                    let struct_size = self.calculate_memory_words_for_ty(ret_ty) * 32;
                    let struct_ptr = self.allocate_memory(&mut builder, struct_size);
                    builder.mstore(offset_val, struct_ptr);
                } else if self.is_fixed_memory_array_type(&ret_var.ty, ret_var.data_location)
                    && let Some(array_ptr) =
                        self.allocate_zeroed_fixed_memory_array(&mut builder, &ret_var.ty)
                {
                    // A named fixed-array return must point at real zeroed
                    // memory like a local declaration; a zero pointer aliases
                    // the scratch space.
                    builder.mstore(offset_val, array_ptr);
                } else {
                    let zero = builder.imm_u256(U256::ZERO);
                    builder.mstore(offset_val, zero);
                }
            }

            if hir_func.kind == hir::FunctionKind::Constructor
                && let Some(contract_id) = hir_func.contract
            {
                self.lower_constructor_prelude(&mut builder, contract_id);
            }

            if let Some(body) = &hir_func.body {
                self.lower_block(&mut builder, body);
            }

            if !builder.func().block(builder.current_block()).is_terminated() {
                if builder.func().returns.is_empty() {
                    builder.stop();
                } else {
                    // Load each return variable's word (the value for value types,
                    // a memory pointer for reference types).
                    let mut items: Vec<(ValueId, Ty<'gcx>)> = Vec::new();
                    for &ret_id in hir_func.returns {
                        let ret_var = self.gcx.hir.variable(ret_id);
                        let ret_val = if let Some(offset) = self.get_local_memory_offset(&ret_id) {
                            let offset_val = self.local_memory_addr(&mut builder, offset);
                            builder.mload(offset_val)
                        } else {
                            builder.imm_u256(U256::ZERO)
                        };
                        items.push((ret_val, self.gcx.type_of_hir_ty(&ret_var.ty)));
                    }
                    self.finish_external_or_internal_return(&mut builder, items, uses_external_abi);
                }
            }
        }

        self.lowering_constructor = false;
        self.lowering_internal_function = false;
        mir_func.internal_frame_size =
            self.next_local_memory_offset.saturating_sub(Self::LOCAL_MEMORY_BASE);
        if uses_external_abi && !self.current_return_tys.iter().any(|&ty| self.abi_is_dynamic(ty)) {
            mir_func.external_static_return_size =
                self.current_return_tys.iter().map(|&ty| self.abi_head_size(ty)).sum();
        }

        *self.module.function_mut(mir_id) = mir_func;
        mir_id
    }

    /// Reverts when calldata does not contain the complete ABI head.
    ///
    /// `calldataload` returns zero for missing bytes, so this guard must run
    /// before parameter validation or short calldata can be accepted as a
    /// canonical zero argument.
    fn emit_external_calldata_head_size_check(builder: &mut FunctionBuilder<'_>, head_size: u64) {
        if head_size == 0 {
            return;
        }
        let calldatasize = builder.calldatasize();
        let selector_size = builder.imm_u64(4);
        let payload_size = builder.sub(calldatasize, selector_size);
        let required_size = builder.imm_u64(head_size);
        let is_short = builder.slt(payload_size, required_size);
        Self::emit_revert_if(builder, is_short);
    }

    /// Validates the ABI encoding of a value-type external parameter.
    ///
    /// Solc via-ir reverts with empty revert data when the calldata word of a
    /// value-type parameter is not its canonical encoding, and downstream code
    /// (including our checked-arithmetic shapes) relies on arguments being
    /// canonical. We mirror solc's `validator_revert_t_*` semantics:
    /// - `uintN` (N < 256): high bits must be zero
    /// - `intN` (N < 256): the word must equal its sign extension
    /// - `address` / contract types: top 96 bits must be zero
    /// - `bool`: the word must be 0 or 1
    /// - `bytesN` (N < 32): low `32 - N` bytes must be zero
    /// - enums: the value must be less than the member count
    ///
    /// Reference and dynamic types are not validated here.
    ///
    /// The check reads the raw word with an explicit `calldataload` instead of
    /// reusing the `Arg` value: optimization passes are allowed to assume that
    /// `Arg` values of external functions are canonical (this validation is
    /// what establishes that invariant), so the validator itself must read the
    /// unvalidated word opaquely or it would be folded away.
    fn emit_abi_param_validation(
        &mut self,
        builder: &mut FunctionBuilder<'_>,
        arg_index: u64,
        hir_ty: &hir::Type<'_>,
        source: AbiParamSource,
    ) {
        enum Validator {
            /// The word must equal itself masked with the given mask.
            Mask(U256),
            /// The word must equal `signextend(byte_index, word)`.
            SignExtend(u64),
            /// The word must equal `iszero(iszero(word))`.
            Bool,
            /// The word must be less than the member count.
            EnumRange(u64),
        }

        let mut ty = self.gcx.type_of_hir_ty(hir_ty);
        if let TyKind::Udvt(underlying, _) = ty.kind {
            ty = underlying;
        }
        let validator = match ty.kind {
            TyKind::Elementary(elem) => match elem {
                ElementaryType::UInt(size) => {
                    let bits = size.bits();
                    if bits >= 256 {
                        return;
                    }
                    Validator::Mask(U256::MAX >> (256 - usize::from(bits)))
                }
                ElementaryType::Int(size) => {
                    let bits = size.bits();
                    if bits >= 256 {
                        return;
                    }
                    Validator::SignExtend(u64::from(bits / 8) - 1)
                }
                ElementaryType::Address(_) => Validator::Mask(U256::MAX >> 96),
                ElementaryType::Bool => Validator::Bool,
                ElementaryType::FixedBytes(size) => {
                    let bytes = size.bytes();
                    if bytes >= 32 {
                        return;
                    }
                    Validator::Mask(U256::MAX << (256 - 8 * usize::from(bytes)))
                }
                _ => return,
            },
            TyKind::Contract(_) => Validator::Mask(U256::MAX >> 96),
            TyKind::Enum(enum_id) => {
                Validator::EnumRange(self.gcx.hir.enumm(enum_id).variants.len() as u64)
            }
            _ => return,
        };

        let word = match source {
            AbiParamSource::ExternalCalldata => {
                // Runtime ABI encoding: selector (4 bytes) + one head word per parameter.
                let offset = builder.imm_u64(4 + arg_index * 32);
                builder.calldataload(offset)
            }
            AbiParamSource::ConstructorMemory => {
                // Constructor ABI arguments are copied to memory at 0x80 by the backend.
                let offset = builder.imm_u64(0x80 + arg_index * 32);
                builder.mload(offset)
            }
        };
        let ok = match validator {
            Validator::Mask(mask) => {
                let mask = builder.imm_u256(mask);
                let canonical = builder.and(word, mask);
                builder.eq(word, canonical)
            }
            Validator::SignExtend(byte_index) => {
                let byte_index = builder.imm_u64(byte_index);
                let canonical = builder.signextend(byte_index, word);
                builder.eq(word, canonical)
            }
            Validator::Bool => {
                let is_zero = builder.iszero(word);
                let canonical = builder.iszero(is_zero);
                builder.eq(word, canonical)
            }
            Validator::EnumRange(count) => {
                let count = builder.imm_u64(count);
                builder.lt(word, count)
            }
        };
        Self::emit_revert_unless(builder, ok);
    }

    /// Branches to a plain `revert(0, 0)` when `cond` is zero, then continues
    /// lowering in the fallthrough block.
    fn emit_revert_unless(builder: &mut FunctionBuilder<'_>, cond: ValueId) {
        let revert_block = builder.create_block();
        let continue_block = builder.create_block();
        builder.branch(cond, continue_block, revert_block);

        builder.switch_to_block(revert_block);
        let zero = builder.imm_u64(0);
        builder.revert(zero, zero);

        builder.switch_to_block(continue_block);
    }

    /// Reverts with empty data when `cond` is true, continuing otherwise.
    /// Branching directly on the condition avoids an `iszero` polarity flip.
    fn emit_revert_if(builder: &mut FunctionBuilder<'_>, cond: ValueId) {
        let revert_block = builder.create_block();
        let continue_block = builder.create_block();
        builder.branch(cond, revert_block, continue_block);

        builder.switch_to_block(revert_block);
        let zero = builder.imm_u64(0);
        builder.revert(zero, zero);

        builder.switch_to_block(continue_block);
    }

    /// Lowers state-variable initializers and base constructors for an explicit constructor.
    fn lower_constructor_prelude(
        &mut self,
        builder: &mut FunctionBuilder<'_>,
        contract_id: ContractId,
    ) {
        let contract = self.gcx.hir.contract(contract_id);

        // Solidity runs construction from base to derived. For each contract in that order,
        // initialize its state variables, then run its constructor body. The current contract's
        // own constructor body is lowered by the caller after this prelude.
        let construction_order: Vec<_> = contract
            .linearized_bases
            .iter()
            .enumerate()
            .map(|(idx, &base_id)| {
                let args = idx.checked_sub(1).and_then(|arg_idx| {
                    contract.linearized_bases_args.get(arg_idx).and_then(|m| *m)
                });
                (base_id, args)
            })
            .collect();

        for (base_id, args) in construction_order.into_iter().rev() {
            let base_contract = self.gcx.hir.contract(base_id);
            for var_id in base_contract.variables() {
                let var = self.gcx.hir.variable(var_id);
                if var.is_state_variable()
                    && !var.is_constant()
                    && let Some(init) = var.initializer
                {
                    let init_val = self.lower_expr(builder, init);
                    if let Some(&offset) = self.immutable_slots.get(&var_id) {
                        self.store_immutable_value(builder, offset, init_val);
                    } else if let Some(&location) = self.storage_locations.get(&var_id) {
                        self.store_storage_location(builder, location, init_val);
                    }
                }
            }

            if base_id != contract_id
                && let Some(ctor_id) = base_contract.ctor
            {
                self.lower_base_constructor_call(builder, ctor_id, args);
            }
        }
    }

    fn function_selector(&self, func_id: HirFunctionId) -> [u8; 4] {
        self.gcx.function_selector(func_id).0
    }

    pub(super) fn mcopy(
        &self,
        builder: &mut FunctionBuilder<'_>,
        dest: ValueId,
        src: ValueId,
        len: ValueId,
        span: Option<Span>,
    ) {
        if self.gcx.sess.opts.evm_version.has_mcopy() {
            builder.mcopy(dest, src, len);
        } else {
            let err = self.gcx.dcx().err("codegen requires Cancun-compatible EVM for memory copy");
            let err = if let Some(span) = span { err.span(span) } else { err };
            err.help("compile with `--evm-version cancun` or newer").emit();
        }
    }

    /// Lowers a type from a variable declaration.
    fn lower_type_from_var(&self, var: &hir::Variable<'_>) -> MirType {
        self.lower_type_from_ty(self.gcx.type_of_hir_ty(&var.ty))
    }

    /// Lowers a type-checked Solidity type to MIR's coarse value type.
    fn lower_type_from_ty(&self, ty: Ty<'gcx>) -> MirType {
        match ty.peel_refs().kind {
            TyKind::Elementary(elem) => match elem {
                ElementaryType::Bool => MirType::Bool,
                ElementaryType::Address(_) => MirType::Address,
                ElementaryType::Int(bits) => MirType::Int(bits.bits()),
                ElementaryType::UInt(bits) => MirType::UInt(bits.bits()),
                ElementaryType::Fixed(_, _) => MirType::Int(256),
                ElementaryType::UFixed(_, _) => MirType::UInt(256),
                ElementaryType::FixedBytes(n) => MirType::FixedBytes(n.bytes()),
                ElementaryType::String | ElementaryType::Bytes => MirType::MemPtr,
            },
            TyKind::Mapping(_, _) => MirType::StoragePtr,
            TyKind::DynArray(_) | TyKind::Array(_, _) | TyKind::Slice(_) => MirType::MemPtr,
            TyKind::Fn(_) => MirType::Function,
            TyKind::Struct(_) => MirType::MemPtr,
            TyKind::Enum(_) => MirType::UInt(8),
            TyKind::Contract(_) | TyKind::Super(_) => MirType::Address,
            TyKind::StringLiteral(_, _)
            | TyKind::IntLiteral(_, _, _)
            | TyKind::Tuple(_)
            | TyKind::Variadic
            | TyKind::Error(_, _)
            | TyKind::Event(_, _)
            | _ => MirType::uint256(),
        }
    }

    /// Returns the completed module.
    #[must_use]
    pub fn finish(self) -> Module {
        self.module
    }

    /// Collects variables that are assigned after declaration in a block.
    fn collect_assigned_vars_block(&mut self, block: &hir::Block<'_>) {
        for stmt in block.stmts {
            self.collect_assigned_vars_stmt(stmt);
        }
    }

    /// Collects variables that are assigned after declaration in a statement.
    fn collect_assigned_vars_stmt(&mut self, stmt: &hir::Stmt<'_>) {
        use hir::StmtKind;
        match &stmt.kind {
            StmtKind::Expr(expr) => self.collect_assigned_vars_expr(expr),
            StmtKind::Block(block) | StmtKind::UncheckedBlock(block) => {
                self.collect_assigned_vars_block(block)
            }
            StmtKind::If(cond, then_stmt, else_stmt) => {
                self.collect_assigned_vars_expr(cond);
                self.collect_assigned_vars_stmt(then_stmt);
                if let Some(else_s) = else_stmt {
                    self.collect_assigned_vars_stmt(else_s);
                }
            }
            StmtKind::Loop(block, _) => self.collect_assigned_vars_block(block),
            StmtKind::Switch(switch) => {
                self.collect_assigned_vars_expr(switch.selector);
                for case in switch.cases {
                    self.collect_assigned_vars_block(&case.body);
                }
            }
            StmtKind::Return(Some(expr)) | StmtKind::Revert(expr) | StmtKind::Emit(expr) => {
                self.collect_assigned_vars_expr(expr)
            }
            StmtKind::Try(try_stmt) => {
                self.collect_assigned_vars_expr(&try_stmt.expr);
                for clause in try_stmt.clauses {
                    self.collect_assigned_vars_block(&clause.block);
                }
            }
            StmtKind::AssemblyBlock(block) => self.collect_assigned_vars_block(block),
            StmtKind::DeclSingle(_)
            | StmtKind::DeclMulti(_, _)
            | StmtKind::Return(None)
            | StmtKind::Continue
            | StmtKind::Break
            | StmtKind::Placeholder
            | StmtKind::Err(_) => {}
        }
    }

    /// Collects variables that are assigned in an expression.
    fn collect_assigned_vars_expr(&mut self, expr: &hir::Expr<'_>) {
        use hir::ExprKind;
        match &expr.kind {
            ExprKind::Assign(lhs, _, rhs) => {
                // Record assignment targets
                self.mark_assigned_var(lhs);
                self.collect_assigned_vars_expr(rhs);
            }
            ExprKind::Binary(lhs, _, rhs) => {
                self.collect_assigned_vars_expr(lhs);
                self.collect_assigned_vars_expr(rhs);
            }
            ExprKind::Unary(op, operand) => {
                // ++x, x++, --x, x-- are unary ops that mutate the operand
                use solar_ast::UnOpKind;
                if matches!(
                    op.kind,
                    UnOpKind::PreInc | UnOpKind::PostInc | UnOpKind::PreDec | UnOpKind::PostDec
                ) {
                    self.mark_assigned_var(operand);
                }
                self.collect_assigned_vars_expr(operand);
            }
            ExprKind::Ternary(cond, true_val, false_val) => {
                self.collect_assigned_vars_expr(cond);
                self.collect_assigned_vars_expr(true_val);
                self.collect_assigned_vars_expr(false_val);
            }
            ExprKind::Call(callee, args, _) => {
                self.collect_assigned_vars_expr(callee);
                for arg in args.kind.exprs() {
                    self.collect_assigned_vars_expr(arg);
                }
            }
            ExprKind::Index(base, idx) => {
                self.collect_assigned_vars_expr(base);
                if let Some(i) = idx {
                    self.collect_assigned_vars_expr(i);
                }
            }
            ExprKind::Slice(base, start, end) => {
                self.collect_assigned_vars_expr(base);
                if let Some(s) = start {
                    self.collect_assigned_vars_expr(s);
                }
                if let Some(e) = end {
                    self.collect_assigned_vars_expr(e);
                }
            }
            ExprKind::Member(base, _) | ExprKind::YulMember(base, _) => {
                self.collect_assigned_vars_expr(base)
            }
            ExprKind::Array(elems) => {
                for elem in elems.iter() {
                    self.collect_assigned_vars_expr(elem);
                }
            }
            ExprKind::Tuple(elems) => {
                for elem in elems.iter().flatten() {
                    self.collect_assigned_vars_expr(elem);
                }
            }
            ExprKind::Payable(inner) | ExprKind::Delete(inner) => {
                self.collect_assigned_vars_expr(inner)
            }
            ExprKind::New(_)
            | ExprKind::TypeCall(_)
            | ExprKind::Lit(_)
            | ExprKind::Ident(_)
            | ExprKind::Type(_)
            | ExprKind::Err(_) => {}
        }
    }

    /// Marks a variable as being assigned (needs memory storage).
    fn mark_assigned_var(&mut self, expr: &hir::Expr<'_>) {
        if let Some(var_id) = self.ident_variable(expr) {
            self.assigned_vars.insert(var_id);
        }
    }

    /// Returns true if a variable is assigned after declaration.
    pub fn is_var_assigned(&self, var_id: &VariableId) -> bool {
        self.assigned_vars.contains(var_id)
    }

    /// Checks if an expression contains an external call.
    /// External calls write their return data to shared memory at offset 0,
    /// so variables initialized from them must be stored in memory to preserve the value
    /// across subsequent calls.
    pub fn has_external_call(&self, expr: &hir::Expr<'_>) -> bool {
        use hir::ExprKind;
        match &expr.kind {
            ExprKind::Call(callee, args, _) => {
                // Check if this is an external call (method call on a contract)
                if self.is_external_call(callee) {
                    return true;
                }
                // Check callee and arguments for nested external calls
                if self.has_external_call(callee) {
                    return true;
                }
                for arg in args.kind.exprs() {
                    if self.has_external_call(arg) {
                        return true;
                    }
                }
                false
            }
            ExprKind::Member(base, _) | ExprKind::YulMember(base, _) => {
                // Member access itself doesn't contain external calls
                // but the base might
                self.has_external_call(base)
            }
            ExprKind::Binary(lhs, _, rhs) => {
                self.has_external_call(lhs) || self.has_external_call(rhs)
            }
            ExprKind::Unary(_, operand) => self.has_external_call(operand),
            ExprKind::Ternary(cond, true_val, false_val) => {
                self.has_external_call(cond)
                    || self.has_external_call(true_val)
                    || self.has_external_call(false_val)
            }
            ExprKind::Index(base, idx) => {
                self.has_external_call(base) || idx.is_some_and(|i| self.has_external_call(i))
            }
            ExprKind::Array(elems) => elems.iter().any(|e| self.has_external_call(e)),
            ExprKind::Tuple(elems) => {
                elems.iter().any(|e| e.is_some_and(|expr| self.has_external_call(expr)))
            }
            ExprKind::Payable(inner) | ExprKind::Delete(inner) => self.has_external_call(inner),
            ExprKind::Slice(base, start, end) => {
                self.has_external_call(base)
                    || start.is_some_and(|s| self.has_external_call(s))
                    || end.is_some_and(|e| self.has_external_call(e))
            }
            ExprKind::Assign(lhs, _, rhs) => {
                self.has_external_call(lhs) || self.has_external_call(rhs)
            }
            ExprKind::New(_)
            | ExprKind::TypeCall(_)
            | ExprKind::Lit(_)
            | ExprKind::Ident(_)
            | ExprKind::Type(_)
            | ExprKind::Err(_) => false,
        }
    }

    /// Checks if a call expression is an external call (method on a contract).
    fn is_external_call(&self, callee: &hir::Expr<'_>) -> bool {
        // External calls are Member expressions where the base is a contract
        if let hir::ExprKind::Member(base, _) = &callee.kind
            && let Some(var_id) = self.ident_variable(base)
        {
            let var = self.gcx.hir.variable(var_id);
            // Contract type variables are external call targets
            if matches!(var.ty.kind, hir::TypeKind::Custom(hir::ItemId::Contract(_))) {
                return true;
            }
        }
        false
    }
}

/// Lowers a contract from HIR to MIR.
pub fn lower_contract(gcx: Gcx<'_>, contract_id: ContractId) -> Module {
    lower_contract_with_bytecodes(gcx, contract_id, &FxHashMap::default())
}

/// Returns contracts whose creation bytecode is referenced by `contract_id`.
pub fn contract_bytecode_dependencies(
    gcx: Gcx<'_>,
    contract_id: ContractId,
) -> FxHashSet<ContractId> {
    let mut deps = FxHashSet::default();
    BytecodeDependencyCollector { gcx, deps: &mut deps }.collect_contract(contract_id);
    deps.remove(&contract_id);
    deps
}

struct BytecodeDependencyCollector<'a, 'gcx> {
    gcx: Gcx<'gcx>,
    deps: &'a mut FxHashSet<ContractId>,
}

impl<'a, 'gcx> BytecodeDependencyCollector<'a, 'gcx> {
    fn collect_contract(&mut self, contract_id: ContractId) {
        let contract = self.gcx.hir.contract(contract_id);

        for modifier in contract.linearized_bases_args.iter().flatten() {
            let ControlFlow::Continue(()) = self.visit_modifier(modifier);
        }

        for &base_id in contract.linearized_bases {
            let base = self.gcx.hir.contract(base_id);

            for var_id in base.variables() {
                let ControlFlow::Continue(()) = self.visit_nested_var(var_id);
            }

            for func_id in base.all_functions() {
                let func = self.gcx.hir.function(func_id);

                for modifier in func.modifiers {
                    let ControlFlow::Continue(()) = self.visit_modifier(modifier);
                }

                if let Some(body) = func.body {
                    for stmt in body.stmts {
                        let ControlFlow::Continue(()) = self.visit_stmt(stmt);
                    }
                }
            }
        }
    }

    fn collect_type(&mut self, ty: &hir::Type<'gcx>) {
        if let hir::TypeKind::Custom(hir::ItemId::Contract(contract_id)) = &ty.kind {
            self.deps.insert(*contract_id);
        }
    }
}

impl<'gcx> Visit<'gcx> for BytecodeDependencyCollector<'_, 'gcx> {
    type BreakValue = Never;

    fn hir(&self) -> &'gcx hir::Hir<'gcx> {
        &self.gcx.hir
    }

    fn visit_expr(&mut self, expr: &'gcx hir::Expr<'gcx>) -> ControlFlow<Self::BreakValue> {
        match &expr.kind {
            hir::ExprKind::New(ty) => self.collect_type(ty),
            hir::ExprKind::Member(base, member)
                if matches!(member.name, sym::creationCode | sym::runtimeCode) =>
            {
                if let hir::ExprKind::TypeCall(ty) = &base.kind {
                    self.collect_type(ty);
                }
            }
            _ => {}
        }

        self.walk_expr(expr)
    }
}

/// Lowers a contract from HIR to MIR with pre-compiled bytecodes available for `new` expressions.
pub fn lower_contract_with_bytecodes(
    gcx: Gcx<'_>,
    contract_id: ContractId,
    child_bytecodes: &FxHashMap<ContractId, Vec<u8>>,
) -> Module {
    let contract = gcx.hir.contract(contract_id);
    let mut lowerer = Lowerer::new(gcx, contract.name);

    // Register all child contract bytecodes
    for (&child_id, bytecode) in child_bytecodes {
        lowerer.register_contract_bytecode(child_id, bytecode.clone());
    }

    lowerer.lower_contract(contract_id);
    lowerer.finish()
}