nvvm

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 16 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

NVVM

Go bindings for NVIDIA's NVVM compiler, generated by codegen's gen-nvidia -api nvvm. Use NVVM for NVVM IR; use nvrtc for CUDA C++.

Create a Program, add IR and libdevice with AddModuleTo or LazyAddModuleTo, call Compile, and retrieve CompiledResult. Log returns compiler diagnostics. Destroy releases the program. Keep lazily supplied buffers alive through compilation.

Compile([]string{"-arch=compute_120", "-gen-lto"}) produces LTOIR for nvjitlink. Host-visible entry points must be retained through device LTO; the test IR includes llvm.used for that purpose, as cuda-oxide does.

The generated surface uses the CUDA 13.2.51 NVVM header, including LLVMVersion. Loading is lazy. Set NVVM_LIB_PATH to select a library before its first use. Older libraries remain usable; unavailable functions return *SymbolError. LLVMVersion is absent from the tested CUDA 13.0 library.

Validation

From the nvidia module root on Linux with an NVIDIA GPU and CUDA 13:

export CUDA_HOME=/usr/local/cuda-13
export NVVM_LIB_PATH="$CUDA_HOME/nvvm/lib64/libnvvm.so.4"
export NVJITLINK_LIB_PATH="$CUDA_HOME/lib64/libnvJitLink.so.13"
export CUDA_LIBDEVICE="$CUDA_HOME/nvvm/libdevice/libdevice.10.bc"
CUDA_COMPILER_TEST=1 GOWORK=off go test -tags cuda -v \
  ./nvvm ./nvjitlink ./driver -count=1 -timeout=120s

The pipeline test selects the GPU's compute capability, compiles a sine kernel with libdevice, links LTOIR to cubin, loads and launches it, and checks all 128 results against math.Sin. It also encodes a two-dimensional tensor map, replaces its address, and checks malformed IR rejection and compiler logs. The cuda tag enables runnable examples with checked output.

Set CUDA_ARTIFACT_DIR to a persistent scratch directory to retain the LTOIR and cubin. The test logs input and output SHA-256 digests. Without CUDA_COMPILER_TEST=1, the GPU test skips; this does not prove GPU execution. Ordinary package tests cover import behavior and missing-library/symbol errors.

The test IR uses the modern NVVM dialect for Blackwell; runtime evidence was collected on GB10 (sm_121). Other architectures and Windows were not tested.

Documentation

Overview

Package nvvm provides Go bindings for the NVIDIA NVVM compiler.

NVVM compiles NVVM IR and libdevice bitcode to PTX or LTOIR. Programs must be destroyed after use. Lazy module inputs must remain reachable and unchanged until compilation completes.

Load opens the path it is given. With an empty path it opens the path in NVVM_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:

  1. the copy in the toolkit that CUDA_HOME names, then the one that CUDA_PATH names
  2. the system library names, which the dynamic loader resolves
  3. the copy in each installed /usr/local/cuda-N.M toolkit, newest first, then /usr/local/cuda
  4. the system library names in the directories pkg-config reports for nvvm

Other

Example

Example compiles a small NVVM IR module to PTX. It returns early when the NVVM library is not available. The PTX can then be loaded with the driver package, or linked with libdevice and other inputs first.

package main

import (
	"fmt"
	"unsafe"

	"github.com/tmc/lib/nvidia/nvvm"
)

func main() {
	if _, _, err := nvvm.Version(); err != nil {
		fmt.Println("NVVM unavailable:", err)
		return
	}

	const module = `
target datalayout = "e-p:64:64:64-i64:64:64-f64:64:64-n16:32:64"
target triple = "nvptx64-nvidia-cuda"

define void @zero(float* %out) {
  store float 0.0, float* %out
  ret void
}

!nvvm.annotations = !{!0}
!0 = !{void (float*)* @zero, !"kernel", i32 1}
`
	prog, err := nvvm.CreateProgram()
	if err != nil {
		fmt.Println("create:", err)
		return
	}
	defer prog.Destroy()

	ir := []byte(module)
	if err := prog.AddModuleTo(unsafe.Pointer(&ir[0]), uint(len(ir)), "zero.ll"); err != nil {
		fmt.Println("add module:", err)
		return
	}
	if err := prog.Compile("-arch=compute_70"); err != nil {
		log, _ := prog.Log()
		fmt.Printf("compile: %v\n%s", err, log)
		return
	}
	ptx, err := prog.CompiledResult()
	if err != nil {
		fmt.Println("result:", err)
		return
	}
	fmt.Println("compiled", len(ptx), "bytes of PTX")
}

Index

Examples

Constants

View Source
const (
	FlagG                = "-g"
	FlagOpt              = "-opt"
	FlagArch             = "-arch"
	FlagFtz              = "-ftz"
	FlagPrecSqrt         = "-prec-sqrt"
	FlagPrecDiv          = "-prec-div"
	FlagFma              = "-fma"
	FlagJumpTableDensity = "-jump-table-density"
	FlagGenLTO           = "-gen-lto"
	FlagPTXVersionTarget = "-ptx-version-target"
	FlagNVVMLatest       = "-nvvm-latest"
)

Standard compiler flag constants accepted by NVVM.

Variables

This section is empty.

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

func ComputeArch(major, minor int) string

ComputeArch returns the virtual compute architecture string for major.minor (e.g., "compute_80" for 8, 0).

func Has

func Has(symbol string) bool

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 HasAddModuleToProgram

func HasAddModuleToProgram() bool

HasAddModuleToProgram reports whether nvvmAddModuleToProgram resolved in the loaded library.

func HasCompileProgram

func HasCompileProgram() bool

HasCompileProgram reports whether nvvmCompileProgram resolved in the loaded library.

func HasCreateProgram

func HasCreateProgram() bool

HasCreateProgram reports whether nvvmCreateProgram resolved in the loaded library.

func HasDestroyProgram

func HasDestroyProgram() bool

HasDestroyProgram reports whether nvvmDestroyProgram resolved in the loaded library.

func HasGetCompiledResult

func HasGetCompiledResult() bool

HasGetCompiledResult reports whether nvvmGetCompiledResult resolved in the loaded library.

func HasGetCompiledResultSize

func HasGetCompiledResultSize() bool

HasGetCompiledResultSize reports whether nvvmGetCompiledResultSize resolved in the loaded library.

func HasGetErrorString

func HasGetErrorString() bool

HasGetErrorString reports whether nvvmGetErrorString resolved in the loaded library.

func HasGetProgramLog

func HasGetProgramLog() bool

HasGetProgramLog reports whether nvvmGetProgramLog resolved in the loaded library.

func HasGetProgramLogSize

func HasGetProgramLogSize() bool

HasGetProgramLogSize reports whether nvvmGetProgramLogSize resolved in the loaded library.

func HasIRVersion

func HasIRVersion() bool

HasIRVersion reports whether nvvmIRVersion resolved in the loaded library.

func HasLLVMVersion

func HasLLVMVersion() bool

HasLLVMVersion reports whether nvvmLLVMVersion resolved in the loaded library.

func HasLazyAddModuleToProgram

func HasLazyAddModuleToProgram() bool

HasLazyAddModuleToProgram reports whether nvvmLazyAddModuleToProgram resolved in the loaded library.

func HasVerifyProgram

func HasVerifyProgram() bool

HasVerifyProgram reports whether nvvmVerifyProgram resolved in the loaded library.

func HasVersion

func HasVersion() bool

HasVersion reports whether nvvmVersion resolved in the loaded library.

func IRVersion

func IRVersion() (majorIR int32, minorIR int32, majorDbg int32, minorDbg int32, err error)

IRVersion gets the NVVM IR version.

  • majorIR (out): NVVM IR major version number
  • minorIR (out): NVVM IR minor version number
  • majorDbg (out): NVVM IR debug metadata major version number
  • minorDbg (out): NVVM IR debug metadata minor version number

Wraps nvvmIRVersion.

func LLVMVersion

func LLVMVersion(arch string) (int32, error)

LLVMVersion gets the LLVM IR version guaranteed to be supported by NVVM.

The valid arch strings are the ones supported by Program.Compile.

Requires CUDA 13.1 or later; see HasLLVMVersion.

  • arch (in): Architecture string

Wraps nvvmLLVMVersion.

func Load

func Load(path string) error

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 ValidateOption

func ValidateOption(flag string) error

ValidateOption checks a documented NVVM compiler option before native compilation.

func Version

func Version() (major int32, minor int32, err error)

Version gets the NVVM version.

  • major (out): NVVM major version number
  • minor (out): NVVM minor version number

Wraps nvvmVersion.

Types

type BindFailure

type BindFailure struct {
	Symbol string
	Err    error
}

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 CallError

type CallError struct {
	Func   string // the C symbol called
	Result Result
}

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.

func (*CallError) Error

func (e *CallError) Error() string

Error reports the C symbol called and the result it returned.

func (*CallError) Unwrap

func (e *CallError) Unwrap() error

Unwrap returns the result the call reported.

type LibraryAttempt

type LibraryAttempt struct {
	Name string // path or soname passed to dlopen
	Err  error
}

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 libnvvm could not be opened. Attempts lists every name tried in order. Path is set when an explicit path, from Load or NVVM_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 Program

type Program uintptr

Program is an opaque handle for nvvmProgram.

func CreateProgram

func CreateProgram() (Program, error)

CreateProgram creates a program, and sets the value of its handle to *prog.

Wraps nvvmCreateProgram.

func (Program) AddModuleTo

func (p Program) AddModuleTo(buffer unsafe.Pointer, size uint, name string) error

AddModuleTo adds a module level NVVM IR to a program.

The buffer should contain an NVVM IR module. The module should have NVVM IR either in the LLVM 7.0.1 bitcode representation or in the LLVM 7.0.1 text representation. Support for reading the text representation of NVVM IR is deprecated and may be removed in a later version.

  • buffer (in): NVVM IR module in the bitcode or text representation
  • size (in): Size of the NVVM IR module
  • name (in): Name of the NVVM IR module. If NULL, "<unnamed>" is used as the name

Wraps nvvmAddModuleToProgram.

func (Program) Compile

func (p Program) Compile(options ...string) error

Compile compiles the NVVM program.

The NVVM IR modules in the program will be linked at the IR level. The linked IR program is compiled to PTX.

The target datalayout in the linked IR program is used to determine the address size (32bit vs 64bit).

The valid compiler options are:

  • -g (enable generation of full debugging information).

Full debug support is only valid with '-opt=0'. Debug support requires the input module to utilize NVVM IR Debug Metadata. Line number (line info) only generation is also enabled via NVVM IR Debug Metadata, there is no specific libNVVM API flag for that case.

  • -opt=
  • 0 (disable optimizations)
  • 3 (default, enable optimizations)
  • -arch=
  • compute_75 (default)
  • compute_80
  • compute_87
  • compute_89
  • compute_90
  • compute_90a
  • compute_100
  • compute_100a
  • compute_100f
  • compute_103
  • compute_103a
  • compute_103f
  • compute_110
  • compute_110a
  • compute_110f
  • compute_120
  • compute_120a
  • compute_120f
  • compute_121
  • compute_121a
  • compute_121f
  • -ftz=
  • 0 (default, preserve denormal values, when performing single-precision floating-point operations)
  • 1 (flush denormal values to zero, when performing single-precision floating-point operations)
  • -prec-sqrt=
  • 0 (use a faster approximation for single-precision floating-point square root)
  • 1 (default, use IEEE round-to-nearest mode for single-precision floating-point square root)
  • -prec-div=
  • 0 (use a faster approximation for single-precision floating-point division and reciprocals)
  • 1 (default, use IEEE round-to-nearest mode for single-precision floating-point division and reciprocals)
  • -fma=
  • 0 (disable FMA contraction)
  • 1 (default, enable FMA contraction)
  • -jump-table-density=[0-101]

Specify the case density percentage in switch statements, and use it as a minimal threshold to determine whether jump table(brx.idx instruction) will be used to implement a switch statement. Default value is 101. The percentage ranges from 0 to 101 inclusively.

  • -gen-lto (Generate LTO IR instead of PTX).
  • -ptx-version-target=[86-94]

Specify the target PTX version as (MAJOR VERSION * 10 + MINOR VERSION). This is supported only for Blackwell and later architectures (compute capability compute_100 or greater). Using this option implies that the operations in incoming prog are compliant with targeted PTX version. If not set, highest available PTX version is used.

  • -nvvm-latest

Use the most recent LLVM-based NVVM release. Previews this newer NVVM on all GPU architectures. No-op for Blackwell and later where it is already the default.

  • options (in): Compiler options in the form of C string array

Wraps nvvmCompileProgram.

func (Program) CompiledResult

func (p Program) CompiledResult() ([]byte, error)

CompiledResult gets the compiled result.

The result does not include the C string's terminating NUL.

Wraps nvvmGetCompiledResult.

func (Program) CompiledResultSize

func (p Program) CompiledResultSize() (uint, error)

CompiledResultSize gets the size of the compiled result.

The size counts the terminating NUL that Program.CompiledResult drops, so it is one more than the length of that result.

Wraps nvvmGetCompiledResultSize.

func (*Program) Destroy

func (p *Program) Destroy() error

Destroy destroys a program.

It is not named Close because it takes a pointer to the handle.

Wraps nvvmDestroyProgram.

func (Program) LazyAddModuleTo

func (p Program) LazyAddModuleTo(buffer unsafe.Pointer, size uint, name string) error

LazyAddModuleTo adds a module level NVVM IR to a program.

The buffer should contain an NVVM IR module. The module should have NVVM IR in the LLVM 7.0.1 bitcode representation.

A module added using this API is lazily loaded - the only symbols loaded are those that are required by module(s) loaded using Program.AddModuleTo. It is an error for a program to have all modules loaded using this API. Compiler may also optimize entities in this module by making them internal to the linked NVVM IR module, making them eligible for other optimizations. Due to these optimizations, this API to load a module is more efficient and should be used where possible.

  • buffer (in): NVVM IR module in the bitcode representation
  • size (in): Size of the NVVM IR module
  • name (in): Name of the NVVM IR module. If NULL, "<unnamed>" is used as the name

Wraps nvvmLazyAddModuleToProgram.

func (Program) Log

func (p Program) Log() (string, error)

Log gets the Compiler/Verifier Message.

Wraps nvvmGetProgramLog.

func (Program) LogSize

func (p Program) LogSize() (uint, error)

LogSize gets the Size of Compiler/Verifier Message.

The size of the message string (including the trailing NULL) is returned when the return value is Success.

The size counts the terminating NUL that Program.Log drops, so it is one more than the length of that result.

Wraps nvvmGetProgramLogSize.

func (Program) Verify

func (p Program) Verify(options ...string) error

Verify verifies the NVVM program.

The valid compiler options are:

Same as for Program.Compile.

  • options (in): Compiler options in the form of C string array

Wraps nvvmVerifyProgram.

type Result

type Result int32

Result represents a nvvm API error code (nvvmResult).

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
	ErrIrVersionMismatch      Result = 3
	ErrInvalidInput           Result = 4
	ErrInvalidProgram         Result = 5
	ErrInvalidIr              Result = 6
	ErrInvalidOption          Result = 7
	ErrNoModuleInProgram      Result = 8
	ErrCompilation            Result = 9
	ErrCancelled              Result = 10
)

nvvm error codes from nvvm.h.

func (Result) Code

func (r Result) Code() int32

Code returns the underlying result code for programmatic error handling.

func (Result) Error

func (r Result) Error() string

Error implements the error interface. When the library is loaded, it returns the error description from GetErrorString. Otherwise it returns a fallback string with the Go constant name and numeric code.

func (Result) String

func (r Result) String() string

String returns the Go constant name of the result.

type SymbolError

type SymbolError struct {
	Symbol string
	Err    error
}

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL