1use std::{
4 ffi::{CString, c_char},
5 mem, ptr, result,
6};
7
8use singe_core::{LibraryVersion, impl_enum_display, report_cleanup_failure};
9use singe_cuda_sys::nvvm as sys;
10
11use crate::{
12 architecture::GpuArchitecture,
13 error::{Error, Result},
14 module::ModuleImage,
15 try_nvvm,
16 utility::{bytes_to_string, to_c_ulong, to_i32, to_usize},
17};
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub struct IrVersion {
22 pub major: i32,
24 pub minor: i32,
26 pub debug_major: i32,
28 pub debug_minor: i32,
30}
31
32singe_core::wrapper_status! {
33 library = "nvvm",
34 error = Error::Nvvm,
35 raw = sys::nvvmResult,
36 success = NVVM_SUCCESS,
37 absence = singe_cuda_sys::take_absence,
38 check = check_nvvm,
39 unknown = "UNKNOWN_NVVM_STATUS",
40 description = sys::nvvmGetErrorString,
41 pub enum Status: u32 {
43 Success = NVVM_SUCCESS,
45 OutOfMemory = NVVM_ERROR_OUT_OF_MEMORY,
47 ProgramCreationFailure = NVVM_ERROR_PROGRAM_CREATION_FAILURE,
49 IrVersionMismatch = NVVM_ERROR_IR_VERSION_MISMATCH,
51 InvalidInput = NVVM_ERROR_INVALID_INPUT,
53 InvalidProgram = NVVM_ERROR_INVALID_PROGRAM,
55 InvalidIr = NVVM_ERROR_INVALID_IR,
57 InvalidOption = NVVM_ERROR_INVALID_OPTION,
59 NoModuleInProgram = NVVM_ERROR_NO_MODULE_IN_PROGRAM,
61 Compilation = NVVM_ERROR_COMPILATION,
63 Cancelled = NVVM_ERROR_CANCELLED,
65 }
66}
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
70#[non_exhaustive]
71pub enum OptimizationLevel {
72 Zero,
74 Three,
76}
77
78impl_enum_display!(OptimizationLevel, {
79 Self::Zero => "0",
80 Self::Three => "3",
81});
82
83#[derive(Debug, Clone, Default)]
87pub struct CompileOptions<'a> {
88 pub device_debug: bool,
91 pub optimization_level: Option<OptimizationLevel>,
93 pub gpu_architecture: Option<GpuArchitecture>,
96 pub flush_to_zero: Option<bool>,
98 pub precise_square_root: Option<bool>,
100 pub precise_division: Option<bool>,
102 pub fma: Option<bool>,
104 pub jump_table_density: Option<u8>,
107 pub generate_lto: bool,
109 pub raw_options: Vec<&'a str>,
111}
112
113impl<'a> CompileOptions<'a> {
114 #[must_use]
116 pub const fn new() -> Self {
117 Self {
118 device_debug: false,
119 optimization_level: None,
120 gpu_architecture: None,
121 flush_to_zero: None,
122 precise_square_root: None,
123 precise_division: None,
124 fma: None,
125 jump_table_density: None,
126 generate_lto: false,
127 raw_options: Vec::new(),
128 }
129 }
130
131 #[must_use]
134 pub fn device_debug(mut self, value: bool) -> Self {
135 self.device_debug = value;
136 self
137 }
138
139 #[must_use]
141 pub fn optimization_level(mut self, value: OptimizationLevel) -> Self {
142 self.optimization_level = Some(value);
143 self
144 }
145
146 #[must_use]
149 pub fn gpu_architecture(mut self, value: GpuArchitecture) -> Self {
150 self.gpu_architecture = Some(value);
151 self
152 }
153
154 #[must_use]
156 pub fn flush_to_zero(mut self, value: bool) -> Self {
157 self.flush_to_zero = Some(value);
158 self
159 }
160
161 #[must_use]
163 pub fn precise_square_root(mut self, value: bool) -> Self {
164 self.precise_square_root = Some(value);
165 self
166 }
167
168 #[must_use]
170 pub fn precise_division(mut self, value: bool) -> Self {
171 self.precise_division = Some(value);
172 self
173 }
174
175 #[must_use]
177 pub fn fma(mut self, value: bool) -> Self {
178 self.fma = Some(value);
179 self
180 }
181
182 #[must_use]
184 pub fn jump_table_density(mut self, value: u8) -> Self {
185 self.jump_table_density = Some(value.min(101));
186 self
187 }
188
189 #[must_use]
191 pub fn generate_lto(mut self, value: bool) -> Self {
192 self.generate_lto = value;
193 self
194 }
195
196 #[must_use]
198 pub fn raw_option(mut self, value: &'a str) -> Self {
199 self.raw_options.push(value);
200 self
201 }
202
203 #[must_use]
205 pub fn as_arguments(&self) -> Vec<String> {
206 let mut arguments = Vec::new();
207 if self.device_debug {
208 arguments.push(String::from("-g"));
209 }
210
211 if let Some(value) = self.optimization_level {
212 arguments.push(format!("-opt={value}"));
213 }
214
215 if let Some(value) = self.gpu_architecture {
216 arguments.push(format!("-arch={value}"));
217 }
218
219 if let Some(value) = self.flush_to_zero {
220 arguments.push(format!("-ftz={}", flag_bit(value)));
221 }
222
223 if let Some(value) = self.precise_square_root {
224 arguments.push(format!("-prec-sqrt={}", flag_bit(value)));
225 }
226
227 if let Some(value) = self.precise_division {
228 arguments.push(format!("-prec-div={}", flag_bit(value)));
229 }
230
231 if let Some(value) = self.fma {
232 arguments.push(format!("-fma={}", flag_bit(value)));
233 }
234
235 if let Some(value) = self.jump_table_density {
236 arguments.push(format!("-jump-table-density={value}"));
237 }
238
239 if self.generate_lto {
240 arguments.push(String::from("-gen-lto"));
241 }
242
243 arguments.extend(self.raw_options.iter().map(|value| (*value).to_string()));
244 arguments
245 }
246
247 fn validate(&self) -> Result<()> {
248 if let Some(architecture) = self.gpu_architecture
249 && !architecture.is_virtual()
250 {
251 return Err(Error::UnsupportedArchitecture {
252 target: architecture.to_string(),
253 });
254 }
255 Ok(())
256 }
257}
258
259#[derive(Debug, Clone, Copy)]
261pub struct Module<'a> {
262 pub ir: &'a [u8],
264 pub name: &'a str,
267}
268
269#[derive(Debug)]
272pub struct Program {
273 handle: sys::nvvmProgram,
274}
275
276#[derive(Debug)]
280pub struct RawProgram {
281 pub handle: sys::nvvmProgram,
283}
284
285impl Program {
286 pub fn create() -> Result<Self> {
292 let mut handle = ptr::null_mut();
293 unsafe {
295 try_nvvm!(sys::nvvmCreateProgram(&raw mut handle))?;
296 }
297
298 if handle.is_null() {
299 return Err(Error::NullHandle);
300 }
301 Ok(Self { handle })
302 }
303
304 #[expect(
315 clippy::needless_pass_by_value,
316 reason = "taking the raw owner by value transfers ownership of its handle"
317 )]
318 pub unsafe fn from_raw(raw: RawProgram) -> Result<Self> {
319 if raw.handle.is_null() {
320 return Err(Error::NullHandle);
321 }
322
323 Ok(Self { handle: raw.handle })
324 }
325
326 pub fn add_module(&mut self, module: Module<'_>) -> Result<()> {
332 self.add_module_raw(&module, false)
333 }
334
335 pub fn lazy_add_module(&mut self, module: Module<'_>) -> Result<()> {
342 self.add_module_raw(&module, true)
343 }
344
345 pub fn compile(&self, options: &CompileOptions<'_>) -> Result<()> {
353 options.validate()?;
354 let arguments = options.as_arguments();
355 let argument_refs = arguments.iter().map(String::as_str).collect::<Vec<_>>();
356 self.compile_raw(sys::nvvmCompileProgram, &argument_refs)
357 }
358
359 pub fn verify(&self, options: &CompileOptions<'_>) -> Result<()> {
366 options.validate()?;
367 let arguments = options.as_arguments();
368 let argument_refs = arguments.iter().map(String::as_str).collect::<Vec<_>>();
369 self.compile_raw(sys::nvvmVerifyProgram, &argument_refs)
370 }
371
372 pub fn compiled_result(&self) -> Result<Vec<u8>> {
379 self.bytes(sys::nvvmGetCompiledResultSize, sys::nvvmGetCompiledResult)
380 }
381
382 pub fn compiled_image(&self) -> Result<ModuleImage<'static>> {
389 ModuleImage::from_ptx(self.compiled_result()?)
390 }
391
392 pub fn compiled_string(&self) -> Result<String> {
399 Ok(bytes_to_string(self.compiled_result()?))
400 }
401
402 pub fn log(&self) -> Result<String> {
408 Ok(bytes_to_string(self.bytes(
409 sys::nvvmGetProgramLogSize,
410 sys::nvvmGetProgramLog,
411 )?))
412 }
413
414 #[must_use]
417 pub const fn as_raw(&self) -> sys::nvvmProgram {
418 self.handle
419 }
420
421 #[must_use]
425 pub fn into_raw(self) -> RawProgram {
426 let handle = self.handle;
427 mem::forget(self);
428 RawProgram { handle }
429 }
430
431 fn add_module_raw(&mut self, module: &Module<'_>, lazy: bool) -> Result<()> {
432 if module.ir.is_empty() {
433 return Err(Error::empty("nvvm module ir"));
434 }
435
436 let name = CString::new(module.name)?;
437 let function = if lazy {
438 sys::nvvmLazyAddModuleToProgram
439 } else {
440 sys::nvvmAddModuleToProgram
441 };
442
443 let size = to_c_ulong(module.ir.len(), "nvvm module size")?;
444 unsafe {
446 try_nvvm!(function(
447 self.handle,
448 module.ir.as_ptr().cast(),
449 size,
450 name.as_ptr(),
451 ))
452 }
453 }
454
455 fn compile_raw(
456 &self,
457 function: unsafe extern "C" fn(
458 sys::nvvmProgram,
459 i32,
460 *mut *const c_char,
461 ) -> sys::nvvmResult,
462 options: &[&str],
463 ) -> Result<()> {
464 let options = options
465 .iter()
466 .map(|option| CString::new(*option))
467 .collect::<result::Result<Vec<_>, _>>()?;
468 let mut option_ptrs = options
469 .iter()
470 .map(|value| value.as_ptr())
471 .collect::<Vec<_>>();
472
473 unsafe {
475 try_nvvm!(function(
476 self.handle,
477 to_i32(option_ptrs.len(), "NVVM option count")?,
478 if option_ptrs.is_empty() {
479 ptr::null_mut()
480 } else {
481 option_ptrs.as_mut_ptr()
482 },
483 ))
484 }
485 }
486
487 fn bytes(
488 &self,
489 get_size: unsafe extern "C" fn(sys::nvvmProgram, *mut u64) -> sys::nvvmResult,
490 get_data: unsafe extern "C" fn(sys::nvvmProgram, *mut c_char) -> sys::nvvmResult,
491 ) -> Result<Vec<u8>> {
492 let mut size = 0;
493 unsafe {
495 try_nvvm!(get_size(self.handle, &raw mut size))?;
496 }
497
498 let mut bytes = vec![0u8; to_usize(size, "NVVM output byte count")?];
499 if bytes.is_empty() {
500 return Ok(bytes);
501 }
502
503 unsafe {
505 try_nvvm!(get_data(self.handle, bytes.as_mut_ptr().cast()))?;
506 }
507 Ok(bytes)
508 }
509}
510
511impl Drop for Program {
512 fn drop(&mut self) {
513 unsafe {
515 if !self.handle.is_null()
516 && let Err(error) = try_nvvm!(sys::nvvmDestroyProgram(&raw mut self.handle))
517 {
518 report_cleanup_failure("destroy", "nvvm program", &error);
519 }
520 }
521 }
522}
523
524pub fn version() -> Result<LibraryVersion> {
530 let mut major = 0;
531 let mut minor = 0;
532 unsafe {
534 try_nvvm!(sys::nvvmVersion(&raw mut major, &raw mut minor))?;
535 }
536 LibraryVersion::from_properties(major, minor, 0)
537 .ok_or_else(|| Error::out_of_range("nvvm version"))
538}
539
540pub fn ir_version() -> Result<IrVersion> {
546 let mut major = 0;
547 let mut minor = 0;
548 let mut debug_major = 0;
549 let mut debug_minor = 0;
550 unsafe {
552 try_nvvm!(sys::nvvmIRVersion(
553 &raw mut major,
554 &raw mut minor,
555 &raw mut debug_major,
556 &raw mut debug_minor,
557 ))?;
558 }
559 Ok(IrVersion {
560 major,
561 minor,
562 debug_major,
563 debug_minor,
564 })
565}
566
567pub fn llvm_version(architecture: GpuArchitecture) -> Result<i32> {
573 if !architecture.is_virtual() {
574 return Err(Error::UnsupportedArchitecture {
575 target: architecture.to_string(),
576 });
577 }
578 llvm_version_for_architecture(&architecture.to_string())
579}
580
581pub fn llvm_version_for_architecture(architecture: &str) -> Result<i32> {
587 let architecture = CString::new(architecture)?;
588 let mut major = 0;
589 unsafe {
591 try_nvvm!(sys::nvvmLLVMVersion(architecture.as_ptr(), &raw mut major,))?;
592 }
593 Ok(major)
594}
595
596fn flag_bit(value: bool) -> u8 {
597 u8::from(value)
598}
599
600#[cfg(test)]
601mod tests {
602 use super::*;
603
604 #[test]
605 fn test_compile_options_build_expected_arguments() {
606 let options = CompileOptions::new()
607 .device_debug(true)
608 .optimization_level(OptimizationLevel::Zero)
609 .gpu_architecture(GpuArchitecture::Compute90)
610 .flush_to_zero(true)
611 .precise_square_root(false)
612 .precise_division(true)
613 .fma(false)
614 .jump_table_density(200)
615 .generate_lto(true)
616 .raw_option("-custom");
617
618 assert_eq!(
619 options.as_arguments(),
620 vec![
621 "-g",
622 "-opt=0",
623 "-arch=compute_90",
624 "-ftz=1",
625 "-prec-sqrt=0",
626 "-prec-div=1",
627 "-fma=0",
628 "-jump-table-density=101",
629 "-gen-lto",
630 "-custom",
631 ]
632 );
633 }
634
635 #[test]
636 fn test_version_queries_are_available() {
637 let version = version().unwrap();
638 assert!(version.major() > 0);
639
640 let ir_version = ir_version().unwrap();
641 assert!(ir_version.major > 0);
642
643 let llvm_version = llvm_version(GpuArchitecture::Compute90).unwrap();
644 assert!(llvm_version > 0);
645 }
646
647 #[test]
648 fn test_real_architecture_is_rejected_for_nvvm_options() {
649 let options = CompileOptions::new().gpu_architecture(GpuArchitecture::Sm90);
650 assert!(matches!(
651 options.validate(),
652 Err(Error::UnsupportedArchitecture { .. })
653 ));
654 assert!(matches!(
655 llvm_version(GpuArchitecture::Sm90),
656 Err(Error::UnsupportedArchitecture { .. })
657 ));
658 }
659}