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.
Library search ¶
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:
- 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 nvvm
Other ¶
- Program.AddModuleTo: Add a module level NVVM IR to a program.
- Program.Compile: Compile the NVVM program.
- CreateProgram: Create a program, and set the value of its handle to *prog.
- Program.Destroy: Destroy a program.
- Program.CompiledResult: Get the compiled result.
- Program.CompiledResultSize: Get the size of the compiled result.
- Program.Log: Get the Compiler/Verifier Message.
- Program.LogSize: Get the Size of Compiler/Verifier Message.
- IRVersion: Get the NVVM IR version.
- LLVMVersion: Get the LLVM IR version guaranteed to be supported by NVVM.
- Program.LazyAddModuleTo: Add a module level NVVM IR to a program.
- Program.Verify: Verify the NVVM program.
- Version: Get the NVVM version.
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")
}
Output:
Index ¶
- Constants
- func Close() error
- func ComputeArch(major, minor int) string
- func Has(symbol string) bool
- func HasAddModuleToProgram() bool
- func HasCompileProgram() bool
- func HasCreateProgram() bool
- func HasDestroyProgram() bool
- func HasGetCompiledResult() bool
- func HasGetCompiledResultSize() bool
- func HasGetErrorString() bool
- func HasGetProgramLog() bool
- func HasGetProgramLogSize() bool
- func HasIRVersion() bool
- func HasLLVMVersion() bool
- func HasLazyAddModuleToProgram() bool
- func HasVerifyProgram() bool
- func HasVersion() bool
- func IRVersion() (majorIR int32, minorIR int32, majorDbg int32, minorDbg int32, err error)
- func LLVMVersion(arch string) (int32, error)
- func Load(path string) error
- func Loaded() bool
- func Path() string
- func ValidateOption(flag string) error
- func Version() (major int32, minor int32, err error)
- type BindFailure
- type CallError
- type LibraryAttempt
- type LibraryConflictError
- type LibraryError
- type Program
- func (p Program) AddModuleTo(buffer unsafe.Pointer, size uint, name string) error
- func (p Program) Compile(options ...string) error
- func (p Program) CompiledResult() ([]byte, error)
- func (p Program) CompiledResultSize() (uint, error)
- func (p *Program) Destroy() error
- func (p Program) LazyAddModuleTo(buffer unsafe.Pointer, size uint, name string) error
- func (p Program) Log() (string, error)
- func (p Program) LogSize() (uint, error)
- func (p Program) Verify(options ...string) error
- type Result
- type SymbolError
Examples ¶
Constants ¶
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 ¶
ComputeArch returns the virtual compute architecture string for major.minor (e.g., "compute_80" for 8, 0).
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 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 ¶
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 ¶
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 ¶
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 ¶
ValidateOption checks a documented NVVM compiler option before native compilation.
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 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 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 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 ¶
CreateProgram creates a program, and sets the value of its handle to *prog.
Wraps nvvmCreateProgram.
func (Program) AddModuleTo ¶
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 ¶
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 ¶
CompiledResult gets the compiled result.
The result does not include the C string's terminating NUL.
Wraps nvvmGetCompiledResult.
func (Program) CompiledResultSize ¶
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 ¶
Destroy destroys a program.
It is not named Close because it takes a pointer to the handle.
Wraps nvvmDestroyProgram.
func (Program) LazyAddModuleTo ¶
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) LogSize ¶
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.
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.
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.