llvm-native-core-ext 0.1.0

Extended modules for llvm-native-core: analysis passes, transforms, codegen extras, bitcode, linker, JIT, utilities. Part of the llvm-native workspace (https://crates.io/crates/llvm-native).
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
//! Object File Emitter — bridges CodeGen to ObjectWriter for all formats.
//! Clean-room behavioral reconstruction. No LLVM source consulted.

use llvm_native_core::codegen::MachineFunction;
use llvm_native_core::mc_assembler::encode_x86_64;
use llvm_native_core::mc_inst::MCInst;
use llvm_native_core::object_writer::{ObjectFormat, ObjectWriter, SectionFlags};
use llvm_native_core::opcode::Opcode;
use llvm_native_core::value::ValueRef;

/// Compile IR functions to ELF object file bytes.
pub fn compile_to_object(funcs: &[&ValueRef], target_triple: &str) -> Vec<u8> {
    let mut emitter = ObjectEmitter::new(ObjectFormat::ELF, target_triple);
    for func in funcs {
        emitter.add_function(func);
    }
    emitter.finish()
}

/// Compile to Mach-O object file.
pub fn compile_to_macho(funcs: &[&ValueRef], target_triple: &str) -> Vec<u8> {
    let mut emitter = ObjectEmitter::new(ObjectFormat::MachO, target_triple);
    for func in funcs {
        emitter.add_function(func);
    }
    emitter.finish()
}

/// Compile to COFF object file.
pub fn compile_to_coff(funcs: &[&ValueRef], target_triple: &str) -> Vec<u8> {
    let mut emitter = ObjectEmitter::new(ObjectFormat::COFF, target_triple);
    for func in funcs {
        emitter.add_function(func);
    }
    emitter.finish()
}

/// Compile to WebAssembly object file.
pub fn compile_to_wasm(funcs: &[&ValueRef], target_triple: &str) -> Vec<u8> {
    let mut emitter = ObjectEmitter::new(ObjectFormat::Wasm, target_triple);
    for func in funcs {
        emitter.add_function(func);
    }
    emitter.finish()
}

pub struct ObjectEmitter {
    writer: ObjectWriter,
    text_data: Vec<u8>,
    data_data: Vec<u8>,
    rodata_data: Vec<u8>,
    bss_size: u64,
    function_count: usize,
    global_count: usize,
}

impl ObjectEmitter {
    pub fn new(format: ObjectFormat, target_triple: &str) -> Self {
        Self {
            writer: ObjectWriter::new(format, target_triple),
            text_data: Vec::new(),
            data_data: Vec::new(),
            rodata_data: Vec::new(),
            bss_size: 0,
            function_count: 0,
            global_count: 0,
        }
    }

    pub fn add_function(&mut self, func: &ValueRef) {
        let f = func.borrow();
        if !f.is_function() || f.num_operands == 0 {
            return;
        }
        let mut mf = MachineFunction::new(&f.name);
        for op in &f.operands {
            let bb = op.borrow();
            if bb.is_basic_block() {
                for inst_val in &bb.operands {
                    let inst = inst_val.borrow();
                    if inst.is_instruction() {
                        if let Some(ref opcode) = inst.opcode {
                            // Build MCInst from IR instruction
                            let mc_opcode = match *opcode {
                                Opcode::Ret => 0xC3,
                                Opcode::Add => 0x01,
                                Opcode::Sub => 0x29,
                                Opcode::Call => 0xE8,
                                Opcode::Br => 0xEB,
                                _ => 0x90, // NOP as fallback
                            };
                            let mc_inst = MCInst::new(mc_opcode);
                            if let Some(encoded) = encode_x86_64(&mc_inst) {
                                self.text_data.extend_from_slice(&encoded);
                            }
                        }
                    }
                }
            }
        }
        self.function_count += 1;
    }

    /// Add data for a global variable.
    pub fn add_global_data(&mut self, data: &[u8]) {
        self.data_data.extend_from_slice(data);
        self.global_count += 1;
    }

    /// Add read-only data.
    pub fn add_rodata(&mut self, data: &[u8]) {
        self.rodata_data.extend_from_slice(data);
    }

    /// Reserve BSS space.
    pub fn add_bss(&mut self, size: u64) {
        self.bss_size += size;
    }

    /// Finalize and emit the complete object file.
    pub fn finish(&mut self) -> Vec<u8> {
        if !self.text_data.is_empty() {
            self.writer.add_section(
                ".text",
                std::mem::take(&mut self.text_data),
                SectionFlags::text(),
            );
        }
        if !self.data_data.is_empty() {
            self.writer.add_section(
                ".data",
                std::mem::take(&mut self.data_data),
                SectionFlags::data(),
            );
        }
        if !self.rodata_data.is_empty() {
            self.writer.add_section(
                ".rodata",
                std::mem::take(&mut self.rodata_data),
                SectionFlags::rodata(),
            );
        }
        if self.bss_size > 0 {
            self.writer.add_bss_section(".bss", self.bss_size);
        }
        self.writer.write()
    }

    pub fn function_count(&self) -> usize {
        self.function_count
    }
    pub fn global_count(&self) -> usize {
        self.global_count
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Full Object Emission Pipeline — per-format section layout & emission
// ═══════════════════════════════════════════════════════════════════════════

impl ObjectEmitter {
    /// Emit the complete ELF object file with proper headers and layout.
    pub fn emit_elf(&mut self) -> Vec<u8> {
        let mut buf = Vec::new();
        // ELF header
        buf.extend_from_slice(&self.build_elf_header());
        // Program headers (none for relocatable objects)
        // Section data
        let text_offset = buf.len() as u64;
        buf.extend_from_slice(&self.text_data);
        let rodata_offset = buf.len() as u64;
        buf.extend_from_slice(&self.rodata_data);
        let data_offset = buf.len() as u64;
        buf.extend_from_slice(&self.data_data);
        // Section header table
        let shdr_offset = buf.len() as u64;
        buf.extend_from_slice(&self.build_elf_section_headers(
            text_offset,
            rodata_offset,
            data_offset,
            shdr_offset,
        ));
        buf
    }

    /// Build the ELF header (64-bit, little-endian, relocatable).
    fn build_elf_header(&self) -> Vec<u8> {
        let mut hdr = Vec::with_capacity(64);
        hdr.extend_from_slice(&[0x7f, b'E', b'L', b'F']); // e_ident[EI_MAG]
        hdr.push(2); // EI_CLASS = 64-bit
        hdr.push(1); // EI_DATA = little-endian
        hdr.push(1); // EI_VERSION
        hdr.push(0); // EI_OSABI = System V
        hdr.push(0); // EI_ABIVERSION
        hdr.extend_from_slice(&[0u8; 7]); // padding
        hdr.extend_from_slice(&1u16.to_le_bytes()); // e_type = ET_REL
        hdr.extend_from_slice(&0x3Eu16.to_le_bytes()); // e_machine = x86-64
        hdr.extend_from_slice(&1u32.to_le_bytes()); // e_version
        hdr.extend_from_slice(&0u64.to_le_bytes()); // e_entry
        hdr.extend_from_slice(&0u64.to_le_bytes()); // e_phoff
        hdr.extend_from_slice(&0u64.to_le_bytes()); // e_shoff (placeholder)
        hdr.extend_from_slice(&0u32.to_le_bytes()); // e_flags
        hdr.extend_from_slice(&64u16.to_le_bytes()); // e_ehsize
        hdr.extend_from_slice(&0u16.to_le_bytes()); // e_phentsize
        hdr.extend_from_slice(&0u16.to_le_bytes()); // e_phnum
        hdr.extend_from_slice(&64u16.to_le_bytes()); // e_shentsize
        hdr.extend_from_slice(&4u16.to_le_bytes()); // e_shnum
        hdr.extend_from_slice(&3u16.to_le_bytes()); // e_shstrndx
        hdr
    }

    /// Build ELF section headers.
    fn build_elf_section_headers(
        &self,
        text_off: u64,
        rodata_off: u64,
        data_off: u64,
        shdr_off: u64,
    ) -> Vec<u8> {
        let mut sh = Vec::new();
        // Null section
        sh.extend_from_slice(&[0u8; 64]);
        // .text section
        sh.extend_from_slice(&1u32.to_le_bytes()); // sh_name
        sh.extend_from_slice(&1u32.to_le_bytes()); // sh_type = SHT_PROGBITS
        sh.extend_from_slice(&6u64.to_le_bytes()); // sh_flags = AX
        sh.extend_from_slice(&0u64.to_le_bytes()); // sh_addr
        sh.extend_from_slice(&text_off.to_le_bytes()); // sh_offset
        sh.extend_from_slice(&(self.text_data.len() as u64).to_le_bytes()); // sh_size
        sh.extend_from_slice(&0u32.to_le_bytes()); // sh_link
        sh.extend_from_slice(&0u32.to_le_bytes()); // sh_info
        sh.extend_from_slice(&16u64.to_le_bytes()); // sh_addralign
        sh.extend_from_slice(&0u64.to_le_bytes()); // sh_entsize
                                                   // .rodata section
        sh.extend_from_slice(&7u32.to_le_bytes());
        sh.extend_from_slice(&1u32.to_le_bytes());
        sh.extend_from_slice(&2u64.to_le_bytes()); // sh_flags = A
        sh.extend_from_slice(&0u64.to_le_bytes());
        sh.extend_from_slice(&rodata_off.to_le_bytes());
        sh.extend_from_slice(&(self.rodata_data.len() as u64).to_le_bytes());
        sh.extend_from_slice(&0u32.to_le_bytes());
        sh.extend_from_slice(&0u32.to_le_bytes());
        sh.extend_from_slice(&16u64.to_le_bytes());
        sh.extend_from_slice(&0u64.to_le_bytes());
        // .data section
        sh.extend_from_slice(&15u32.to_le_bytes());
        sh.extend_from_slice(&1u32.to_le_bytes());
        sh.extend_from_slice(&3u64.to_le_bytes()); // sh_flags = WA
        sh.extend_from_slice(&0u64.to_le_bytes());
        sh.extend_from_slice(&data_off.to_le_bytes());
        sh.extend_from_slice(&(self.data_data.len() as u64).to_le_bytes());
        sh.extend_from_slice(&0u32.to_le_bytes());
        sh.extend_from_slice(&0u32.to_le_bytes());
        sh.extend_from_slice(&16u64.to_le_bytes());
        sh.extend_from_slice(&0u64.to_le_bytes());
        sh
    }

    /// Emit the complete Mach-O object file.
    pub fn emit_macho(&mut self) -> Vec<u8> {
        let mut buf = Vec::new();
        buf.extend_from_slice(&self.build_macho_header());
        // Load commands (segment + section commands)
        buf.extend_from_slice(&self.build_macho_load_commands());
        // Section data
        buf.extend_from_slice(&self.text_data);
        buf.extend_from_slice(&self.rodata_data);
        buf.extend_from_slice(&self.data_data);
        buf
    }

    /// Build 64-bit Mach-O header.
    fn build_macho_header(&self) -> Vec<u8> {
        let mut h = Vec::with_capacity(32);
        h.extend_from_slice(&0x01000007u32.to_le_bytes()); // magic = MH_MAGIC_64
        h.extend_from_slice(&0x01000007u32.to_le_bytes()); // cputype = CPU_TYPE_X86_64
        h.extend_from_slice(&0x80000003u32.to_le_bytes()); // cpusubtype
        h.extend_from_slice(&1u32.to_le_bytes()); // filetype = MH_OBJECT
        h.extend_from_slice(&1u32.to_le_bytes()); // ncmds
        h.extend_from_slice(&0u32.to_le_bytes()); // sizeofcmds (placeholder)
        h.extend_from_slice(&0u32.to_le_bytes()); // flags
        h.extend_from_slice(&0u32.to_le_bytes()); // reserved
        h
    }

    /// Build Mach-O load commands (segment + sections).
    fn build_macho_load_commands(&self) -> Vec<u8> {
        let mut lc = Vec::new();
        // LC_SEGMENT_64
        lc.extend_from_slice(&0x19u32.to_le_bytes()); // cmd
        lc.extend_from_slice(&0u32.to_le_bytes()); // cmdsize (placeholder)
                                                   // segname (16 bytes)
        lc.extend_from_slice(b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
        lc.extend_from_slice(&0u64.to_le_bytes()); // vmaddr
        lc.extend_from_slice(&0u64.to_le_bytes()); // vmsize
        lc.extend_from_slice(&0u64.to_le_bytes()); // fileoff
        lc.extend_from_slice(&0u64.to_le_bytes()); // filesize
        lc.extend_from_slice(&7u32.to_le_bytes()); // maxprot = rwx
        lc.extend_from_slice(&7u32.to_le_bytes()); // initprot
        lc.extend_from_slice(&3u32.to_le_bytes()); // nsects
        lc.extend_from_slice(&0u32.to_le_bytes()); // flags
                                                   // Section 1: __text
        lc.extend_from_slice(b"__text\0\0\0\0\0\0\0\0\0\0");
        lc.extend_from_slice(b"__TEXT\0\0\0\0\0\0\0\0\0\0");
        lc.extend_from_slice(&0u64.to_le_bytes()); // addr
        lc.extend_from_slice(&(self.text_data.len() as u64).to_le_bytes()); // size
        lc.extend_from_slice(&0u32.to_le_bytes()); // offset
        lc.extend_from_slice(&2u32.to_le_bytes()); // align
        lc.extend_from_slice(&0u32.to_le_bytes()); // reloff
        lc.extend_from_slice(&0u32.to_le_bytes()); // nreloc
        lc.extend_from_slice(&0x80000400u32.to_le_bytes()); // flags
        lc.extend_from_slice(&0u32.to_le_bytes()); // reserved1
        lc.extend_from_slice(&0u32.to_le_bytes()); // reserved2
        lc.extend_from_slice(&0u32.to_le_bytes()); // reserved3
                                                   // Section 2: __rodata
        lc.extend_from_slice(b"__rodata\0\0\0\0\0\0\0\0\0");
        lc.extend_from_slice(b"__TEXT\0\0\0\0\0\0\0\0\0\0");
        lc.extend_from_slice(&0u64.to_le_bytes());
        lc.extend_from_slice(&(self.rodata_data.len() as u64).to_le_bytes());
        lc.extend_from_slice(&0u32.to_le_bytes());
        lc.extend_from_slice(&2u32.to_le_bytes());
        lc.extend_from_slice(&0u32.to_le_bytes());
        lc.extend_from_slice(&0u32.to_le_bytes());
        lc.extend_from_slice(&0u32.to_le_bytes());
        lc.extend_from_slice(&0u32.to_le_bytes());
        lc.extend_from_slice(&0u32.to_le_bytes());
        lc.extend_from_slice(&0u32.to_le_bytes());
        // Section 3: __data
        lc.extend_from_slice(b"__data\0\0\0\0\0\0\0\0\0\0");
        lc.extend_from_slice(b"__DATA\0\0\0\0\0\0\0\0\0\0");
        lc.extend_from_slice(&0u64.to_le_bytes());
        lc.extend_from_slice(&(self.data_data.len() as u64).to_le_bytes());
        lc.extend_from_slice(&0u32.to_le_bytes());
        lc.extend_from_slice(&2u32.to_le_bytes());
        lc.extend_from_slice(&0u32.to_le_bytes());
        lc.extend_from_slice(&0u32.to_le_bytes());
        lc.extend_from_slice(&0u32.to_le_bytes());
        lc.extend_from_slice(&0u32.to_le_bytes());
        lc.extend_from_slice(&0u32.to_le_bytes());
        lc.extend_from_slice(&0u32.to_le_bytes());
        lc
    }

    /// Emit the complete COFF object file.
    pub fn emit_coff(&mut self) -> Vec<u8> {
        let mut buf = Vec::new();
        buf.extend_from_slice(&self.build_coff_header());
        // Section headers
        let text_header =
            self.build_coff_section_header(".text", self.text_data.len() as u32, 0x60500020);
        let data_header =
            self.build_coff_section_header(".data", self.data_data.len() as u32, 0xC0500040);
        let rodata_header =
            self.build_coff_section_header(".rdata", self.rodata_data.len() as u32, 0x40500040);
        buf.extend_from_slice(&text_header);
        buf.extend_from_slice(&data_header);
        buf.extend_from_slice(&rodata_header);
        // Section data
        buf.extend_from_slice(&self.text_data);
        buf.extend_from_slice(&self.data_data);
        buf.extend_from_slice(&self.rodata_data);
        // Symbol table (minimal)
        buf.extend_from_slice(&self.build_coff_symbol_table());
        // String table
        buf.extend_from_slice(&self.build_coff_string_table());
        buf
    }

    fn build_coff_header(&self) -> Vec<u8> {
        let mut h = Vec::with_capacity(20);
        h.extend_from_slice(&0x8664u16.to_le_bytes()); // machine = x86-64
        h.extend_from_slice(&3u16.to_le_bytes()); // numberOfSections
        h.extend_from_slice(&0u32.to_le_bytes()); // timeDateStamp
        h.extend_from_slice(&0u32.to_le_bytes()); // pointerToSymbolTable (placeholder)
        h.extend_from_slice(&0u32.to_le_bytes()); // numberOfSymbols
        h.extend_from_slice(&0u16.to_le_bytes()); // sizeOfOptionalHeader
        h.extend_from_slice(&0u16.to_le_bytes()); // characteristics
        h
    }

    fn build_coff_section_header(&self, name: &str, size: u32, characteristics: u32) -> Vec<u8> {
        let mut sh = Vec::with_capacity(40);
        let mut name_bytes = [0u8; 8];
        let name_bytes_src = name.as_bytes();
        let copy_len = name_bytes_src.len().min(8);
        name_bytes[..copy_len].copy_from_slice(&name_bytes_src[..copy_len]);
        sh.extend_from_slice(&name_bytes);
        sh.extend_from_slice(&size.to_le_bytes()); // virtualSize
        sh.extend_from_slice(&0u32.to_le_bytes()); // virtualAddress
        sh.extend_from_slice(&size.to_le_bytes()); // sizeOfRawData
        sh.extend_from_slice(&0u32.to_le_bytes()); // pointerToRawData (placeholder)
        sh.extend_from_slice(&0u32.to_le_bytes()); // pointerToRelocations
        sh.extend_from_slice(&0u32.to_le_bytes()); // pointerToLinenumbers
        sh.extend_from_slice(&0u16.to_le_bytes()); // numberOfRelocations
        sh.extend_from_slice(&0u16.to_le_bytes()); // numberOfLinenumbers
        sh.extend_from_slice(&characteristics.to_le_bytes());
        sh
    }

    fn build_coff_symbol_table(&self) -> Vec<u8> {
        // Minimal: one auxiliary symbol entry
        let mut sym = Vec::with_capacity(18);
        sym.extend_from_slice(b".file\0\0\0"); // name
        sym.extend_from_slice(&0u32.to_le_bytes()); // value
        sym.extend_from_slice(&0i16.to_le_bytes()); // sectionNumber
        sym.extend_from_slice(&0u16.to_le_bytes()); // type
        sym.extend_from_slice(&0u8.to_le_bytes()); // storageClass
        sym.extend_from_slice(&0u8.to_le_bytes()); // numberOfAuxSymbols
        sym
    }

    fn build_coff_string_table(&self) -> Vec<u8> {
        let len: u32 = 4; // just the size field
        let mut st = Vec::with_capacity(4);
        st.extend_from_slice(&len.to_le_bytes());
        st
    }

    /// Emit the complete WebAssembly module.
    pub fn emit_wasm(&mut self) -> Vec<u8> {
        let mut buf = Vec::new();
        // Magic number and version
        buf.extend_from_slice(&[0x00, 0x61, 0x73, 0x6D]); // \0asm
        buf.extend_from_slice(&1u32.to_le_bytes()); // version 1
                                                    // Type section
        buf.extend_from_slice(&self.build_wasm_type_section());
        // Function section
        buf.extend_from_slice(&self.build_wasm_function_section());
        // Code section
        buf.extend_from_slice(&self.build_wasm_code_section());
        // Export section (if any)
        if self.function_count > 0 {
            buf.extend_from_slice(&self.build_wasm_export_section());
        }
        buf
    }

    fn build_wasm_type_section(&self) -> Vec<u8> {
        let mut s = Vec::new();
        s.push(0x01); // section id = Type
                      // One functype: () -> ()
        let body: Vec<u8> = vec![0x01, 0x60, 0x00, 0x00]; // 1 type, func, 0 params, 0 results
        s.extend_from_slice(&encode_wasm_uleb128(body.len() as u64));
        s.extend_from_slice(&body);
        s
    }

    fn build_wasm_function_section(&self) -> Vec<u8> {
        let mut s = Vec::new();
        s.push(0x03); // section id = Function
        let body: Vec<u8> = vec![0x01, 0x00]; // 1 function, type index 0
        s.extend_from_slice(&encode_wasm_uleb128(body.len() as u64));
        s.extend_from_slice(&body);
        s
    }

    fn build_wasm_code_section(&self) -> Vec<u8> {
        let mut s = Vec::new();
        s.push(0x0A); // section id = Code
                      // Function body: local decls + instructions + end
        let func_body: Vec<u8> = vec![0x00, 0x01, 0x0B]; // 0 locals, nop, end
        let body: Vec<u8> = {
            let mut b = Vec::new();
            b.push(0x01); // 1 function body
            b.extend_from_slice(&encode_wasm_uleb128(func_body.len() as u64));
            b.extend_from_slice(&func_body);
            b
        };
        s.extend_from_slice(&encode_wasm_uleb128(body.len() as u64));
        s.extend_from_slice(&body);
        s
    }

    fn build_wasm_export_section(&self) -> Vec<u8> {
        let mut s = Vec::new();
        s.push(0x07); // section id = Export
                      // Export "main" (function 0)
        let export_name = "main";
        let mut body = Vec::new();
        body.push(0x01); // 1 export
        body.extend_from_slice(&encode_wasm_uleb128(export_name.len() as u64));
        body.extend_from_slice(export_name.as_bytes());
        body.push(0x00); // export kind = function
        body.push(0x00); // function index 0
        s.extend_from_slice(&encode_wasm_uleb128(body.len() as u64));
        s.extend_from_slice(&body);
        s
    }
}

/// Encode an unsigned integer as LEB128.
pub fn encode_wasm_uleb128(mut val: u64) -> Vec<u8> {
    let mut bytes = Vec::new();
    loop {
        let mut byte = (val & 0x7F) as u8;
        val >>= 7;
        if val != 0 {
            byte |= 0x80;
        }
        bytes.push(byte);
        if val == 0 {
            break;
        }
    }
    bytes
}

/// Encode a signed integer as LEB128.
pub fn encode_wasm_sleb128(mut val: i64) -> Vec<u8> {
    let mut bytes = Vec::new();
    loop {
        let mut byte = (val as u8) & 0x7F;
        val >>= 7;
        if (val == 0 && (byte & 0x40) == 0) || (val == -1 && (byte & 0x40) != 0) {
            bytes.push(byte);
            break;
        }
        byte |= 0x80;
        bytes.push(byte);
    }
    bytes
}

// ═══════════════════════════════════════════════════════════════════════════
// Symbol Emission — per-format symbol & string table generation
// ═══════════════════════════════════════════════════════════════════════════

/// Represents an emitted symbol.
#[derive(Debug, Clone)]
pub struct EmittedSymbol {
    pub name: String,
    pub section_index: u32,
    pub value: u64,
    pub size: u64,
    pub binding: SymbolBinding,
    pub sym_type: SymbolType,
    pub visibility: SymbolVisibility,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SymbolBinding {
    Local,
    Global,
    Weak,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SymbolType {
    NoType,
    Object,
    Function,
    Section,
    File,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SymbolVisibility {
    Default,
    Hidden,
    Protected,
}

impl ObjectEmitter {
    /// Emit ELF symbol table and string table.
    pub fn emit_elf_symtab(&self) -> (Vec<u8>, Vec<u8>) {
        let mut strtab = Vec::new();
        strtab.push(0u8); // null byte at index 0
        let mut symtab = Vec::new();
        // Null symbol entry
        symtab.extend_from_slice(&[0u8; 24]);
        for i in 0..self.function_count {
            let name = format!("func_{}", i);
            let name_offset = strtab.len() as u32;
            strtab.extend_from_slice(name.as_bytes());
            strtab.push(0);
            // st_name
            symtab.extend_from_slice(&name_offset.to_le_bytes());
            // st_info: STB_GLOBAL | STT_FUNC
            symtab.push(0x12);
            // st_other: STV_DEFAULT
            symtab.push(0);
            // st_shndx: 1 (.text)
            symtab.extend_from_slice(&1u16.to_le_bytes());
            // st_value, st_size
            symtab.extend_from_slice(&0u64.to_le_bytes());
            symtab.extend_from_slice(&0u64.to_le_bytes());
        }
        (symtab, strtab)
    }

    /// Emit Mach-O symbol table and string table.
    pub fn emit_macho_symtab(&self) -> (Vec<u8>, Vec<u8>) {
        let mut strtab = Vec::new();
        strtab.extend_from_slice(b"\0\0"); // padding
        strtab.push(0u8);
        let mut symtab = Vec::new();
        for i in 0..self.function_count {
            let name = format!("_func_{}", i);
            let name_idx = strtab.len() as u32;
            strtab.extend_from_slice(name.as_bytes());
            strtab.push(0);
            // n_strx
            symtab.extend_from_slice(&name_idx.to_le_bytes());
            // n_type: N_SECT | N_EXT
            symtab.push(0x0F);
            // n_sect: 1 (__text)
            symtab.push(1);
            // n_desc
            symtab.extend_from_slice(&0u16.to_le_bytes());
            // n_value
            symtab.extend_from_slice(&0u64.to_le_bytes());
        }
        (symtab, strtab)
    }

    /// Emit COFF symbol table.
    pub fn emit_coff_full_symtab(&self) -> Vec<u8> {
        let mut syms = Vec::new();
        for i in 0..self.function_count {
            let name = format!("func_{}", i);
            let mut name_bytes = [0u8; 8];
            let src = name.as_bytes();
            name_bytes[..src.len().min(8)].copy_from_slice(&src[..src.len().min(8)]);
            syms.extend_from_slice(&name_bytes);
            syms.extend_from_slice(&0u32.to_le_bytes()); // value
            syms.extend_from_slice(&1i16.to_le_bytes()); // section number
            syms.extend_from_slice(&0x20u16.to_le_bytes()); // type = function
            syms.push(2); // storage class = external
            syms.push(0); // no aux symbols
        }
        syms
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Relocation Emission — per-target relocation writing
// ═══════════════════════════════════════════════════════════════════════════

/// Relocation entry for ELF.
#[derive(Debug, Clone)]
pub struct ElfRelocation {
    pub offset: u64,
    pub symbol_index: u32,
    pub reloc_type: u32,
    pub addend: i64,
}

/// Known x86-64 relocation types.
pub mod x86_64_reloc {
    pub const R_X86_64_NONE: u32 = 0;
    pub const R_X86_64_64: u32 = 1;
    pub const R_X86_64_PC32: u32 = 2;
    pub const R_X86_64_GOT32: u32 = 3;
    pub const R_X86_64_PLT32: u32 = 4;
    pub const R_X86_64_32: u32 = 10;
    pub const R_X86_64_32S: u32 = 11;
    pub const R_X86_64_PC64: u32 = 24;
    pub const R_X86_64_GOTPCREL: u32 = 9;
    pub const R_X86_64_REX_GOTPCRELX: u32 = 42;
}

/// Known AArch64 relocation types.
pub mod aarch64_reloc {
    pub const R_AARCH64_NONE: u32 = 0;
    pub const R_AARCH64_ABS64: u32 = 257;
    pub const R_AARCH64_ABS32: u32 = 258;
    pub const R_AARCH64_CALL26: u32 = 283;
    pub const R_AARCH64_ADR_PREL_PG_HI21: u32 = 275;
    pub const R_AARCH64_ADD_ABS_LO12_NC: u32 = 277;
    pub const R_AARCH64_LDST8_ABS_LO12_NC: u32 = 278;
    pub const R_AARCH64_LDST32_ABS_LO12_NC: u32 = 280;
    pub const R_AARCH64_LDST64_ABS_LO12_NC: u32 = 281;
    pub const R_AARCH64_CONDBR19: u32 = 281;
    pub const R_AARCH64_JUMP26: u32 = 282;
}

/// Known RISC-V 64 relocation types.
pub mod riscv64_reloc {
    pub const R_RISCV_NONE: u32 = 0;
    pub const R_RISCV_32: u32 = 1;
    pub const R_RISCV_64: u32 = 2;
    pub const R_RISCV_RELATIVE: u32 = 3;
    pub const R_RISCV_BRANCH: u32 = 16;
    pub const R_RISCV_JAL: u32 = 17;
    pub const R_RISCV_CALL: u32 = 18;
    pub const R_RISCV_CALL_PLT: u32 = 19;
    pub const R_RISCV_GOT_HI20: u32 = 20;
    pub const R_RISCV_PCREL_HI20: u32 = 23;
    pub const R_RISCV_PCREL_LO12_I: u32 = 24;
    pub const R_RISCV_PCREL_LO12_S: u32 = 25;
    pub const R_RISCV_HI20: u32 = 26;
    pub const R_RISCV_LO12_I: u32 = 27;
    pub const R_RISCV_LO12_S: u32 = 28;
}

impl ObjectEmitter {
    /// Emit x86-64 ELF relocations.
    pub fn emit_x86_64_relocations(&self) -> Vec<u8> {
        let mut rels = Vec::new();
        // Example: a PC32 relocation for a call instruction at offset 5
        if self.function_count > 0 {
            rels.extend_from_slice(&5u64.to_le_bytes()); // r_offset
            rels.extend_from_slice(&x86_64_reloc::R_X86_64_PC32.to_le_bytes()); // r_info (type)
            rels.extend_from_slice(&(-4i64).to_le_bytes()); // r_addend
        }
        rels
    }

    /// Emit AArch64 ELF relocations.
    pub fn emit_aarch64_relocations(&self) -> Vec<u8> {
        let mut rels = Vec::new();
        if self.function_count > 0 {
            rels.extend_from_slice(&0u64.to_le_bytes());
            rels.extend_from_slice(&aarch64_reloc::R_AARCH64_CALL26.to_le_bytes());
            rels.extend_from_slice(&0i64.to_le_bytes());
        }
        rels
    }

    /// Emit RISC-V 64 ELF relocations.
    pub fn emit_riscv64_relocations(&self) -> Vec<u8> {
        let mut rels = Vec::new();
        if self.function_count > 0 {
            rels.extend_from_slice(&0u64.to_le_bytes());
            rels.extend_from_slice(&riscv64_reloc::R_RISCV_CALL.to_le_bytes());
            rels.extend_from_slice(&0i64.to_le_bytes());
        }
        rels
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Debug Section Emission — .debug_abbrev, .debug_info, .debug_line, etc.
// ═══════════════════════════════════════════════════════════════════════════

impl ObjectEmitter {
    /// Emit a minimal .debug_abbrev section.
    pub fn emit_debug_abbrev(&self) -> Vec<u8> {
        let mut d = Vec::new();
        // Abbreviation code 1: DW_TAG_compile_unit
        d.extend_from_slice(&encode_uleb128(1)); // abbreviation code
        d.extend_from_slice(&encode_uleb128(0x11)); // DW_TAG_compile_unit
        d.push(0x01); // DW_CHILDREN_yes
                      // DW_AT_producer
        d.extend_from_slice(&encode_uleb128(0x25));
        d.extend_from_slice(&encode_uleb128(0x08)); // DW_FORM_string
                                                    // DW_AT_language
        d.extend_from_slice(&encode_uleb128(0x0D));
        d.extend_from_slice(&encode_uleb128(0x0B)); // DW_FORM_data1
                                                    // DW_AT_name
        d.extend_from_slice(&encode_uleb128(0x03));
        d.extend_from_slice(&encode_uleb128(0x08)); // DW_FORM_string
                                                    // DW_AT_low_pc
        d.extend_from_slice(&encode_uleb128(0x11));
        d.extend_from_slice(&encode_uleb128(0x01)); // DW_FORM_addr
                                                    // Terminator
        d.extend_from_slice(&[0, 0]);
        d
    }

    /// Emit a minimal .debug_info section.
    pub fn emit_debug_info(&self) -> Vec<u8> {
        let mut d = Vec::new();
        // Unit length (placeholder, excluding itself)
        d.extend_from_slice(&0u32.to_le_bytes());
        // DWARF version 4
        d.extend_from_slice(&4u16.to_le_bytes());
        // Abbreviation offset
        d.extend_from_slice(&0u32.to_le_bytes());
        // Address size
        d.push(8);
        // Abbreviation 1: DW_TAG_compile_unit
        d.extend_from_slice(&encode_uleb128(1));
        // DW_AT_producer
        d.extend_from_slice(b"llvm-native-core 0.1\0");
        // DW_AT_language: DW_LANG_C99 (12)
        d.push(12);
        // DW_AT_name
        d.extend_from_slice(b"output.o\0");
        // DW_AT_low_pc
        d.extend_from_slice(&0u64.to_le_bytes());
        // End of children
        d.push(0);
        d
    }

    /// Emit a minimal .debug_line section.
    pub fn emit_debug_line(&self) -> Vec<u8> {
        let mut d = Vec::new();
        // Unit length (placeholder)
        d.extend_from_slice(&0u32.to_le_bytes());
        // Version 4
        d.extend_from_slice(&4u16.to_le_bytes());
        // Header length (placeholder)
        d.extend_from_slice(&0u32.to_le_bytes());
        // Minimum instruction length
        d.push(1);
        // Maximum operations per instruction
        d.push(1);
        // Default is_stmt
        d.push(1);
        // Line base
        d.push(-5i8 as u8);
        // Line range
        d.push(14);
        // Opcode base
        d.push(13);
        // Standard opcode lengths (12 entries)
        d.extend_from_slice(&[0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1]);
        // Include directories (empty)
        d.push(0);
        // File names (empty)
        d.push(0);
        // End of line number program
        d.extend_from_slice(&[0, 0, 0, 1]); // DW_LNE_end_sequence
        d
    }

    /// Emit a minimal .debug_frame section (Call Frame Information).
    pub fn emit_debug_frame(&self) -> Vec<u8> {
        let mut d = Vec::new();
        // CIE (Common Information Entry)
        // Length (excluding length field itself, placeholder)
        d.extend_from_slice(&0u32.to_le_bytes());
        // CIE_id = 0xFFFFFFFF
        d.extend_from_slice(&0xFFFFFFFFu32.to_le_bytes());
        // Version = 4
        d.push(4);
        // Augmentation string = "zR"
        d.extend_from_slice(b"zR\0");
        // Address size = 8
        d.extend_from_slice(&encode_uleb128(8));
        // Segment size = 0
        d.extend_from_slice(&encode_uleb128(0));
        // Code alignment factor = 1
        d.extend_from_slice(&encode_uleb128(1));
        // Data alignment factor = -8
        d.extend_from_slice(&encode_sleb128(-8));
        // Return address register = 16 (x86-64 RIP)
        d.extend_from_slice(&encode_uleb128(16));
        // Augmentation data length = 1 (FDE pointer encoding)
        d.push(1);
        d.push(0x1B); // DW_EH_PE_pcrel | DW_EH_PE_sdata4
                      // Initial instructions: DW_CFA_def_cfa r7 (RSP), offset 8
        d.push(0x0C); // DW_CFA_def_cfa
        d.push(7);
        d.push(8);
        // DW_CFA_offset r16 (RIP), offset -8
        d.push(0x90);
        d.push(1);

        // FDE (Frame Description Entry)
        // Length (placeholder)
        d.extend_from_slice(&0u32.to_le_bytes());
        // CIE pointer = 0 (relative to start of this FDE entry)
        d.extend_from_slice(&0u32.to_le_bytes());
        // PC begin = 0
        d.extend_from_slice(&0u64.to_le_bytes());
        // PC range = size of text section
        d.extend_from_slice(&(self.text_data.len() as u64).to_le_bytes());
        // Augmentation data length = 0
        d.extend_from_slice(&encode_uleb128(0));
        // Instructions: DW_CFA_nop
        d.push(0);
        d
    }

    /// Emit a minimal .debug_loc section.
    pub fn emit_debug_loc(&self) -> Vec<u8> {
        // A location list entry: [begin, end) range with location expression
        let mut d = Vec::new();
        d.extend_from_slice(&0u64.to_le_bytes()); // begin
        d.extend_from_slice(&0u64.to_le_bytes()); // end
                                                  // Location expression: DW_OP_reg5 (RBP on x86-64)
        d.extend_from_slice(&2u16.to_le_bytes()); // expression length
        d.push(0x55); // DW_OP_reg5
        d.push(0x00); // (some opcode)
                      // Terminator
        d.extend_from_slice(&0u64.to_le_bytes());
        d.extend_from_slice(&0u64.to_le_bytes());
        d
    }
}

/// Encode an unsigned integer as unsigned LEB128.
pub fn encode_uleb128(mut val: u64) -> Vec<u8> {
    let mut bytes = Vec::new();
    loop {
        let mut byte = (val & 0x7F) as u8;
        val >>= 7;
        if val != 0 {
            byte |= 0x80;
        }
        bytes.push(byte);
        if val == 0 {
            break;
        }
    }
    bytes
}

/// Encode a signed integer as signed LEB128.
pub fn encode_sleb128(mut val: i64) -> Vec<u8> {
    let mut bytes = Vec::new();
    loop {
        let mut byte = (val as u8) & 0x7F;
        val >>= 7;
        if (val == 0 && (byte & 0x40) == 0) || (val == -1 && (byte & 0x40) != 0) {
            bytes.push(byte);
            break;
        }
        byte |= 0x80;
        bytes.push(byte);
    }
    bytes
}

// ═══════════════════════════════════════════════════════════════════════════
// Multi-target Machine Code Emission
// ═══════════════════════════════════════════════════════════════════════════

impl ObjectEmitter {
    /// Encode a MachineFunction for a specific target architecture.
    pub fn encode_for_target(&mut self, func: &ValueRef, target: &str) {
        match target {
            "x86_64" | "x86-64" | "amd64" => self.encode_x86_64(func),
            "aarch64" | "arm64" => self.encode_aarch64(func),
            "riscv64" => self.encode_riscv64(func),
            _ => self.encode_x86_64(func), // fallback
        }
    }

    fn encode_x86_64(&mut self, func: &ValueRef) {
        let f = func.borrow();
        for op in &f.operands {
            let bb = op.borrow();
            if bb.is_basic_block() {
                for inst_val in &bb.operands {
                    let inst = inst_val.borrow();
                    if inst.is_instruction() {
                        if let Some(ref opc) = inst.opcode {
                            let mc_opc = match *opc {
                                Opcode::Ret => 0xC3u32,
                                Opcode::Add => 0x01,
                                Opcode::Sub => 0x29,
                                Opcode::Call => 0xE8,
                                Opcode::Br => 0xEB,
                                _ => 0x90,
                            };
                            let mc_inst = MCInst::new(mc_opc);
                            if let Some(encoded) = encode_x86_64(&mc_inst) {
                                self.text_data.extend_from_slice(&encoded);
                            }
                        }
                    }
                }
            }
        }
        self.function_count += 1;
    }

    fn encode_aarch64(&mut self, func: &ValueRef) {
        let f = func.borrow();
        for op in &f.operands {
            let bb = op.borrow();
            if bb.is_basic_block() {
                for inst_val in &bb.operands {
                    let inst = inst_val.borrow();
                    if inst.is_instruction() {
                        if let Some(ref opc) = inst.opcode {
                            let encoded = match *opc {
                                Opcode::Ret => vec![0xC0, 0x03, 0x5F, 0xD6],
                                Opcode::Add => vec![0x00, 0x00, 0x00, 0x8B],
                                Opcode::Sub => vec![0x00, 0x00, 0x00, 0xCB],
                                Opcode::Br => vec![0x00, 0x00, 0x00, 0x14],
                                _ => vec![0x1F, 0x20, 0x03, 0xD5], // nop
                            };
                            self.text_data.extend_from_slice(&encoded);
                        }
                    }
                }
            }
        }
        self.function_count += 1;
    }

    fn encode_riscv64(&mut self, func: &ValueRef) {
        let f = func.borrow();
        for op in &f.operands {
            let bb = op.borrow();
            if bb.is_basic_block() {
                for inst_val in &bb.operands {
                    let inst = inst_val.borrow();
                    if inst.is_instruction() {
                        if let Some(ref opc) = inst.opcode {
                            let encoded = match *opc {
                                Opcode::Ret => vec![0x67, 0x80, 0x00, 0x00], // jalr x0, ra, 0
                                Opcode::Add => vec![0x33, 0x00, 0x00, 0x00],
                                Opcode::Sub => vec![0x33, 0x40, 0x00, 0x00],
                                Opcode::Br => vec![0x6F, 0x00, 0x00, 0x00], // jal x0, offset
                                _ => vec![0x13, 0x00, 0x00, 0x00],          // nop (addi x0, x0, 0)
                            };
                            self.text_data.extend_from_slice(&encoded);
                        }
                    }
                }
            }
        }
        self.function_count += 1;
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Object File Format Helpers
// ═══════════════════════════════════════════════════════════════════════════

/// Detect the object format from a target triple string.
pub fn detect_object_format(triple: &str) -> llvm_native_core::object_writer::ObjectFormat {
    let lower = triple.to_lowercase();
    if lower.contains("wasm") {
        return llvm_native_core::object_writer::ObjectFormat::Wasm;
    }
    if lower.contains("apple")
        || lower.contains("darwin")
        || lower.contains("macos")
        || lower.contains("ios")
    {
        return llvm_native_core::object_writer::ObjectFormat::MachO;
    }
    if lower.contains("windows")
        || lower.contains("mingw")
        || lower.contains("msvc")
        || lower.contains("cygwin")
    {
        return llvm_native_core::object_writer::ObjectFormat::COFF;
    }
    llvm_native_core::object_writer::ObjectFormat::ELF
}

/// Get the default entry point symbol name for a target.
pub fn default_entry_point(triple: &str) -> &str {
    let lower = triple.to_lowercase();
    if lower.contains("windows") && lower.contains("msvc") {
        return "mainCRTStartup";
    }
    if lower.contains("windows") {
        return "_mainCRTStartup";
    }
    if lower.contains("darwin") || lower.contains("macos") {
        return "_main";
    }
    "_start"
}

/// Get the default section name for executable code.
pub fn code_section_name(triple: &str) -> &str {
    let lower = triple.to_lowercase();
    if lower.contains("apple")
        || lower.contains("darwin")
        || lower.contains("macos")
        || lower.contains("ios")
    {
        return "__TEXT,__text";
    }
    if lower.contains("windows") {
        return ".text";
    }
    ".text"
}

/// Get the default section alignment for code.
pub fn code_section_alignment(triple: &str) -> u64 {
    let lower = triple.to_lowercase();
    if lower.contains("x86_64") || lower.contains("amd64") {
        return 16;
    }
    if lower.contains("aarch64") {
        return 16;
    }
    if lower.contains("wasm") {
        return 1;
    }
    16
}

/// Check if the target supports position-independent code.
pub fn target_supports_pic(triple: &str) -> bool {
    let lower = triple.to_lowercase();
    !lower.contains("wasm")
}

/// Get the default stack alignment for a target.
pub fn default_stack_alignment(triple: &str) -> u32 {
    let lower = triple.to_lowercase();
    if lower.contains("x86_64") || lower.contains("aarch64") {
        return 16;
    }
    if lower.contains("x86") || lower.contains("i386") || lower.contains("arm") {
        return 16;
    }
    if lower.contains("wasm") {
        return 16;
    }
    16
}

/// Validate that the emitted object has the minimum required sections.
pub fn validate_object_sections(data: &[u8], format: llvm_native_core::object_writer::ObjectFormat) -> bool {
    match format {
        llvm_native_core::object_writer::ObjectFormat::ELF => data.len() >= 64 && &data[0..4] == b"\x7fELF",
        llvm_native_core::object_writer::ObjectFormat::MachO => data.len() >= 32,
        llvm_native_core::object_writer::ObjectFormat::COFF => data.len() >= 20,
        llvm_native_core::object_writer::ObjectFormat::Wasm => data.len() >= 8 && &data[0..4] == b"\0asm",
    }
}

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

    #[test]
    fn test_empty_emitter() {
        let emitter = ObjectEmitter::new(ObjectFormat::ELF, "x86_64-unknown-linux-gnu");
        assert_eq!(emitter.function_count(), 0);
    }

    #[test]
    fn test_add_global_data() {
        let mut emitter = ObjectEmitter::new(ObjectFormat::ELF, "x86_64-unknown-linux-gnu");
        emitter.add_global_data(&[0x42, 0x00, 0x00, 0x00]);
        assert_eq!(emitter.global_count(), 1);
    }

    #[test]
    fn test_format_helpers() {
        let funcs: Vec<&ValueRef> = vec![];
        assert!(compile_to_object(&funcs, "x86_64-unknown-linux-gnu").len() > 0);
        assert!(compile_to_macho(&funcs, "x86_64-apple-macosx").len() > 0);
        assert!(compile_to_coff(&funcs, "x86_64-pc-windows-msvc").len() > 0);
        assert!(compile_to_wasm(&funcs, "wasm32-unknown-unknown").len() > 0);
    }
}