trueno-gpu 0.4.15

Pure Rust PTX generation for NVIDIA CUDA - no LLVM, no nvcc
Documentation
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
//! WMMA (Tensor Core) operation emission
//!
//! Handles: WmmaLoadA, WmmaLoadB, WmmaLoadC, WmmaMma, WmmaStoreD

use super::operand::emit_operand;
use crate::ptx::instructions::{PtxInstruction, PtxOp};

/// Emit WMMA load instruction with proper register list format
/// Format: wmma.load.{a|b|c}.sync.aligned.m16n16k16.{layout}.{type} {regs}, [ptr], stride
pub(crate) fn emit_wmma_load(prefix: String, instr: &PtxInstruction, matrix: &str) -> String {
    let mut s = prefix;

    // Parse label to get layout, type, stride
    // Label format: "m16n16k16.{layout}.{type}.stride.{stride}"
    let label = instr
        .label
        .as_deref()
        .unwrap_or("m16n16k16.row.f16.stride.16");
    let parts: Vec<&str> = label.split('.').collect();

    // Build instruction opcode
    s.push_str(&format!("wmma.load.{}.sync.aligned", matrix));

    // Add shape, layout, type from label (e.g., "m16n16k16.row.f16")
    if parts.len() >= 3 {
        s.push('.');
        s.push_str(parts[0]); // m16n16k16
        s.push('.');
        s.push_str(parts[1]); // row/col
        s.push('.');
        s.push_str(parts[2]); // f16/f32
    } else {
        s.push_str(".m16n16k16.row.f16");
    }

    s.push(' ');

    // Destination registers: {%r0, %r1, ..., %r7}
    s.push('{');
    for (i, dst) in instr.dsts.iter().enumerate() {
        s.push_str(&emit_operand(dst));
        if i < instr.dsts.len() - 1 {
            s.push_str(", ");
        }
    }
    s.push_str("}, ");

    // Source: [ptr]
    if let Some(src) = instr.srcs.first() {
        s.push('[');
        s.push_str(&emit_operand(src));
        s.push_str("], ");
    }

    // Stride
    if let Some(stride) = instr.srcs.get(1) {
        s.push_str(&emit_operand(stride));
    } else {
        // Extract stride from label (last part after "stride.")
        if let Some(stride_pos) = label.find("stride.") {
            s.push_str(&label[stride_pos + 7..]);
        } else {
            s.push_str("16");
        }
    }

    s.push_str(";\n");
    s
}

/// Emit WMMA MMA instruction with proper register list format
/// Format: wmma.mma.sync.aligned.m16n16k16.row.col.f32.f32 {d}, {a}, {b}, {c}
pub(crate) fn emit_wmma_mma(prefix: String, instr: &PtxInstruction) -> String {
    let mut s = prefix;

    // Label format: "m16n16k16.row.col.f32.f32"
    let label = instr
        .label
        .as_deref()
        .unwrap_or("m16n16k16.row.col.f32.f32");

    s.push_str("wmma.mma.sync.aligned.");
    s.push_str(label);
    s.push(' ');

    // D registers (first 8 of dsts)
    s.push('{');
    for (i, dst) in instr.dsts.iter().enumerate() {
        s.push_str(&emit_operand(dst));
        if i < instr.dsts.len() - 1 {
            s.push_str(", ");
        }
    }
    s.push_str("}, ");

    // A, B, C registers (each 8 registers from srcs)
    // Total srcs = 24 (8 A + 8 B + 8 C)
    let groups = [
        (0, 8),   // A
        (8, 16),  // B
        (16, 24), // C
    ];

    for (start, end) in groups {
        s.push('{');
        for i in start..end.min(instr.srcs.len()) {
            s.push_str(&emit_operand(&instr.srcs[i]));
            if i < end.min(instr.srcs.len()) - 1 {
                s.push_str(", ");
            }
        }
        s.push('}');
        if end < 24 && end <= instr.srcs.len() {
            s.push_str(", ");
        }
    }

    s.push_str(";\n");
    s
}

/// Emit WMMA store instruction with proper format
/// Format: wmma.store.d.sync.aligned.m16n16k16.{layout}.{type} [ptr], {regs}, stride
pub(crate) fn emit_wmma_store(prefix: String, instr: &PtxInstruction) -> String {
    let mut s = prefix;

    // Label format: "m16n16k16.{layout}.{type}.stride.{stride}"
    let label = instr
        .label
        .as_deref()
        .unwrap_or("m16n16k16.row.f32.stride.16");
    let parts: Vec<&str> = label.split('.').collect();

    s.push_str("wmma.store.d.sync.aligned");

    // Add shape, layout, type from label
    if parts.len() >= 3 {
        s.push('.');
        s.push_str(parts[0]); // m16n16k16
        s.push('.');
        s.push_str(parts[1]); // row
        s.push('.');
        s.push_str(parts[2]); // f32
    } else {
        s.push_str(".m16n16k16.row.f32");
    }

    s.push(' ');

    // [ptr]
    if let Some(src) = instr.srcs.first() {
        s.push('[');
        s.push_str(&emit_operand(src));
        s.push_str("], ");
    }

    // {regs} - D fragment (srcs 1-8)
    s.push('{');
    let frag_end = instr.srcs.len().saturating_sub(1).min(9);
    for i in 1..frag_end {
        s.push_str(&emit_operand(&instr.srcs[i]));
        if i < frag_end - 1 {
            s.push_str(", ");
        }
    }
    s.push_str("}, ");

    // Stride (last src)
    if let Some(stride) = instr.srcs.last() {
        s.push_str(&emit_operand(stride));
    } else if let Some(stride_pos) = label.find("stride.") {
        s.push_str(&label[stride_pos + 7..]);
    } else {
        s.push_str("16");
    }

    s.push_str(";\n");
    s
}

/// Check if this is a WMMA operation
pub(crate) fn is_wmma_op(op: &PtxOp) -> bool {
    matches!(
        op,
        PtxOp::WmmaLoadA | PtxOp::WmmaLoadB | PtxOp::WmmaLoadC | PtxOp::WmmaMma | PtxOp::WmmaStoreD
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ptx::instructions::Operand;
    use crate::ptx::registers::VirtualReg;
    use crate::ptx::types::PtxType;

    fn make_instr(op: PtxOp, ty: PtxType) -> PtxInstruction {
        PtxInstruction {
            op,
            ty,
            src_type: None,
            dst: None,
            dsts: vec![],
            srcs: vec![],
            label: None,
            predicate: None,
            state_space: None,
            rounding: None,
        }
    }

    fn vreg(id: u32, ty: PtxType) -> VirtualReg {
        VirtualReg::new(id, ty)
    }

    // === is_wmma_op tests ===

    #[test]
    fn test_is_wmma_op_all_variants() {
        assert!(is_wmma_op(&PtxOp::WmmaLoadA));
        assert!(is_wmma_op(&PtxOp::WmmaLoadB));
        assert!(is_wmma_op(&PtxOp::WmmaLoadC));
        assert!(is_wmma_op(&PtxOp::WmmaMma));
        assert!(is_wmma_op(&PtxOp::WmmaStoreD));
    }

    #[test]
    fn test_is_wmma_op_non_wmma() {
        assert!(!is_wmma_op(&PtxOp::Add));
        assert!(!is_wmma_op(&PtxOp::Ld));
        assert!(!is_wmma_op(&PtxOp::Mul));
        assert!(!is_wmma_op(&PtxOp::Bra));
    }

    // === emit_wmma_load tests ===

    #[test]
    fn test_emit_wmma_load_a_default() {
        let mut instr = make_instr(PtxOp::WmmaLoadA, PtxType::F16);
        instr.dsts = (0..8)
            .map(|i| Operand::Reg(vreg(i, PtxType::F16)))
            .collect();
        instr.srcs = vec![Operand::Reg(vreg(100, PtxType::U64)), Operand::ImmU64(16)];
        let result = emit_wmma_load("    ".to_string(), &instr, "a");
        assert!(result.contains("wmma.load.a.sync.aligned"));
        assert!(result.contains(".m16n16k16.row.f16"));
    }

    #[test]
    fn test_emit_wmma_load_b_with_label() {
        let mut instr = make_instr(PtxOp::WmmaLoadB, PtxType::F16);
        instr.label = Some("m16n16k16.col.f16.stride.32".to_string());
        instr.dsts = (0..8)
            .map(|i| Operand::Reg(vreg(i, PtxType::F16)))
            .collect();
        instr.srcs = vec![Operand::Reg(vreg(100, PtxType::U64))];
        let result = emit_wmma_load("    ".to_string(), &instr, "b");
        assert!(result.contains("wmma.load.b.sync.aligned"));
        assert!(result.contains(".m16n16k16.col.f16"));
        assert!(result.contains("32"));
    }

    #[test]
    fn test_emit_wmma_load_c() {
        let mut instr = make_instr(PtxOp::WmmaLoadC, PtxType::F32);
        instr.label = Some("m16n16k16.row.f32".to_string());
        instr.dsts = (0..8)
            .map(|i| Operand::Reg(vreg(i, PtxType::F32)))
            .collect();
        instr.srcs = vec![Operand::Reg(vreg(100, PtxType::U64)), Operand::ImmU64(16)];
        let result = emit_wmma_load("    ".to_string(), &instr, "c");
        assert!(result.contains("wmma.load.c.sync.aligned"));
        assert!(result.contains(".m16n16k16.row.f32"));
    }

    #[test]
    fn test_emit_wmma_load_partial_label() {
        // Label with fewer than 3 parts
        let mut instr = make_instr(PtxOp::WmmaLoadA, PtxType::F16);
        instr.label = Some("m16n16k16".to_string()); // Only 1 part
        instr.dsts = (0..8)
            .map(|i| Operand::Reg(vreg(i, PtxType::F16)))
            .collect();
        instr.srcs = vec![Operand::Reg(vreg(100, PtxType::U64))];
        let result = emit_wmma_load("    ".to_string(), &instr, "a");
        // Should fall back to default .m16n16k16.row.f16
        assert!(result.contains(".m16n16k16.row.f16"));
    }

    #[test]
    fn test_emit_wmma_load_no_srcs() {
        let mut instr = make_instr(PtxOp::WmmaLoadA, PtxType::F16);
        instr.dsts = (0..8)
            .map(|i| Operand::Reg(vreg(i, PtxType::F16)))
            .collect();
        // No sources
        let result = emit_wmma_load("    ".to_string(), &instr, "a");
        // Should still produce valid output with default stride
        assert!(result.contains("wmma.load.a"));
        assert!(result.contains("16"));
    }

    // === emit_wmma_mma tests ===

    #[test]
    fn test_emit_wmma_mma_default() {
        let mut instr = make_instr(PtxOp::WmmaMma, PtxType::F32);
        instr.dsts = (0..8)
            .map(|i| Operand::Reg(vreg(i, PtxType::F32)))
            .collect();
        // A (8) + B (8) + C (8) = 24 source registers
        instr.srcs = (0..24)
            .map(|i| Operand::Reg(vreg(100 + i, PtxType::F16)))
            .collect();
        let result = emit_wmma_mma("    ".to_string(), &instr);
        assert!(result.contains("wmma.mma.sync.aligned.m16n16k16.row.col.f32.f32"));
    }

    #[test]
    fn test_emit_wmma_mma_with_label() {
        let mut instr = make_instr(PtxOp::WmmaMma, PtxType::F16);
        instr.label = Some("m8n8k4.row.row.f16.f16".to_string());
        instr.dsts = (0..4)
            .map(|i| Operand::Reg(vreg(i, PtxType::F16)))
            .collect();
        instr.srcs = (0..12)
            .map(|i| Operand::Reg(vreg(100 + i, PtxType::F16)))
            .collect();
        let result = emit_wmma_mma("    ".to_string(), &instr);
        assert!(result.contains("wmma.mma.sync.aligned.m8n8k4.row.row.f16.f16"));
    }

    #[test]
    fn test_emit_wmma_mma_partial_srcs() {
        // Fewer than 24 sources
        let mut instr = make_instr(PtxOp::WmmaMma, PtxType::F32);
        instr.dsts = (0..8)
            .map(|i| Operand::Reg(vreg(i, PtxType::F32)))
            .collect();
        instr.srcs = (0..16)
            .map(|i| Operand::Reg(vreg(100 + i, PtxType::F16)))
            .collect();
        let result = emit_wmma_mma("    ".to_string(), &instr);
        // Should handle fewer sources gracefully
        assert!(result.contains("wmma.mma.sync.aligned"));
    }

    // === emit_wmma_store tests ===

    #[test]
    fn test_emit_wmma_store_default() {
        let mut instr = make_instr(PtxOp::WmmaStoreD, PtxType::F32);
        // [ptr], {8 regs}, stride
        instr.srcs = std::iter::once(Operand::Reg(vreg(0, PtxType::U64)))
            .chain((1..9).map(|i| Operand::Reg(vreg(i, PtxType::F32))))
            .chain(std::iter::once(Operand::ImmU64(16)))
            .collect();
        let result = emit_wmma_store("    ".to_string(), &instr);
        assert!(result.contains("wmma.store.d.sync.aligned"));
        assert!(result.contains(".m16n16k16.row.f32"));
    }

    #[test]
    fn test_emit_wmma_store_with_label() {
        let mut instr = make_instr(PtxOp::WmmaStoreD, PtxType::F32);
        instr.label = Some("m16n16k16.col.f32.stride.32".to_string());
        instr.srcs = std::iter::once(Operand::Reg(vreg(0, PtxType::U64)))
            .chain((1..9).map(|i| Operand::Reg(vreg(i, PtxType::F32))))
            .chain(std::iter::once(Operand::ImmU64(32)))
            .collect();
        let result = emit_wmma_store("    ".to_string(), &instr);
        assert!(result.contains(".m16n16k16.col.f32"));
    }

    #[test]
    fn test_emit_wmma_store_partial_label() {
        // Label with fewer than 3 parts
        let mut instr = make_instr(PtxOp::WmmaStoreD, PtxType::F32);
        instr.label = Some("m8n8k4".to_string());
        instr.srcs = std::iter::once(Operand::Reg(vreg(0, PtxType::U64)))
            .chain((1..5).map(|i| Operand::Reg(vreg(i, PtxType::F32))))
            .chain(std::iter::once(Operand::ImmU64(16)))
            .collect();
        let result = emit_wmma_store("    ".to_string(), &instr);
        // Should fall back to default .m16n16k16.row.f32
        assert!(result.contains(".m16n16k16.row.f32"));
    }

    #[test]
    fn test_emit_wmma_store_stride_from_label() {
        // No sources at all, should get stride from label
        let mut instr = make_instr(PtxOp::WmmaStoreD, PtxType::F32);
        instr.label = Some("m16n16k16.row.f32.stride.64".to_string());
        instr.srcs = vec![];
        let result = emit_wmma_store("    ".to_string(), &instr);
        assert!(result.contains("64"));
    }

    #[test]
    fn test_emit_wmma_store_empty_srcs() {
        // Edge case: empty sources
        let mut instr = make_instr(PtxOp::WmmaStoreD, PtxType::F32);
        instr.srcs = vec![];
        let result = emit_wmma_store("    ".to_string(), &instr);
        // Should produce something, even if minimal
        assert!(result.contains("wmma.store.d"));
    }
}