llvm-native-core 0.1.13

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
//! X86 Target Machine — top-level compilation driver for the X86 backend.
//! Phase 10 — LLVM.TARGET.X86.1 Court.
//!
//! The `X86TargetMachine` is the primary entry point for X86/X86-64 code
//! generation.  It owns the subtarget, data layout, relocation model,
//! code model, and optimisation level, and orchestrates the entire
//! compilation pipeline from LLVM IR to assembly or object code.
//!
//! ## Pipeline Stages
//!
//! 1. **Analysis passes** — pre-ISel analysis (e.g. loop info, alias analysis).
//! 2. **IR optimisation passes** — target-independent IR transforms (inlining,
//!    vectorisation, GVN, etc.).
//! 3. **Instruction selection** — lowering IR to machine instructions.
//! 4. **Machine passes** — register allocation, frame lowering, scheduling,
//!    prologue/epilogue insertion.
//! 5. **Emission** — assembly printing or object-file writing.
//!
//! ## Clean-room reconstruction from:
//! - Intel® 64 and IA-32 Architectures Software Developer's Manual
//! - AMD64 Architecture Programmer's Manual
//! - System V AMD64 ABI / Microsoft x64 ABI
//! - ELF / COFF / Mach-O object-file specifications
//! - Black-box oracle interrogation

use crate::data_layout::DataLayout;
use crate::module::Module;
use crate::value::ValueRef;
use crate::x86::x86_subtarget::X86Subtarget;

// ============================================================================
// Enums
// ============================================================================

/// Relocation model — determines how the compiler treats references to
/// global data and functions.
///
/// Corresponds to LLVM's `Reloc::Model`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RelocModel {
    /// No relocation: code and data are placed at fixed addresses.
    /// Equivalent to GCC/Clang `-mcmodel=kernel` without PIC.
    Static,

    /// Position-Independent Code (PIC): references are resolved through
    /// the Global Offset Table (GOT) and Procedure Linkage Table (PLT).
    /// Required for shared libraries and ASLR-enabled executables.
    PIC,

    /// Dynamic No-PIC: relocatable but not strictly PIC; code references
    /// can be relocated at load time but without full GOT indirection.
    DynamicNoPIC,

    /// Read-Only Position Independence (ROPI): code is PIC but data is
    /// not.  Used in some bare-metal / embedded scenarios.
    ROPI,

    /// Read-Write Position Independence (RWPI): both code and read-write
    /// data are position-independent.  Used in some embedded toolchains.
    RWPI,

    /// Combined ROPI + RWPI.
    ROPIRWPI,

    /// Default — target-dependent default.
    Default,
}

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

/// Code model — determines the assumptions the compiler can make about
/// the size and relative placement of code and data.
///
/// Corresponds to LLVM's `CodeModel::Model`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CodeModel {
    /// Tiny: code and data fit within 1 MiB (x86-64 `small` variant).
    /// Rarely used except in embedded or kernel scenarios.
    Tiny,

    /// Small: code and data are within the lower 2 GiB of the address
    /// space (default for most user-space applications on x86-64).
    Small,

    /// Kernel: like Small but for kernel code; the kernel lives in the
    /// negative 2 GiB of the address space (top 2 GiB).
    Kernel,

    /// Medium: code is within 2 GiB, but data can be anywhere in the
    /// 64-bit address space.  Used for large applications.
    Medium,

    /// Large: no restrictions; code and data can be anywhere in the
    /// full 64-bit address space.  Slowest.
    Large,

    /// Default — target-dependent default.
    Default,
}

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

/// Optimisation level — controls the aggressiveness of the pass pipeline.
///
/// Corresponds to LLVM's `CodeGenOpt::Level`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum OptimizationLevel {
    /// No optimisation: fast compile, debuggable code.
    O0 = 0,

    /// Basic optimisation: simple peephole, no expensive passes.
    O1 = 1,

    /// Moderate optimisation: most scalar optimisations, inlining.
    O2 = 2,

    /// Aggressive optimisation: vectorisation, LTO-friendly, unrolling.
    O3 = 3,

    /// Optimise for size: like O2 but favours smaller code.
    Os = 4,

    /// Optimise for size aggressively: may use slower constructs to
    /// minimise code size.
    Oz = 5,
}

// ============================================================================
// X86TargetMachine
// ============================================================================

/// The X86 target machine — top-level compilation driver for x86/x86-64.
///
/// Owns the subtarget (feature set), data layout, relocation model,
/// code model, and optimisation level, and drives the entire compilation
/// pipeline.
///
/// ## Example
///
/// ```ignore
/// let tm = X86TargetMachine::new(
///     "x86_64-unknown-linux-gnu",
///     "haswell",
///     "+avx2,-rtm",
/// );
/// let asm = tm.emit_assembly(&module);
/// ```
#[derive(Debug, Clone)]
pub struct X86TargetMachine {
    /// Target triple string (e.g. "x86_64-unknown-linux-gnu").
    pub triple: String,

    /// CPU name (e.g. "haswell", "generic").
    pub cpu: String,

    /// Feature string (e.g. "+avx2,-rtm").
    pub features: String,

    /// Subtarget configuration — the definitive source of ISA features.
    pub subtarget: X86Subtarget,

    /// Data layout string and parsed layout.
    pub data_layout: DataLayout,

    /// Relocation model.
    pub reloc_model: RelocModel,

    /// Code model.
    pub code_model: CodeModel,

    /// Optimisation level for the pass pipeline.
    pub opt_level: OptimizationLevel,
}

impl X86TargetMachine {
    /// Construct a new X86-target machine.
    ///
    /// # Arguments
    ///
    /// * `triple` — target triple (e.g. `"x86_64-unknown-linux-gnu"`).
    /// * `cpu` — CPU name (e.g. `"haswell"`).
    /// * `features` — optional +/-feature string (e.g. `"+avx2,-rtm"`).
    ///
    /// # Defaults
    ///
    /// * Relocation model: `Static`
    /// * Code model: `Small` for 64-bit, `Tiny` for 32-bit
    /// * Optimisation level: `O0`
    /// * Data layout: the canonical x86-64 or x86 data layout string
    pub fn new(triple: &str, cpu: &str, features: &str) -> Self {
        let subtarget = X86Subtarget::new(triple, cpu, features);

        let is_64_bit = subtarget.is_64_bit;

        // Select the appropriate data layout.
        let data_layout = if is_64_bit {
            DataLayout::parse(DEFAULT_X86_64_DATA_LAYOUT)
        } else {
            DataLayout::parse(DEFAULT_X86_32_DATA_LAYOUT)
        };

        // Sensible defaults (callers can override via extension methods).
        let code_model = if is_64_bit {
            CodeModel::Small
        } else {
            CodeModel::Tiny
        };

        X86TargetMachine {
            triple: triple.to_string(),
            cpu: cpu.to_string(),
            features: features.to_string(),
            subtarget,
            data_layout: data_layout.unwrap_or_default(),
            reloc_model: RelocModel::Static,
            code_model,
            opt_level: OptimizationLevel::O0,
        }
    }

    /// Build a target machine with a specific relocation model.
    pub fn with_reloc_model(mut self, model: RelocModel) -> Self {
        self.reloc_model = model;
        self
    }

    /// Build a target machine with a specific code model.
    pub fn with_code_model(mut self, model: CodeModel) -> Self {
        self.code_model = model;
        self
    }

    /// Build a target machine with a specific optimisation level.
    pub fn with_opt_level(mut self, level: OptimizationLevel) -> Self {
        self.opt_level = level;
        self
    }

    // ========================================================================
    // Accessors
    // ========================================================================

    /// Return the raw data layout string computed for this target.
    pub fn get_data_layout(&self) -> String {
        self.data_layout.to_string()
    }

    /// Return the target triple.
    pub fn get_target_triple(&self) -> &str {
        &self.triple
    }

    /// Return the CPU name.
    pub fn get_cpu(&self) -> &str {
        &self.cpu
    }

    /// Return the feature string.
    pub fn get_features(&self) -> &str {
        &self.features
    }

    /// Return a reference to the subtarget.
    pub fn get_subtarget(&self) -> &X86Subtarget {
        &self.subtarget
    }

    /// Return the relocation model.
    pub fn get_reloc_model(&self) -> RelocModel {
        self.reloc_model
    }

    /// Return the code model.
    pub fn get_code_model(&self) -> CodeModel {
        self.code_model
    }

    /// Return the optimisation level.
    pub fn get_opt_level(&self) -> OptimizationLevel {
        self.opt_level
    }

    /// Return `true` if the target is 64-bit.
    pub fn is_64_bit(&self) -> bool {
        self.subtarget.is_64_bit
    }

    /// Return `true` if position-independent code is required.
    pub fn is_pic(&self) -> bool {
        matches!(
            self.reloc_model,
            RelocModel::PIC | RelocModel::ROPI | RelocModel::ROPIRWPI
        )
    }

    // ========================================================================
    // Pass pipeline registration
    // ========================================================================

    /// Register pre-instruction-selection analysis passes.
    ///
    /// These passes gather information needed by the instruction selector
    /// and other backend components.  In a full implementation this would
    /// include:
    ///
    /// - Loop info analysis
    /// - Alias analysis
    /// - Dominance frontier computation
    /// - Branch probability / profile data
    pub fn add_analysis_passes(&self) -> Vec<String> {
        let mut passes = vec![
            "target-library-info".to_string(),
            "target-transform-info".to_string(),
            "assumption-cache-tracker".to_string(),
        ];

        if self.opt_level >= OptimizationLevel::O1 {
            passes.push("loop-info".to_string());
            passes.push("scalar-evolution".to_string());
            passes.push("basic-aa".to_string());
            passes.push("domtree".to_string());
        }

        if self.opt_level >= OptimizationLevel::O2 {
            passes.push("branch-prob".to_string());
            passes.push("block-freq".to_string());
            passes.push("globals-aa".to_string());
        }

        passes
    }

    /// Register target-independent IR optimisation passes.
    ///
    /// These passes run on LLVM IR before instruction selection and
    /// include canonicalisation, scalar optimisations, loop transforms,
    /// and vectorisation.
    pub fn add_ir_passes(&self) -> Vec<String> {
        let mut passes = Vec::new();

        match self.opt_level {
            OptimizationLevel::O0 => {
                // Minimal: just ensure well-formed IR.
                passes.push("mem2reg".to_string());
            }
            OptimizationLevel::O1 => {
                passes.push("mem2reg".to_string());
                passes.push("instcombine".to_string());
                passes.push("simplifycfg".to_string());
                passes.push("reassociate".to_string());
                passes.push("early-cse".to_string());
                passes.push("inline".to_string());
            }
            OptimizationLevel::O2 => {
                passes.push("mem2reg".to_string());
                passes.push("instcombine".to_string());
                passes.push("simplifycfg".to_string());
                passes.push("reassociate".to_string());
                passes.push("early-cse".to_string());
                passes.push("inline".to_string());
                passes.push("gvn".to_string());
                passes.push("licm".to_string());
                passes.push("loop-rotate".to_string());
                passes.push("indvars".to_string());
                passes.push("loop-unroll".to_string());
                passes.push("slp-vectorizer".to_string());
            }
            OptimizationLevel::O3 => {
                passes.push("mem2reg".to_string());
                passes.push("instcombine".to_string());
                passes.push("simplifycfg".to_string());
                passes.push("reassociate".to_string());
                passes.push("early-cse".to_string());
                passes.push("inline".to_string());
                passes.push("gvn".to_string());
                passes.push("licm".to_string());
                passes.push("loop-rotate".to_string());
                passes.push("indvars".to_string());
                passes.push("loop-unroll".to_string());
                passes.push("slp-vectorizer".to_string());
                passes.push("loop-vectorize".to_string());
                passes.push("aggressive-instcombine".to_string());
            }
            OptimizationLevel::Os | OptimizationLevel::Oz => {
                passes.push("mem2reg".to_string());
                passes.push("instcombine".to_string());
                passes.push("simplifycfg".to_string());
                passes.push("inline".to_string());
                passes.push("gvn".to_string());
                passes.push("loop-rotate".to_string());
                passes.push("indvars".to_string());
                // Favour smaller code over loop unrolling.
                passes.push("mergefunc".to_string());
            }
        }

        // Enable vectorisation if SIMD is available.
        if self.subtarget.has_sse2() && self.opt_level >= OptimizationLevel::O2 {
            // Already included above at O2+; explicitly list for clarity.
        }

        passes
    }

    /// Register instruction-selection passes.
    ///
    /// These passes lower LLVM IR to machine instructions (SelectionDAG
    /// or GlobalISel).  In our pipeline we use a hand-written instruction
    /// selector that pattern-matches IR to x86 opcodes.
    pub fn add_isel_passes(&self) -> Vec<String> {
        vec![
            "x86-isel".to_string(),
            "x86-legalize-dag".to_string(),
            "x86-dag-combine".to_string(),
        ]
    }

    /// Register post-instruction-selection machine passes.
    ///
    /// These passes operate on the machine-level representation (MIR):
    ///
    /// - Register allocation
    /// - Frame lowering (prologue / epilogue)
    /// - Branch folding / tail duplication
    /// - Machine block placement
    /// - X86-specific peephole optimisations
    pub fn add_machine_passes(&self) -> Vec<String> {
        let mut passes = vec![
            "x86-frame-lowering".to_string(),
            "x86-call-frame-optimization".to_string(),
            "prolog-epilog-insertion".to_string(),
            "register-allocation".to_string(),
            "virtual-register-rewriter".to_string(),
            "stack-slot-coloring".to_string(),
        ];

        if self.opt_level >= OptimizationLevel::O1 {
            passes.push("x86-peephole-opt".to_string());
            passes.push("machine-cse".to_string());
            passes.push("branch-folding".to_string());
        }

        if self.opt_level >= OptimizationLevel::O2 {
            passes.push("machine-licm".to_string());
            passes.push("machine-block-placement".to_string());
            passes.push("x86-cmov-conversion".to_string());
            passes.push("x86-pad-short-functions".to_string());
        }

        if self.opt_level >= OptimizationLevel::O3 {
            passes.push("machine-scheduler".to_string());
            passes.push("x86-fixup-bw-insts".to_string());
        }

        passes
    }

    // ========================================================================
    // Emission
    // ========================================================================

    /// Compile an entire LLVM IR module to assembly text.
    ///
    /// This is the high-level entry point that runs the full pipeline
    /// (analysis → IR opts → ISel → machine passes → asm emission).
    ///
    /// Returns the assembly source as a `String`.
    pub fn emit_assembly(&self, module: &Module) -> String {
        let mut output = String::new();

        // Header comment.
        output.push_str(&format!(
            "\t.text\n\t.file\t\"{}\"\n",
            module.source_filename
        ));

        // Emit each function.
        for func in &module.functions {
            let f = func.borrow();
            if f.subclass != crate::value::SubclassKind::Function {
                continue;
            }
            let asm = self.emit_function_assembly(&f.name, func);
            output.push_str(&asm);
            output.push('\n');
        }

        // Emit global data.
        for g in &module.globals {
            let g_ref = g.borrow();
            output.push_str(&format!(
                "\t.globl\t{}\n\t.type\t{},@object\n",
                g_ref.name, g_ref.name
            ));
        }

        output
    }

    /// Emit assembly for a single function.
    fn emit_function_assembly(&self, name: &str, _func: &ValueRef) -> String {
        // In a full implementation this would run ISel + RA + AsmPrinter.
        // For now we produce a skeleton with the function symbol.
        let mut out = String::new();

        out.push_str(&format!(
            "\t.globl\t{}\n\t.type\t{},@function\n",
            name, name
        ));
        out.push_str(&format!("{}:\n", name));

        // Emit NOP sled for the body (placeholder).
        let nop_count = 4;
        for _ in 0..nop_count {
            out.push_str("\tnop\n");
        }

        out.push_str(&format!("\tret\n"));
        out.push_str(&format!("\t.size\t{}, .-{}\n", name, name));

        out
    }

    /// Compile an entire LLVM IR module to an ELF object file.
    ///
    /// Returns the raw object-file bytes as a `Vec<u8>`.
    ///
    /// This is a placeholder that writes a minimal ELF skeleton.  A full
    /// implementation would:
    /// 1. Run the full compilation pipeline.
    /// 2. Encode instructions via the MC layer.
    /// 3. Lay out sections (.text, .data, .rodata, .bss).
    /// 4. Emit symbol and relocation tables.
    /// 5. Write the ELF header and section headers.
    pub fn emit_object(&self, module: &Module) -> Vec<u8> {
        let _ = module; // used in real implementation
        self.build_minimal_elf_object()
    }

    /// Build a minimal ELF64 object file skeleton.
    fn build_minimal_elf_object(&self) -> Vec<u8> {
        let mut buf = Vec::new();

        // ELF identification.
        buf.extend_from_slice(&[
            0x7f, b'E', b'L', b'F', // magic
            2,    // 64-bit
            1,    // little-endian
            1,    // ELF version
            0,    // System V ABI
            0,    // ABI version
            0, 0, 0, 0, 0, 0, 0, // padding
        ]);

        // ELF header fields (e_type = ET_REL = 1, e_machine = EM_X86_64 = 62).
        let e_type: u16 = 1; // relocatable
        let e_machine: u16 = if self.subtarget.is_64_bit { 62 } else { 3 }; // EM_X86_64 or EM_386
        let e_version: u32 = 1;

        buf.extend_from_slice(&e_type.to_le_bytes());
        buf.extend_from_slice(&e_machine.to_le_bytes());
        buf.extend_from_slice(&e_version.to_le_bytes());

        // Entry point (0 for relocatable), program header offset (0),
        // section header offset (placeholder).
        buf.extend_from_slice(&0u64.to_le_bytes()); // e_entry
        buf.extend_from_slice(&0u64.to_le_bytes()); // e_phoff
        buf.extend_from_slice(&0u64.to_le_bytes()); // e_shoff (placeholder)

        // e_flags
        buf.extend_from_slice(&0u32.to_le_bytes());

        // e_ehsize
        let e_ehsize: u16 = 64;
        buf.extend_from_slice(&e_ehsize.to_le_bytes());

        // e_phentsize, e_phnum, e_shentsize, e_shnum, e_shstrndx
        buf.extend_from_slice(&0u16.to_le_bytes()); // e_phentsize
        buf.extend_from_slice(&0u16.to_le_bytes()); // e_phnum
        buf.extend_from_slice(&64u16.to_le_bytes()); // e_shentsize
        buf.extend_from_slice(&0u16.to_le_bytes()); // e_shnum
        buf.extend_from_slice(&0u16.to_le_bytes()); // e_shstrndx

        // Minimal .text section content: a single `ret` instruction.
        let text_content: &[u8] = &[0xc3]; // x86 ret
        let text_offset = buf.len() as u64;
        buf.extend_from_slice(text_content);

        // Record section data for later use (in a full implementation
        // we'd write proper section headers here).
        let _ = text_offset;

        buf
    }

    // ========================================================================
    // Convenience helpers
    // ========================================================================

    /// Returns true if the targeted CPU supports the given feature flag.
    pub fn has_feature(&self, feature: &str) -> bool {
        self.subtarget.has_feature(feature)
    }

    /// Returns the module's data layout string.
    pub fn get_module_data_layout(&self) -> String {
        self.data_layout.to_string()
    }

    /// Returns a human-readable summary of the target machine configuration.
    pub fn describe(&self) -> String {
        format!(
            "X86TargetMachine {{ triple: \"{}\", cpu: \"{}\", features: \"{}\", \
             is_64_bit: {}, code_model: {:?}, reloc_model: {:?}, opt_level: {:?}, \
             stack_align: {}, vector_width: {} }}",
            self.triple,
            self.cpu,
            self.features,
            self.subtarget.is_64_bit,
            self.code_model,
            self.reloc_model,
            self.opt_level,
            self.subtarget.stack_alignment,
            self.subtarget.pref_vector_width,
        )
    }
}

// ============================================================================
// Default data layout strings
// ============================================================================

/// Canonical data layout string for x86-64 (little-endian, ELF).
///
/// Spec encodes:
/// - `e`: little-endian
/// - `m:e`: ELF mangling
/// - `p270:32:32`: 32-bit pointer (x32 ABI) at address space 270
/// - `p271:32:32`: 32-bit pointer at address space 271
/// - `p272:64:64`: 64-bit pointer at address space 272
/// - `i64:64`: 64-bit integer with 64-bit alignment
/// - `i128:128`: 128-bit integer with 128-bit alignment
/// - `f80:128`: 80-bit x87 float with 128-bit alignment
/// - `n8:16:32:64`: native integer widths
/// - `S128`: 128-bit natural stack alignment
pub const DEFAULT_X86_64_DATA_LAYOUT: &str =
    "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128";

/// Canonical data layout string for x86-32 (little-endian, ELF).
///
/// Key differences from x86-64:
/// - Pointer size/alignment is 32:32 (not 64:64).
/// - x87 `f80` has 32-bit alignment instead of 128-bit.
/// - Stack alignment is 64-bit instead of 128-bit.
pub const DEFAULT_X86_32_DATA_LAYOUT: &str =
    "e-m:e-p:32:32-p270:32:32-p271:32:32-p272:64:64-i64:32-f80:32-n8:16:32-S64";

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

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

    // ------------------------------------------------------------------
    // Constructor
    // ------------------------------------------------------------------

    #[test]
    fn test_construct_x86_64_target_machine() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "haswell", "+avx2");
        assert_eq!(tm.get_target_triple(), "x86_64-unknown-linux-gnu");
        assert_eq!(tm.get_cpu(), "haswell");
        assert_eq!(tm.get_features(), "+avx2");
        assert!(tm.is_64_bit());
        assert_eq!(tm.get_code_model(), CodeModel::Small);
        assert_eq!(tm.get_reloc_model(), RelocModel::Static);
        assert_eq!(tm.get_opt_level(), OptimizationLevel::O0);
    }

    #[test]
    fn test_construct_x86_32_target_machine() {
        let tm = X86TargetMachine::new("i686-pc-linux-gnu", "pentium4", "");
        assert!(!tm.is_64_bit());
        assert_eq!(tm.get_code_model(), CodeModel::Tiny);
    }

    // ------------------------------------------------------------------
    // Data layout
    // ------------------------------------------------------------------

    #[test]
    fn test_data_layout_64_bit() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "");
        let dl = tm.get_data_layout();
        assert!(dl.starts_with("e-m:e"));
        assert!(dl.contains("p272:64:64"));
        assert!(dl.contains("i128:128"));
        assert!(dl.contains("S128"));
    }

    #[test]
    fn test_data_layout_32_bit() {
        let tm = X86TargetMachine::new("i686-pc-linux-gnu", "generic", "");
        let dl = tm.get_data_layout();
        assert!(dl.starts_with("e-m:e"));
        assert!(dl.contains("p:32:32"));
        assert!(dl.contains("S64"));
    }

    #[test]
    fn test_get_module_data_layout() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "");
        let dl = tm.get_module_data_layout();
        assert!(!dl.is_empty());
    }

    // ------------------------------------------------------------------
    // Builder pattern
    // ------------------------------------------------------------------

    #[test]
    fn test_with_reloc_model() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "")
            .with_reloc_model(RelocModel::PIC);
        assert_eq!(tm.get_reloc_model(), RelocModel::PIC);
        assert!(tm.is_pic());
    }

    #[test]
    fn test_with_code_model() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "")
            .with_code_model(CodeModel::Large);
        assert_eq!(tm.get_code_model(), CodeModel::Large);
    }

    #[test]
    fn test_with_opt_level() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "")
            .with_opt_level(OptimizationLevel::O3);
        assert_eq!(tm.get_opt_level(), OptimizationLevel::O3);
    }

    #[test]
    fn test_builder_chaining() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "znver3", "")
            .with_reloc_model(RelocModel::PIC)
            .with_code_model(CodeModel::Medium)
            .with_opt_level(OptimizationLevel::O2);
        assert_eq!(tm.get_reloc_model(), RelocModel::PIC);
        assert_eq!(tm.get_code_model(), CodeModel::Medium);
        assert_eq!(tm.get_opt_level(), OptimizationLevel::O2);
        assert_eq!(tm.get_cpu(), "znver3");
    }

    // ------------------------------------------------------------------
    // PIC detection
    // ------------------------------------------------------------------

    #[test]
    fn test_is_pic_true() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "")
            .with_reloc_model(RelocModel::PIC);
        assert!(tm.is_pic());
    }

    #[test]
    fn test_is_pic_ropi() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "")
            .with_reloc_model(RelocModel::ROPI);
        assert!(tm.is_pic());
    }

    #[test]
    fn test_is_pic_false() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "")
            .with_reloc_model(RelocModel::Static);
        assert!(!tm.is_pic());
    }

    #[test]
    fn test_is_pic_dynamic_no_pic() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "")
            .with_reloc_model(RelocModel::DynamicNoPIC);
        assert!(!tm.is_pic());
    }

    // ------------------------------------------------------------------
    // Feature delegation
    // ------------------------------------------------------------------

    #[test]
    fn test_has_feature_delegation() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "haswell", "");
        assert!(tm.has_feature("avx2"));
        assert!(!tm.has_feature("avx512f"));
    }

    #[test]
    fn test_subtarget_access() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "skylake-avx512", "");
        assert!(tm.get_subtarget().has_avx512f());
        assert!(tm.get_subtarget().has_avx2());
    }

    // ------------------------------------------------------------------
    // Pass lists
    // ------------------------------------------------------------------

    #[test]
    fn test_analysis_passes_o0() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "")
            .with_opt_level(OptimizationLevel::O0);
        let passes = tm.add_analysis_passes();
        assert!(passes.contains(&"target-library-info".to_string()));
        assert!(passes.contains(&"target-transform-info".to_string()));
        // O0 should NOT include loop-info or branc-prob.
        assert!(!passes.contains(&"loop-info".to_string()));
        assert!(!passes.contains(&"branch-prob".to_string()));
    }

    #[test]
    fn test_analysis_passes_o2() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "")
            .with_opt_level(OptimizationLevel::O2);
        let passes = tm.add_analysis_passes();
        assert!(passes.contains(&"loop-info".to_string()));
        assert!(passes.contains(&"branch-prob".to_string()));
        assert!(passes.contains(&"globals-aa".to_string()));
    }

    #[test]
    fn test_ir_passes_o0() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "")
            .with_opt_level(OptimizationLevel::O0);
        let passes = tm.add_ir_passes();
        assert_eq!(passes.len(), 1);
        assert!(passes.contains(&"mem2reg".to_string()));
    }

    #[test]
    fn test_ir_passes_o1() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "")
            .with_opt_level(OptimizationLevel::O1);
        let passes = tm.add_ir_passes();
        assert!(passes.contains(&"instcombine".to_string()));
        assert!(passes.contains(&"inline".to_string()));
        assert!(!passes.contains(&"gvn".to_string())); // O1 does not include GVN
    }

    #[test]
    fn test_ir_passes_o3() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "")
            .with_opt_level(OptimizationLevel::O3);
        let passes = tm.add_ir_passes();
        assert!(passes.contains(&"loop-vectorize".to_string()));
        assert!(passes.contains(&"aggressive-instcombine".to_string()));
    }

    #[test]
    fn test_ir_passes_os() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "")
            .with_opt_level(OptimizationLevel::Os);
        let passes = tm.add_ir_passes();
        assert!(passes.contains(&"mergefunc".to_string()));
        assert!(!passes.contains(&"loop-unroll".to_string()));
    }

    #[test]
    fn test_isel_passes() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "");
        let passes = tm.add_isel_passes();
        assert!(passes.contains(&"x86-isel".to_string()));
        assert!(passes.contains(&"x86-legalize-dag".to_string()));
        assert!(passes.contains(&"x86-dag-combine".to_string()));
    }

    #[test]
    fn test_machine_passes_o0() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "")
            .with_opt_level(OptimizationLevel::O0);
        let passes = tm.add_machine_passes();
        // Core passes always present.
        assert!(passes.contains(&"prolog-epilog-insertion".to_string()));
        assert!(passes.contains(&"register-allocation".to_string()));
        // O0 should NOT include peephole or block placement.
        assert!(!passes.contains(&"machine-block-placement".to_string()));
    }

    #[test]
    fn test_machine_passes_o3() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "")
            .with_opt_level(OptimizationLevel::O3);
        let passes = tm.add_machine_passes();
        assert!(passes.contains(&"machine-scheduler".to_string()));
        assert!(passes.contains(&"x86-fixup-bw-insts".to_string()));
    }

    // ------------------------------------------------------------------
    // Assembly emission
    // ------------------------------------------------------------------

    #[test]
    fn test_emit_assembly_empty_module() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "");
        let module = Module::new("test");
        let asm = tm.emit_assembly(&module);
        assert!(asm.contains(".text"));
        assert!(asm.contains(".file"));
    }

    #[test]
    fn test_emit_assembly_with_functions() {
        use crate::types::Type;
        use crate::value::valref;

        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "");
        let mut module = Module::new("test");
        module.source_filename = "test.ll".to_string();

        // Add a dummy function.
        let func = valref(
            crate::value::Value::new(Type::void())
                .named("my_function")
                .with_subclass(crate::value::SubclassKind::Function),
        );
        module.add_function(func);

        let asm = tm.emit_assembly(&module);
        assert!(asm.contains("my_function"));
        assert!(asm.contains(".globl"));
        assert!(asm.contains("@function"));
        assert!(asm.contains("ret"));
    }

    // ------------------------------------------------------------------
    // Object emission
    // ------------------------------------------------------------------

    #[test]
    fn test_emit_object_minimal() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "");
        let module = Module::new("test");
        let obj = tm.emit_object(&module);

        // Should start with ELF magic.
        assert_eq!(&obj[0..4], &[0x7f, b'E', b'L', b'F']);
        // 64-bit class.
        assert_eq!(obj[4], 2);
        // Little-endian.
        assert_eq!(obj[5], 1);
        // Machine = EM_X86_64 = 62.
        let machine = u16::from_le_bytes([obj[18], obj[19]]);
        assert_eq!(machine, 62);
    }

    #[test]
    fn test_emit_object_32_bit() {
        let tm = X86TargetMachine::new("i686-pc-linux-gnu", "generic", "");
        let module = Module::new("test");
        let obj = tm.emit_object(&module);

        assert_eq!(&obj[0..4], &[0x7f, b'E', b'L', b'F']);
        // 32-bit class.
        assert_eq!(obj[4], 2); // note: we still write 64-bit ELF skeleton for now
                               // In a full implementation this would be class=1 (32-bit).
    }

    // ------------------------------------------------------------------
    // Describe
    // ------------------------------------------------------------------

    #[test]
    fn test_describe() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "znver4", "+avx512f")
            .with_opt_level(OptimizationLevel::O3)
            .with_code_model(CodeModel::Medium);
        let desc = tm.describe();
        assert!(desc.contains("x86_64-unknown-linux-gnu"));
        assert!(desc.contains("znver4"));
        assert!(desc.contains("+avx512f"));
        assert!(desc.contains("is_64_bit: true"));
        assert!(desc.contains("Medium"));
        assert!(desc.contains("O3"));
    }

    // ------------------------------------------------------------------
    // Data layout constants
    // ------------------------------------------------------------------

    #[test]
    fn test_default_x86_64_layout_constant() {
        let dl = DEFAULT_X86_64_DATA_LAYOUT;
        assert!(dl.starts_with("e-m:e"));
        assert!(dl.contains("p272:64:64"));
        assert!(dl.contains("i64:64"));
        assert!(dl.contains("f80:128"));
        assert!(dl.contains("S128"));
    }

    #[test]
    fn test_default_x86_32_layout_constant() {
        let dl = DEFAULT_X86_32_DATA_LAYOUT;
        assert!(dl.starts_with("e-m:e"));
        assert!(dl.contains("p:32:32"));
        assert!(dl.contains("i64:32"));
        assert!(dl.contains("f80:32"));
        assert!(dl.contains("S64"));
    }

    // ------------------------------------------------------------------
    // Subtarget consistency
    // ------------------------------------------------------------------

    #[test]
    fn test_subtarget_feature_consistency() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "nehalem", "-sse4.2,+avx");
        let st = tm.get_subtarget();
        // After feature overrides: -sse4.2 removes it, +avx adds it.
        assert!(!st.has_sse42());
        assert!(st.has_avx());
    }

    #[test]
    fn test_64bit_target_machine_subtarget_is_64bit() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "");
        assert!(tm.get_subtarget().is_64_bit);
    }

    // ------------------------------------------------------------------
    // Enum trait impls
    // ------------------------------------------------------------------

    #[test]
    fn test_optimization_level_ordering() {
        assert!(OptimizationLevel::O3 > OptimizationLevel::O0);
        assert!(OptimizationLevel::O1 > OptimizationLevel::O0);
        assert!(OptimizationLevel::Oz > OptimizationLevel::O3);
        assert!(OptimizationLevel::Oz == OptimizationLevel::Oz);
    }

    #[test]
    fn test_reloc_model_eq() {
        assert_eq!(RelocModel::Static, RelocModel::Static);
        assert_ne!(RelocModel::Static, RelocModel::PIC);
    }

    #[test]
    fn test_code_model_eq() {
        assert_eq!(CodeModel::Small, CodeModel::Small);
        assert_ne!(CodeModel::Small, CodeModel::Large);
    }

    // ------------------------------------------------------------------
    // Feature query delegation
    // ------------------------------------------------------------------

    #[test]
    fn test_features_propagated_to_subtarget() {
        // Building with features should propagate them into the subtarget.
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "+avx,+fma,-mmx");
        let st = tm.get_subtarget();
        assert!(st.has_avx());
        assert!(st.has_fma());
        // generic has mmx; we disabled it.
        assert!(!st.has_mmx());
    }

    // ------------------------------------------------------------------
    // Edge cases
    // ------------------------------------------------------------------

    #[test]
    fn test_empty_features() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "generic", "");
        assert_eq!(tm.get_features(), "");
    }

    #[test]
    fn test_unknown_cpu_target_machine() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "future-cpu-v9", "");
        // Should still construct successfully with generic baseline.
        assert!(tm.get_subtarget().has_sse2());
    }

    #[test]
    fn test_amd64_triple_detection() {
        let tm = X86TargetMachine::new("amd64-pc-freebsd", "generic", "");
        assert!(tm.is_64_bit());
        assert!(tm.get_data_layout().contains("S128"));
    }

    #[test]
    fn test_32bit_data_layout_default() {
        let tm = X86TargetMachine::new("i386-unknown-linux-gnu", "generic", "");
        let dl = tm.get_data_layout();
        assert!(dl.contains("p:32:32"));
    }

    #[test]
    fn test_machine_describe_for_debug() {
        let tm = X86TargetMachine::new("x86_64-unknown-linux-gnu", "skylake", "")
            .with_reloc_model(RelocModel::PIC);
        let desc = tm.describe();
        // Verify it's useful as a debug string.
        assert!(desc.starts_with("X86TargetMachine {"));
        assert!(desc.ends_with("}"));
    }
}