llvm-native-core 0.1.4

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
// context_adv.rs — Advanced LLVMContext Features
//
// Clean-room forensic-parity expansion:
//   - Thread-safe context with arena allocators
//   - String saver / interning
//   - Intrinsic registry / declaration factory
//   - Diagnostic consumer abstraction
//   - Type canonicalisation with deduplication
//   - Module-level metadata management
//   - Garbage collection strategy metadata
//   - TargetLibraryInfo integration
//   - Opaque pointer mode support
//   - Pass registry for plugin passes

use crate::context::{ConstantPool, DiagnosticEngine, FixItHint, LLVMContext, TypeCache};
use crate::types::{Type, TypeKind};
use crate::value::{Value, ValueRef};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt;
use std::sync::{Arc, Mutex};

// ============================================================================
// Section 1: Thread-Safe Context
// ============================================================================

/// Thread-safe wrapper around LLVMContext for concurrent compilation
pub struct ThreadSafeContext {
    inner: Arc<Mutex<LLVMContext>>,
}

impl ThreadSafeContext {
    pub fn new() -> Self {
        ThreadSafeContext {
            inner: Arc::new(Mutex::new(LLVMContext::new())),
        }
    }

    pub fn lock(&self) -> std::sync::MutexGuard<'_, LLVMContext> {
        self.inner.lock().expect("LLVMContext mutex poisoned")
    }

    pub fn clone_handle(&self) -> Self {
        ThreadSafeContext {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl Default for ThreadSafeContext {
    fn default() -> Self {
        ThreadSafeContext::new()
    }
}

// ============================================================================
// Section 2: String Saver — Interning
// ============================================================================

/// String interning / deduplication table (like LLVM's StringSaver / BumpPtr)
pub struct StringSaver {
    /// Deduplicated strings
    strings: HashSet<String>,
    /// Ordered storage
    storage: Vec<String>,
}

impl StringSaver {
    pub fn new() -> Self {
        StringSaver {
            strings: HashSet::new(),
            storage: Vec::new(),
        }
    }

    /// Intern a string — returns index into storage
    pub fn save(&mut self, s: &str) -> usize {
        if let Some(idx) = self.storage.iter().position(|stored| stored == s) {
            return idx;
        }
        let idx = self.storage.len();
        self.strings.insert(s.to_string());
        self.storage.push(s.to_string());
        idx
    }

    /// Get string by index
    pub fn get(&self, idx: usize) -> Option<&str> {
        self.storage.get(idx).map(|s| s.as_str())
    }

    /// Number of unique strings
    pub fn len(&self) -> usize {
        self.storage.len()
    }

    pub fn is_empty(&self) -> bool {
        self.storage.is_empty()
    }

    /// Clear all strings
    pub fn clear(&mut self) {
        self.strings.clear();
        self.storage.clear();
    }
}

impl Default for StringSaver {
    fn default() -> Self {
        StringSaver::new()
    }
}

// ============================================================================
// Section 3: Intrinsic Registry
// ============================================================================

/// Entry for a single intrinsic
#[derive(Debug, Clone)]
pub struct IntrinsicEntry {
    /// Intrinsic ID
    pub id: u32,
    /// Intrinsic name (e.g., "llvm.memcpy.p0.p0.i64")
    pub name: String,
    /// Return type pattern (or None if overloaded)
    pub return_type_hint: Option<TypeKind>,
    /// Parameter type patterns
    pub param_type_hints: Vec<Option<TypeKind>>,
    /// Properties
    pub properties: IntrinsicProperties,
    /// Can be overloaded on types?
    pub is_overloaded: bool,
}

/// Properties of an intrinsic (mirrors LLVM's Intrinsic::IntrinsicProperties)
#[derive(Debug, Clone, Default)]
pub struct IntrinsicProperties {
    pub is_readnone: bool,
    pub is_readonly: bool,
    pub is_writeonly: bool,
    pub is_argmemonly: bool,
    pub is_nounwind: bool,
    pub is_willreturn: bool,
    pub is_nosync: bool,
    pub is_nofree: bool,
    pub is_nocallback: bool,
    pub is_convergent: bool,
    pub is_speculatable: bool,
    pub is_strictfp: bool,
    pub has_side_effects: bool,
    pub is_commutative: bool,
    pub is_noduplicate: bool,
    pub is_noreturn: bool,
}

/// Registry of all LLVM intrinsics
pub struct IntrinsicRegistry {
    /// Name → entry mapping
    pub by_name: HashMap<String, IntrinsicEntry>,
    /// ID → entry mapping
    pub by_id: HashMap<u32, IntrinsicEntry>,
    /// Next ID to assign
    next_id: u32,
}

impl IntrinsicRegistry {
    pub fn new() -> Self {
        let mut reg = IntrinsicRegistry {
            by_name: HashMap::new(),
            by_id: HashMap::new(),
            next_id: 1,
        };
        reg.register_builtins();
        reg
    }

    /// Register the full set of known LLVM intrinsics
    fn register_builtins(&mut self) {
        // Memory intrinsics
        self.register(
            "llvm.memcpy",
            false,
            IntrinsicProperties {
                is_argmemonly: true,
                is_willreturn: true,
                ..Default::default()
            },
        );
        self.register(
            "llvm.memmove",
            false,
            IntrinsicProperties {
                is_argmemonly: true,
                is_willreturn: true,
                ..Default::default()
            },
        );
        self.register(
            "llvm.memset",
            false,
            IntrinsicProperties {
                is_argmemonly: true,
                is_willreturn: true,
                ..Default::default()
            },
        );
        self.register(
            "llvm.lifetime.start",
            false,
            IntrinsicProperties {
                is_argmemonly: true,
                ..Default::default()
            },
        );
        self.register(
            "llvm.lifetime.end",
            false,
            IntrinsicProperties {
                is_argmemonly: true,
                ..Default::default()
            },
        );
        self.register(
            "llvm.invariant.start",
            false,
            IntrinsicProperties {
                is_readonly: true,
                ..Default::default()
            },
        );
        self.register(
            "llvm.invariant.end",
            false,
            IntrinsicProperties {
                is_readonly: true,
                ..Default::default()
            },
        );
        self.register(
            "llvm.launder.invariant.group",
            false,
            IntrinsicProperties {
                is_readnone: true,
                is_speculatable: true,
                ..Default::default()
            },
        );
        self.register(
            "llvm.strip.invariant.group",
            false,
            IntrinsicProperties {
                is_readnone: true,
                is_speculatable: true,
                ..Default::default()
            },
        );

        // Math intrinsics
        for name in &[
            "llvm.sqrt",
            "llvm.sin",
            "llvm.cos",
            "llvm.pow",
            "llvm.pow.pow",
            "llvm.exp",
            "llvm.exp2",
            "llvm.log",
            "llvm.log2",
            "llvm.log10",
            "llvm.fma",
            "llvm.fmuladd",
            "llvm.fabs",
            "llvm.minnum",
            "llvm.maxnum",
            "llvm.minimum",
            "llvm.maximum",
            "llvm.copysign",
            "llvm.floor",
            "llvm.ceil",
            "llvm.trunc",
            "llvm.rint",
            "llvm.nearbyint",
            "llvm.round",
            "llvm.roundeven",
            "llvm.canonicalize",
        ] {
            self.register(
                name,
                true,
                IntrinsicProperties {
                    is_readnone: true,
                    is_speculatable: true,
                    ..Default::default()
                },
            );
        }

        // Bit manipulation
        for name in &[
            "llvm.bitreverse",
            "llvm.bswap",
            "llvm.ctlz",
            "llvm.cttz",
            "llvm.ctpop",
            "llvm.fshl",
            "llvm.fshr",
        ] {
            self.register(
                name,
                true,
                IntrinsicProperties {
                    is_readnone: true,
                    is_speculatable: true,
                    ..Default::default()
                },
            );
        }

        // Overflow arithmetic
        for name in &[
            "llvm.sadd.with.overflow",
            "llvm.uadd.with.overflow",
            "llvm.ssub.with.overflow",
            "llvm.usub.with.overflow",
            "llvm.smul.with.overflow",
            "llvm.umul.with.overflow",
        ] {
            self.register(
                name,
                false,
                IntrinsicProperties {
                    is_readnone: true,
                    is_speculatable: true,
                    ..Default::default()
                },
            );
        }

        // Saturating arithmetic
        for name in &[
            "llvm.sadd.sat",
            "llvm.uadd.sat",
            "llvm.ssub.sat",
            "llvm.usub.sat",
            "llvm.sshl.sat",
            "llvm.ushl.sat",
        ] {
            self.register(
                name,
                true,
                IntrinsicProperties {
                    is_readnone: true,
                    is_speculatable: true,
                    ..Default::default()
                },
            );
        }

        // Vector reduction
        for name in &[
            "llvm.vector.reduce.add",
            "llvm.vector.reduce.mul",
            "llvm.vector.reduce.and",
            "llvm.vector.reduce.or",
            "llvm.vector.reduce.xor",
            "llvm.vector.reduce.smin",
            "llvm.vector.reduce.smax",
            "llvm.vector.reduce.umin",
            "llvm.vector.reduce.umax",
            "llvm.vector.reduce.fmin",
            "llvm.vector.reduce.fmax",
            "llvm.vector.reduce.fadd",
            "llvm.vector.reduce.fmul",
        ] {
            self.register(
                name,
                true,
                IntrinsicProperties {
                    is_readnone: true,
                    ..Default::default()
                },
            );
        }

        // Matrix intrinsics
        for name in &[
            "llvm.matrix.multiply",
            "llvm.matrix.transpose",
            "llvm.matrix.column.major.load",
            "llvm.matrix.column.major.store",
        ] {
            self.register(
                name,
                true,
                IntrinsicProperties {
                    is_readnone: true,
                    is_speculatable: true,
                    ..Default::default()
                },
            );
        }

        // Expect intrinsic
        self.register(
            "llvm.expect",
            false,
            IntrinsicProperties {
                is_readnone: true,
                is_willreturn: true,
                ..Default::default()
            },
        );
        self.register(
            "llvm.expect.with.probability",
            false,
            IntrinsicProperties {
                is_readnone: true,
                is_willreturn: true,
                ..Default::default()
            },
        );

        // Assume intrinsic
        self.register(
            "llvm.assume",
            false,
            IntrinsicProperties {
                is_readnone: true,
                is_willreturn: true,
                ..Default::default()
            },
        );

        // Trap / Debug
        self.register(
            "llvm.trap",
            false,
            IntrinsicProperties {
                has_side_effects: true,
                is_noreturn: true,
                ..Default::default()
            },
        );
        self.register(
            "llvm.debugtrap",
            false,
            IntrinsicProperties {
                has_side_effects: true,
                ..Default::default()
            },
        );
        self.register(
            "llvm.ubsantrap",
            false,
            IntrinsicProperties {
                has_side_effects: true,
                is_noreturn: true,
                ..Default::default()
            },
        );
    }

    fn register(&mut self, name: &str, overloaded: bool, props: IntrinsicProperties) {
        let id = self.next_id;
        self.next_id += 1;
        let entry = IntrinsicEntry {
            id,
            name: name.to_string(),
            return_type_hint: None,
            param_type_hints: Vec::new(),
            properties: props,
            is_overloaded: overloaded,
        };
        self.by_name.insert(name.to_string(), entry.clone());
        self.by_id.insert(id, entry);
    }

    /// Look up intrinsic by name (supports partial name matching for overloaded variants)
    pub fn lookup(&self, name: &str) -> Option<&IntrinsicEntry> {
        // Direct lookup
        if let Some(entry) = self.by_name.get(name) {
            return Some(entry);
        }
        // Try stripping type suffixes: llvm.memcpy.p0.p0.i64 → llvm.memcpy
        if let Some(dot) = name.find('.') {
            // Check if the part before the type suffix is a known base name
            let base = &name[..dot];
            if let Some(entry) = self.by_name.get(name) {
                return Some(entry);
            }
            // Try matching the first segment
            if let Some(second_dot) = name[dot + 1..].find('.') {
                let prefix = &name[..dot + 1 + second_dot];
                if self.by_name.contains_key(prefix) {
                    return self.by_name.get(prefix);
                }
            }
        }
        None
    }

    /// Check if a function name is an intrinsic
    pub fn is_intrinsic(&self, name: &str) -> bool {
        name.starts_with("llvm.") && self.lookup(name).is_some()
    }

    /// Get intrinsic by numeric ID
    pub fn get_by_id(&self, id: u32) -> Option<&IntrinsicEntry> {
        self.by_id.get(&id)
    }

    pub fn len(&self) -> usize {
        self.by_name.len()
    }

    pub fn is_empty(&self) -> bool {
        self.by_name.is_empty()
    }
}

// ============================================================================
// Section 4: Diagnostic Consumer
// ============================================================================

/// Sink for diagnostics during compilation
pub trait DiagnosticConsumer: fmt::Debug {
    /// Handle a diagnostic
    fn handle_diagnostic(&mut self, diag: &DiagnosticMessage);
    /// Called when compilation finishes
    fn finish(&mut self);
    /// Number of errors seen
    fn get_num_errors(&self) -> usize;
    /// Number of warnings seen
    fn get_num_warnings(&self) -> usize;
    /// Clear all diagnostics
    fn clear(&mut self);
}

/// Rich diagnostic message with source location
#[derive(Debug, Clone)]
pub struct DiagnosticMessage {
    pub severity: DiagSeverity,
    pub message: String,
    pub file: Option<String>,
    pub line: Option<u32>,
    pub column: Option<u32>,
    pub ranges: Vec<SourceRange>,
    pub notes: Vec<(Option<SourceLocation>, String)>,
    pub fixits: Vec<FixItHint>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum DiagSeverity {
    Ignored = 0,
    Note = 1,
    Remark = 2,
    Warning = 3,
    Error = 4,
    Fatal = 5,
}

#[derive(Debug, Clone, Copy)]
pub struct SourceRange {
    pub start: SourceLocation,
    pub end: SourceLocation,
}

#[derive(Debug, Clone, Copy)]
pub struct SourceLocation {
    pub line: u32,
    pub column: u32,
}

/// Simple diagnostic consumer that collects messages in-memory
#[derive(Debug, Clone, Default)]
pub struct CollectingDiagnosticConsumer {
    pub messages: Vec<DiagnosticMessage>,
    pub num_errors: usize,
    pub num_warnings: usize,
}

impl DiagnosticConsumer for CollectingDiagnosticConsumer {
    fn handle_diagnostic(&mut self, diag: &DiagnosticMessage) {
        match diag.severity {
            DiagSeverity::Error | DiagSeverity::Fatal => self.num_errors += 1,
            DiagSeverity::Warning => self.num_warnings += 1,
            _ => {}
        }
        self.messages.push(diag.clone());
    }

    fn finish(&mut self) {}
    fn get_num_errors(&self) -> usize {
        self.num_errors
    }
    fn get_num_warnings(&self) -> usize {
        self.num_warnings
    }
    fn clear(&mut self) {
        self.messages.clear();
        self.num_errors = 0;
        self.num_warnings = 0;
    }
}

/// Diagnostics engine tied to a specific source manager
pub struct SourceDiagnosticEngine {
    pub consumer: Box<dyn DiagnosticConsumer>,
    pub error_limit: usize,
    pub warnings_as_errors: bool,
    pub suppress_warnings: bool,
    pub suppress_notes: bool,
    pub remark_all: bool,
}

impl SourceDiagnosticEngine {
    pub fn new(consumer: Box<dyn DiagnosticConsumer>) -> Self {
        SourceDiagnosticEngine {
            consumer,
            error_limit: 20,
            warnings_as_errors: false,
            suppress_warnings: false,
            suppress_notes: false,
            remark_all: false,
        }
    }

    pub fn emit(
        &mut self,
        severity: DiagSeverity,
        msg: &str,
        file: Option<&str>,
        line: Option<u32>,
        col: Option<u32>,
    ) {
        if self.consumer.get_num_errors() >= self.error_limit && severity >= DiagSeverity::Error {
            return;
        }
        if self.suppress_warnings && severity == DiagSeverity::Warning {
            return;
        }
        if self.suppress_notes && severity == DiagSeverity::Note {
            return;
        }

        let actual_severity = if self.warnings_as_errors && severity == DiagSeverity::Warning {
            DiagSeverity::Error
        } else {
            severity
        };

        self.consumer.handle_diagnostic(&DiagnosticMessage {
            severity: actual_severity,
            message: msg.to_string(),
            file: file.map(|s| s.to_string()),
            line,
            column: col,
            ranges: Vec::new(),
            notes: Vec::new(),
            fixits: Vec::new(),
        });
    }

    pub fn error(&mut self, msg: &str) {
        self.emit(DiagSeverity::Error, msg, None, None, None);
    }
    pub fn warning(&mut self, msg: &str) {
        self.emit(DiagSeverity::Warning, msg, None, None, None);
    }
    pub fn note(&mut self, msg: &str) {
        self.emit(DiagSeverity::Note, msg, None, None, None);
    }

    pub fn has_errors(&self) -> bool {
        self.consumer.get_num_errors() > 0
    }
}

// ============================================================================
// Section 5: Type Canonicalisation
// ============================================================================

/// Type canonicaliser for deduplication
pub struct TypeCanonicalizer {
    /// Cache of canonical types
    cache: HashMap<String, TypeKind>,
    /// Integer types cache
    int_types: HashMap<u32, TypeKind>,
    /// Pointer types cache
    ptr_types: HashMap<(Box<TypeKind>, u32), TypeKind>,
    /// Array types cache
    array_types: HashMap<(Box<TypeKind>, u64), TypeKind>,
}

impl TypeCanonicalizer {
    pub fn new() -> Self {
        TypeCanonicalizer {
            cache: HashMap::new(),
            int_types: HashMap::new(),
            ptr_types: HashMap::new(),
            array_types: HashMap::new(),
        }
    }

    /// Get or create a canonical integer type
    pub fn get_int_type(&mut self, bits: u32) -> TypeKind {
        if let Some(ty) = self.int_types.get(&bits) {
            return ty.clone();
        }
        let ty = TypeKind::Integer { bits };
        self.int_types.insert(bits, ty.clone());
        ty
    }

    /// Get or create a canonical pointer type
    pub fn get_pointer_type(&mut self, pointee: TypeKind, addr_space: u32) -> TypeKind {
        let key = (Box::new(pointee.clone()), addr_space);
        if let Some(ty) = self.ptr_types.get(&key) {
            return ty.clone();
        }
        let ty = TypeKind::Pointer { addr_space };
        self.ptr_types.insert(key, ty.clone());
        ty
    }

    /// Get or create a canonical array type (simplified — returns placeholder)
    pub fn get_array_type(&mut self, element_type: TypeKind, num_elements: u64) -> TypeKind {
        // TypeKind::Array uses TypeId which requires a full context.
        // For canonicalization, we return the original type.
        element_type
    }

    /// Get canonical type by string key
    pub fn get_canonical(&mut self, ty: &TypeKind) -> TypeKind {
        let key = format!("{:?}", ty);
        if let Some(canonical) = self.cache.get(&key) {
            return canonical.clone();
        }
        self.cache.insert(key, ty.clone());
        ty.clone()
    }

    pub fn clear(&mut self) {
        self.cache.clear();
        self.int_types.clear();
        self.ptr_types.clear();
        self.array_types.clear();
    }
}

impl Default for TypeCanonicalizer {
    fn default() -> Self {
        TypeCanonicalizer::new()
    }
}

// ============================================================================
// Section 6: Pass Registry
// ============================================================================

/// Information about a registered pass
#[derive(Debug, Clone)]
pub struct PassInfo {
    /// Pass argument string (e.g., "-instcombine")
    pub pass_arg: String,
    /// Pass name
    pub pass_name: String,
    /// Pass type
    pub pass_type: PassType,
    /// Is this an analysis pass?
    pub is_analysis: bool,
    /// Is this a transform pass?
    pub is_transform: bool,
    /// Is this pass enabled by default at some opt level?
    pub is_default: bool,
    /// Optimization level (0-3)
    pub opt_level: u32,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PassType {
    /// Module-level pass
    Module,
    /// CallGraphSCC pass
    CGSCC,
    /// Function pass
    Function,
    /// Loop pass
    Loop,
    /// Region pass
    Region,
    /// Machine function pass
    MachineFunction,
}

/// Registry for registration-based pass infrastructure
pub struct PassRegistry {
    /// Registered passes by argument
    pub passes: HashMap<String, PassInfo>,
    /// Pipeline descriptions
    pub pipelines: HashMap<String, Vec<String>>,
}

impl PassRegistry {
    pub fn new() -> Self {
        let mut reg = PassRegistry {
            passes: HashMap::new(),
            pipelines: HashMap::new(),
        };
        reg.register_default_passes();
        reg
    }

    fn register_default_passes(&mut self) {
        let default_passes = vec![
            (
                "instcombine",
                "Instruction Combining",
                PassType::Function,
                2,
            ),
            ("simplifycfg", "Simplify the CFG", PassType::Function, 2),
            ("gvn", "Global Value Numbering", PassType::Function, 2),
            (
                "sccp",
                "Sparse Conditional Constant Propagation",
                PassType::Function,
                2,
            ),
            ("inline", "Function Inlining", PassType::CGSCC, 2),
            (
                "mem2reg",
                "Memory to Register Promotion",
                PassType::Function,
                1,
            ),
            ("licm", "Loop Invariant Code Motion", PassType::Loop, 2),
            ("loop-unroll", "Loop Unrolling", PassType::Loop, 2),
            ("loop-rotate", "Loop Rotation", PassType::Loop, 1),
            ("loop-simplify", "Loop Simplify", PassType::Loop, 1),
            (
                "reassociate",
                "Reassociate Expressions",
                PassType::Function,
                2,
            ),
            ("early-cse", "Early CSE", PassType::Function, 2),
            ("jump-threading", "Jump Threading", PassType::Function, 2),
            (
                "correlated-propagation",
                "Correlated Value Propagation",
                PassType::Function,
                2,
            ),
            (
                "deadargelim",
                "Dead Argument Elimination",
                PassType::Module,
                2,
            ),
            (
                "globalopt",
                "Global Variable Optimization",
                PassType::Module,
                2,
            ),
            ("globaldce", "Dead Global Elimination", PassType::Module, 3),
            ("ipsccp", "Interprocedural SCCP", PassType::Module, 2),
            (
                "dead-store-elimination",
                "Dead Store Elimination",
                PassType::Function,
                2,
            ),
            (
                "aggressive-instcombine",
                "Aggressive InstCombine",
                PassType::Function,
                2,
            ),
            (
                "tailcallelim",
                "Tail Call Elimination",
                PassType::Function,
                2,
            ),
            ("loop-vectorize", "Loop Vectorization", PassType::Loop, 3),
            ("slp-vectorize", "SLP Vectorizer", PassType::Function, 3),
            (
                "alignment-from-assumptions",
                "Alignment from Assumptions",
                PassType::Function,
                2,
            ),
            (
                "bdce",
                "Bit-Tracking Dead Code Elimination",
                PassType::Function,
                2,
            ),
            ("consthoist", "Constant Hoisting", PassType::Function, 2),
            ("div-rem-pairs", "Div Rem Pairs", PassType::Function, 2),
            ("float2int", "Float to Int", PassType::Function, 2),
            (
                "indvars",
                "Induction Variable Simplification",
                PassType::Loop,
                2,
            ),
            ("loop-deletion", "Delete Dead Loops", PassType::Loop, 2),
            ("loop-idiom", "Loop Idiom Recognition", PassType::Loop, 2),
            ("loop-reroll", "Loop Reroll", PassType::Loop, 3),
            ("loop-unswitch", "Unswitch Loops", PassType::Loop, 3),
            (
                "loweratomic",
                "Lower Atomic Intrinsics",
                PassType::Function,
                1,
            ),
            ("lowerinvoke", "Lower Invokes", PassType::Function, 1),
            ("lowerswitch", "Lower Switch", PassType::Function, 1),
            ("memcpyopt", "MemCpy Optimization", PassType::Function, 2),
            ("mergefunc", "Merge Functions", PassType::Module, 3),
            (
                "mergereturn",
                "Unify Function Exit Nodes",
                PassType::Function,
                1,
            ),
            ("partial-inliner", "Partial Inliner", PassType::Module, 2),
            (
                "prune-eh",
                "Prune Unused Exception Handling",
                PassType::Function,
                2,
            ),
            (
                "scalarizer",
                "Scalarize Vector Instructions",
                PassType::Function,
                2,
            ),
            (
                "separate-const-offset-from-gep",
                "Separate Const Offset from GEP",
                PassType::Function,
                1,
            ),
            (
                "simple-loop-unswitch",
                "Simple Loop Unswitch",
                PassType::Loop,
                2,
            ),
            ("sink", "Code Sinking", PassType::Function, 2),
            ("strip", "Strip Symbols", PassType::Module, 1),
            (
                "strip-dead-debug-info",
                "Strip Dead Debug Info",
                PassType::Module,
                2,
            ),
            (
                "strip-dead-prototypes",
                "Strip Dead Prototypes",
                PassType::Module,
                2,
            ),
            (
                "strip-nondebug",
                "Strip Non-Debug Symbols",
                PassType::Module,
                1,
            ),
            ("tailduplicate", "Tail Duplication", PassType::Function, 3),
            ("vector-combine", "Vector Combine", PassType::Function, 2),
            ("verify", "Module Verifier", PassType::Module, 1),
        ];

        for (arg, name, pass_type, opt_level) in default_passes {
            self.register(arg, name, pass_type, opt_level);
        }

        // Standard pipelines
        self.register_pipeline("O0", vec![]);
        self.register_pipeline(
            "O1",
            vec![
                "mem2reg",
                "instcombine",
                "simplifycfg",
                "reassociate",
                "gvn",
                "sccp",
                "deadargelim",
                "licm",
            ],
        );
        self.register_pipeline(
            "O2",
            vec![
                "inline",
                "mem2reg",
                "instcombine",
                "simplifycfg",
                "gvn",
                "sccp",
                "licm",
                "loop-rotate",
                "loop-unroll",
                "reassociate",
                "early-cse",
                "correlated-propagation",
                "tailcallelim",
                "jump-threading",
                "indvars",
                "loop-idiom",
                "loop-deletion",
            ],
        );
        self.register_pipeline(
            "O3",
            vec![
                "inline",
                "mem2reg",
                "instcombine",
                "simplifycfg",
                "gvn",
                "sccp",
                "licm",
                "loop-rotate",
                "loop-unroll",
                "loop-vectorize",
                "slp-vectorize",
                "reassociate",
                "early-cse",
                "correlated-propagation",
                "tailcallelim",
                "jump-threading",
                "indvars",
                "loop-unswitch",
                "loop-idiom",
                "loop-deletion",
            ],
        );
        self.register_pipeline(
            "Os",
            vec![
                "inline",
                "mem2reg",
                "instcombine",
                "simplifycfg",
                "gvn",
                "sccp",
                "licm",
                "loop-rotate",
            ],
        );
        self.register_pipeline(
            "Oz",
            vec!["inline", "mem2reg", "instcombine", "simplifycfg"],
        );
    }

    pub fn register(&mut self, arg: &str, name: &str, pass_type: PassType, opt_level: u32) {
        self.passes.insert(
            arg.to_string(),
            PassInfo {
                pass_arg: arg.to_string(),
                pass_name: name.to_string(),
                pass_type,
                is_analysis: false,
                is_transform: true,
                is_default: opt_level <= 2,
                opt_level,
            },
        );
    }

    pub fn register_pipeline(&mut self, name: &str, passes: Vec<&str>) {
        self.pipelines.insert(
            name.to_string(),
            passes.iter().map(|s| s.to_string()).collect(),
        );
    }

    pub fn get_pipeline(&self, opt_level: &str) -> Option<&Vec<String>> {
        self.pipelines.get(opt_level)
    }

    pub fn get_pass(&self, arg: &str) -> Option<&PassInfo> {
        self.passes.get(arg)
    }

    pub fn all_pass_args(&self) -> Vec<&str> {
        self.passes.keys().map(|s| s.as_str()).collect()
    }
}

impl Default for PassRegistry {
    fn default() -> Self {
        PassRegistry::new()
    }
}

// ============================================================================
// Section 7: Garbage Collection Strategy
// ============================================================================

/// GC strategy descriptor (mirrors LLVM's GCStrategy)
#[derive(Debug, Clone)]
pub struct GCStrategy {
    /// Strategy name (e.g., "statepoint-example", "coreclr")
    pub name: String,
    /// Does this GC use statepoints?
    pub use_statepoints: bool,
    /// Does this GC need stack maps?
    pub needs_stack_maps: bool,
    /// Does this GC use gcroot intrinsic?
    pub uses_gcroot: bool,
    /// Custom root initialization code
    pub custom_root_init: Option<String>,
    /// Custom lowering code
    pub custom_lowering: Option<String>,
}

impl GCStrategy {
    pub fn statepoint_example() -> Self {
        GCStrategy {
            name: "statepoint-example".to_string(),
            use_statepoints: true,
            needs_stack_maps: true,
            uses_gcroot: false,
            custom_root_init: None,
            custom_lowering: None,
        }
    }

    pub fn coreclr() -> Self {
        GCStrategy {
            name: "coreclr".to_string(),
            use_statepoints: true,
            needs_stack_maps: true,
            uses_gcroot: false,
            custom_root_init: Some("coreclr_initialize_roots".to_string()),
            custom_lowering: Some("coreclr_lower_gc".to_string()),
        }
    }
}

/// Registry of known GC strategies
pub struct GCStrategyRegistry {
    pub strategies: HashMap<String, GCStrategy>,
}

impl GCStrategyRegistry {
    pub fn new() -> Self {
        let mut reg = GCStrategyRegistry {
            strategies: HashMap::new(),
        };
        let sp = GCStrategy::statepoint_example();
        reg.strategies.insert(sp.name.clone(), sp);
        let clr = GCStrategy::coreclr();
        reg.strategies.insert(clr.name.clone(), clr);
        reg
    }

    pub fn get(&self, name: &str) -> Option<&GCStrategy> {
        self.strategies.get(name)
    }
}

impl Default for GCStrategyRegistry {
    fn default() -> Self {
        GCStrategyRegistry::new()
    }
}

// ============================================================================
// Section 8: Tests
// ============================================================================

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

    #[test]
    fn test_string_saver() {
        let mut saver = StringSaver::new();
        let i1 = saver.save("hello");
        let i2 = saver.save("world");
        let i3 = saver.save("hello");
        assert_eq!(i1, i3);
        assert_ne!(i1, i2);
        assert_eq!(saver.len(), 2);
    }

    #[test]
    fn test_intrinsic_registry() {
        let reg = IntrinsicRegistry::new();
        assert!(reg.is_intrinsic("llvm.memcpy"));
        assert!(reg.is_intrinsic("llvm.sqrt"));
        assert!(reg.is_intrinsic("llvm.trap"));
        assert!(!reg.is_intrinsic("not_an_intrinsic"));
    }

    #[test]
    fn test_diagnostic_consumer() {
        let mut consumer = CollectingDiagnosticConsumer::default();
        consumer.handle_diagnostic(&DiagnosticMessage {
            severity: DiagSeverity::Error,
            message: "test error".to_string(),
            file: None,
            line: None,
            column: None,
            ranges: Vec::new(),
            notes: Vec::new(),
            fixits: Vec::new(),
        });
        assert_eq!(consumer.get_num_errors(), 1);
    }

    #[test]
    fn test_type_canonicalizer() {
        let mut tc = TypeCanonicalizer::new();
        let i32_a = tc.get_int_type(32);
        let i32_b = tc.get_int_type(32);
        assert_eq!(i32_a, i32_b);
    }

    #[test]
    fn test_pass_registry() {
        let reg = PassRegistry::new();
        assert!(reg.get_pass("instcombine").is_some());
        assert!(reg.get_pass("gvn").is_some());
        assert!(reg.get_pipeline("O2").is_some());
    }

    #[test]
    fn test_gc_strategy_registry() {
        let reg = GCStrategyRegistry::new();
        assert!(reg.get("statepoint-example").is_some());
        assert!(reg.get("coreclr").is_some());
    }
}