Skip to main content

gcn_assembler/
lib.rs

1#![warn(missing_docs)]
2
3//! GCN (Graphics Core Next) assembler for AMD GPUs.
4//!
5//! This crate provides utilities for assembling GCN instructions and programs.
6
7pub mod instructions;
8pub mod program;
9
10use crate::{instructions::GcnInstruction, program::GcnProgram};
11use gaia_types::Result;
12
13/// GCN 汇编器/写入器
14pub struct GcnWriter {}
15
16impl GcnWriter {
17    pub fn new() -> Self {
18        Self {}
19    }
20
21    pub fn write(&self, program: &GcnProgram) -> Result<Vec<u8>> {
22        let mut code = String::new();
23        for kernel in &program.kernels {
24            code.push_str(&format!(".text\n.globl {}\n{}:\n", kernel.name, kernel.name));
25            for inst in &kernel.instructions {
26                code.push_str("    ");
27                code.push_str(&self.format_instruction(inst));
28                code.push('\n');
29            }
30        }
31
32        // 模拟生成二进制 (ELF Magic + 汇编内容)
33        let mut binary = Vec::from("\x7fELF".as_bytes());
34        binary.extend_from_slice(code.as_bytes());
35        Ok(binary)
36    }
37
38    fn format_instruction(&self, inst: &GcnInstruction) -> String {
39        match inst {
40            GcnInstruction::VAddF32 { dst, src0, src1 } => format!("v_add_f32 {}, {}, {}", dst, src0, src1),
41            GcnInstruction::VMulF32 { dst, src0, src1 } => format!("v_mul_f32 {}, {}, {}", dst, src0, src1),
42            GcnInstruction::VDot2F32F16 { dst, src0, src1 } => format!("v_dot2_f32_f16 {}, {}, {}", dst, src0, src1),
43            GcnInstruction::GlobalLoadDword { dst, addr, offset } => {
44                format!("global_load_dword {}, {}, offset:{}", dst, addr, offset)
45            }
46            GcnInstruction::GlobalStoreDword { addr, src, offset } => {
47                format!("global_store_dword {}, {}, offset:{}", addr, src, offset)
48            }
49            GcnInstruction::SEndPgm => "s_endpgm".to_string(),
50            GcnInstruction::SNop(n) => format!("s_nop {}", n),
51        }
52    }
53}