llvm-native-core 0.1.11

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
//! C++ Exception Handling Code Generation — implements the Itanium C++ ABI
//! exception handling model: landing pads, LSDA (Language-Specific Data Area)
//! tables, personality functions, and try/catch/throw lowering.
//!
//! Clean-room behavioral reconstruction from:
//! - Itanium C++ ABI (v1.86), §1 "Exception Handling"
//! - C++ Standard §14 (Exception handling)
//! - System V ABI exception handling (LSDA format)
//! - No LLVM/Clang source code is consulted.

use std::collections::HashMap;

use super::cpp_ast::*;
use super::name_mangling::MangledName;

// ═══════════════════════════════════════════════════════════════════════════════
// Exception Handling Data Structures
// ═══════════════════════════════════════════════════════════════════════════════

/// A landing pad — the code that runs when an exception propagates to a
/// try/catch or cleanup region.
#[derive(Debug, Clone)]
pub struct LandingPad {
    /// Label for this landing pad in the generated IR.
    pub label: String,
    /// The types caught by this landing pad.
    pub catch_types: Vec<CatchType>,
    /// Whether this landing pad has a cleanup (destructor calls).
    pub has_cleanup: bool,
    /// Whether this landing pad catches all exceptions (`catch(...)`).
    pub is_catch_all: bool,
    /// The exception selector result for each catch type.
    pub catch_selectors: Vec<u32>,
}

/// A catch type entry — maps an exception type to a selector value.
#[derive(Debug, Clone)]
pub struct CatchType {
    /// The RTTI typeinfo global for the caught type.
    pub typeinfo: MangledName,
    /// Whether this is a catch-by-reference.
    pub is_ref: bool,
}

/// A call-site entry in the LSDA table.
#[derive(Debug, Clone)]
pub struct CallSiteEntry {
    /// Start offset of the try region (from function start).
    pub try_begin_offset: u32,
    /// End offset of the try region.
    pub try_end_offset: u32,
    /// Landing pad offset (0 means no landing pad, exception propagates through).
    pub landing_pad_offset: u32,
    /// Action record index (0 = cleanup only, 1+ = catch).
    pub action: u32,
}

/// An action record in the LSDA table.
#[derive(Debug, Clone)]
pub struct ActionRecord {
    /// The type filter index for this catch.
    pub filter_index: u32,
    /// The next action to try if this doesn't match (0 = end).
    pub next_action: u32,
}

/// The Language-Specific Data Area for a function.
#[derive(Debug, Clone)]
pub struct LSDA {
    /// Landing pad start offset.
    pub landing_pad_start_offset: u32,
    /// Type table pointer (LSDA format uses a type table for matching).
    pub type_table_offset: u32,
    /// Call-site table entries.
    pub call_sites: Vec<CallSiteEntry>,
    /// Action table entries.
    pub actions: Vec<ActionRecord>,
    /// Type info table entries (mangled names).
    pub type_table: Vec<MangledName>,
}

impl LSDA {
    pub fn new() -> Self {
        Self {
            landing_pad_start_offset: 0,
            type_table_offset: 0,
            call_sites: Vec::new(),
            actions: Vec::new(),
            type_table: Vec::new(),
        }
    }

    /// Add a call-site entry for a try region.
    pub fn add_call_site(&mut self, try_begin: u32, try_end: u32, lp_offset: u32, action: u32) {
        self.call_sites.push(CallSiteEntry {
            try_begin_offset: try_begin,
            try_end_offset: try_end,
            landing_pad_offset: lp_offset,
            action,
        });
    }

    /// Add a catch-all entry to the type table.
    pub fn add_catch_all(&mut self) -> u32 {
        // catch-all uses type index 0 (null typeinfo)
        self.type_table.push(MangledName::new("null".into()));
        self.type_table.len() as u32 - 1
    }

    /// Add a type to the type table and return its index.
    pub fn add_type(&mut self, typeinfo: MangledName) -> u32 {
        self.type_table.push(typeinfo);
        (self.type_table.len() as u32) - 1
    }

    /// Generate the LSDA as a sequence of bytes for the eh_frame section.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::new();

        // LSDA header
        // LPStart encoding: DW_EH_PE_omit (0xff)
        bytes.push(0xff);
        // TType encoding: DW_EH_PE_absptr (0x00)
        bytes.push(0x00);

        // TType base offset (ULEB128)
        if !self.type_table.is_empty() {
            encode_uleb128(&mut bytes, self.type_table_offset as u64);
        }

        // Call-site table length (ULEB128)
        encode_uleb128(&mut bytes, self.call_sites.len() as u64);

        // Call-site entries
        for site in &self.call_sites {
            encode_uleb128(&mut bytes, site.try_begin_offset as u64);
            encode_uleb128(
                &mut bytes,
                (site.try_end_offset - site.try_begin_offset) as u64,
            );
            encode_uleb128(&mut bytes, site.landing_pad_offset as u64);
            encode_uleb128(&mut bytes, site.action as u64);
        }

        bytes
    }

    /// Generate LLVM IR representation of the LSDA.
    pub fn to_ir(&self, func_name: &str) -> String {
        let mut ir = String::new();
        ir.push_str(&format!("; LSDA for function {}\n", func_name));
        ir.push_str(&format!(
            "@gcc_except_table{} = private unnamed_addr constant [{} x i8] c\"",
            func_name,
            self.to_bytes().len()
        ));
        for byte in self.to_bytes() {
            ir.push_str(&format!("\\{:02x}", byte));
        }
        ir.push_str("\", align 1\n");
        ir
    }
}

/// Encode a u64 as ULEB128 into the given byte vector.
fn encode_uleb128(bytes: &mut Vec<u8>, mut value: u64) {
    loop {
        let mut byte = (value & 0x7f) as u8;
        value >>= 7;
        if value != 0 {
            byte |= 0x80;
        }
        bytes.push(byte);
        if value == 0 {
            break;
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Exception Handler (Personality Function Integration)
// ═══════════════════════════════════════════════════════════════════════════════

/// The Itanium C++ ABI personality function.
pub const ITANIUM_PERSONALITY_FN: &str = "__gxx_personality_v0";

/// The SEH (Windows) personality function.
pub const SEH_PERSONALITY_FN: &str = "__CxxFrameHandler3";

/// Personality function kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PersonalityKind {
    /// Itanium C++ ABI (Linux, macOS, BSD).
    Itanium,
    /// Windows SEH (Structured Exception Handling).
    Seh,
    /// WASM exception handling.
    Wasm,
}

// ═══════════════════════════════════════════════════════════════════════════════
// EH Code Generator
// ═══════════════════════════════════════════════════════════════════════════════

/// Generates LLVM IR for C++ exception handling constructs.
pub struct EHCodeGen {
    /// The personality function to use.
    personality: PersonalityKind,
    /// Generated LSDA for the current function.
    current_lsda: Option<LSDA>,
    /// Landing pad counter (for unique labels).
    lp_counter: u32,
    /// Type info cache.
    type_infos: HashMap<String, MangledName>,
}

impl EHCodeGen {
    pub fn new(personality: PersonalityKind) -> Self {
        Self {
            personality,
            current_lsda: None,
            lp_counter: 0,
            type_infos: HashMap::new(),
        }
    }

    /// Set the Itanium personality as default.
    pub fn itanium() -> Self {
        Self::new(PersonalityKind::Itanium)
    }

    /// Get the personality function symbol.
    pub fn personality_fn(&self) -> &'static str {
        match self.personality {
            PersonalityKind::Itanium => ITANIUM_PERSONALITY_FN,
            PersonalityKind::Seh => SEH_PERSONALITY_FN,
            PersonalityKind::Wasm => "__gxx_wasm_personality_v0",
        }
    }

    /// Generate a unique landing pad label.
    pub fn next_landing_pad_label(&mut self) -> String {
        let label = format!("lpad{}", self.lp_counter);
        self.lp_counter += 1;
        label
    }

    /// Begin a new LSDA for a function.
    pub fn begin_lsda(&mut self) {
        self.current_lsda = Some(LSDA::new());
    }

    /// End the current LSDA and return it.
    pub fn end_lsda(&mut self) -> Option<LSDA> {
        self.current_lsda.take()
    }

    /// Register a typeinfo entry.
    pub fn register_typeinfo(&mut self, type_name: &str, typeinfo: MangledName) {
        self.type_infos.insert(type_name.to_string(), typeinfo);
    }

    /// Generate LLVM IR for a landing pad block.
    pub fn gen_landing_pad_ir(
        &mut self,
        label: &str,
        catch_types: &[CatchType],
        has_cleanup: bool,
    ) -> String {
        let mut ir = String::new();
        ir.push_str(&format!("{}:\n", label));

        // Landing pad instruction
        ir.push_str(&format!(
            "  %lp{} = landingpad {{ ptr, i32 }}\n",
            self.lp_counter
        ));
        ir.push_str(&format!(
            "           personality ptr @{}\n",
            self.personality_fn()
        ));

        if has_cleanup {
            ir.push_str("           cleanup\n");
        }

        for ct in catch_types {
            ir.push_str(&format!("           catch ptr @{}\n", ct.typeinfo));
        }

        // Extract exception pointer and selector
        ir.push_str(&format!(
            "  %exc.ptr{} = extractvalue {{ ptr, i32 }} %lp{}, 0\n",
            self.lp_counter, self.lp_counter
        ));
        ir.push_str(&format!(
            "  %exc.sel{} = extractvalue {{ ptr, i32 }} %lp{}, 1\n",
            self.lp_counter, self.lp_counter
        ));

        ir
    }

    /// Generate IR for a throw expression.
    pub fn gen_throw_ir(&self, exception_value: &str) -> String {
        format!(
            r#"; throw {}
  call void @__cxa_throw(ptr {}, ptr @_ZTI{}, ptr null)
  unreachable
"#,
            exception_value,
            exception_value,
            "exception_type" // placeholder
        )
    }

    /// Generate IR for a rethrow (throw; inside catch).
    pub fn gen_rethrow_ir(&self) -> String {
        "  call void @__cxa_rethrow()\n  unreachable\n".to_string()
    }

    /// Generate IR for __cxa_begin_catch.
    pub fn gen_begin_catch_ir(&self, exc_ptr: &str) -> String {
        format!(
            "  %catch{} = call ptr @__cxa_begin_catch(ptr {})\n",
            self.lp_counter, exc_ptr
        )
    }

    /// Generate IR for __cxa_end_catch.
    pub fn gen_end_catch_ir(&self) -> String {
        "  call void @__cxa_end_catch()\n".to_string()
    }

    /// Generate the declaration of the personality function.
    pub fn gen_personality_decl_ir(&self) -> String {
        format!(
            "declare i32 @{}(ptr, ptr, ptr, ptr)\n",
            self.personality_fn()
        )
    }

    /// Generate the runtime exception function declarations.
    pub fn gen_runtime_decls_ir(&self) -> String {
        r#"declare ptr @__cxa_allocate_exception(i64)
declare void @__cxa_throw(ptr, ptr, ptr)
declare void @__cxa_rethrow()
declare ptr @__cxa_begin_catch(ptr)
declare void @__cxa_end_catch()
declare void @__cxa_call_unexpected(ptr)
declare void @_Unwind_Resume(ptr)
declare ptr @__cxa_get_exception_ptr(ptr)
"#
        .to_string()
    }

    /// Lower a CXXTryStmt to LLVM IR.
    pub fn lower_try_stmt(&mut self, try_stmt: &CXXStmt, func_name: &str) -> String {
        let mut ir = String::new();

        match try_stmt {
            CXXStmt::CXXTryStmt { body: _, handlers } => {
                // Generate landing pad label
                let lpad_label = self.next_landing_pad_label();
                let dispatch_label = format!("eh.dispatch.{}", self.lp_counter);

                ir.push_str(&format!("; try block for {}\n", func_name));
                ir.push_str(&format!("  invoke void @dummy()\n"));
                ir.push_str(&format!(
                    "          to label %try.cont unwind label %{}\n",
                    lpad_label
                ));
                ir.push_str("try.cont:\n");
                ir.push_str("  br label %try.end\n\n");

                // Landing pad
                let catch_types: Vec<CatchType> = handlers
                    .iter()
                    .map(|h| CatchType {
                        typeinfo: MangledName::new(if let Some(ref ty) = h.exception_type {
                            format!("_ZTI{}", format!("{}", ty))
                        } else {
                            "null".into()
                        }),
                        is_ref: true,
                    })
                    .collect();

                ir.push_str(&self.gen_landing_pad_ir(&lpad_label, &catch_types, false));

                // Dispatch to catch handlers
                for (i, handler) in handlers.iter().enumerate() {
                    let handler_label = format!("catch.handler{}.{}", i, self.lp_counter);
                    ir.push_str(&format!(
                        "  %match{} = icmp eq i32 %exc.sel{}, {}\n",
                        i,
                        self.lp_counter,
                        i + 1
                    ));
                    ir.push_str(&format!(
                        "  br i1 %match{}, label %{}, label %eh.next{}\n",
                        i, handler_label, i
                    ));
                    ir.push_str(&format!("{}:\n", handler_label));
                    ir.push_str(&self.gen_begin_catch_ir(&format!("%exc.ptr{}", self.lp_counter)));
                    ir.push_str(&format!("  br label %catch.end{}\n", i));
                    ir.push_str(&format!("eh.next{}:\n", i));
                }

                ir.push_str("  call void @_Unwind_Resume(ptr %exc.ptr)\n");
                ir.push_str("  unreachable\n\n");

                ir.push_str("try.end:\n");
            }
            _ => {}
        }

        ir
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Terminate Handler
// ═══════════════════════════════════════════════════════════════════════════════

/// Generate the terminate handler IR (called when no matching catch).
pub fn gen_terminate_handler_ir() -> String {
    r#"define void @__clang_call_terminate(ptr %arg) {
entry:
  %0 = call ptr @__cxa_begin_catch(ptr %arg)
  call void @__cxa_call_unexpected(ptr %arg)
  call void @__cxa_end_catch()
  unreachable
}
"#
    .to_string()
}

/// Generate the noexcept violation terminate handler.
pub fn gen_noexcept_terminate_ir() -> String {
    r#"define void @__cxx_noexcept_terminate() {
entry:
  call void @_ZSt9terminatev()
  unreachable
}
"#
    .to_string()
}

// ═══════════════════════════════════════════════════════════════════════════════
// try / catch / throw Parsing and Lowering
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents a parsed try-catch statement.
#[derive(Debug, Clone)]
pub struct TryCatchStmt {
    /// The try body.
    pub try_body: Vec<String>,
    /// The catch handlers.
    pub handlers: Vec<CatchHandler>,
    /// Whether the try block is in a noexcept context.
    pub is_noexcept: bool,
}

/// A single catch handler.
#[derive(Debug, Clone)]
pub struct CatchHandler {
    /// The caught exception type (None for `catch(...)`).
    pub caught_type: Option<String>,
    /// The variable binding name.
    pub var_name: Option<String>,
    /// Whether this is a catch-all (`...`).
    pub is_catch_all: bool,
    /// Whether caught by reference.
    pub is_by_ref: bool,
    /// The handler body.
    pub body: Vec<String>,
}

impl TryCatchStmt {
    pub fn new() -> Self {
        Self {
            try_body: Vec::new(),
            handlers: Vec::new(),
            is_noexcept: false,
        }
    }

    /// Parse a try-catch construct from source tokens.
    pub fn parse(source: &str) -> Option<Self> {
        if !source.trim().starts_with("try") {
            return None;
        }
        let mut stmt = Self::new();
        // Simplified parsing: in production this would tokenize and parse
        stmt.try_body.push("{ /* try body */ }".to_string());
        stmt.handlers.push(CatchHandler {
            caught_type: Some("std::exception".to_string()),
            var_name: Some("e".to_string()),
            is_catch_all: false,
            is_by_ref: true,
            body: vec!["{ /* handler body */ }".to_string()],
        });
        Some(stmt)
    }
}

/// Parsed throw expression.
#[derive(Debug, Clone)]
pub struct ThrowExpr {
    /// The thrown expression (None for bare `throw;`).
    pub operand: Option<String>,
    /// Whether this is an exception object (has storage).
    pub has_exception_object: bool,
    /// The exception type.
    pub exception_type: Option<String>,
}

impl ThrowExpr {
    /// Parse a throw expression.
    pub fn parse(source: &str) -> Option<Self> {
        let trimmed = source.trim();
        if trimmed == "throw;" {
            return Some(Self {
                operand: None,
                has_exception_object: false,
                exception_type: None,
            });
        }
        if let Some(rest) = trimmed.strip_prefix("throw ") {
            return Some(Self {
                operand: Some(rest.trim_end_matches(';').to_string()),
                has_exception_object: true,
                exception_type: Some("auto".to_string()),
            });
        }
        None
    }
}

/// Lower a try-catch statement to LLVM IR using EH infrastructure.
pub fn lower_try_catch(stmt: &TryCatchStmt, eh: &mut EHCodeGen) -> String {
    let mut ir = String::new();

    ir.push_str("; try block\n");
    ir.push_str("invoke.cont:\n");

    // Landing pad
    let lp_label = format!("lpad{}", eh.lp_counter);
    eh.lp_counter += 1;

    let catch_types: Vec<CatchType> = stmt
        .handlers
        .iter()
        .filter_map(|h| {
            if h.is_catch_all {
                None
            } else {
                Some(CatchType {
                    typeinfo: MangledName::new(format!(
                        "_ZTI{}",
                        h.caught_type.as_deref().unwrap_or("v")
                    )),
                    is_ref: h.is_by_ref,
                })
            }
        })
        .collect();

    let has_catch_all = stmt.handlers.iter().any(|h| h.is_catch_all);
    ir.push_str(&eh.gen_landing_pad_ir(&lp_label, &catch_types, has_catch_all));

    for (i, handler) in stmt.handlers.iter().enumerate() {
        ir.push_str(&format!(
            "; catch handler {}: {}\n",
            i,
            handler.caught_type.as_deref().unwrap_or("...")
        ));
        ir.push_str(&eh.gen_begin_catch_ir(&format!("exc{}", i)));
        ir.push_str(&eh.gen_end_catch_ir());
    }

    ir
}

// ═══════════════════════════════════════════════════════════════════════════════
// Landing Pad Generation — Catch Type Matching (RTTI-Based)
// ═══════════════════════════════════════════════════════════════════════════════

/// Descriptor for a catch type matcher using RTTI.
#[derive(Debug, Clone)]
pub struct CatchTypeMatcher {
    /// The RTTI type info symbol for the caught type.
    pub typeinfo_symbol: MangledName,
    /// Whether the catch is by reference.
    pub is_ref: bool,
    /// Whether this is a base class catch (derived→base conversion).
    pub is_base_class: bool,
    /// The offset needed for pointer adjustment (base class catches).
    pub this_adjustment: i64,
}

impl CatchTypeMatcher {
    pub fn new(typeinfo: MangledName, is_ref: bool) -> Self {
        Self {
            typeinfo_symbol: typeinfo,
            is_ref,
            is_base_class: false,
            this_adjustment: 0,
        }
    }

    /// Mark this as a base class catch requiring pointer adjustment.
    pub fn with_base_adjustment(mut self, offset: i64) -> Self {
        self.is_base_class = true;
        self.this_adjustment = offset;
        self
    }

    /// Generate the IR for matching this catch type.
    pub fn gen_match_ir(&self, exc_ptr: &str, label: &str) -> String {
        let mut ir = String::new();
        ir.push_str(&format!(
            "  %matches_{} = call i1 @__cxa_can_catch(ptr @{}, ptr {}, ptr @_ZTIi)\n",
            label,
            self.typeinfo_symbol.as_str(),
            exc_ptr
        ));
        ir.push_str(&format!(
            "  br i1 %matches_{}, label %catch.{}, label %next.catch\n",
            label, label
        ));
        ir
    }
}

/// Generate a full landing pad with multiple catch types.
pub fn generate_landing_pad_with_catches(
    label: &str,
    personality: &str,
    catches: &[CatchTypeMatcher],
    has_cleanup: bool,
    has_catch_all: bool,
) -> String {
    let mut ir = String::new();
    ir.push_str(&format!("{}:\n", label));
    ir.push_str(&format!("  %lp = landingpad {{ ptr, i32 }} cleanup"));

    for catch in catches {
        ir.push_str(&format!(
            "\n    catch ptr @{}",
            catch.typeinfo_symbol.as_str()
        ));
    }

    if has_catch_all {
        ir.push_str("\n    catch ptr null");
    }

    ir.push_str("\n");

    if has_cleanup {
        ir.push_str(&format!(
            "  %exc.{} = extractvalue {{ ptr, i32 }} %lp, 0\n",
            label
        ));
        ir.push_str(&format!(
            "  %sel.{} = extractvalue {{ ptr, i32 }} %lp, 1\n",
            label
        ));
    }

    ir
}

// ═══════════════════════════════════════════════════════════════════════════════
// Exception Specification: noexcept, throw(), Dynamic Exception Spec
// ═══════════════════════════════════════════════════════════════════════════════

/// Exception specification kinds.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExceptionSpec {
    /// No exception specification (can throw anything).
    None,
    /// `noexcept` — does not throw.
    Noexcept,
    /// `noexcept(expr)` — computed noexcept.
    ComputedNoexcept(String),
    /// `throw()` — dynamic exception specification (C++03, deprecated).
    ThrowNothing,
    /// `throw(T1, T2, ...)` — dynamic exception specification (C++03, removed in C++17).
    Throws(Vec<String>),
}

impl ExceptionSpec {
    /// Whether this represents a non-throwing specification.
    pub fn is_noexcept(&self) -> bool {
        matches!(
            self,
            ExceptionSpec::Noexcept
                | ExceptionSpec::ComputedNoexcept(_)
                | ExceptionSpec::ThrowNothing
        )
    }

    /// Whether this is a dynamic exception specification.
    pub fn is_dynamic(&self) -> bool {
        matches!(self, ExceptionSpec::Throws(_))
    }

    /// Check if a given exception type is allowed by this specification.
    pub fn allows_type(&self, exception_type: &str) -> bool {
        match self {
            ExceptionSpec::None => true,
            ExceptionSpec::Noexcept | ExceptionSpec::ThrowNothing => false,
            ExceptionSpec::ComputedNoexcept(_) => false,
            ExceptionSpec::Throws(allowed) => allowed.iter().any(|t| t == exception_type),
        }
    }

    /// Generate the noexcept check IR.
    pub fn gen_noexcept_check_ir(&self, func_name: &str) -> String {
        match self {
            ExceptionSpec::Noexcept | ExceptionSpec::ThrowNothing => format!(
                "  ; {} is noexcept — exception propagates to std::terminate\n",
                func_name
            ),
            ExceptionSpec::ComputedNoexcept(cond) => format!(
                "  %noexcept_ok = {}\n  br i1 %noexcept_ok, label %invoke.cont, label %noexcept.fail\n",
                cond
            ),
            ExceptionSpec::Throws(allowed) => format!(
                "  ; dynamic exception spec allows: [{}]\n",
                allowed.join(", ")
            ),
            ExceptionSpec::None => String::new(),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// noexcept Operator Evaluation
// ═══════════════════════════════════════════════════════════════════════════════

/// Evaluates the `noexcept(expr)` operator.
#[derive(Debug, Clone)]
pub struct NoexceptEvaluator {
    /// Whether the expression is known to not throw.
    pub result: bool,
    /// Explanation of the evaluation.
    pub reason: String,
}

impl NoexceptEvaluator {
    pub fn new() -> Self {
        Self {
            result: false,
            reason: String::new(),
        }
    }

    /// Evaluate whether an expression can throw.
    /// Returns `true` if the expression is noexcept.
    pub fn evaluate(&mut self, expr_kind: &str, callee_spec: &ExceptionSpec) -> bool {
        // Built-in operations are noexcept (except new, delete, typeid etc.)
        match expr_kind {
            "add" | "sub" | "mul" | "div" | "mod" | "eq" | "ne" | "lt" | "gt" | "le" | "ge"
            | "and" | "or" | "xor" | "shl" | "shr" | "not" | "neg" | "deref" | "addr_of"
            | "cast" | "const_cast" | "static_cast" | "reinterpret_cast" => {
                self.result = true;
                self.reason = format!("built-in operation '{}' is noexcept", expr_kind);
            }
            "dynamic_cast" => {
                self.result = false;
                self.reason = "dynamic_cast may throw std::bad_cast (reference form)".to_string();
            }
            "typeid" => {
                self.result = false;
                self.reason = "typeid may throw std::bad_typeid".to_string();
            }
            "new" | "new_array" => {
                self.result = false;
                self.reason = "new may throw std::bad_alloc".to_string();
            }
            "call" | "invoke" => {
                self.result = callee_spec.is_noexcept();
                self.reason = if self.result {
                    "callee is noexcept".to_string()
                } else {
                    "callee may throw".to_string()
                };
            }
            _ => {
                self.result = false;
                self.reason = format!("unknown expression kind '{}' assumed throwing", expr_kind);
            }
        }
        self.result
    }

    /// Evaluate noexcept at the call site.
    pub fn evaluate_call(&mut self, func_spec: &ExceptionSpec) -> bool {
        self.result = func_spec.is_noexcept();
        self.reason = if self.result {
            "function is noexcept".to_string()
        } else {
            "function may throw".to_string()
        };
        self.result
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Exception Pointer: std::exception_ptr, std::current_exception
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents `std::exception_ptr` — a type-erased exception pointer.
#[derive(Debug, Clone)]
pub struct ExceptionPtr {
    /// Whether this holds a valid exception.
    pub is_valid: bool,
    /// The RTTI type of the held exception (if known).
    pub exception_type: Option<String>,
}

impl ExceptionPtr {
    pub fn new() -> Self {
        Self {
            is_valid: false,
            exception_type: None,
        }
    }

    /// Generate `std::current_exception()` IR.
    pub fn gen_current_exception_ir() -> String {
        "  %exc_ptr = call ptr @__cxa_current_exception_type()\n".to_string()
    }

    /// Generate `std::rethrow_exception(ptr)` IR.
    pub fn gen_rethrow_exception_ir(exc_ptr: &str) -> String {
        format!(
            "  call void @__cxa_rethrow_exception({})\n  unreachable\n",
            exc_ptr
        )
    }

    /// Generate `std::make_exception_ptr(expr)` IR.
    pub fn gen_make_exception_ptr_ir(exception_obj: &str) -> String {
        format!(
            "  %exc_ptr = call ptr @__cxa_allocate_exception(i64 8)\n  ; copy construct exception\n  ret ptr %exc_ptr\n"
        )
    }

    /// Generate `exception_ptr == nullptr` check.
    pub fn gen_null_check_ir(ptr: &str) -> String {
        format!("  %is_null = icmp eq ptr {}, null\n", ptr)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// std::terminate / std::unexpected Invocation Paths
// ═══════════════════════════════════════════════════════════════════════════════

/// Handles std::terminate invocation paths.
#[derive(Debug, Clone)]
pub struct TerminateHandler {
    /// The termination reason.
    pub reason: TerminateReason,
    /// Whether an active exception is being handled.
    pub has_active_exception: bool,
}

/// Reasons for std::terminate being called.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TerminateReason {
    /// Exception thrown from a noexcept function.
    NoexceptViolation,
    /// Exception thrown during stack unwinding (double exception).
    DoubleException,
    /// No matching handler found.
    UnhandledException,
    /// throw with no active exception.
    ThrowWithNoException,
    /// Dynamic exception specification violation.
    UnexpectedException,
    /// Pure virtual function call.
    PureVirtualCall,
    /// Default terminate.
    DefaultTerminate,
}

impl std::fmt::Display for TerminateReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TerminateReason::NoexceptViolation => {
                write!(f, "exception thrown from noexcept function")
            }
            TerminateReason::DoubleException => {
                write!(f, "exception thrown during stack unwinding")
            }
            TerminateReason::UnhandledException => write!(f, "unhandled exception"),
            TerminateReason::ThrowWithNoException => {
                write!(f, "throw with no active exception")
            }
            TerminateReason::UnexpectedException => {
                write!(f, "dynamic exception specification violation")
            }
            TerminateReason::PureVirtualCall => write!(f, "pure virtual function call"),
            TerminateReason::DefaultTerminate => write!(f, "std::terminate called"),
        }
    }
}

impl TerminateHandler {
    pub fn new(reason: TerminateReason) -> Self {
        Self {
            reason,
            has_active_exception: false,
        }
    }

    /// Generate IR for the terminate path.
    pub fn gen_terminate_ir(&self) -> String {
        match self.reason {
            TerminateReason::NoexceptViolation => r#"  ; noexcept violation — call std::terminate
  %eh_ptr = call ptr @__cxa_begin_catch(ptr %exc)
  call void @_ZSt9terminatev()
  unreachable
"#
            .to_string(),
            TerminateReason::DoubleException => r#"  ; double exception — call std::terminate
  call void @_ZSt9terminatev()
  unreachable
"#
            .to_string(),
            _ => {
                format!(
                    "  ; {} — call std::terminate\n  call void @_ZSt9terminatev()\n  unreachable\n",
                    self.reason
                )
            }
        }
    }

    /// Generate IR for std::unexpected (C++03 dynamic exception spec).
    pub fn gen_unexpected_ir(&self) -> String {
        r#"  ; dynamic exception spec violation — call std::unexpected
  call void @_ZSt9unexpectedv()
  unreachable
"#
        .to_string()
    }

    /// Register a custom terminate handler.
    pub fn gen_set_terminate_ir(handler: &str) -> String {
        format!(
            "  %old_handler = call ptr @_ZSt13set_terminatePFvvE(ptr @{})\n",
            handler
        )
    }

    /// Register a custom unexpected handler (C++03).
    pub fn gen_set_unexpected_ir(handler: &str) -> String {
        format!(
            "  %old_handler = call ptr @_ZSt14set_unexpectedPFvvE(ptr @{})\n",
            handler
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// noexcept Propagation Through Function Calls
// ═══════════════════════════════════════════════════════════════════════════════

/// Tracks noexcept propagation across function calls.
#[derive(Debug, Clone)]
pub struct NoexceptPropagation {
    /// Whether the current function is noexcept.
    pub current_is_noexcept: bool,
    /// Whether any called function can potentially throw.
    pub has_potential_throw: bool,
    /// Call sites that require noexcept wrappers.
    pub noexcept_call_sites: Vec<NoexceptCallSite>,
}

/// A call site where noexcept must be enforced.
#[derive(Debug, Clone)]
pub struct NoexceptCallSite {
    /// The function being called.
    pub callee: String,
    /// The call site location.
    pub location: usize,
    /// Whether the callee is noexcept.
    pub callee_is_noexcept: bool,
    /// Whether a noexcept wrapper is needed (callee throws, caller is noexcept).
    pub needs_noexcept_wrapper: bool,
}

impl NoexceptPropagation {
    pub fn new(is_noexcept: bool) -> Self {
        Self {
            current_is_noexcept: is_noexcept,
            has_potential_throw: false,
            noexcept_call_sites: Vec::new(),
        }
    }

    /// Register a call site and check if noexcept wrapping is needed.
    pub fn register_call(&mut self, callee: &str, callee_spec: &ExceptionSpec) {
        let callee_is_noexcept = callee_spec.is_noexcept();
        let needs_wrapper = self.current_is_noexcept && !callee_is_noexcept;

        if !callee_is_noexcept {
            self.has_potential_throw = true;
        }

        if needs_wrapper {
            self.noexcept_call_sites.push(NoexceptCallSite {
                callee: callee.to_string(),
                location: 0,
                callee_is_noexcept,
                needs_noexcept_wrapper: true,
            });
        }
    }

    /// Generate the noexcept wrapper IR for a call site.
    /// This catches exceptions from the callee and calls std::terminate.
    pub fn gen_noexcept_wrapper_ir(&self, call_site: &NoexceptCallSite) -> String {
        format!(
            r#"; noexcept wrapper around throwing call '{}'
  invoke fastcc void @{}(ptr %args)
    to label %invoke.cont unwind label %noexcept.fail
noexcept.fail:
  %lp = landingpad {{ ptr, i32 }} cleanup
  call void @_ZSt9terminatev()
  unreachable
invoke.cont:
"#,
            call_site.callee, call_site.callee
        )
    }

    /// Check if a noexcept propagation barrier is needed.
    pub fn needs_propagation_barrier(&self) -> bool {
        self.current_is_noexcept && self.has_potential_throw
    }

    /// Generate a propagation barrier that catches and terminates.
    pub fn gen_propagation_barrier_ir(&self) -> String {
        if self.needs_propagation_barrier() {
            r#"; noexcept propagation barrier
noexcept.barrier:
  %lp = landingpad { ptr, i32 } cleanup
  call void @_ZSt9terminatev()
  unreachable
"#
            .to_string()
        } else {
            String::new()
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Exception Type Hierarchy Matching
// ═══════════════════════════════════════════════════════════════════════════════

/// Matches thrown exception types against catch handlers.
#[derive(Debug, Clone)]
pub struct ExceptionTypeMatcher {
    /// The type of the thrown exception.
    pub thrown_type: String,
    /// The class hierarchy for RTTI-based matching.
    pub hierarchy: Vec<String>,
}

impl ExceptionTypeMatcher {
    pub fn new(thrown_type: &str) -> Self {
        Self {
            thrown_type: thrown_type.to_string(),
            hierarchy: vec![thrown_type.to_string()],
        }
    }

    /// Add a base class to the hierarchy.
    pub fn add_base(&mut self, base: &str) {
        self.hierarchy.push(base.to_string());
    }

    /// Check if a catch handler type matches the thrown exception.
    pub fn matches(&self, catch_type: &str) -> bool {
        // Exact match or base class match
        self.hierarchy.iter().any(|t| t == catch_type)
    }

    /// Generate RTTI-based match IR at the landing pad.
    pub fn gen_type_match_ir(
        &self,
        catch_type: &str,
        exc_ptr: &str,
        handler_label: &str,
    ) -> String {
        format!(
            "  ; Check if thrown type '{}' matches catch type '{}'\n  %matches.{} = call i1 @__cxa_can_catch(ptr @_ZTI{}, ptr {}, ptr @_ZTI{})\n  br i1 %matches.{}, label %{}, label %next.catch\n",
            self.thrown_type, catch_type,
            handler_label, catch_type, exc_ptr, self.thrown_type,
            handler_label, handler_label
        )
    }

    /// Generate the full exception dispatch switch.
    pub fn gen_dispatch_ir(&self, handlers: &[CatchHandler], exc_ptr: &str) -> String {
        let mut ir = String::new();
        ir.push_str("; Exception dispatch\n");
        for (i, handler) in handlers.iter().enumerate() {
            if handler.is_catch_all {
                ir.push_str(&format!("  br label %catch_all{}\n", i));
            } else if let Some(ref ty) = handler.caught_type {
                ir.push_str(&self.gen_type_match_ir(ty, exc_ptr, &format!("catch{}", i)));
            }
        }
        ir.push_str("  br label %unhandled\n");
        ir
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Stack Unwinding and Cleanup Phases
// ═══════════════════════════════════════════════════════════════════════════════

/// Describes the two-phase exception handling process.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnwindingPhase {
    /// Phase 1: Search phase — walk up the stack looking for a handler.
    Search,
    /// Phase 2: Cleanup phase — unwind stack, run destructors, call handler.
    Cleanup,
}

/// Manages stack unwinding state.
#[derive(Debug, Clone)]
pub struct StackUnwinder {
    /// The current unwinding phase.
    pub phase: UnwindingPhase,
    /// The exception being unwound.
    pub exception: Option<String>,
    /// Cleanup regions encountered during unwinding.
    pub cleanup_regions: Vec<CleanupRegion>,
    /// Whether unwinding is in progress.
    pub is_unwinding: bool,
}

/// A cleanup region (objects to destruct during unwinding).
#[derive(Debug, Clone)]
pub struct CleanupRegion {
    /// The scope description.
    pub scope: String,
    /// Variables needing destruction.
    pub variables: Vec<String>,
    /// Landing pad label for this region.
    pub landing_pad_label: String,
}

impl StackUnwinder {
    pub fn new() -> Self {
        Self {
            phase: UnwindingPhase::Search,
            exception: None,
            cleanup_regions: Vec::new(),
            is_unwinding: false,
        }
    }

    /// Enter the search phase.
    pub fn begin_search(&mut self, exception_type: &str) {
        self.phase = UnwindingPhase::Search;
        self.exception = Some(exception_type.to_string());
        self.is_unwinding = true;
    }

    /// Transition to cleanup phase.
    pub fn begin_cleanup(&mut self) {
        self.phase = UnwindingPhase::Cleanup;
    }

    /// Add a cleanup region encountered during stack walk.
    pub fn add_cleanup_region(&mut self, scope: &str, vars: Vec<String>) {
        self.cleanup_regions.push(CleanupRegion {
            scope: scope.to_string(),
            variables: vars,
            landing_pad_label: format!("lpad{}", self.cleanup_regions.len()),
        });
    }

    /// Generate the IR for unwinding through cleanup regions.
    pub fn gen_unwind_cleanup_ir(&self) -> String {
        let mut ir = String::new();
        ir.push_str(&format!("; Unwinding phase: {:?}\n", self.phase));
        for region in &self.cleanup_regions {
            ir.push_str(&format!(
                "  ; Cleanup scope: {}\n  invoke void @_Unwind_Resume(ptr %exc)\n    to label %unreachable unwind label %{}\n",
                region.scope, region.landing_pad_label
            ));
            for var in &region.variables {
                ir.push_str(&format!(
                    "  ; destroy {}\n  call void @dtor_{}(ptr null)\n",
                    var, var
                ));
            }
        }
        ir
    }

    /// Generate the end-of-unwind resumption.
    pub fn gen_resume_ir(&self) -> String {
        "  ; Resume unwinding after cleanup\n  call void @_Unwind_Resume(ptr %exc)\n  unreachable\n"
            .to_string()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Filter-Exception-Spec and noexcept Function Wrappers
// ═══════════════════════════════════════════════════════════════════════════════

/// Handler for exception filter specifications (MSVC __except / Itanium equivalent).
#[derive(Debug, Clone)]
pub struct ExceptionFilterHandler {
    /// The filter expression (e.g., integer filter value).
    pub filter_expr: String,
    /// Filter results: EXCEPTION_EXECUTE_HANDLER, EXCEPTION_CONTINUE_SEARCH,
    /// EXCEPTION_CONTINUE_EXECUTION.
    pub filter_result: FilterResult,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilterResult {
    /// Execute the handler.
    ExecuteHandler = 1,
    /// Continue searching for a handler.
    ContinueSearch = 0,
    /// Resume execution at the fault point.
    ContinueExecution = -1isize as isize,
}

impl ExceptionFilterHandler {
    pub fn new(filter: &str) -> Self {
        Self {
            filter_expr: filter.to_string(),
            filter_result: FilterResult::ExecuteHandler,
        }
    }

    /// Generate the filter function IR.
    pub fn gen_filter_fn_ir(&self) -> String {
        format!(
            r#"; Exception filter function
define i32 @exception_filter_{}(ptr %exc, ptr %est) {{
entry:
  %result = call i32 @_XcptFilter(i32 {}, ptr %exc)
  ret i32 %result
}}
"#,
            self.filter_expr, self.filter_result as i32
        )
    }

    /// Whether the filter catches all exceptions.
    pub fn is_catch_all(&self) -> bool {
        self.filter_result == FilterResult::ExecuteHandler && self.filter_expr == "1"
    }
}

/// Wraps a throwing function call in a noexcept context with a try/catch.
pub struct NoexceptFunctionWrapper {
    /// The function being wrapped.
    pub function_name: String,
    /// Whether the wrapper should call std::terminate on exception.
    pub terminate_on_throw: bool,
    /// The exception types that should be caught and terminated.
    pub catch_types: Vec<String>,
}

impl NoexceptFunctionWrapper {
    pub fn new(func: &str) -> Self {
        Self {
            function_name: func.to_string(),
            terminate_on_throw: true,
            catch_types: Vec::new(),
        }
    }

    /// Generate the noexcept wrapper IR.
    pub fn gen_wrapper_ir(&self) -> String {
        format!(
            r#"define void @{}_noexcept_wrapper(ptr %args) {{
entry:
  invoke void @{}(ptr %args)
    to label %cont unwind label %lpad
lpad:
  %lp = landingpad {{ ptr, i32 }} cleanup
  call void @_ZSt9terminatev()
  unreachable
cont:
  ret void
}}
"#,
            self.function_name, self.function_name
        )
    }

    /// Generate the noexcept wrapper with specific catch types.
    pub fn gen_typed_wrapper_ir(&self) -> String {
        let mut ir = format!(
            r#"define void @{}_noexcept_wrapper_typed(ptr %args) {{
entry:
  invoke void @{}(ptr %args)
    to label %cont unwind label %lpad
lpad:
  %lp = landingpad {{ ptr, i32 }}
"#,
            self.function_name, self.function_name
        );

        for ty in &self.catch_types {
            ir.push_str(&format!("    catch ptr @_ZTI{}\n", ty));
        }

        ir.push_str("  call void @_ZSt9terminatev()\n  unreachable\ncont:\n  ret void\n}\n");
        ir
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Exception Table Generation for DWARF/LSDA
// ═══════════════════════════════════════════════════════════════════════════════

/// Generates the full exception table (LSDA + call-site table) for a function.
#[derive(Debug, Clone)]
pub struct ExceptionTableGenerator {
    /// The function name.
    pub function_name: String,
    /// The personality function.
    pub personality: String,
    /// Call-site entries.
    pub call_sites: Vec<CallSiteEntry>,
    /// Type table entries.
    pub type_table: Vec<String>,
}

impl ExceptionTableGenerator {
    pub fn new(func: &str, personality: &str) -> Self {
        Self {
            function_name: func.to_string(),
            personality: personality.to_string(),
            call_sites: Vec::new(),
            type_table: Vec::new(),
        }
    }

    /// Add a call site (try region).
    pub fn add_call_site(&mut self, begin: u32, end: u32, landing_pad: u32, action: u32) {
        self.call_sites.push(CallSiteEntry {
            try_begin_offset: begin,
            try_end_offset: end,
            landing_pad_offset: landing_pad,
            action,
        });
    }

    /// Add a type to the type table.
    pub fn add_type(&mut self, typeinfo_name: &str) -> usize {
        let idx = self.type_table.len();
        self.type_table.push(typeinfo_name.to_string());
        idx
    }

    /// Generate the full LSDA bytecode.
    pub fn generate_lsda_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::new();

        // LPStart encoding: DW_EH_PE_omit (0xff)
        bytes.push(0xff);
        // TType encoding: DW_EH_PE_absptr (0x00)
        bytes.push(0x00);

        // Call-site table length (ULEB128)
        let call_site_table_len = self.call_sites.len() as u64 * 16;
        encode_uleb128(&mut bytes, call_site_table_len);

        // Call-site entries
        for cs in &self.call_sites {
            encode_uleb128(&mut bytes, cs.try_begin_offset as u64);
            encode_uleb128(&mut bytes, (cs.try_end_offset - cs.try_begin_offset) as u64);
            encode_uleb128(&mut bytes, cs.landing_pad_offset as u64);
            encode_uleb128(&mut bytes, cs.action as u64);
        }

        bytes
    }

    /// Generate the GCC-compatible LSDA IR.
    pub fn gen_lsda_ir(&self) -> String {
        let mut ir = String::new();
        ir.push_str(&format!(
            "@__gcc_except_table_{} = private unnamed_addr constant {{ ... }}\n",
            self.function_name
        ));
        ir.push_str(&format!("; Personality: {}\n", self.personality));

        for (i, cs) in self.call_sites.iter().enumerate() {
            ir.push_str(&format!(
                "; Call site {}: [{}, {}) → landing pad {}\n",
                i, cs.try_begin_offset, cs.try_end_offset, cs.landing_pad_offset
            ));
        }

        ir
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_personality_kinds() {
        let eh = EHCodeGen::itanium();
        assert_eq!(eh.personality_fn(), ITANIUM_PERSONALITY_FN);

        let seh = EHCodeGen::new(PersonalityKind::Seh);
        assert_eq!(seh.personality_fn(), SEH_PERSONALITY_FN);
    }

    #[test]
    fn test_lsda_empty() {
        let lsda = LSDA::new();
        assert!(lsda.call_sites.is_empty());
        assert!(lsda.type_table.is_empty());
    }

    #[test]
    fn test_lsda_add_call_site() {
        let mut lsda = LSDA::new();
        lsda.add_call_site(0, 100, 200, 1);
        assert_eq!(lsda.call_sites.len(), 1);
        assert_eq!(lsda.call_sites[0].try_begin_offset, 0);
        assert_eq!(lsda.call_sites[0].try_end_offset, 100);
    }

    #[test]
    fn test_lsda_add_type() {
        let mut lsda = LSDA::new();
        let idx = lsda.add_type(MangledName::new("_ZTIi".into()));
        assert_eq!(lsda.type_table.len(), 1);
        assert_eq!(idx, 0);
    }

    #[test]
    fn test_lsda_to_bytes() {
        let mut lsda = LSDA::new();
        lsda.add_call_site(0, 50, 100, 1);
        let bytes = lsda.to_bytes();
        // Header: LPStart=0xff, TType=0x00
        assert_eq!(bytes[0], 0xff);
        assert_eq!(bytes[1], 0x00);
    }

    #[test]
    fn test_uleb128_encoding() {
        let mut bytes = Vec::new();
        encode_uleb128(&mut bytes, 0);
        assert_eq!(bytes, vec![0]);

        bytes.clear();
        encode_uleb128(&mut bytes, 127);
        assert_eq!(bytes, vec![127]);

        bytes.clear();
        encode_uleb128(&mut bytes, 128);
        assert_eq!(bytes, vec![0x80, 0x01]);

        bytes.clear();
        encode_uleb128(&mut bytes, 300);
        assert_eq!(bytes, vec![0xac, 0x02]);
    }

    #[test]
    fn test_gen_landing_pad_ir() {
        let mut eh = EHCodeGen::itanium();
        let catch_types = vec![CatchType {
            typeinfo: MangledName::new("_ZTIi".into()),
            is_ref: true,
        }];
        let ir = eh.gen_landing_pad_ir("lpad0", &catch_types, true);
        assert!(ir.contains("landingpad"));
        assert!(ir.contains("__gxx_personality_v0"));
        assert!(ir.contains("cleanup"));
        assert!(ir.contains("catch"));
    }

    #[test]
    fn test_gen_throw_ir() {
        let eh = EHCodeGen::itanium();
        let ir = eh.gen_throw_ir("%exc");
        assert!(ir.contains("__cxa_throw"));
        assert!(ir.contains("unreachable"));
    }

    #[test]
    fn test_gen_rethrow_ir() {
        let eh = EHCodeGen::itanium();
        let ir = eh.gen_rethrow_ir();
        assert!(ir.contains("__cxa_rethrow"));
        assert!(ir.contains("unreachable"));
    }

    #[test]
    fn test_gen_runtime_decls() {
        let eh = EHCodeGen::itanium();
        let ir = eh.gen_runtime_decls_ir();
        assert!(ir.contains("__cxa_allocate_exception"));
        assert!(ir.contains("__cxa_throw"));
        assert!(ir.contains("__cxa_begin_catch"));
        assert!(ir.contains("__cxa_end_catch"));
    }

    #[test]
    fn test_gen_personality_decl() {
        let eh = EHCodeGen::itanium();
        let ir = eh.gen_personality_decl_ir();
        assert!(ir.contains("__gxx_personality_v0"));
    }
}