llvm-native-core 0.1.10

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
//! LLVMContext — global state, type uniquing, module ownership.
//! Phase 1 — LLVM.IR.1 Court.

use crate::module::Module;
use crate::types::{Type, TypeId, TypeKind};
use crate::value::ValueRef;
use std::collections::HashMap;

#[derive(Debug, Clone)]
pub struct LLVMContext {
    type_cache: HashMap<TypeKind, Type>,
    pub modules: Vec<Module>,
    /// Cache for integer types by bit width.
    int_types: HashMap<u32, Type>,
    /// Cache for pointer types by address space.
    pointer_types: HashMap<u32, Type>,
    /// Cache for named struct types.
    named_structs: HashMap<String, Type>,
}

impl LLVMContext {
    pub fn new() -> Self {
        let mut ctx = Self {
            type_cache: HashMap::new(),
            modules: Vec::new(),
            int_types: HashMap::new(),
            pointer_types: HashMap::new(),
            named_structs: HashMap::new(),
        };
        // Pre-populate common types
        ctx.i1();
        ctx.i8();
        ctx.i32();
        ctx.i64();
        ctx.void_ty();
        ctx.float_ty();
        ctx.double_ty();
        ctx.label_ty();
        ctx
    }

    pub fn get_type(&mut self, kind: TypeKind) -> Type {
        self.type_cache
            .entry(kind.clone())
            .or_insert_with(|| Type::new(kind))
            .clone()
    }

    pub fn i1(&mut self) -> Type {
        self.get_type(Type::i1().kind)
    }
    pub fn i8(&mut self) -> Type {
        self.get_type(Type::i8().kind)
    }
    pub fn i32(&mut self) -> Type {
        self.get_type(Type::i32().kind)
    }
    pub fn i64(&mut self) -> Type {
        self.get_type(Type::i64().kind)
    }
    pub fn void_ty(&mut self) -> Type {
        self.get_type(TypeKind::Void)
    }
    pub fn float_ty(&mut self) -> Type {
        self.get_type(TypeKind::Float)
    }
    pub fn double_ty(&mut self) -> Type {
        self.get_type(TypeKind::Double)
    }
    pub fn label_ty(&mut self) -> Type {
        self.get_type(TypeKind::Label)
    }

    pub fn create_module(&mut self, name: &str) -> &mut Module {
        self.modules.push(Module::new(name));
        self.modules.last_mut().unwrap()
    }
}

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

// ============================================================================
// LLVMContext — predefined types (Phase 2 expansion)
// ============================================================================

impl LLVMContext {
    /// Return the label type (used for basic block addresses).
    ///
    /// @llvm_behavior: Equivalent to `Type::getLabelTy(Context)`.
    /// This is idempotent — repeated calls return the same canonical type.
    pub fn label_ty_cached(&self) -> Option<&Type> {
        self.int_types.get(&0); // not relevant; label is in type_cache
        None
    }

    /// Return the metadata type. Metadata is not a first-class type but
    /// is used for metadata operands.
    ///
    /// @llvm_behavior: Equivalent to `Type::getMetadataTy(Context)`.
    pub fn metadata_ty(&mut self) -> Type {
        self.get_type(TypeKind::Metadata)
    }

    /// Return the token type. Used for exception-handling and other
    /// special operations that produce a token value.
    ///
    /// @llvm_behavior: Equivalent to `Type::getTokenTy(Context)`.
    pub fn token_ty(&mut self) -> Type {
        self.get_type(TypeKind::Token)
    }

    /// Return the x86_mmx type — 64-bit MMX vector.
    ///
    /// @llvm_behavior: Equivalent to `Type::getX86_MMXTy(Context)`.
    pub fn x86_mmx_ty(&mut self) -> Type {
        self.get_type(TypeKind::X86MMX)
    }

    /// Return the bfloat type — 16-bit brain floating point.
    ///
    /// @llvm_behavior: Equivalent to `Type::getBFloatTy(Context)`.
    pub fn bfloat_ty(&mut self) -> Type {
        self.get_type(TypeKind::BFloat)
    }

    /// Return the x86_fp80 type — 80-bit x87 extended precision.
    ///
    /// @llvm_behavior: Equivalent to `Type::getX86_FP80Ty(Context)`.
    pub fn x86_fp80_ty(&mut self) -> Type {
        self.get_type(TypeKind::X86FP80)
    }

    /// Return the fp128 type — 128-bit IEEE 754 quadruple precision.
    ///
    /// @llvm_behavior: Equivalent to `Type::getFP128Ty(Context)`.
    pub fn fp128_ty(&mut self) -> Type {
        self.get_type(TypeKind::FP128)
    }

    /// Return the ppc_fp128 type — 128-bit double-double (PowerPC).
    ///
    /// @llvm_behavior: Equivalent to `Type::getPPC_FP128Ty(Context)`.
    pub fn ppc_fp128_ty(&mut self) -> Type {
        self.get_type(TypeKind::PPCFP128)
    }

    // ========================================================================
    // Integer type factory (cached)
    // ========================================================================

    /// Return a canonical integer type with the given bit width.
    ///
    /// Integer types are cached per bit width so that repeated calls
    /// with the same width return the same Type.
    ///
    /// @llvm_behavior: Equivalent to `IntegerType::get(Context, NumBits)`.
    pub fn int_ty(&mut self, bits: u32) -> Type {
        if let Some(ty) = self.int_types.get(&bits) {
            return ty.clone();
        }
        let ty = Type::int(bits);
        self.int_types.insert(bits, ty.clone());
        ty
    }

    // ========================================================================
    // Pointer type factory (cached)
    // ========================================================================

    /// Return a canonical opaque pointer type with the given address space.
    ///
    /// Opaque pointers (LLVM 15+) don't carry a pointee type.
    /// Types are cached per address space.
    ///
    /// @llvm_behavior: Equivalent to `PointerType::get(Context, AddressSpace)`.
    pub fn pointer_ty(&mut self, addr_space: u32) -> Type {
        if let Some(ty) = self.pointer_types.get(&addr_space) {
            return ty.clone();
        }
        let ty = Type::pointer(addr_space);
        self.pointer_types.insert(addr_space, ty.clone());
        ty
    }

    // ========================================================================
    // Compound type factories
    // ========================================================================

    /// Create an array type: `[len x elem]`.
    ///
    /// @llvm_behavior: Equivalent to `ArrayType::get(elemType, NumElements)`.
    /// Array types are uniqued by the LLVMContext so that identical
    /// element-type + length combinations return the same type.
    pub fn array_ty(&mut self, elem: &Type, len: u64) -> Type {
        let kind = TypeKind::Array {
            len,
            element_type_id: elem.id,
        };
        self.get_type(kind)
    }

    /// Create a fixed-length vector type: `<len x elem>`.
    ///
    /// @llvm_behavior: Equivalent to `FixedVectorType::get(elemType, NumElements)`.
    pub fn vector_ty(&mut self, elem: &Type, len: u32) -> Type {
        let kind = TypeKind::FixedVector {
            len,
            element_type_id: elem.id,
        };
        self.get_type(kind)
    }

    /// Create a literal (anonymous) struct type.
    ///
    /// If `is_packed`, the struct has no inter-element padding.
    ///
    /// @llvm_behavior: Equivalent to `StructType::get(Context, ElementTypes, isPacked)`.
    pub fn struct_ty(&mut self, elements: &[Type], is_packed: bool) -> Type {
        let element_ids: Vec<_> = elements.iter().map(|t| t.id).collect();
        let kind = TypeKind::Struct {
            name: None,
            is_packed,
            is_opaque: false,
            element_type_ids: element_ids,
        };
        self.get_type(kind)
    }

    /// Create or retrieve a named struct type.
    ///
    /// Named struct types are uniqued by name. If the name has been seen
    /// before, the existing (possibly opaque) type is returned. This
    /// enables forward-declared structs to be completed later.
    ///
    /// @llvm_behavior: Equivalent to `StructType::create(Context, Name)`.
    pub fn named_struct_ty(&mut self, name: &str, is_packed: bool) -> Type {
        if let Some(ty) = self.named_structs.get(name) {
            return ty.clone();
        }
        let kind = TypeKind::Struct {
            name: Some(name.to_string()),
            is_packed,
            is_opaque: true, // initially opaque; can be completed later
            element_type_ids: Vec::new(),
        };
        let ty = self.get_type(kind);
        self.named_structs.insert(name.to_string(), ty.clone());
        ty
    }

    /// Create a function type.
    ///
    /// @llvm_behavior: Equivalent to `FunctionType::get(ReturnType, ParamTypes, isVarArg)`.
    /// Function types are uniqued so identical signatures return the same type.
    pub fn function_ty(&mut self, ret: &Type, params: &[Type], is_vararg: bool) -> Type {
        let param_ids: Vec<_> = params.iter().map(|t| t.id).collect();
        let kind = TypeKind::Function {
            return_type_id: ret.id,
            param_type_ids: param_ids,
            is_vararg,
        };
        self.get_type(kind)
    }

    // ========================================================================
    // Type deduplication (LLVMContext is the canonical type owner)
    // ========================================================================

    /// Look up a cached canonical type by its TypeKind.
    ///
    /// Returns `Some(type)` if a type with the exact same kind has been
    /// created through this context, or `None` if no such type exists yet.
    ///
    /// @llvm_behavior: LLVM type uniquing ensures that types with the same
    /// structural description share the same pointer. This method provides
    /// read-only access to the cache.
    pub fn get_cached_type(&self, kind: &TypeKind) -> Option<Type> {
        self.type_cache.get(kind).cloned()
    }

    /// Insert a type into the canonical type cache.
    ///
    /// If a type with the same kind already exists, it is replaced.
    /// This is useful when completing an opaque struct type with its
    /// element types.
    ///
    /// @llvm_behavior: Equivalent to `StructType::setBody(...)` — the type
    /// is re-uniqued in the context.
    pub fn cache_type(&mut self, ty: Type) {
        self.type_cache.insert(ty.kind.clone(), ty);
    }

    // ========================================================================
    /// Create a module (owned by value).
    ///
    /// Unlike `create_module` which returns a mutable reference, this
    /// returns an owned `Module` that the caller manages.
    ///
    /// @llvm_behavior: Equivalent to `new Module(name, Context)`.
    pub fn create_module_owned(&self, name: &str) -> Module {
        Module::new(name)
    }

    // ========================================================================
    // Constant creation factories
    // ========================================================================

    /// Create a signed integer constant.
    ///
    /// @llvm_behavior: Equivalent to `ConstantInt::getSigned(ty, value)`.
    pub fn const_int(&self, ty: &Type, value: u64) -> crate::constants::Constant {
        crate::constants::Constant::UInt(value, ty.clone())
    }

    /// Create a floating-point constant.
    ///
    /// @llvm_behavior: Equivalent to `ConstantFP::get(ty, value)`.
    pub fn const_float(&self, ty: &Type, value: f64) -> crate::constants::Constant {
        crate::constants::Constant::Float(value, ty.clone())
    }

    /// Create a null constant for the given type.
    ///
    /// @llvm_behavior: Equivalent to `Constant::getNullValue(ty)`.
    pub fn const_null(&self, ty: &Type) -> crate::constants::Constant {
        crate::constants::Constant::Null(ty.clone())
    }

    /// Create an undef constant for the given type.
    ///
    /// @llvm_behavior: Equivalent to `UndefValue::get(ty)`.
    pub fn const_undef(&self, ty: &Type) -> crate::constants::Constant {
        crate::constants::Constant::Undef(ty.clone())
    }

    /// Create a poison constant for the given type.
    ///
    /// @llvm_behavior: Equivalent to `PoisonValue::get(ty)`.
    pub fn const_poison(&self, ty: &Type) -> crate::constants::Constant {
        crate::constants::Constant::Poison(ty.clone())
    }

    /// Create a zeroinitializer constant for the given type.
    ///
    /// @llvm_behavior: Equivalent to `ConstantAggregateZero::get(ty)`.
    pub fn const_zeroinitializer(&self, ty: &Type) -> crate::constants::Constant {
        crate::constants::Constant::ZeroInitializer(ty.clone())
    }

    // ========================================================================
    // Convenience: half type
    // ========================================================================

    /// Return the half type — 16-bit IEEE 754 half precision.
    pub fn half_ty(&mut self) -> Type {
        self.get_type(TypeKind::Half)
    }
}

// ============================================================================
// Diagnostic Engine — error/warning/note emission
// ============================================================================

/// Severity level for diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DiagSeverity {
    Ignored,
    Note,
    Remark,
    Warning,
    Error,
    Fatal,
}

/// A single diagnostic message.
#[derive(Debug, Clone)]
pub struct Diagnostic {
    pub severity: DiagSeverity,
    pub message: String,
    pub file: Option<String>,
    pub line: Option<u32>,
    pub column: Option<u32>,
    pub source_range: Option<(u32, u32, u32, u32)>, // (start_line, start_col, end_line, end_col)
    pub notes: Vec<String>,
    pub fixit_hints: Vec<FixItHint>,
}

/// A fix-it hint suggesting a source replacement.
#[derive(Debug, Clone)]
pub struct FixItHint {
    pub start_line: u32,
    pub start_col: u32,
    pub end_line: u32,
    pub end_col: u32,
    pub replacement: String,
}

impl Diagnostic {
    pub fn new(severity: DiagSeverity, message: impl Into<String>) -> Self {
        Self {
            severity,
            message: message.into(),
            file: None,
            line: None,
            column: None,
            source_range: None,
            notes: Vec::new(),
            fixit_hints: Vec::new(),
        }
    }

    pub fn at(mut self, file: &str, line: u32, col: u32) -> Self {
        self.file = Some(file.to_string());
        self.line = Some(line);
        self.column = Some(col);
        self
    }

    pub fn with_note(mut self, note: impl Into<String>) -> Self {
        self.notes.push(note.into());
        self
    }

    pub fn with_fixit(mut self, hint: FixItHint) -> Self {
        self.fixit_hints.push(hint);
        self
    }

    pub fn is_error(&self) -> bool {
        matches!(self.severity, DiagSeverity::Error | DiagSeverity::Fatal)
    }

    pub fn is_warning(&self) -> bool {
        self.severity == DiagSeverity::Warning
    }
}

/// A diagnostic engine that collects and filters diagnostics.
#[derive(Debug, Clone, Default)]
pub struct DiagnosticEngine {
    pub diagnostics: Vec<Diagnostic>,
    pub error_count: u32,
    pub warning_count: u32,
    /// Suppress all warnings (like -w flag).
    pub suppress_warnings: bool,
    /// Treat warnings as errors (like -Werror).
    pub warnings_as_errors: bool,
    /// Maximum number of errors before bailing out.
    pub error_limit: Option<u32>,
}

impl DiagnosticEngine {
    pub fn new() -> Self {
        Self {
            diagnostics: Vec::new(),
            error_count: 0,
            warning_count: 0,
            suppress_warnings: false,
            warnings_as_errors: false,
            error_limit: Some(20),
        }
    }

    /// Emit a diagnostic. If it exceeds error limits, returns false.
    pub fn emit(&mut self, mut diag: Diagnostic) -> bool {
        if diag.severity == DiagSeverity::Warning && self.suppress_warnings {
            return true;
        }
        if diag.severity == DiagSeverity::Warning && self.warnings_as_errors {
            diag.severity = DiagSeverity::Error;
        }
        match diag.severity {
            DiagSeverity::Error | DiagSeverity::Fatal => {
                self.error_count += 1;
                if let Some(limit) = self.error_limit {
                    if self.error_count > limit {
                        self.diagnostics.push(diag);
                        return false; // Too many errors
                    }
                }
            }
            DiagSeverity::Warning => self.warning_count += 1,
            _ => {}
        }
        self.diagnostics.push(diag);
        true
    }

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

    pub fn has_warnings(&self) -> bool {
        self.warning_count > 0
    }

    pub fn clear(&mut self) {
        self.diagnostics.clear();
        self.error_count = 0;
        self.warning_count = 0;
    }

    /// Get all error diagnostics.
    pub fn errors(&self) -> Vec<&Diagnostic> {
        self.diagnostics.iter().filter(|d| d.is_error()).collect()
    }
}

// ============================================================================
// Constant Pool — deduplicated constant storage
// ============================================================================

/// A pool of deduplicated constants owned by the LLVMContext.
///
/// @llvm_behavior: LLVM maintains a constant pool per module/context.
/// Constants with the same type and value share a single instance.
#[derive(Debug, Clone, Default)]
pub struct ConstantPool {
    /// Integer constants keyed by (bit_width, signed_value, unsigned_value).
    int_constants: HashMap<(u32, i64, u64), ValueRef>,
    /// Float constants keyed by (is_double, bits).
    float_constants: HashMap<(bool, u64), ValueRef>,
    /// Null constants keyed by type id.
    null_constants: HashMap<TypeId, ValueRef>,
    /// Undef constants.
    undef_constants: HashMap<TypeId, ValueRef>,
    /// Poison constants.
    poison_constants: HashMap<TypeId, ValueRef>,
    /// Zero-initializer constants.
    zero_constants: HashMap<TypeId, ValueRef>,
    /// Aggregate constants keyed by hash.
    aggregate_constants: HashMap<u64, ValueRef>,
    /// Total number of unique constants.
    pub count: usize,
}

impl ConstantPool {
    pub fn new() -> Self {
        Self {
            int_constants: HashMap::new(),
            float_constants: HashMap::new(),
            null_constants: HashMap::new(),
            undef_constants: HashMap::new(),
            poison_constants: HashMap::new(),
            zero_constants: HashMap::new(),
            aggregate_constants: HashMap::new(),
            count: 0,
        }
    }

    /// Get or create an integer constant.
    pub fn get_int(&mut self, ty: &Type, signed: i64, unsigned: u64, bits: u32) -> ValueRef {
        let key = (bits, signed, unsigned);
        if let Some(c) = self.int_constants.get(&key) {
            return c.clone();
        }
        let c = crate::constants::const_int(ty.clone(), signed);
        self.int_constants.insert(key, c.clone());
        self.count += 1;
        c
    }

    /// Get or create a floating-point constant.
    pub fn get_float(&mut self, ty: &Type, is_double: bool, bits: u64) -> ValueRef {
        let key = (is_double, bits);
        if let Some(c) = self.float_constants.get(&key) {
            return c.clone();
        }
        let val = if is_double {
            f64::from_bits(bits)
        } else {
            f32::from_bits(bits as u32) as f64
        };
        let c = if is_double {
            crate::constants::const_double(val)
        } else {
            crate::constants::const_float(val)
        };
        self.float_constants.insert(key, c.clone());
        self.count += 1;
        c
    }

    /// Get or create a null constant.
    pub fn get_null(&mut self, ty: &Type) -> ValueRef {
        let key = ty.id;
        if let Some(c) = self.null_constants.get(&key) {
            return c.clone();
        }
        let c = crate::constants::const_null_ptr(ty.clone());
        self.null_constants.insert(key, c.clone());
        self.count += 1;
        c
    }

    /// Get or create an undef constant.
    pub fn get_undef(&mut self, ty: &Type) -> ValueRef {
        let key = ty.id;
        if let Some(c) = self.undef_constants.get(&key) {
            return c.clone();
        }
        let c = crate::constants::undef_value(ty.clone());
        self.undef_constants.insert(key, c.clone());
        self.count += 1;
        c
    }

    /// Get or create a poison constant.
    pub fn get_poison(&mut self, ty: &Type) -> ValueRef {
        let key = ty.id;
        if let Some(c) = self.poison_constants.get(&key) {
            return c.clone();
        }
        let c = crate::constants::poison_value(ty.clone());
        self.poison_constants.insert(key, c.clone());
        self.count += 1;
        c
    }

    /// Clear all constants.
    pub fn clear(&mut self) {
        self.int_constants.clear();
        self.float_constants.clear();
        self.null_constants.clear();
        self.undef_constants.clear();
        self.poison_constants.clear();
        self.zero_constants.clear();
        self.aggregate_constants.clear();
        self.count = 0;
    }
}

// ============================================================================
// Named Metadata Storage
// ============================================================================

/// Storage for named metadata nodes (like !llvm.module.flags, !dbg, etc.).
#[derive(Debug, Clone, Default)]
pub struct NamedMDNode {
    /// The name of this metadata collection.
    pub name: String,
    /// The MDNode operands.
    pub operands: Vec<crate::constants::MDNode>,
}

impl NamedMDNode {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            operands: Vec::new(),
        }
    }

    pub fn add_operand(&mut self, node: crate::constants::MDNode) {
        self.operands.push(node);
    }

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

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

/// Collection of named metadata nodes owned by the context.
#[derive(Debug, Clone, Default)]
pub struct NamedMetadataStore {
    pub nodes: HashMap<String, NamedMDNode>,
}

impl NamedMetadataStore {
    pub fn new() -> Self {
        Self {
            nodes: HashMap::new(),
        }
    }

    pub fn get_or_create(&mut self, name: &str) -> &mut NamedMDNode {
        self.nodes
            .entry(name.to_string())
            .or_insert_with(|| NamedMDNode::new(name))
    }

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

    pub fn remove(&mut self, name: &str) -> Option<NamedMDNode> {
        self.nodes.remove(name)
    }

    pub fn clear(&mut self) {
        self.nodes.clear();
    }

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

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

/// A specialized cache for canonical types, organized by category.
///
/// The TypeCache provides fast lookup for commonly-requested types
/// (integers, pointers, named structs) without needing to hash the
/// full TypeKind every time.
///
/// @llvm_behavior: LLVM maintains per-context type caches internally.
/// This struct exposes them for external inspection and bulk operations.
#[derive(Debug, Clone, Default)]
pub struct TypeCache {
    /// Integer types indexed by bit width.
    pub int_types: HashMap<u32, Type>,
    /// Pointer types indexed by address space.
    pub pointer_types: HashMap<u32, Type>,
    /// Named struct types indexed by name.
    pub named_structs: HashMap<String, Type>,
}

impl TypeCache {
    /// Create an empty TypeCache.
    pub fn new() -> Self {
        Self {
            int_types: HashMap::new(),
            pointer_types: HashMap::new(),
            named_structs: HashMap::new(),
        }
    }

    /// Check whether the cache is completely empty.
    pub fn is_empty(&self) -> bool {
        self.int_types.is_empty() && self.pointer_types.is_empty() && self.named_structs.is_empty()
    }

    /// Return the number of cached types across all categories.
    pub fn len(&self) -> usize {
        self.int_types.len() + self.pointer_types.len() + self.named_structs.len()
    }

    /// Clear all cached types.
    pub fn clear(&mut self) {
        self.int_types.clear();
        self.pointer_types.clear();
        self.named_structs.clear();
    }

    /// Look up an integer type by bit width.
    pub fn get_int_type(&self, bits: u32) -> Option<&Type> {
        self.int_types.get(&bits)
    }

    /// Look up a pointer type by address space.
    pub fn get_pointer_type(&self, addr_space: u32) -> Option<&Type> {
        self.pointer_types.get(&addr_space)
    }

    /// Look up a named struct type by name.
    pub fn get_named_struct(&self, name: &str) -> Option<&Type> {
        self.named_structs.get(name)
    }

    /// Merge the contents of this cache into an LLVMContext.
    ///
    /// This is useful for bulk-loading pre-built type caches into a
    /// fresh context (e.g., when deserializing modules).
    pub fn merge_into_context(&self, ctx: &mut LLVMContext) {
        for (&bits, ty) in &self.int_types {
            ctx.int_types.entry(bits).or_insert_with(|| ty.clone());
        }
        for (&addr, ty) in &self.pointer_types {
            ctx.pointer_types.entry(addr).or_insert_with(|| ty.clone());
        }
        for (name, ty) in &self.named_structs {
            ctx.named_structs
                .entry(name.clone())
                .or_insert_with(|| ty.clone());
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    // ========================================================================
    // Existing tests (preserved from Phase 1)
    // ========================================================================

    // Note: No tests existed in the original 74-line file.
    // The following tests are all new additions.

    // ========================================================================
    // New tests (Phase 2)
    // ========================================================================

    #[test]
    fn test_metadata_ty() {
        let mut ctx = LLVMContext::new();
        let mt = ctx.metadata_ty();
        assert!(mt.is_metadata());
    }

    #[test]
    fn test_token_ty() {
        let mut ctx = LLVMContext::new();
        let tt = ctx.token_ty();
        assert!(tt.is_token());
    }

    #[test]
    fn test_x86_mmx_ty() {
        let mut ctx = LLVMContext::new();
        let mmx = ctx.x86_mmx_ty();
        // Should not panic and should be a valid type
        assert!(!mmx.is_void());
    }

    #[test]
    fn test_bfloat_ty() {
        let mut ctx = LLVMContext::new();
        let bf = ctx.bfloat_ty();
        assert!(bf.is_floating_point());
    }

    #[test]
    fn test_x86_fp80_ty() {
        let mut ctx = LLVMContext::new();
        let fp80 = ctx.x86_fp80_ty();
        assert!(fp80.is_floating_point());
    }

    #[test]
    fn test_fp128_ty() {
        let mut ctx = LLVMContext::new();
        let fp128 = ctx.fp128_ty();
        assert!(fp128.is_floating_point());
    }

    #[test]
    fn test_ppc_fp128_ty() {
        let mut ctx = LLVMContext::new();
        let ppc = ctx.ppc_fp128_ty();
        assert!(ppc.is_floating_point());
    }

    #[test]
    fn test_half_ty() {
        let mut ctx = LLVMContext::new();
        let half = ctx.half_ty();
        assert!(half.is_floating_point());
    }

    #[test]
    fn test_int_ty_caching() {
        let mut ctx = LLVMContext::new();
        let i32_a = ctx.int_ty(32);
        let i32_b = ctx.int_ty(32);
        // Same bit width should return the same canonical type
        assert!(Type::is_same_type(&i32_a, &i32_b));

        let i64_a = ctx.int_ty(64);
        let i64_b = ctx.int_ty(64);
        assert!(Type::is_same_type(&i64_a, &i64_b));

        // Different widths should be different types
        assert!(!Type::is_same_type(&i32_a, &i64_a));
    }

    #[test]
    fn test_pointer_ty_caching() {
        let mut ctx = LLVMContext::new();
        let p0_a = ctx.pointer_ty(0);
        let p0_b = ctx.pointer_ty(0);
        assert!(Type::is_same_type(&p0_a, &p0_b));

        let p1 = ctx.pointer_ty(1);
        assert!(!Type::is_same_type(&p0_a, &p1));
    }

    #[test]
    fn test_array_ty() {
        let mut ctx = LLVMContext::new();
        let i32 = ctx.i32();
        let arr = ctx.array_ty(&i32, 10);
        assert!(arr.is_array());
        // The array type should be cached and reused
        let arr2 = ctx.array_ty(&i32, 10);
        assert!(Type::is_same_type(&arr, &arr2));
    }

    #[test]
    fn test_vector_ty() {
        let mut ctx = LLVMContext::new();
        let i32 = ctx.i32();
        let v4i32 = ctx.vector_ty(&i32, 4);
        assert!(v4i32.is_vector());
        let v4i32_2 = ctx.vector_ty(&i32, 4);
        assert!(Type::is_same_type(&v4i32, &v4i32_2));
    }

    #[test]
    fn test_struct_ty() {
        let mut ctx = LLVMContext::new();
        let i32 = ctx.i32();
        let f64 = ctx.double_ty();
        let st = ctx.struct_ty(&[i32.clone(), f64.clone()], false);
        assert!(st.is_struct());

        let st2 = ctx.struct_ty(&[i32.clone(), f64.clone()], false);
        assert!(Type::is_same_type(&st, &st2));
    }

    #[test]
    fn test_struct_ty_packed() {
        let mut ctx = LLVMContext::new();
        let i32 = ctx.i32();
        let st_packed = ctx.struct_ty(&[i32.clone()], true);
        let st_unpacked = ctx.struct_ty(&[i32.clone()], false);
        assert!(!Type::is_same_type(&st_packed, &st_unpacked));
    }

    #[test]
    fn test_named_struct_ty() {
        let mut ctx = LLVMContext::new();
        let st1 = ctx.named_struct_ty("MyStruct", false);
        let st2 = ctx.named_struct_ty("MyStruct", false);
        // Same name should return the same type
        assert!(Type::is_same_type(&st1, &st2));
        // Different name should be different
        let st3 = ctx.named_struct_ty("OtherStruct", false);
        assert!(!Type::is_same_type(&st1, &st3));
    }

    #[test]
    fn test_function_ty() {
        let mut ctx = LLVMContext::new();
        let i32 = ctx.i32();
        let f64 = ctx.double_ty();
        let void = ctx.void_ty();

        let fn_ty = ctx.function_ty(&i32, &[f64.clone()], false);
        assert!(fn_ty.is_function());

        let fn_ty2 = ctx.function_ty(&i32, &[f64.clone()], false);
        assert!(Type::is_same_type(&fn_ty, &fn_ty2));

        let fn_vararg = ctx.function_ty(&void, &[i32.clone()], true);
        assert!(fn_vararg.is_function());
        assert!(fn_vararg.is_vararg_function());
    }

    #[test]
    fn test_get_cached_type() {
        let mut ctx = LLVMContext::new();
        let i32 = ctx.i32();
        let cached = ctx.get_cached_type(&i32.kind);
        assert!(cached.is_some());
        assert!(Type::is_same_type(&cached.unwrap(), &i32));

        // A type we haven't created should return None
        let unknown_kind = TypeKind::Integer { bits: 99 };
        assert!(ctx.get_cached_type(&unknown_kind).is_none());

        // After creating via get_type, it should be cached
        ctx.get_type(TypeKind::Integer { bits: 99 });
        assert!(ctx
            .get_cached_type(&TypeKind::Integer { bits: 99 })
            .is_some());
    }

    #[test]
    fn test_cache_type() {
        let mut ctx = LLVMContext::new();
        let custom = Type::int(17);
        ctx.cache_type(custom.clone());
        let cached = ctx.get_cached_type(&custom.kind);
        assert!(cached.is_some());
    }

    #[test]
    fn test_const_creation_methods() {
        let ctx = LLVMContext::new();
        let i32 = Type::i32();

        let c_int = ctx.const_int(&i32, 42);
        assert!(matches!(c_int, crate::constants::Constant::UInt(42, _)));

        let c_float = ctx.const_float(&Type::double(), 3.14);
        assert!(
            matches!(c_float, crate::constants::Constant::Float(v, _) if (v - 3.14).abs() < 0.001)
        );

        let c_null = ctx.const_null(&i32);
        assert!(matches!(c_null, crate::constants::Constant::Null(_)));

        let c_undef = ctx.const_undef(&i32);
        assert!(matches!(c_undef, crate::constants::Constant::Undef(_)));

        let c_poison = ctx.const_poison(&i32);
        assert!(matches!(c_poison, crate::constants::Constant::Poison(_)));

        let c_zero = ctx.const_zeroinitializer(&i32);
        assert!(matches!(
            c_zero,
            crate::constants::Constant::ZeroInitializer(_)
        ));
    }

    #[test]
    fn test_type_cache_empty() {
        let cache = TypeCache::new();
        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);
    }

    #[test]
    fn test_type_cache_clear() {
        let mut cache = TypeCache::new();
        cache.int_types.insert(32, Type::i32());
        cache.pointer_types.insert(0, Type::pointer(0));
        assert!(!cache.is_empty());
        cache.clear();
        assert!(cache.is_empty());
    }

    #[test]
    fn test_type_cache_merge_into_context() {
        let mut cache = TypeCache::new();
        cache.int_types.insert(16, Type::i16());
        cache.pointer_types.insert(0, Type::pointer(0));

        let mut ctx = LLVMContext::new();
        cache.merge_into_context(&mut ctx);

        // After merge, the context should have these types cached
        let i16_cached = ctx.int_types.get(&16);
        assert!(i16_cached.is_some());
        assert!(i16_cached.unwrap().is_integer());
        assert_eq!(i16_cached.unwrap().integer_bit_width(), 16);

        let ptr_cached = ctx.pointer_types.get(&0);
        assert!(ptr_cached.is_some());
        assert!(ptr_cached.unwrap().is_pointer());
    }

    #[test]
    fn test_type_cache_get_methods() {
        let mut cache = TypeCache::new();
        cache.int_types.insert(32, Type::i32());
        cache.pointer_types.insert(0, Type::pointer(0));
        cache.named_structs.insert("Foo".to_string(), Type::int(64));

        assert!(cache.get_int_type(32).is_some());
        assert!(cache.get_int_type(99).is_none());
        assert!(cache.get_pointer_type(0).is_some());
        assert!(cache.get_pointer_type(1).is_none());
        assert!(cache.get_named_struct("Foo").is_some());
        assert!(cache.get_named_struct("Bar").is_none());
    }

    #[test]
    fn test_type_cache_default() {
        let cache = TypeCache::default();
        assert!(cache.is_empty());
    }

    #[test]
    fn test_create_module_owned() {
        let ctx = LLVMContext::new();
        let module = ctx.create_module_owned("my_module");
        assert_eq!(module.name, "my_module");
    }
}