Documentation
¶
Overview ¶
Package nvrtc provides low-level Go bindings for NVIDIA Runtime Compilation (NVRTC).
NVRTC compiles CUDA C++ source code to PTX, cubin, or LTO-IR at runtime, enabling just-in-time kernel compilation without a separate nvcc invocation.
The central type is Program. Create one with CreateProgram, compile with Program.Compile, and retrieve output with Program.PTX or Program.CUBIN. Clean up with Program.Destroy.
This package provides bindings generated from nvrtc.h using github.com/ebitengine/purego for cgo-free dynamic loading of libnvrtc. Functions returning a C status report errors wrapping nvrtcResult with descriptive messages from nvrtcGetErrorString.
Library search ¶
Load opens the path it is given. With an empty path it opens the path in NVRTC_LIB_PATH, if that is set. A path named either way is the only one tried: if it does not load, Load returns the error.
Otherwise Load, or the first call that needs the library, tries in order:
- the copy in the toolkit that CUDA_HOME names, then the one that CUDA_PATH names
- the system library names, which the dynamic loader resolves
- the copy in each installed /usr/local/cuda-N.M toolkit, newest first, then /usr/local/cuda
- the system library names in the directories pkg-config reports for nvrtc
A library whose version these bindings do not accept is skipped.
Name Expressions ¶
- Program.AddNameExpression: Program.AddNameExpression notes the given name expression denoting the address of a global function or device/__constant__ variable.
- Program.LoweredName: Program.LoweredName extracts the lowered (mangled) name for a global function or device/__constant__ variable, and updates *lowered_name to point to it.
Compilation ¶
- Program.Compile: Program.Compile compiles the given program.
Program Management ¶
- CreateProgram: CreateProgram creates an instance of Program with the given input parameters, and sets the output parameter prog with it.
- Program.Destroy: Program.Destroy destroys the given program.
Bundled Headers ¶
- GetBundledHeadersInfo: GetBundledHeadersInfo queries information about the bundled headers without extracting them.
- InstallBundledHeaders: InstallBundledHeaders extracts CUDA headers bundled with NVRTC to a specified directory for use during compilation.
- RemoveBundledHeaders: RemoveBundledHeaders removes previously installed bundled headers.
Output Retrieval ¶
- Program.CUBIN: Program.CUBIN stores the cubin generated by the previous compilation of prog in the memory pointed by cubin.
- Program.CUBINSize: Program.CUBINSize sets the value of cubinSizeRet with the size of the cubin generated by the previous compilation of prog.
- Program.LTOIR: Program.LTOIR stores the LTO IR generated by the previous compilation of prog in the memory pointed by LTOIR.
- Program.LTOIRSize: Program.LTOIRSize sets the value of LTOIRSizeRet with the size of the LTO IR generated by the previous compilation of prog.
- Program.OptiXIR: Program.OptiXIR stores the OptiX IR generated by the previous compilation of prog in the memory pointed by optixir.
- Program.OptiXIRSize: Program.OptiXIRSize sets the value of optixirSizeRet with the size of the OptiX IR generated by the previous compilation of prog.
- Program.PTX: Program.PTX stores the PTX generated by the previous compilation of prog in the memory pointed by ptx.
- Program.PTXSize: Program.PTXSize sets the value of ptxSizeRet with the size of the PTX generated by the previous compilation of prog (including the trailing NULL).
- Program.Log: Program.Log stores the log generated by the previous compilation of prog in the memory pointed by log.
- Program.LogSize: Program.LogSize sets logSizeRet with the size of the log generated by the previous compilation of prog (including the trailing NULL).
- Program.TileIR: Program.TileIR stores the cuda_tile IR generated by the previous compilation of prog in the memory pointed by TileIR.
- Program.TileIRSize: Program.TileIRSize sets the value of TileIRSizeRet with the size of the cuda_tile IR generated by the previous compilation of prog.
Architecture Queries ¶
- GetNumSupportedArchs: GetNumSupportedArchs sets the output parameter numArchs with the number of architectures supported by NVRTC.
- GetSupportedArchs: GetSupportedArchs populates the array passed via the output parameter supportedArchs with the architectures supported by NVRTC.
Version Queries ¶
- Version: Version sets the output parameters major and minor with the CUDA Runtime Compilation version number.
Other ¶
- Program.PCHCreateStatus: returns the PCH creation status.
- GetPCHHeapSize: retrieve the current size of the PCH Heap.
- Program.PCHHeapSizeRequired: retrieve the required size of the PCH heap required to compile the given program.
- Program.SetFlowCallback: Program.SetFlowCallback registers a callback function that the compiler will invoke at different points during a call to Program.Compile, and the callback function can decide whether to cancel compilation by returning specific values.
- SetPCHHeapSize: set the size of the PCH Heap.
Example ¶
Example compiles a CUDA kernel to PTX at runtime. It returns early when the NVRTC library is not available. The resulting PTX can be loaded and launched with the driver package. It has no Output comment, so it is compiled but not run: what it prints depends on the host's NVRTC.
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/nvrtc"
)
func main() {
major, minor, err := nvrtc.Version()
if err != nil {
fmt.Println("NVRTC unavailable:", err)
return
}
const src = `
extern "C" __global__ void saxpy(float a, float *x, float *y, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) y[i] = a*x[i] + y[i];
}`
prog, err := nvrtc.CreateProgram(src, "saxpy.cu")
if err != nil {
fmt.Println("create:", err)
return
}
defer prog.Destroy()
if err := prog.Compile("--gpu-architecture=compute_70"); err != nil {
log, _ := prog.Log()
fmt.Printf("compile: %v\n%s", err, log)
return
}
ptx, err := prog.PTX()
if err != nil {
fmt.Println("ptx:", err)
return
}
fmt.Printf("NVRTC %d.%d compiled %d bytes of PTX\n", major, minor, len(ptx))
}
Output:
Index ¶
- Constants
- Variables
- func Close() error
- func ComputeArch(major, minor int) string
- func GetNumSupportedArchs() (int32, error)
- func GetPCHHeapSize() (uint, error)
- func GetSupportedArchs(supportedArchs *int32) error
- func Has(symbol string) bool
- func HasAddNameExpression() bool
- func HasCompileProgram() bool
- func HasCreateProgram() bool
- func HasDestroyProgram() bool
- func HasGetBundledHeadersInfo() bool
- func HasGetCUBIN() bool
- func HasGetCUBINSize() bool
- func HasGetErrorString() bool
- func HasGetLTOIR() bool
- func HasGetLTOIRSize() bool
- func HasGetLoweredName() bool
- func HasGetNVVM() bool
- func HasGetNVVMSize() bool
- func HasGetNumSupportedArchs() bool
- func HasGetOptiXIR() bool
- func HasGetOptiXIRSize() bool
- func HasGetPCHCreateStatus() bool
- func HasGetPCHHeapSize() bool
- func HasGetPCHHeapSizeRequired() bool
- func HasGetPTX() bool
- func HasGetPTXSize() bool
- func HasGetProgramLog() bool
- func HasGetProgramLogSize() bool
- func HasGetSupportedArchs() bool
- func HasGetTileIR() bool
- func HasGetTileIRSize() bool
- func HasInstallBundledHeaders() bool
- func HasRemoveBundledHeaders() bool
- func HasSetFlowCallback() bool
- func HasSetPCHHeapSize() bool
- func HasVersion() bool
- func InstallBundledHeaders(installPath string, flags uint32) error
- func Load(path string) error
- func Loaded() bool
- func Path() string
- func RemoveBundledHeaders(installPath string) error
- func SetPCHHeapSize(size uint) error
- func SmArch(major, minor int) string
- func ValidateOption(flag string) error
- func Version() (major int32, minor int32, err error)
- type BindFailure
- type BundledHeadersInfo
- type CallError
- type Header
- type LibraryAttempt
- type LibraryConflictError
- type LibraryError
- type OptionDef
- type Program
- func (p Program) AddNameExpression(nameExpression *byte) error
- func (p Program) CUBIN() ([]byte, error)
- func (p Program) CUBINSize() (uint, error)
- func (p Program) Compile(options ...string) error
- func (p *Program) Destroy() error
- func (p Program) LTOIR() ([]byte, error)
- func (p Program) LTOIRSize() (uint, error)
- func (p Program) Log() (string, error)
- func (p Program) LogSize() (uint, error)
- func (p Program) LoweredName(nameExpression *byte, loweredName **byte) error
- func (p Program) NVVM() ([]byte, error)deprecated
- func (p Program) NVVMSize() (uint, error)deprecated
- func (p Program) OptiXIR() ([]byte, error)
- func (p Program) OptiXIRSize() (uint, error)
- func (p Program) PCHCreateStatus() error
- func (p Program) PCHHeapSizeRequired() (uint, error)
- func (p Program) PTX() ([]byte, error)
- func (p Program) PTXSize() (uint, error)
- func (p Program) SetFlowCallback(callback uintptr, payload uintptr) error
- func (p Program) TileIR() ([]byte, error)
- func (p Program) TileIRSize() (uint, error)
- type Result
- type SymbolError
- type VersionMismatchError
Examples ¶
Constants ¶
const ( InstallHeadersForceOverwrite uint32 = 0x1 InstallHeadersNoWait uint32 = 0x2 InstallHeadersSkipIfExists uint32 = 0x0 )
Flags for InstallBundledHeaders.
const ( // FlagGpuArchitecture selects --gpu-architecture. FlagGpuArchitecture = "--gpu-architecture" // FlagStd selects -std. FlagStd = "-std" // FlagUseFastMath selects --use_fast_math. FlagUseFastMath = "--use_fast_math" // FlagFtz selects -ftz. FlagFtz = "-ftz" // FlagPrecDiv selects -prec-div. FlagPrecDiv = "-prec-div" // FlagPrecSqrt selects -prec-sqrt. FlagPrecSqrt = "-prec-sqrt" // FlagFmad selects -fmad. FlagFmad = "-fmad" // FlagDeviceAsDefaultExecutionSpace selects --device-as-default-execution-space. FlagDeviceAsDefaultExecutionSpace = "--device-as-default-execution-space" // FlagDeviceDebug selects --device-debug. FlagDeviceDebug = "--device-debug" // FlagGenerateLineInfo selects --generate-line-info. FlagGenerateLineInfo = "--generate-line-info" // FlagRelocatableDeviceCode selects --relocatable-device-code. FlagRelocatableDeviceCode = "--relocatable-device-code" // FlagMaxrregcount selects --maxrregcount. FlagMaxrregcount = "--maxrregcount" // FlagExtraDeviceVectorization selects --extra-device-vectorization. FlagExtraDeviceVectorization = "--extra-device-vectorization" // FlagDisableWarnings selects -w. FlagDisableWarnings = "-w" // FlagWarningAsError selects --warning-as-error. FlagWarningAsError = "--warning-as-error" // FlagIncludePath selects --include-path. FlagIncludePath = "--include-path" // FlagDefineMacro selects -D. FlagDefineMacro = "-D" // FlagUndefineMacro selects -U. FlagUndefineMacro = "-U" // FlagPreInclude selects --pre-include. FlagPreInclude = "--pre-include" // FlagDLTO selects -dlto. FlagDLTO = "-dlto" // FlagTileOnly selects --tile-only. FlagTileOnly = "--tile-only" // FlagEnableTile selects --enable-tile. FlagEnableTile = "--enable-tile" // FlagOptiXIR selects --optix-ir. FlagOptiXIR = "--optix-ir" // FlagPCH selects -pch. FlagPCH = "-pch" // FlagCreatePCH selects --create-pch. FlagCreatePCH = "--create-pch" // FlagUsePCH selects --use-pch. FlagUsePCH = "--use-pch" // FlagOfastCompile selects --Ofast-compile. FlagOfastCompile = "--Ofast-compile" // FlagRandomSeed selects --frandom-seed. FlagRandomSeed = "--frandom-seed" // FlagExtensibleWholeProgram selects --extensible-whole-program. FlagExtensibleWholeProgram = "--extensible-whole-program" // FlagDeviceStackProtector selects --device-stack-protector. FlagDeviceStackProtector = "--device-stack-protector" // FlagTime selects --time. FlagTime = "--time" // FlagNoCache selects --no-cache. FlagNoCache = "--no-cache" )
Standard compiler flag constants accepted by NVRTC.
const ( StdCXX03 = "c++03" StdCXX11 = "c++11" StdCXX14 = "c++14" StdCXX17 = "c++17" StdCXX20 = "c++20" // StdCXX23 selects -std=c++23. StdCXX23 = "c++23" )
C++ language standards accepted by NVRTC -std flag.
const ( FastCompile0 = "0" FastCompileMin = "min" FastCompileMid = "mid" FastCompileMax = "max" )
Fast compilation levels accepted by NVRTC --Ofast-compile flag.
Variables ¶
var SupportedOptions = []OptionDef{ {Name: "--gpu-architecture", Short: "-arch", Arity: "value", Default: "", Values: []string{"all", "all-major", "compute_100", "compute_100a", "compute_100f", "compute_103", "compute_103a", "compute_103f", "compute_107", "compute_107a", "compute_107f", "compute_110", "compute_110a", "compute_110f", "compute_120", "compute_120a", "compute_120f", "compute_121", "compute_121a", "compute_121f", "compute_75", "compute_80", "compute_86", "compute_87", "compute_88", "compute_89", "compute_90", "compute_90a", "lto_100", "lto_100a", "lto_100f", "lto_103", "lto_103a", "lto_103f", "lto_107", "lto_107a", "lto_107f", "lto_110", "lto_110a", "lto_110f", "lto_120", "lto_120a", "lto_120f", "lto_121", "lto_121a", "lto_121f", "lto_75", "lto_80", "lto_86", "lto_87", "lto_88", "lto_89", "lto_90", "lto_90a", "native", "sm_100", "sm_100a", "sm_100f", "sm_103", "sm_103a", "sm_103f", "sm_107", "sm_107a", "sm_107f", "sm_110", "sm_110a", "sm_110f", "sm_120", "sm_120a", "sm_120f", "sm_121", "sm_121a", "sm_121f", "sm_75", "sm_80", "sm_86", "sm_87", "sm_88", "sm_89", "sm_90", "sm_90a"}}, {Name: "-std", Short: "--std", Arity: "value", Default: "", Values: []string{"c++03", "c++11", "c++14", "c++17", "c++20", "c++23"}}, {Name: "--use_fast_math", Short: "-use_fast_math", Arity: "bare", Default: ""}, {Name: "-ftz", Short: "--ftz", Arity: "value", Default: "false", Values: []string{"true", "false"}}, {Name: "-prec-div", Short: "--prec-div", Arity: "value", Default: "true", Values: []string{"true", "false"}}, {Name: "-prec-sqrt", Short: "--prec-sqrt", Arity: "value", Default: "true", Values: []string{"true", "false"}}, {Name: "-fmad", Short: "--fmad", Arity: "value", Default: "true", Values: []string{"true", "false"}}, {Name: "--device-as-default-execution-space", Short: "-default-device", Arity: "bare", Default: ""}, {Name: "--device-debug", Short: "-G", Arity: "bare", Default: ""}, {Name: "--generate-line-info", Short: "-lineinfo", Arity: "bare", Default: ""}, {Name: "--relocatable-device-code", Short: "-rdc", Arity: "value", Default: "false", Values: []string{"true", "false"}}, {Name: "--maxrregcount", Short: "-maxrregcount", Arity: "value", Default: ""}, {Name: "--extra-device-vectorization", Short: "-extra-device-vectorization", Arity: "bare", Default: ""}, {Name: "-w", Short: "--disable-warnings", Arity: "bare", Default: ""}, {Name: "--warning-as-error", Short: "-Werror", Arity: "value", Default: "", Separator: ",", Values: []string{"all-warnings", "conversion"}}, {Name: "--include-path", Short: "-I", Arity: "value", Default: ""}, {Name: "-D", Short: "--define-macro", Arity: "value", Default: ""}, {Name: "-U", Short: "--undefine-macro", Arity: "value", Default: ""}, {Name: "--pre-include", Short: "-include", Arity: "value", Default: ""}, {Name: "-dlto", Short: "--dlink-time-opt", Arity: "bare", Default: ""}, {Name: "--tile-only", Short: "-tile-only", Arity: "bare", Default: ""}, {Name: "--enable-tile", Short: "-enable-tile", Arity: "bare", Default: ""}, {Name: "--optix-ir", Short: "-optix-ir", Arity: "bare", Default: ""}, {Name: "-pch", Short: "--pch", Arity: "bare", Default: ""}, {Name: "--create-pch", Short: "-create-pch", Arity: "value", Default: ""}, {Name: "--use-pch", Short: "-use-pch", Arity: "value", Default: ""}, {Name: "--Ofast-compile", Short: "-Ofc", Arity: "value", Default: "", Values: []string{"0", "max", "mid", "min"}}, {Name: "--frandom-seed", Short: "-frandom-seed", Arity: "value", Default: ""}, {Name: "--extensible-whole-program", Short: "-ewp", Arity: "bare", Default: ""}, {Name: "--device-stack-protector", Short: "-device-stack-protector", Arity: "value", Default: "false", Values: []string{"true", "false"}}, {Name: "--time", Short: "-time", Arity: "value", Default: ""}, {Name: "--no-cache", Short: "-no-cache", Arity: "bare", Default: ""}, }
SupportedOptions records all compiler options recognized by NVRTC.
Functions ¶
func Close ¶
func Close() error
Close unloads the library and clears all bound function pointers.
The function pointers are package-level state, so Close must not be called concurrently with any other call into this package: doing so is a use-after-free. It is intended for test teardown, not for reclaiming a live library.
func ComputeArch ¶
ComputeArch returns the virtual compute architecture string for major.minor (e.g., "compute_80" for 8, 0).
func GetNumSupportedArchs ¶
GetNumSupportedArchs sets the output parameter numArchs with the number of architectures supported by NVRTC.
This can then be used to pass an array to GetSupportedArchs to get the supported architectures. see GetSupportedArchs
Errors:
Wraps nvrtcGetNumSupportedArchs.
func GetPCHHeapSize ¶
GetPCHHeapSize retrieves the current size of the PCH Heap.
Requires CUDA 12.8 or later; see HasGetPCHHeapSize.
Errors:
Wraps nvrtcGetPCHHeapSize.
func GetSupportedArchs ¶
GetSupportedArchs populates the array passed via the output parameter supportedArchs with the architectures supported by NVRTC.
The array is sorted in the ascending order. The size of the array to be passed can be determined using GetNumSupportedArchs. see GetNumSupportedArchs
- supportedArchs: sorted array of supported architectures
Errors:
Wraps nvrtcGetSupportedArchs.
func Has ¶
Has reports whether the named C symbol resolved in the loaded library, loading it first if necessary. It returns false if the library failed to load. Use it to gate on capabilities before calling into them.
func HasAddNameExpression ¶
func HasAddNameExpression() bool
HasAddNameExpression reports whether nvrtcAddNameExpression resolved in the loaded library.
func HasCompileProgram ¶
func HasCompileProgram() bool
HasCompileProgram reports whether nvrtcCompileProgram resolved in the loaded library.
func HasCreateProgram ¶
func HasCreateProgram() bool
HasCreateProgram reports whether nvrtcCreateProgram resolved in the loaded library.
func HasDestroyProgram ¶
func HasDestroyProgram() bool
HasDestroyProgram reports whether nvrtcDestroyProgram resolved in the loaded library.
func HasGetBundledHeadersInfo ¶
func HasGetBundledHeadersInfo() bool
HasGetBundledHeadersInfo reports whether nvrtcGetBundledHeadersInfo resolved in the loaded library.
func HasGetCUBIN ¶
func HasGetCUBIN() bool
HasGetCUBIN reports whether nvrtcGetCUBIN resolved in the loaded library.
func HasGetCUBINSize ¶
func HasGetCUBINSize() bool
HasGetCUBINSize reports whether nvrtcGetCUBINSize resolved in the loaded library.
func HasGetErrorString ¶
func HasGetErrorString() bool
HasGetErrorString reports whether nvrtcGetErrorString resolved in the loaded library.
func HasGetLTOIR ¶
func HasGetLTOIR() bool
HasGetLTOIR reports whether nvrtcGetLTOIR resolved in the loaded library.
func HasGetLTOIRSize ¶
func HasGetLTOIRSize() bool
HasGetLTOIRSize reports whether nvrtcGetLTOIRSize resolved in the loaded library.
func HasGetLoweredName ¶
func HasGetLoweredName() bool
HasGetLoweredName reports whether nvrtcGetLoweredName resolved in the loaded library.
func HasGetNVVM ¶
func HasGetNVVM() bool
HasGetNVVM reports whether nvrtcGetNVVM resolved in the loaded library.
func HasGetNVVMSize ¶
func HasGetNVVMSize() bool
HasGetNVVMSize reports whether nvrtcGetNVVMSize resolved in the loaded library.
func HasGetNumSupportedArchs ¶
func HasGetNumSupportedArchs() bool
HasGetNumSupportedArchs reports whether nvrtcGetNumSupportedArchs resolved in the loaded library.
func HasGetOptiXIR ¶
func HasGetOptiXIR() bool
HasGetOptiXIR reports whether nvrtcGetOptiXIR resolved in the loaded library.
func HasGetOptiXIRSize ¶
func HasGetOptiXIRSize() bool
HasGetOptiXIRSize reports whether nvrtcGetOptiXIRSize resolved in the loaded library.
func HasGetPCHCreateStatus ¶
func HasGetPCHCreateStatus() bool
HasGetPCHCreateStatus reports whether nvrtcGetPCHCreateStatus resolved in the loaded library.
func HasGetPCHHeapSize ¶
func HasGetPCHHeapSize() bool
HasGetPCHHeapSize reports whether nvrtcGetPCHHeapSize resolved in the loaded library.
func HasGetPCHHeapSizeRequired ¶
func HasGetPCHHeapSizeRequired() bool
HasGetPCHHeapSizeRequired reports whether nvrtcGetPCHHeapSizeRequired resolved in the loaded library.
func HasGetPTX ¶
func HasGetPTX() bool
HasGetPTX reports whether nvrtcGetPTX resolved in the loaded library.
func HasGetPTXSize ¶
func HasGetPTXSize() bool
HasGetPTXSize reports whether nvrtcGetPTXSize resolved in the loaded library.
func HasGetProgramLog ¶
func HasGetProgramLog() bool
HasGetProgramLog reports whether nvrtcGetProgramLog resolved in the loaded library.
func HasGetProgramLogSize ¶
func HasGetProgramLogSize() bool
HasGetProgramLogSize reports whether nvrtcGetProgramLogSize resolved in the loaded library.
func HasGetSupportedArchs ¶
func HasGetSupportedArchs() bool
HasGetSupportedArchs reports whether nvrtcGetSupportedArchs resolved in the loaded library.
func HasGetTileIR ¶
func HasGetTileIR() bool
HasGetTileIR reports whether nvrtcGetTileIR resolved in the loaded library.
func HasGetTileIRSize ¶
func HasGetTileIRSize() bool
HasGetTileIRSize reports whether nvrtcGetTileIRSize resolved in the loaded library.
func HasInstallBundledHeaders ¶
func HasInstallBundledHeaders() bool
HasInstallBundledHeaders reports whether nvrtcInstallBundledHeaders resolved in the loaded library.
func HasRemoveBundledHeaders ¶
func HasRemoveBundledHeaders() bool
HasRemoveBundledHeaders reports whether nvrtcRemoveBundledHeaders resolved in the loaded library.
func HasSetFlowCallback ¶
func HasSetFlowCallback() bool
HasSetFlowCallback reports whether nvrtcSetFlowCallback resolved in the loaded library.
func HasSetPCHHeapSize ¶
func HasSetPCHHeapSize() bool
HasSetPCHHeapSize reports whether nvrtcSetPCHHeapSize resolved in the loaded library.
func HasVersion ¶
func HasVersion() bool
HasVersion reports whether nvrtcVersion resolved in the loaded library.
func InstallBundledHeaders ¶
InstallBundledHeaders extracts CUDA headers bundled with NVRTC to a specified directory for use during compilation.
NVRTC bundles a set of CUDA Toolkit headers and CUDA C++ Core Libraries (CCCL) within libnvrtc-builtins. This function extracts these headers to the specified directory, allowing NVRTC programs to compile without requiring a separate CUDA Toolkit installation. The bundled headers match those available in the CUDA Toolkit plus CCCL libraries. After extraction, users can compile kernels by passing appropriate include paths (such as “-I” and “-I/cccl”) to Program.Compile. A version marker file (.nvrtc_headers_version) is created in the installation directory to track the installed version. This function is thread-safe and process-safe. Concurrent calls from multiple threads or processes will be serialized using file locking. By default, the function waits for the lock; use NVRTC_INSTALL_HEADERS_NO_WAIT to return immediately with ErrBusy if another process holds the lock.
Note: Use NVRTC_INSTALL_HEADERS_SKIP_IF_EXISTS to avoid reinstalling if headers already exist. Use NVRTC_INSTALL_HEADERS_FORCE_OVERWRITE to guarantee consistency by clearing the directory first.
See also: Program.Compile
Requires CUDA 13.3 or later; see HasInstallBundledHeaders.
- installPath: Path where headers should be extracted (UTF-8 encoded). The directory will be created if it doesn’t exist
- flags: NVRTC_INSTALL_HEADERS_* flags:0 (SKIP_IF_EXISTS): Skip if version marker exists and version matches. This is the default.NVRTC_INSTALL_HEADERS_FORCE_OVERWRITE: Clear directory first, then install. Guarantees consistency.NVRTC_INSTALL_HEADERS_NO_WAIT: Return ErrBusy immediately if lock cannot be acquired. NO_WAIT can be combined with FORCE_OVERWRITE
Errors:
- ErrBuiltinOperationFailure: extraction failed or version mismatch
- ErrBusy: lock held by another process and NVRTC_INSTALL_HEADERS_NO_WAIT was specified
- ErrInvalidInput: invalid path or conflicting flags like SKIP_IF_EXISTS | FORCE_OVERWRITE
Wraps nvrtcInstallBundledHeaders.
func Load ¶
Load opens the shared library from path, or from the default search list when path is empty, and binds all symbols. Callers that need to direct loading should call Load before any other function; otherwise the first call loads from the default search list.
Load is idempotent: calling it again with the same path, or with an empty path, returns nil. Calling it with a different path after a successful load returns *LibraryConflictError rather than replacing the library. After a failed load, Load retries.
func Loaded ¶
func Loaded() bool
Loaded reports whether the library is currently loaded. It does not trigger a load.
func Path ¶
func Path() string
Path returns the path or name the loaded library was opened from, or the empty string if no library is loaded.
func RemoveBundledHeaders ¶
RemoveBundledHeaders removes previously installed bundled headers.
This function removes the headers installed by InstallBundledHeaders, helping users manage disk space. It recursively removes all files and subdirectories within the installation directory.
Note: This function will remove ALL contents of the specified directory, not just files installed by NVRTC. Use with caution.
Requires CUDA 13.3 or later; see HasRemoveBundledHeaders.
- installPath: Path where headers were previously installed. Must be the same path used with InstallBundledHeaders
Errors:
- ErrBuiltinOperationFailure: removal failed
- ErrInvalidInput: invalid path
Wraps nvrtcRemoveBundledHeaders.
func SetPCHHeapSize ¶
SetPCHHeapSize sets the size of the PCH Heap.
The requested size may be rounded up to a platform dependent alignment (e.g. page size). If the PCH Heap has already been allocated, the heap memory will be freed and a new PCH Heap will be allocated.
Requires CUDA 12.8 or later; see HasSetPCHHeapSize.
- size: requested size of the PCH Heap, in bytes
Wraps nvrtcSetPCHHeapSize.
func SmArch ¶
SmArch returns the physical GPU architecture string for major.minor (e.g., "sm_80" for 8, 0).
func ValidateOption ¶
ValidateOption checks the spelling and value of a recognized NVRTC option.
Types ¶
type BindFailure ¶
BindFailure names a symbol the loaded library exports but that could not be bound, and why.
func BindFailures ¶
func BindFailures() []BindFailure
BindFailures returns the symbols the loaded library exports that could not be bound, sorted by symbol name, or nil if every exported symbol bound. Calling one of these reports *SymbolError with the same Err.
A load that reports no error can still leave symbols unbound: the library is fine and the signatures are not representable here. Call this after Load to find that out at once rather than one call site at a time. It does not trigger a load, and returns nil if none has happened.
type BundledHeadersInfo ¶
type BundledHeadersInfo struct {
// Non-zero if bundled headers are available
Available int32
// Size of compressed archive in bytes
CompressedSize uint
// Estimated size when extracted in bytes
UncompressedSize uint
// CUDA major version of bundled headers
CudaVersionMajor int32
// CUDA minor version of bundled headers
CudaVersionMinor int32
// Number of header files in the bundle
NumFiles uint32
}
BundledHeadersInfo contains information about bundled headers.
func GetBundledHeadersInfo ¶
func GetBundledHeadersInfo() (BundledHeadersInfo, error)
GetBundledHeadersInfo queries information about the bundled headers without extracting them.
This function allows users to determine if bundled headers are available and get size estimates before calling InstallBundledHeaders.
Requires CUDA 13.3 or later; see HasGetBundledHeadersInfo.
Errors:
- ErrBuiltinOperationFailure: failed to query bundled headers
- ErrInvalidInput: info is NULL
Wraps nvrtcGetBundledHeadersInfo.
type CallError ¶
CallError reports that a library call returned a failure result.
Unwrap returns Result, so errors.Is(err, c) reports whether the call returned the Result constant c, and errors.As(err, &r) with r of type Result recovers the code.
type Header ¶
type Header struct {
// Name is the name the program's #include directive uses.
Name string
// Source is the contents of the header.
Source string
}
A Header is a header a program can include by name. It is passed to CreateProgram.
type LibraryAttempt ¶
LibraryAttempt records one failed attempt to open the shared library.
type LibraryConflictError ¶
type LibraryConflictError struct {
Loaded string
Requested string
// Implicit reports that the loaded library was opened lazily and no
// successful Load has since acknowledged it. A
// caller that sees this called some
// other function first, and that call took the default search list.
Implicit bool
}
LibraryConflictError reports a Load call naming a different library than the one already loaded. Only one library is loaded per process.
func (*LibraryConflictError) Error ¶
func (e *LibraryConflictError) Error() string
Error reports the conflicting library paths, and whether the library that is already loaded got there without a Load call.
type LibraryError ¶
type LibraryError struct {
Library string
Env string
Path string
Attempts []LibraryAttempt
Hint string
}
LibraryError reports that libnvrtc could not be opened. Attempts lists every name tried in order. Path is set when an explicit path, from Load or NVRTC_LIB_PATH, was requested and failed. Hint reports pkg-config discovery results and query failures, when discovery ran.
func (*LibraryError) Error ¶
func (e *LibraryError) Error() string
Error describes the library load attempts and their errors.
func (*LibraryError) Unwrap ¶
func (e *LibraryError) Unwrap() []error
Unwrap returns the error from each attempt.
type OptionDef ¶
type OptionDef struct {
Name string
Short string
Arity string // "bare" or "value"
Default string
Values []string
Separator string
}
OptionDef describes a compiler option recognized by NVRTC.
type Program ¶
type Program uintptr
Program is an opaque handle for nvrtcProgram.
func CreateProgram ¶
CreateProgram creates an instance of Program with the given input parameters, and sets the output parameter prog with it.
See also: Program.Destroy
- src: CUDA program source
- name: CUDA program name. name can be NULL; "default_program" is used when name is NULL or “”
Errors:
Wraps nvrtcCreateProgram.
func (Program) AddNameExpression ¶
AddNameExpression notes the given name expression denoting the address of a global function or device/__constant__ variable.
The identical name expression string must be provided on a subsequent call to Program.LoweredName to extract the lowered name.
See also: Program.LoweredName
- nameExpression: constant expression denoting the address of a global function or device/__constant__ variable
Errors:
Wraps nvrtcAddNameExpression.
func (Program) CUBIN ¶
CUBIN returns the cubin generated by the previous compilation of prog.
No cubin is available if the value specified to -arch is a virtual architecture instead of an actual architecture. The cubin does not contain code for the Tile functions ( __tile__ / __tile_global__) or variables ( __tile__); use Program.TileIR to extract the cuda_tile IR generated for Tile code.
See also: Program.CUBINSize
Errors:
Wraps nvrtcGetCUBIN.
func (Program) CUBINSize ¶
CUBINSize returns the size of the cubin generated by the previous compilation of prog.
The result is 0 if the value specified to -arch is a virtual architecture instead of an actual architecture.
See also: Program.CUBIN
Errors:
Wraps nvrtcGetCUBINSize.
func (Program) Compile ¶
Compile compiles the given program.
It supports compile options listed in Supported Compile Options.
- options: Compiler options in the form of C string array. options can be NULL when numOptions is 0
Errors:
- ErrBuiltinOperationFailure
- ErrCancelled
- ErrCompilation
- ErrInvalidInput
- ErrInvalidOption
- ErrInvalidProgram
- ErrOutOfMemory
- ErrTimeFileWriteFailed
Wraps nvrtcCompileProgram.
func (*Program) Destroy ¶
Destroy destroys the given program.
See also: CreateProgram
Errors:
It is not named Close because it takes a pointer to the handle.
Wraps nvrtcDestroyProgram.
func (Program) LTOIR ¶
LTOIR returns the LTO IR generated by the previous compilation of prog.
No LTO IR is available if the program was compiled without -dlto.
See also: Program.LTOIRSize
Errors:
Wraps nvrtcGetLTOIR.
func (Program) LTOIRSize ¶
LTOIRSize returns the size of the LTO IR generated by the previous compilation of prog.
The result is 0 if the program was not compiled with -dlto.
See also: Program.LTOIR
Errors:
Wraps nvrtcGetLTOIRSize.
func (Program) Log ¶
Log returns the log generated by the previous compilation of prog.
See also: Program.LogSize
Errors:
Wraps nvrtcGetProgramLog.
func (Program) LogSize ¶
LogSize returns the size of the log generated by the previous compilation of prog (including the trailing NULL).
Note that compilation log may be generated with warnings and informative messages, even when the compilation of prog succeeds.
See also: Program.Log
Errors:
The size counts the terminating NUL that Program.Log drops, so it is one more than the length of that result.
Wraps nvrtcGetProgramLogSize.
func (Program) LoweredName ¶
LoweredName extracts the lowered (mangled) name for a global function or device/__constant__ variable, and updates *loweredName to point to it.
The memory containing the name is released when the NVRTC program is destroyed by Program.Destroy. The identical name expression must have been previously provided to Program.AddNameExpression.
See also: Program.AddNameExpression
- nameExpression: constant expression denoting the address of a global function or device/__constant__ variable
- loweredName: initialized by the function to point to a C string containing the lowered (mangled) name corresponding to the provided name expression
Errors:
Wraps nvrtcGetLoweredName.
func (Program) NVVM
deprecated
NVVM wraps nvrtcGetNVVM.
Deprecated: Deprecated in CUDA 12.0. Use Program.LTOIR instead. NVIDIA removed this function in CUDA 13.0.
func (Program) NVVMSize
deprecated
NVVMSize wraps nvrtcGetNVVMSize.
Deprecated: Deprecated in CUDA 12.0. Use Program.LTOIRSize instead. NVIDIA removed this function in CUDA 13.0.
func (Program) OptiXIR ¶
OptiXIR returns the OptiX IR generated by the previous compilation of prog.
No OptiX IR is available if the program was compiled with options incompatible with OptiX IR generation.
See also: Program.OptiXIRSize
Errors:
Wraps nvrtcGetOptiXIR.
func (Program) OptiXIRSize ¶
OptiXIRSize returns the size of the OptiX IR generated by the previous compilation of prog.
The value of Program.OptiXIRSize is set to 0 if the program was compiled with options incompatible with OptiX IR generation.
See also: Program.OptiXIR
Errors:
Wraps nvrtcGetOptiXIRSize.
func (Program) PCHCreateStatus ¶
PCHCreateStatus returns the PCH creation status.
Success indicates that the PCH was successfully created. ErrNoPchCreateAttempted indicates that no PCH creation was attempted, either because PCH functionality was not requested during the preceding Program.Compile call, or automatic PCH processing was requested, and compiler chose not to create a PCH file. ErrPchCreateHeapExhausted indicates that a PCH file could potentially have been created, but the compiler ran out space in the PCH heap. In this scenario, the Program.PCHHeapSizeRequired can be used to query the required heap size, the heap can be reallocated for this size with SetPCHHeapSize and PCH creation may be reattempted again invoking Program.Compile with a new NVRTC program instance. ErrPchCreate indicates that an error condition prevented the PCH file from being created.
Requires CUDA 12.8 or later; see HasGetPCHCreateStatus.
Errors:
Wraps nvrtcGetPCHCreateStatus.
func (Program) PCHHeapSizeRequired ¶
PCHHeapSizeRequired retrieves the required size of the PCH heap required to compile the given program.
Requires CUDA 12.8 or later; see HasGetPCHHeapSizeRequired.
Errors:
- ErrInvalidInput: The size retrieved using this function is only valid if Program.PCHCreateStatus returned Success or ErrPchCreateHeapExhausted
- ErrInvalidProgram
Wraps nvrtcGetPCHHeapSizeRequired.
func (Program) PTX ¶
PTX returns the PTX generated by the previous compilation of prog.
See also: Program.PTXSize
Errors:
The result does not include the C string's terminating NUL.
Wraps nvrtcGetPTX.
func (Program) PTXSize ¶
PTXSize returns the size of the PTX generated by the previous compilation of prog (including the trailing NULL).
See also: Program.PTX
Errors:
The size counts the terminating NUL that Program.PTX drops, so it is one more than the length of that result.
Wraps nvrtcGetPTXSize.
func (Program) SetFlowCallback ¶
SetFlowCallback registers a callback function that the compiler will invoke at different points during a call to Program.Compile, and the callback function can decide whether to cancel compilation by returning specific values.
The callback function must satisfy the following constraints:
When invoking the callback, the compiler will always pass payload to param1 so that the callback may make decisions based on payload . It’ll always pass NULL to param2 for now which is reserved for future extensions. (2) It must return 1 to cancel compilation or 0 to continue. Other return values are reserved for future use. (3) It must return consistent values. Once it returns 1 at one point, it must return 1 in all following invocations during the current Program.Compile call in progress. (4) It must be thread-safe. (5) It must not invoke any nvrtc/libnvvm/ptx APIs.
Requires CUDA 12.8 or later; see HasSetFlowCallback.
- callback: the callback that issues cancellation signal
- payload: to be passed as a parameter when invoking the callback
Errors:
Wraps nvrtcSetFlowCallback.
func (Program) TileIR ¶
TileIR returns the cuda_tile IR generated by the previous compilation of prog.
See also: Program.TileIRSize
Requires CUDA 13.2 or later; see HasGetTileIR.
Errors:
Wraps nvrtcGetTileIR.
func (Program) TileIRSize ¶
TileIRSize returns the size of the cuda_tile IR generated by the previous compilation of prog.
See also: Program.TileIR
Requires CUDA 13.2 or later; see HasGetTileIRSize.
Errors:
Wraps nvrtcGetTileIRSize.
type Result ¶
type Result int32
Result represents a nvrtc API error code (nvrtcResult).
When the library is loaded, Result.Error returns rich messages from GetErrorString. When the library is not loaded, it falls back to the numeric error code and Go-defined name.
const ( Success Result = 0 ErrOutOfMemory Result = 1 ErrProgramCreationFailure Result = 2 ErrInvalidInput Result = 3 ErrInvalidProgram Result = 4 ErrInvalidOption Result = 5 ErrCompilation Result = 6 ErrBuiltinOperationFailure Result = 7 ErrNoNameExpressionsAfterCompilation Result = 8 ErrNoLoweredNamesBeforeCompilation Result = 9 ErrNameExpressionNotValid Result = 10 ErrInternalError Result = 11 ErrTimeFileWriteFailed Result = 12 ErrNoPchCreateAttempted Result = 13 ErrPchCreateHeapExhausted Result = 14 ErrPchCreate Result = 15 ErrCancelled Result = 16 ErrTimeTraceFileWriteFailed Result = 17 ErrBusy Result = 18 )
nvrtc error codes from nvrtc.h.
type SymbolError ¶
SymbolError reports that a symbol is not callable.
Err distinguishes the two ways that happens. A nil Err means the loaded library does not export the symbol, which is what an installation older than the symbol looks like. A non-nil Err means the library does export it and the binding itself failed; the library is not at fault.
func (*SymbolError) Error ¶
func (e *SymbolError) Error() string
Error reports the uncallable library symbol and, when the symbol was present but could not be bound, why.
func (*SymbolError) Unwrap ¶
func (e *SymbolError) Unwrap() error
Unwrap returns the reason the symbol could not be bound, or nil when the loaded library does not export it.
type VersionMismatchError ¶
type VersionMismatchError struct {
Path string // the library that was opened
Want int // major version these bindings were generated for
Got int // major version the library reports
Raw int // the version value the library reported, undecoded
}
VersionMismatchError reports that the shared library that opened is not from the version train nvrtc was generated for. dlsym matches on name alone, so a library from a neighbouring train opens and resolves nearly every symbol; asking it its own version is what tells the two apart.
func (*VersionMismatchError) Error ¶
func (e *VersionMismatchError) Error() string
Error reports which library was opened and the two majors that disagree.
A decoder is only a decoder for the version schemes it was measured against, and a library from a train that predates the scheme can report a value it does not decode. Naming a major of 0 in that case would attribute to the library a claim it never made, so the raw value is reported instead.