singe-cuda 0.1.0

Safe Rust wrappers for the CUDA driver and runtime APIs, including runtime compilation of CUDA C++ and NVTX annotations.
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
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
//! NVVM IR compilation and compiler options.

use std::{
    ffi::{CString, c_char},
    mem, ptr, result,
};

use singe_core::{LibraryVersion, impl_enum_display, report_cleanup_failure};
use singe_cuda_sys::nvvm as sys;

use crate::{
    architecture::GpuArchitecture,
    error::{Error, Result},
    module::ModuleImage,
    try_nvvm,
    utility::{bytes_to_string, to_c_ulong, to_i32, to_usize},
};

/// NVVM IR and debug metadata versions supported by the loaded compiler.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct IrVersion {
    /// Major supported NVVM IR version.
    pub major: i32,
    /// Minor supported NVVM IR version.
    pub minor: i32,
    /// Major supported debug metadata version.
    pub debug_major: i32,
    /// Minor supported debug metadata version.
    pub debug_minor: i32,
}

singe_core::wrapper_status! {
    library = "nvvm",
    error = Error::Nvvm,
    raw = sys::nvvmResult,
    success = NVVM_SUCCESS,
    absence = singe_cuda_sys::take_absence,
    check = check_nvvm,
    unknown = "UNKNOWN_NVVM_STATUS",
    description = sys::nvvmGetErrorString,
    /// NVVM result code returned by compiler operations.
    pub enum Status: u32 {
        /// The operation completed successfully.
        Success = NVVM_SUCCESS,
        /// NVVM could not allocate the required memory.
        OutOfMemory = NVVM_ERROR_OUT_OF_MEMORY,
        /// NVVM could not create the program.
        ProgramCreationFailure = NVVM_ERROR_PROGRAM_CREATION_FAILURE,
        /// The input IR version is incompatible with the NVVM library.
        IrVersionMismatch = NVVM_ERROR_IR_VERSION_MISMATCH,
        /// An input argument is invalid.
        InvalidInput = NVVM_ERROR_INVALID_INPUT,
        /// The program handle is invalid.
        InvalidProgram = NVVM_ERROR_INVALID_PROGRAM,
        /// The input NVVM IR is invalid.
        InvalidIr = NVVM_ERROR_INVALID_IR,
        /// A compilation option is invalid.
        InvalidOption = NVVM_ERROR_INVALID_OPTION,
        /// The program contains no IR modules.
        NoModuleInProgram = NVVM_ERROR_NO_MODULE_IN_PROGRAM,
        /// NVVM compilation failed; the program log contains diagnostics.
        Compilation = NVVM_ERROR_COMPILATION,
        /// The operation was cancelled.
        Cancelled = NVVM_ERROR_CANCELLED,
    }
}

/// Native optimization level for NVVM IR compilation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum OptimizationLevel {
    /// Disables compiler optimizations.
    Zero,
    /// Enables the native default optimization level.
    Three,
}

impl_enum_display!(OptimizationLevel, {
    Self::Zero => "0",
    Self::Three => "3",
});

/// Typed NVVM compiler options.
/// Unset optional values leave native defaults in effect; raw options are appended after typed options.
/// Typed compilation and verification reject concrete GPU architecture targets.
#[derive(Debug, Clone, Default)]
pub struct CompileOptions<'a> {
    /// Whether to emit full device debug information.
    /// Native full debug support requires optimization level zero and IR debug metadata.
    pub device_debug: bool,
    /// Optimization effort applied to the input IR.
    pub optimization_level: Option<OptimizationLevel>,
    /// Virtual GPU architecture target.
    /// Typed compilation and verification reject a concrete architecture.
    pub gpu_architecture: Option<GpuArchitecture>,
    /// Whether single-precision denormal values are flushed to zero.
    pub flush_to_zero: Option<bool>,
    /// Whether single-precision square roots use the precise native implementation.
    pub precise_square_root: Option<bool>,
    /// Whether single-precision division uses the precise native implementation.
    pub precise_division: Option<bool>,
    /// Whether floating-point multiply and add operations may be contracted.
    pub fma: Option<bool>,
    /// Switch case-density threshold, in percent, from zero through 101.
    /// The builder clamps larger values to 101.
    pub jump_table_density: Option<u8>,
    /// Whether to generate link-time intermediate representation instead of PTX.
    pub generate_lto: bool,
    /// Additional native options appended after the typed options.
    pub raw_options: Vec<&'a str>,
}

impl<'a> CompileOptions<'a> {
    /// Creates an empty compiler option set that leaves native defaults in effect.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            device_debug: false,
            optimization_level: None,
            gpu_architecture: None,
            flush_to_zero: None,
            precise_square_root: None,
            precise_division: None,
            fma: None,
            jump_table_density: None,
            generate_lto: false,
            raw_options: Vec::new(),
        }
    }

    /// Enables or disables full device debug information.
    /// Native full debug support requires optimization level zero and IR debug metadata.
    #[must_use]
    pub fn device_debug(mut self, value: bool) -> Self {
        self.device_debug = value;
        self
    }

    /// Sets the native optimization level.
    #[must_use]
    pub fn optimization_level(mut self, value: OptimizationLevel) -> Self {
        self.optimization_level = Some(value);
        self
    }

    /// Sets the virtual GPU architecture target.
    /// Concrete targets are rejected when typed options are compiled or verified.
    #[must_use]
    pub fn gpu_architecture(mut self, value: GpuArchitecture) -> Self {
        self.gpu_architecture = Some(value);
        self
    }

    /// Controls whether single-precision denormal values are flushed to zero.
    #[must_use]
    pub fn flush_to_zero(mut self, value: bool) -> Self {
        self.flush_to_zero = Some(value);
        self
    }

    /// Selects precise or approximate single-precision square roots.
    #[must_use]
    pub fn precise_square_root(mut self, value: bool) -> Self {
        self.precise_square_root = Some(value);
        self
    }

    /// Selects precise or approximate single-precision division.
    #[must_use]
    pub fn precise_division(mut self, value: bool) -> Self {
        self.precise_division = Some(value);
        self
    }

    /// Controls contraction of floating-point multiply and add operations.
    #[must_use]
    pub fn fma(mut self, value: bool) -> Self {
        self.fma = Some(value);
        self
    }

    /// Sets the switch case-density percentage threshold, clamping values above 101 to 101.
    #[must_use]
    pub fn jump_table_density(mut self, value: u8) -> Self {
        self.jump_table_density = Some(value.min(101));
        self
    }

    /// Selects link-time intermediate representation generation instead of PTX.
    #[must_use]
    pub fn generate_lto(mut self, value: bool) -> Self {
        self.generate_lto = value;
        self
    }

    /// Appends a native option string after the typed options.
    #[must_use]
    pub fn raw_option(mut self, value: &'a str) -> Self {
        self.raw_options.push(value);
        self
    }

    /// Renders compiler settings as owned native option strings without validating or compiling them.
    #[must_use]
    pub fn as_arguments(&self) -> Vec<String> {
        let mut arguments = Vec::new();
        if self.device_debug {
            arguments.push(String::from("-g"));
        }

        if let Some(value) = self.optimization_level {
            arguments.push(format!("-opt={value}"));
        }

        if let Some(value) = self.gpu_architecture {
            arguments.push(format!("-arch={value}"));
        }

        if let Some(value) = self.flush_to_zero {
            arguments.push(format!("-ftz={}", flag_bit(value)));
        }

        if let Some(value) = self.precise_square_root {
            arguments.push(format!("-prec-sqrt={}", flag_bit(value)));
        }

        if let Some(value) = self.precise_division {
            arguments.push(format!("-prec-div={}", flag_bit(value)));
        }

        if let Some(value) = self.fma {
            arguments.push(format!("-fma={}", flag_bit(value)));
        }

        if let Some(value) = self.jump_table_density {
            arguments.push(format!("-jump-table-density={value}"));
        }

        if self.generate_lto {
            arguments.push(String::from("-gen-lto"));
        }

        arguments.extend(self.raw_options.iter().map(|value| (*value).to_string()));
        arguments
    }

    fn validate(&self) -> Result<()> {
        if let Some(architecture) = self.gpu_architecture
            && !architecture.is_virtual()
        {
            return Err(Error::UnsupportedArchitecture {
                target: architecture.to_string(),
            });
        }
        Ok(())
    }
}

/// Borrowed NVVM IR bytes and a module name for addition to a compiler program.
#[derive(Debug, Clone, Copy)]
pub struct Module<'a> {
    /// NVVM IR bytes in the representation accepted by the selected module-addition API.
    pub ir: &'a [u8],
    /// Module name used in compiler diagnostics.
    /// Interior NUL bytes are rejected when adding it.
    pub name: &'a str,
}

/// Owned NVVM program containing IR modules to link, verify, and compile.
/// The native program is destroyed when this wrapper is dropped.
#[derive(Debug)]
pub struct Program {
    handle: sys::nvvmProgram,
}

/// Raw ownership of an NVVM program.
///
/// Destroy `handle` with NVVM, or re-adopt the value with [`Program::from_raw`].
#[derive(Debug)]
pub struct RawProgram {
    /// Native program handle.
    pub handle: sys::nvvmProgram,
}

impl Program {
    /// Creates an empty native NVVM compiler program.
    ///
    /// # Errors
    ///
    /// Returns an error if NVVM cannot create the program or returns a null handle.
    pub fn create() -> Result<Self> {
        let mut handle = ptr::null_mut();
        // SAFETY: `handle` is a local output.
        unsafe {
            try_nvvm!(sys::nvvmCreateProgram(&raw mut handle))?;
        }

        if handle.is_null() {
            return Err(Error::NullHandle);
        }
        Ok(Self { handle })
    }

    /// Takes ownership of a raw NVVM program.
    ///
    /// # Safety
    ///
    /// `raw.handle` must be a valid NVVM program that is not owned by any other wrapper.
    /// The returned wrapper destroys it on drop.
    ///
    /// # Errors
    ///
    /// Returns an error if `raw.handle` is null.
    #[expect(
        clippy::needless_pass_by_value,
        reason = "taking the raw owner by value transfers ownership of its handle"
    )]
    pub unsafe fn from_raw(raw: RawProgram) -> Result<Self> {
        if raw.handle.is_null() {
            return Err(Error::NullHandle);
        }

        Ok(Self { handle: raw.handle })
    }

    /// Adds an NVVM IR module in text or bitcode form to the program.
    ///
    /// # Errors
    ///
    /// Returns an error if the IR byte slice is empty, the module name contains an interior NUL, or NVVM rejects the module or program.
    pub fn add_module(&mut self, module: Module<'_>) -> Result<()> {
        self.add_module_raw(&module, false)
    }

    /// Adds a bitcode module whose symbols are loaded only as required by eagerly added modules.
    /// A program must contain at least one eagerly added module.
    ///
    /// # Errors
    ///
    /// Returns an error if the IR byte slice is empty, the module name contains an interior NUL, or NVVM rejects the module or program.
    pub fn lazy_add_module(&mut self, module: Module<'_>) -> Result<()> {
        self.add_module_raw(&module, true)
    }

    /// Validates `options`, links the added IR modules, and compiles the program.
    /// Output is PTX unless link-time IR generation is requested.
    ///
    /// # Errors
    ///
    /// Returns an error if `options.gpu_architecture` is a concrete GPU target, an option contains an interior NUL, the option count does not fit an `i32`, or NVVM rejects the options or fails compilation.
    /// Compiler diagnostics are available from [`Self::log`].
    pub fn compile(&self, options: &CompileOptions<'_>) -> Result<()> {
        options.validate()?;
        let arguments = options.as_arguments();
        let argument_refs = arguments.iter().map(String::as_str).collect::<Vec<_>>();
        self.compile_raw(sys::nvvmCompileProgram, &argument_refs)
    }

    /// Validates `options` and verifies the added NVVM IR modules.
    ///
    /// # Errors
    ///
    /// Returns an error if `options.gpu_architecture` is a concrete GPU target, an option contains an interior NUL, the option count does not fit an `i32`, or NVVM rejects the options or finds invalid IR.
    /// Verification diagnostics are available from [`Self::log`].
    pub fn verify(&self, options: &CompileOptions<'_>) -> Result<()> {
        options.validate()?;
        let arguments = options.as_arguments();
        let argument_refs = arguments.iter().map(String::as_str).collect::<Vec<_>>();
        self.compile_raw(sys::nvvmVerifyProgram, &argument_refs)
    }

    /// Returns owned bytes of the last compiled PTX or link-time IR output.
    /// Native PTX output includes its trailing NUL byte.
    ///
    /// # Errors
    ///
    /// Returns an error if NVVM cannot query or copy the requested output, or the returned byte count cannot be represented as `usize`.
    pub fn compiled_result(&self) -> Result<Vec<u8>> {
        self.bytes(sys::nvvmGetCompiledResultSize, sys::nvvmGetCompiledResult)
    }

    /// Copies the last compiled PTX output into an owned module image.
    ///
    /// # Errors
    ///
    /// Returns an error if NVVM cannot query or copy the requested output, the returned byte count cannot be represented as `usize`, or the output is empty.
    /// Returns `Error::InteriorNul` if the output contains a NUL byte before its end, which rejects binary link-time IR.
    pub fn compiled_image(&self) -> Result<ModuleImage<'static>> {
        ModuleImage::from_ptx(self.compiled_result()?)
    }

    /// Interprets the last compiled output as text, removing a trailing NUL and replacing invalid UTF-8 lossily.
    /// Intended for PTX output.
    ///
    /// # Errors
    ///
    /// Returns an error if NVVM cannot query or copy the requested output, or the returned byte count cannot be represented as `usize`.
    pub fn compiled_string(&self) -> Result<String> {
        Ok(bytes_to_string(self.compiled_result()?))
    }

    /// Returns the compiler or verification log, removing a trailing NUL and replacing invalid UTF-8 lossily.
    ///
    /// # Errors
    ///
    /// Returns an error if NVVM cannot query or copy the requested output, or the returned byte count cannot be represented as `usize`.
    pub fn log(&self) -> Result<String> {
        Ok(bytes_to_string(self.bytes(
            sys::nvvmGetProgramLogSize,
            sys::nvvmGetProgramLog,
        )?))
    }

    /// Borrows the native program handle without transferring ownership.
    /// It remains valid until the wrapper is dropped or converted with [`Self::into_raw`].
    #[must_use]
    pub const fn as_raw(&self) -> sys::nvvmProgram {
        self.handle
    }

    /// Transfers ownership of the NVVM program to the caller.
    ///
    /// The caller becomes responsible for destroying it.
    #[must_use]
    pub fn into_raw(self) -> RawProgram {
        let handle = self.handle;
        mem::forget(self);
        RawProgram { handle }
    }

    fn add_module_raw(&mut self, module: &Module<'_>, lazy: bool) -> Result<()> {
        if module.ir.is_empty() {
            return Err(Error::empty("nvvm module ir"));
        }

        let name = CString::new(module.name)?;
        let function = if lazy {
            sys::nvvmLazyAddModuleToProgram
        } else {
            sys::nvvmAddModuleToProgram
        };

        let size = to_c_ulong(module.ir.len(), "nvvm module size")?;
        // SAFETY: `self` owns the live program exclusively, and the counted IR bytes and NUL-terminated name are borrowed for the call.
        unsafe {
            try_nvvm!(function(
                self.handle,
                module.ir.as_ptr().cast(),
                size,
                name.as_ptr(),
            ))
        }
    }

    fn compile_raw(
        &self,
        function: unsafe extern "C" fn(
            sys::nvvmProgram,
            i32,
            *mut *const c_char,
        ) -> sys::nvvmResult,
        options: &[&str],
    ) -> Result<()> {
        let options = options
            .iter()
            .map(|option| CString::new(*option))
            .collect::<result::Result<Vec<_>, _>>()?;
        let mut option_ptrs = options
            .iter()
            .map(|value| value.as_ptr())
            .collect::<Vec<_>>();

        // SAFETY: `self` owns the live program, and `option_ptrs` holds the counted NUL-terminated options in `options`, which outlive the call.
        unsafe {
            try_nvvm!(function(
                self.handle,
                to_i32(option_ptrs.len(), "NVVM option count")?,
                if option_ptrs.is_empty() {
                    ptr::null_mut()
                } else {
                    option_ptrs.as_mut_ptr()
                },
            ))
        }
    }

    fn bytes(
        &self,
        get_size: unsafe extern "C" fn(sys::nvvmProgram, *mut u64) -> sys::nvvmResult,
        get_data: unsafe extern "C" fn(sys::nvvmProgram, *mut c_char) -> sys::nvvmResult,
    ) -> Result<Vec<u8>> {
        let mut size = 0;
        // SAFETY: `self` owns the live program, and `size` is a local output.
        unsafe {
            try_nvvm!(get_size(self.handle, &raw mut size))?;
        }

        let mut bytes = vec![0u8; to_usize(size, "NVVM output byte count")?];
        if bytes.is_empty() {
            return Ok(bytes);
        }

        // SAFETY: `bytes` holds the `size` bytes NVVM reported for the same output of the live program.
        unsafe {
            try_nvvm!(get_data(self.handle, bytes.as_mut_ptr().cast()))?;
        }
        Ok(bytes)
    }
}

impl Drop for Program {
    fn drop(&mut self) {
        // SAFETY: this wrapper owns the non-null program, and NVVM nulls the handle field it destroys.
        unsafe {
            if !self.handle.is_null()
                && let Err(error) = try_nvvm!(sys::nvvmDestroyProgram(&raw mut self.handle))
            {
                report_cleanup_failure("destroy", "nvvm program", &error);
            }
        }
    }
}

/// Returns the loaded NVVM compiler library version.
///
/// # Errors
///
/// Returns an error if NVVM cannot report its library version.
pub fn version() -> Result<LibraryVersion> {
    let mut major = 0;
    let mut minor = 0;
    // SAFETY: `major` and `minor` are local outputs.
    unsafe {
        try_nvvm!(sys::nvvmVersion(&raw mut major, &raw mut minor))?;
    }
    LibraryVersion::from_properties(major, minor, 0)
        .ok_or_else(|| Error::out_of_range("nvvm version"))
}

/// Returns the NVVM IR and debug metadata versions supported by the loaded compiler.
///
/// # Errors
///
/// Returns an error if NVVM cannot report its supported IR versions.
pub fn ir_version() -> Result<IrVersion> {
    let mut major = 0;
    let mut minor = 0;
    let mut debug_major = 0;
    let mut debug_minor = 0;
    // SAFETY: the four versions are local outputs.
    unsafe {
        try_nvvm!(sys::nvvmIRVersion(
            &raw mut major,
            &raw mut minor,
            &raw mut debug_major,
            &raw mut debug_minor,
        ))?;
    }
    Ok(IrVersion {
        major,
        minor,
        debug_major,
        debug_minor,
    })
}

/// Returns the LLVM major version supported for a virtual GPU architecture.
///
/// # Errors
///
/// Returns an error if `architecture` is a concrete target or NVVM cannot report the version.
pub fn llvm_version(architecture: GpuArchitecture) -> Result<i32> {
    if !architecture.is_virtual() {
        return Err(Error::UnsupportedArchitecture {
            target: architecture.to_string(),
        });
    }
    llvm_version_for_architecture(&architecture.to_string())
}

/// Returns the LLVM major version supported for the supplied native architecture string.
///
/// # Errors
///
/// Returns an error if `architecture` contains an interior NUL or NVVM rejects the architecture or version query.
pub fn llvm_version_for_architecture(architecture: &str) -> Result<i32> {
    let architecture = CString::new(architecture)?;
    let mut major = 0;
    // SAFETY: `architecture` is a NUL-terminated string borrowed for the call, and `major` is a local output.
    unsafe {
        try_nvvm!(sys::nvvmLLVMVersion(architecture.as_ptr(), &raw mut major,))?;
    }
    Ok(major)
}

fn flag_bit(value: bool) -> u8 {
    u8::from(value)
}

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

    #[test]
    fn test_compile_options_build_expected_arguments() {
        let options = CompileOptions::new()
            .device_debug(true)
            .optimization_level(OptimizationLevel::Zero)
            .gpu_architecture(GpuArchitecture::Compute90)
            .flush_to_zero(true)
            .precise_square_root(false)
            .precise_division(true)
            .fma(false)
            .jump_table_density(200)
            .generate_lto(true)
            .raw_option("-custom");

        assert_eq!(
            options.as_arguments(),
            vec![
                "-g",
                "-opt=0",
                "-arch=compute_90",
                "-ftz=1",
                "-prec-sqrt=0",
                "-prec-div=1",
                "-fma=0",
                "-jump-table-density=101",
                "-gen-lto",
                "-custom",
            ]
        );
    }

    #[test]
    fn test_version_queries_are_available() {
        let version = version().unwrap();
        assert!(version.major() > 0);

        let ir_version = ir_version().unwrap();
        assert!(ir_version.major > 0);

        let llvm_version = llvm_version(GpuArchitecture::Compute90).unwrap();
        assert!(llvm_version > 0);
    }

    #[test]
    fn test_real_architecture_is_rejected_for_nvvm_options() {
        let options = CompileOptions::new().gpu_architecture(GpuArchitecture::Sm90);
        assert!(matches!(
            options.validate(),
            Err(Error::UnsupportedArchitecture { .. })
        ));
        assert!(matches!(
            llvm_version(GpuArchitecture::Sm90),
            Err(Error::UnsupportedArchitecture { .. })
        ));
    }
}