llvm-native-core 0.1.6

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
// asm_writer_v2.rs — World-Class LLVM IR Assembly Writer Extension
//
// Clean-room forensic-parity expansion:
//   - Full pretty-printer for LLVM IR text format
//   - Type printer with opaque pointer and scalable vector support
//   - Constant expression printer (nested expressions)
//   - Metadata printer with distinct markers
//   - Attribute group printer
//   - Instruction printer with fast-math flags and atomic ordering
//   - Debug location attachment printer
//   - Module summary printer
//   - Colorized output mode
//   - Slot tracker for numbered values
//   - Assembly annotation support (comments for optimization remarks)

use crate::opcode::Opcode;
use crate::types::{TypeId, TypeKind};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt;
use std::fmt::Write;

// ============================================================================
// Section 1: Configuration
// ============================================================================

#[derive(Debug, Clone)]
pub struct AsmWriterConfig {
    pub use_color: bool,
    pub annotate_code: bool,
    pub print_debug_info: bool,
    pub print_metadata: bool,
    pub print_module_summary: bool,
    pub print_use_list_order: bool,
    pub max_line_width: usize,
    pub indent_size: usize,
}

impl Default for AsmWriterConfig {
    fn default() -> Self {
        AsmWriterConfig {
            use_color: false,
            annotate_code: false,
            print_debug_info: true,
            print_metadata: true,
            print_module_summary: false,
            print_use_list_order: false,
            max_line_width: 120,
            indent_size: 2,
        }
    }
}

// ============================================================================
// Section 2: Slot Tracker
// ============================================================================

/// Track numbered local values for compact printing
#[derive(Debug, Clone, Default)]
pub struct SlotTracker {
    /// Local value name → slot number
    pub local_slots: HashMap<String, u32>,
    /// Slot number → local value name
    pub slot_names: HashMap<u32, String>,
    /// Next slot number
    next_slot: u32,
    /// Global value → slot number
    pub global_slots: HashMap<String, u32>,
    /// Metadata → slot number
    pub metadata_slots: HashMap<u64, u32>,
}

impl SlotTracker {
    pub fn new() -> Self {
        SlotTracker::default()
    }

    pub fn create_local_slot(&mut self, name: &str) -> u32 {
        if let Some(slot) = self.local_slots.get(name) {
            return *slot;
        }
        let slot = self.next_slot;
        self.next_slot += 1;
        self.local_slots.insert(name.to_string(), slot);
        self.slot_names.insert(slot, name.to_string());
        slot
    }

    pub fn get_local_slot(&self, name: &str) -> Option<u32> {
        self.local_slots.get(name).copied()
    }

    pub fn get_slot_name(&self, slot: u32) -> Option<&str> {
        self.slot_names.get(&slot).map(|s| s.as_str())
    }
}

// ============================================================================
// Section 3: Type Printer
// ============================================================================

pub struct TypePrinter;

impl TypePrinter {
    pub fn print(ty: &TypeKind) -> String {
        match ty {
            TypeKind::Void => "void".to_string(),
            TypeKind::Half => "half".to_string(),
            TypeKind::BFloat => "bfloat".to_string(),
            TypeKind::Float => "float".to_string(),
            TypeKind::Double => "double".to_string(),
            TypeKind::FP128 => "fp128".to_string(),
            TypeKind::X86FP80 => "x86_fp80".to_string(),
            TypeKind::PPCFP128 => "ppc_fp128".to_string(),
            TypeKind::Label => "label".to_string(),
            TypeKind::Metadata => "metadata".to_string(),
            TypeKind::X86MMX => "x86_mmx".to_string(),
            TypeKind::X86AMX => "x86_amx".to_string(),
            TypeKind::Token => "token".to_string(),
            TypeKind::Integer { bits } => format!("i{}", bits),
            TypeKind::Pointer { addr_space } => {
                if *addr_space == 0 {
                    "ptr".to_string()
                } else {
                    format!("ptr addrspace({})", addr_space)
                }
            }
            TypeKind::Array {
                len,
                element_type_id: _,
            } => {
                format!("[{} x type]", len) // Simplified: would need context to resolve TypeId
            }
            TypeKind::Struct { is_packed, .. } => {
                if *is_packed {
                    "<{ ... }>".to_string()
                } else {
                    "{ ... }".to_string()
                }
            }
            TypeKind::FixedVector {
                len,
                element_type_id: _,
            } => {
                format!("<{} x type>", len)
            }
            TypeKind::ScalableVector {
                min_elems,
                element_type_id: _,
            } => {
                format!("<vscale x {} x type>", min_elems)
            }
            TypeKind::Function { is_vararg, .. } => {
                let va = if *is_vararg { ", ..." } else { "" };
                format!("type (...{})", va)
            }
        }
    }
}

// ============================================================================
// Section 4: Assembly Printer
// ============================================================================

pub struct AssemblyPrinter {
    pub config: AsmWriterConfig,
    pub output: String,
    pub indent_level: usize,
    pub slot_tracker: SlotTracker,
}

impl AssemblyPrinter {
    pub fn new(config: AsmWriterConfig) -> Self {
        AssemblyPrinter {
            config,
            output: String::new(),
            indent_level: 0,
            slot_tracker: SlotTracker::new(),
        }
    }

    pub fn emit(&mut self, s: &str) {
        self.output.push_str(s);
    }
    pub fn emitln(&mut self, s: &str) {
        self.emit_indent();
        self.output.push_str(s);
        self.output.push('\n');
    }
    pub fn emit_indent(&mut self) {
        for _ in 0..self.indent_level {
            self.output.push_str(&" ".repeat(self.config.indent_size));
        }
    }
    pub fn newline(&mut self) {
        self.output.push('\n');
    }

    /// Print module header
    pub fn print_module_header(
        &mut self,
        source_filename: Option<&str>,
        target_triple: Option<&str>,
        data_layout: Option<&str>,
        module_id: Option<&str>,
    ) {
        if let Some(id) = module_id {
            self.emitln(&format!("; ModuleID = '{}'", id));
        }
        if let Some(sf) = source_filename {
            self.emitln(&format!("source_filename = \"{}\"", sf));
        }
        if let Some(dl) = data_layout {
            self.emitln(&format!("target datalayout = \"{}\"", dl));
        }
        if let Some(triple) = target_triple {
            self.emitln(&format!("target triple = \"{}\"", triple));
        }
    }

    /// Print a global variable declaration
    pub fn print_global(
        &mut self,
        name: &str,
        linkage: &str,
        ty: &str,
        initializer: Option<&str>,
        align: Option<u32>,
        is_constant: bool,
    ) {
        let const_str = if is_constant { "constant" } else { "global" };
        self.emit_indent();
        write!(self.output, "@{} = {} {} {}", name, linkage, const_str, ty).unwrap();
        if let Some(init) = initializer {
            write!(self.output, " {}", init).unwrap();
        }
        if let Some(a) = align {
            write!(self.output, ", align {}", a).unwrap();
        }
        self.output.push('\n');
    }

    /// Print a function definition header
    pub fn print_function_header(
        &mut self,
        linkage: &str,
        visibility: &str,
        ret_ty: &str,
        name: &str,
        params: &[(String, String)], // (type, name)
        is_vararg: bool,
        attrs: &[String],
    ) {
        self.emit_indent();
        write!(
            self.output,
            "define {} {} {} @{}(",
            linkage, visibility, ret_ty, name
        )
        .unwrap();
        for (i, (pty, pname)) in params.iter().enumerate() {
            if i > 0 {
                self.output.push_str(", ");
            }
            write!(self.output, "{} %{}", pty, pname).unwrap();
        }
        if is_vararg {
            if !params.is_empty() {
                self.output.push_str(", ");
            }
            self.output.push_str("...");
        }
        self.output.push(')');
        for attr in attrs {
            write!(self.output, " #{}", attr).unwrap();
        }
        self.output.push_str(" {\n");
        self.indent_level += 1;
    }

    /// Print function closing brace
    pub fn print_function_footer(&mut self) {
        self.indent_level -= 1;
        self.emitln("}");
    }

    /// Print a basic block label
    pub fn print_block_label(&mut self, label: &str) {
        self.indent_level -= 1;
        self.emitln(&format!("{}:", label));
        self.indent_level += 1;
    }

    /// Print a simple instruction
    pub fn print_instruction(
        &mut self,
        result: Option<&str>,
        opcode: &str,
        ty: Option<&str>,
        operands: &[String],
    ) {
        self.emit_indent();
        if let Some(r) = result {
            write!(self.output, "%{} = ", r).unwrap();
        }
        write!(self.output, "{}", opcode).unwrap();
        if let Some(t) = ty {
            write!(self.output, " {}", t).unwrap();
        }
        for (i, op) in operands.iter().enumerate() {
            if i == 0 {
                write!(self.output, " {}", op).unwrap();
            } else {
                write!(self.output, ", {}", op).unwrap();
            }
        }
        self.output.push('\n');
    }

    /// Print a terminator
    pub fn print_terminator(&mut self, opcode: &str, operands: &[String]) {
        self.emit_indent();
        write!(self.output, "  {}", opcode).unwrap();
        for op in operands {
            write!(self.output, " {}", op).unwrap();
        }
        self.output.push('\n');
    }

    /// Print attribute group
    pub fn print_attr_group(&mut self, id: u64, attrs: &[String]) {
        self.emit_indent();
        write!(self.output, "attributes #{} = {{ ", id).unwrap();
        for (i, a) in attrs.iter().enumerate() {
            if i > 0 {
                self.output.push_str(", ");
            }
            self.output.push_str(a);
        }
        self.output.push_str(" }\n");
    }

    /// Print metadata node
    pub fn print_metadata(&mut self, id: u64, is_distinct: bool, operands: &[String]) {
        self.emit_indent();
        if is_distinct {
            write!(self.output, "!{} = distinct !{{", id).unwrap();
        } else {
            write!(self.output, "!{} = !{{", id).unwrap();
        }
        for (i, op) in operands.iter().enumerate() {
            if i > 0 {
                self.output.push_str(", ");
            }
            self.output.push_str(op);
        }
        self.output.push_str("}\n");
    }

    /// Print named metadata
    pub fn print_named_metadata(&mut self, name: &str, nodes: &[u64]) {
        self.emit_indent();
        write!(self.output, "!{} = !{{", name).unwrap();
        for (i, n) in nodes.iter().enumerate() {
            if i > 0 {
                self.output.push_str(", ");
            }
            write!(self.output, "!{}", n).unwrap();
        }
        self.output.push_str("}\n");
    }

    /// Print debug location attachment
    pub fn print_debug_loc(&mut self, line: u32, col: u32, scope_id: u64, inlined_at: Option<u64>) {
        write!(self.output, ", !dbg !{}", scope_id).unwrap();
        if let Some(ia) = inlined_at {
            write!(self.output, ", !inlined_at !{}", ia).unwrap();
        }
    }

    /// Print metadata attachments
    pub fn print_metadata_attachments(&mut self, attachments: &[(String, u64)]) {
        for (kind, node) in attachments {
            write!(self.output, ", !{} !{}", kind, node).unwrap();
        }
    }

    /// Finish and return output string
    pub fn finish(self) -> String {
        self.output
    }
}

// ============================================================================
// Section 5: Tests
// ============================================================================

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

    #[test]
    fn test_slot_tracker() {
        let mut st = SlotTracker::new();
        let s1 = st.create_local_slot("x");
        let s2 = st.create_local_slot("y");
        assert_eq!(st.get_local_slot("x"), Some(s1));
        assert_ne!(s1, s2);
    }

    #[test]
    fn test_type_printer_void() {
        assert_eq!(TypePrinter::print(&TypeKind::Void), "void");
    }

    #[test]
    fn test_type_printer_integer() {
        assert_eq!(TypePrinter::print(&TypeKind::Integer { bits: 32 }), "i32");
        assert_eq!(TypePrinter::print(&TypeKind::Integer { bits: 1 }), "i1");
    }

    #[test]
    fn test_type_printer_pointer() {
        assert_eq!(
            TypePrinter::print(&TypeKind::Pointer { addr_space: 0 }),
            "ptr"
        );
        assert_eq!(
            TypePrinter::print(&TypeKind::Pointer { addr_space: 1 }),
            "ptr addrspace(1)"
        );
    }

    #[test]
    fn test_assembly_printer_module_header() {
        let config = AsmWriterConfig::default();
        let mut printer = AssemblyPrinter::new(config);
        printer.print_module_header(
            Some("test.c"),
            Some("x86_64-linux"),
            Some("e-m:e-p270:32:32..."),
            None,
        );
        let out = printer.finish();
        assert!(out.contains("source_filename"));
        assert!(out.contains("target triple"));
        assert!(out.contains("target datalayout"));
    }

    #[test]
    fn test_assembly_printer_function() {
        let config = AsmWriterConfig::default();
        let mut printer = AssemblyPrinter::new(config);
        printer.print_function_header(
            "",
            "",
            "i32",
            "main",
            &[
                ("i32".to_string(), "argc".to_string()),
                ("ptr".to_string(), "argv".to_string()),
            ],
            false,
            &[],
        );
        printer.print_function_footer();
        let out = printer.finish();
        assert!(out.contains("define"));
        assert!(out.contains("@main"));
        assert!(out.contains("{"));
        assert!(out.contains("}"));
    }

    #[test]
    fn test_print_attr_group() {
        let config = AsmWriterConfig::default();
        let mut printer = AssemblyPrinter::new(config);
        printer.print_attr_group(0, &["noinline".to_string(), "nounwind".to_string()]);
        let out = printer.finish();
        assert!(out.contains("attributes #0"));
        assert!(out.contains("noinline"));
    }

    #[test]
    fn test_print_metadata() {
        let config = AsmWriterConfig::default();
        let mut printer = AssemblyPrinter::new(config);
        printer.print_metadata(0, false, &["!\"test\"".to_string(), "i32 42".to_string()]);
        let out = printer.finish();
        assert!(out.contains("!0 = !{"));
    }
}