sass

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: 39 Imported by: ? modules, 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

Real-tool checks

TestInstalledTools requires a real CUBIN in CUDASASS_TEST_CUBIN. It exercises text, JSON, graph and register-life output and a known cu++filt symbol. Set NVDISASM and CUFILT to choose executables explicitly.

On Linux, TestInstalledCancellation uses an exec launcher to record the child PID, waits until /proc/PID/exe identifies the selected nvdisasm, then cancels the context. It requires context.Canceled, a reaped process, and empty scratch storage. If the tool finishes before it can be observed, the test fails as inconclusive. It does not suspend the process or substitute a fake disassembler.

From the nvidia module directory:

TMPDIR="$HOME/tmp" GOWORK=off \
  CUDASASS_TEST_CUBIN="$HOME/tmp/cuobjdump-fixture/addone.cubin" \
  NVDISASM=/usr/local/cuda/bin/nvdisasm \
  go test -count=1 -v -run '^TestInstalledCancellation$' ./x/isa/sass

The fixture recipe in x/cudaobjdump/README.md creates a real CUBIN without executing GPU code. These tests inspect binaries and do not require a GPU. Cancellation evidence covers an observed live executable; it does not establish that a particular instruction or output record had already been processed.

TestInstalledKnownJSON separately checks the retained sass.cubin from the native JSON fixture, using nvdisasm 13.0.85. Set CUDASASS_TEST_KNOWN_CUBIN to that file and NVDISASM to the pinned executable. The required CUBIN SHA-256 is cc5746145dc7f00f91c458925f3513a4e4c91ff5a252be744272501055d41027. This fixture uses the source in testdata/README.md, not the broader-indexing cuobjdump example. The test compares metadata and complete function records, including instruction operands, padding and control-flow attributes. Host negative controls alter valid JSON and require these changes to be detected. Neither test executes the kernel.

TestSASS_DOTExport_GraphvizStructure compares (*CFG).DOT with the committed nvdisasm basic-block graph in testdata/roundtrip, and, when nvdisasm is in PATH, with the output of DisassembleCFG for the same cubin. Without the tool the second comparison skips; that is a skip, not a pass.

Host-Only SASS Demos (D01, D04, D10, D14, D15, D17)

  • D01 (Function.WaterfallTrace): Real sm_121a 4-bit stall counts, barrier indices, and wait masks are decoded from the 128-bit instruction control word via DecodeControl and emitted as Chrome Trace Event JSON with one track per warp slot and scoreboard flow arrows. Event timestamps and durations use stall-field order as a heuristic display unit, not true hardware latency (no silicon latency tables exist).
  • D04 (CompareWithWitness & Scramble): CompareWithWitness builds the real sassequiv value-graph bisimulation over Function CFGs and emits the matched (or differing) root WitnessPair expressions and equivalence classes, while Scramble performs bijective GPR renaming of internal temporaries and dependency-checked reordering of adjacent independent instructions via DefsUses. Scramble operates at the disassembled instruction-listing level (without re-encoding 128-bit control words) and CompareWithWitness inherits sassequiv's static value-graph scope, returning Unknown when integer expression forms or control-flow graphs differ.
  • D10 (ScoreboardBlame): Real control-word WriteBarrier/ReadBarrier/WaitMask bits and DefsUses register overlap link waiting instructions back to the barrier-arming producer in straight-line program order. Any arc that crosses a basic-block or branch boundary is explicitly marked Uncertain: true because static straight-line analysis does not prove which predecessor path executed.
  • D14 (DiagnoseFaultPC): Real DefsUses backward def-use slicing from a recorded fault PC's [...] memory operand traces address registers back to c[0x0][offset] parameter loads and maps them through elf.Param ordinals to Go FieldLayout entries. It operates purely on a recorded PC and assumes intra-procedural straight-line register flow without live GPU fault state.
  • D15 (AuditDeterminism): Real DefsUses forward taint propagation tracks SR_NCTAID (grid-size) reads into floating-point accumulation/reduction instructions and flags non-associative RED/REDG/ATOM/ATOMG float atomics while leaving SR_CTAID (block-index) row indexing untainted. It is a conservative static over-approximation over program order and does not prove runtime value invariance for complex predicated loops.
  • D17 (CompareOpTables): Real ObservedLatencies() (derived from ptxas separations in committed sm_121a fixtures) and DecodeControl barrier/stall observations are compared against caller-supplied OpTableClaim entries. The silicon column is explicitly left unmeasured (host-only) with cuda.ErrHardwarePending; no hardware numbers are invented.

Native SASS Decoding and sm_121a Hardware Latencies

Decode, DecodeFunction, DecodeCUBIN, and Native (NativeSource) decode 128-bit SM90 (sm_90/sm_90a), SM100 (sm_100/sm_100a), and SM120 (sm_120/sm_121/sm_121a) SASS instruction words directly in pure Go using generated numeric tables (isa_sm90.gen.go, isa_sm100.gen.go, isa_sm120.gen.go), with NvdisasmSource providing the nvdisasm -hex differential oracle.

The isa_sm*.gen.go files are not part of public trees or release module archives; TestReleaseExcludesISATables and TestReleaseReadinessAndProxyConsumer check that. When they are absent, Decode and DecodeCUBIN return ErrNoISATables (wrapping cuda.ErrUnsupported), and CLI tools (cudavet, cudabin, cudaprof) automatically fall back to .sass sidecars or DisassembleCUBIN (nvdisasm). To generate the tables locally from a sassgen descriptor cache extracted from an installed CUDA nvdisasm binary, run from the nvidia module directory:

SASSGEN_CACHE=/path/to/sassgen/cache/13.5 go generate -run gensasstables ./x/isa/sass

(If SASSGEN_CACHE is unset, gensasstables defaults to $HOME/go/src/github.com/tmc/sassgen/cache/13.5.)

TestSM121aLatencyProbeNative (gated on CUDASASS_LATENCY_NATIVE=1 under an inherited gpu-lock lease on NVIDIA GB10, sm_121a) measures dependent chains, independent issue rates, and binary-patched hot/cold NOP differentials that populate MeasuredSM121aLatencyRecords(), SM121aLatencies(), MeasuredLatencies, and RecomputeSwap.

Documentation

Overview

Package sass parses and analyzes NVIDIA SASS disassemblies, models SM occupancy and memory-hierarchy residency, extracts kernel parameter memory effects, wait bounds, and cubin contracts, audits PTX/LLVM-to-SASS lowering, and checks trace-free bounded SASS equivalence.

Native Decoding

Decode, DecodeFunction, DecodeCUBIN, DecodeCUBINWithPressure, and Native decode 128-bit SM90, SM100/SM103, and SM120/SM121 SASS instruction words in pure Go when the numeric ISA tables (isa_sm90.gen.go, isa_sm100.gen.go, isa_sm120.gen.go) are present. Public trees and release module archives omit those generated files; without them, native decode entry points wrap ErrNoISATables (which itself wraps github.com/tmc/lib/nvidia/x/cuda.ErrUnsupported) and callers fall back to Parse over .sass sidecar listings or DisassembleCUBIN using an installed nvdisasm binary.

To generate the local ISA tables from a sassgen descriptor cache extracted from an installed CUDA nvdisasm binary, run from the nvidia module directory:

SASSGEN_CACHE=/path/to/sassgen/cache/13.5 go generate -run gensasstables ./x/isa/sass

Bounded Equivalence

CompareEquiv, CompareAll, and CompareWithWitness build a shared symbolic value graph over two compilations of a kernel (from Parse or native DecodeCUBIN) and compare their branch conditions and memory-effect chains by bisimulation. When 128-bit instruction encodings are present on a supported target (sm_90/sm_90a, sm_100/sm_100a, sm_120/sm_121a) and local ISA tables are generated, Decode supplies operand roles and register widths so side-effect-free instructions lift to canonical uninterpreted DAG nodes and uniform-datapath (UR/UP) address and integer operations unify with vector (R/P) ones. Instructions with unmodeled memory, barrier, surface, texture, tensor-memory, or control side effects abstain with Unknown rather than Equal.

Kernel Checks

CheckSharedBounds follows each shared memory address as a value of threadIdx.x and reports accesses proved out of the CTA's window, or proved inside it; CheckBarriers reports CTA barriers some threads of a block reach and others skip, and barriers that wait for more threads than a block has. Both report only what they prove and say unknown otherwise.

This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.

Example
package main

import (
	"fmt"
	"log"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	// A sample compiled kernel allocating 40 registers and 1024 bytes static shared memory
	kernel := sass.KernelResource{
		Name:            "matvec_q8_0",
		Registers:       40,
		StaticSharedMem: 1024,
	}

	// Calculate theoretical occupancy on Blackwell (sm_121) with 256 threads/block
	report, err := kernel.Calculate("sm_121", 256, 0)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s: %d/%d warps (%.0f%%) limited by %s\n",
		report.Architecture, report.TheoreticalWarps, report.MaxWarps, report.Occupancy*100, report.LimitingFactor)

	// Add 32 KiB dynamic shared memory
	reportSmem, err := kernel.Calculate("sm_121", 256, 32768)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s (+32KB smem): %d/%d warps (%.0f%%) limited by %s\n",
		reportSmem.Architecture, reportSmem.TheoreticalWarps, reportSmem.MaxWarps, reportSmem.Occupancy*100, reportSmem.LimitingFactor)

}
Output:
sm_121: 48/48 warps (100%) limited by none
sm_121 (+32KB smem): 24/48 warps (50%) limited by shared_memory

Index

Examples

Constants

View Source
const (
	// RCudaAbs32Lo32 patches the low 32 bits of a 64-bit symbol address into
	// a UMOV URd, 32@lo(sym) instruction (0x38 = 56).
	RCudaAbs32Lo32 uint32 = 56

	// RCudaAbs32Hi32 patches the high 32 bits of a 64-bit symbol address into
	// a UMOV URd, 32@hi(sym) instruction (0x39 = 57).
	RCudaAbs32Hi32 uint32 = 57
)

CUDA ELF64 relocation types for sm_121a UMOV 32-bit immediate instructions.

View Source
const (
	RZNum  = 255
	PTNum  = 7
	URZNum = 63
)

Sentinel register numbers. RZ and URZ read as zero and discard writes; PT and UPT read as true. A write to one of them is not a definition.

View Source
const (
	AttrReqNTID     = 0x10 // EIATTR_REQ_NTID (required CTA dimensions)
	EIATTR_REQ_NTID = AttrReqNTID
	EIATTR_REQNTID  = AttrReqNTID
)

ELF attribute IDs in NVIDIA .nv.info sections.

View Source
const (
	AttrParamCBank        = 0x0a // EIATTR_PARAM_CBANK (constant bank parameter offset & size)
	AttrFrameSize         = 0x11 // EIATTR_FRAME_SIZE (per-thread stack frame bytes)
	AttrMinStackSize      = 0x12 // EIATTR_MIN_STACK_SIZE
	AttrMaxRegCount       = 0x1b // EIATTR_MAXREG_COUNT (compiler register ceiling)
	AttrRegCount          = 0x2f // EIATTR_REGCOUNT / EIATTR_REG_COUNT (registers per thread)
	AttrSharedScratch     = 0x30 // EIATTR_SHARED_SCRATCH / EIATTR_SHARED_SIZE_SYSMEM
	AttrReservedSmem0Size = 0x3e // EIATTR_RESERVED_SMEM_0_SIZE
)

ELF attribute IDs in NVIDIA .nv.info sections.

View Source
const (
	EIATTR_PARAM_CBANK        = AttrParamCBank
	EIATTR_FRAME_SIZE         = AttrFrameSize
	EIATTR_MIN_STACK_SIZE     = AttrMinStackSize
	EIATTR_MAXREG_COUNT       = AttrMaxRegCount
	EIATTR_REGCOUNT           = AttrRegCount
	EIATTR_REG_COUNT          = AttrRegCount
	EIATTR_SHARED_SIZE_SYSMEM = AttrSharedScratch
)

Legacy and specification aliases for attribute IDs.

View Source
const (
	LimitRegisters    = "registers"
	LimitSharedMemory = "shared_memory"
	LimitBlockSize    = "block_size"
	LimitBlocks       = "blocks"
	LimitTensorMemory = "tensor_memory"
	LimitCluster      = "cluster"
	LimitNone         = "none"
)

LimitingFactor constants identify which hardware constraint determines theoretical occupancy.

View Source
const (
	// FlightCfgSymbol is the ABI-preserving .nv.global symbol for live tracing control.
	FlightCfgSymbol = "__iket_flight_cfg"

	// FlightCfgSize is the exact 16-byte size of the __iket_flight_cfg struct.
	FlightCfgSize = 16

	// GlobalSection is the ELF section name for initialized device globals.
	GlobalSection = ".nv.global.init"

	// FlightModeOff disables instrumentation (uniform fast path bypass).
	FlightModeOff uint32 = 0

	// FlightModeEntryExit traces entry and exit flight boundaries only.
	FlightModeEntryExit uint32 = 1

	// FlightModeFull traces full instructions/events.
	FlightModeFull uint32 = 2
)
View Source
const (
	// SM121aMaxGPRs is the maximum number of general-purpose registers per
	// thread on sm_121a (R0..R254; R255 is the RZ zero sink).
	SM121aMaxGPRs = 255

	// SM121aMaxPreds is the number of allocatable predicate registers on
	// sm_121a (P0..P6; P7 is PT).
	SM121aMaxPreds = 7

	// SM121aMaxUGPRs is the number of allocatable uniform general-purpose
	// registers on sm_121a (UR0..UR62; UR63 is URZ).
	SM121aMaxUGPRs = 63

	// SM121aMaxBarriers is the number of hardware scoreboard barriers on
	// sm_121a (indices 0..5; 7 is NoBarrier).
	SM121aMaxBarriers = 6
)

Architectural resource limits for sm_121a.

View Source
const CoverageMapSize = 65536

CoverageMapSize is the number of counters in an edge coverage map, cuFuzz's MAP_SIZE.

View Source
const DefaultMaxNOPFraction = 0.10

DefaultMaxNOPFraction is the interior NOP fraction [Compare] reports above.

Only NOPs ahead of a kernel's last real instruction are counted. Every kernel ends in NOPs, because ptxas pads the section to its alignment, and on a short kernel that padding is a third of the instructions; counting it would make the check fire everywhere and mean nothing. A NOP in the body is the other thing: ptxas issuing nothing to hold a pipe, which is what displaces the instruction mix a throughput prediction was made from.

View Source
const FlightEventSlotBytes = 32

FlightEventSlotBytes is the stride of each flight recorder event slot in bytes (matching iket.FlightRecordSize).

View Source
const HierarchySchema = 1

HierarchySchema is the version of the JSON form of Hierarchy. It changes whenever a field changes meaning.

View Source
const NoBarrier = 7

NoBarrier is the write- or read-barrier index meaning the instruction sets no barrier. It is a real encoded value, not an absence marker.

View Source
const PTXTextFile = ".nv_debug_ptx_txt"

PTXTextFile is the name nvdisasm gives the embedded PTX text. It is exported so a caller can recognise the name in data it did not parse here; a caller that has a SourceDirective should read its Kind instead.

View Source
const RegisterFileSize = 65536

RegisterFileSize is the number of 32-bit registers in one SM's register file on sm_90 through sm_121.

View Source
const StallSampleUnavailable = -1.0

StallSampleUnavailable is the percentage StallProfile carries when no sampler measured the instruction. It is not zero: an instruction that was never sampled and an instruction sampled at zero percent are different facts, and only the second is a measurement. The sentinel follows cudaroofline's FloorUnavailable.

View Source
const ToolName = "nvdisasm"

ToolName is the executable Disassembler runs. It is also the name cudatool.Capabilities records option sets under.

Variables

View Source
var (
	// Volta V100 (SM 7.0). cudadevicetable has no sm_70 profile.
	SM70 = DeviceProperties{
		Architecture:            "sm_70",
		MaxThreadsPerBlock:      1024,
		WarpSize:                32,
		MaxWarpsPerSM:           64,
		MaxBlocksPerSM:          32,
		MaxRegistersPerSM:       65536,
		MaxSharedMemoryPerSM:    98304,
		MaxSharedMemoryPerBlock: 49152,
		MaxSharedMemoryOptin:    98304,
		RegAllocationUnit:       256,
		SmemAllocationUnit:      128,
	}

	SM75  = profileLimits("sm_75", "sm_75")    // Turing T4
	SM80  = profileLimits("sm_80", "sm_80")    // Ampere A100
	SM86  = profileLimits("sm_86", "sm_86")    // Ampere A10, RTX 30xx
	SM87  = profileLimits("sm_87", "sm_87")    // Jetson Orin
	SM89  = profileLimits("sm_89", "sm_89")    // Ada L40S, L4, RTX 40xx
	SM90  = profileLimits("sm_90", "sm_90a")   // Hopper H100, H200
	SM100 = profileLimits("sm_100", "sm_100a") // Blackwell B200, GB200
	SM103 = profileLimits("sm_103", "sm_103a") // Blackwell Ultra B300, GB300
	SM110 = profileLimits("sm_110", "sm_110a") // Jetson Thor
	SM120 = profileLimits("sm_120", "sm_120a") // Blackwell RTX PRO 6000, RTX 5090
	SM121 = profileLimits("sm_121", "sm_121a") // Blackwell GB10
)

Predefined device specifications for modern NVIDIA GPU architectures.

Every architecture but sm_70 takes its per-SM limits -- warps, blocks, shared memory, Tensor Memory and the cluster limit -- from the cudadevicetable profile of its "a" target, which holds a probed value where a device was probed and a cited datasheet value elsewhere. What is written here is what that table does not hold: registers and allocation granularities.

View Source
var (
	// ForbidSIMDFallbacks contains scalar integer arithmetic and bit-manipulation
	// opcodes emitted when packed SIMD operations (such as IDP4A / IDP.4A) fall back
	// to scalar computation and lane unpacking.
	ForbidSIMDFallbacks = []string{
		"IMAD",
		"IMAD.WIDE",
		"SHR",
		"SHF",
		"BFE",
	}

	// ForbidFMAFallbacks contains separate multiply and add opcodes emitted when
	// fused multiply-add (FFMA / DFMA) falls back to unfused arithmetic.
	ForbidFMAFallbacks = []string{
		"FMUL",
		"FADD",
		"DMUL",
		"DADD",
	}

	// ForbidWarpShuffleFallbacks contains shared memory opcodes emitted when
	// warp register shuffle communication (SHFL.SYNC) falls back to shared memory staging.
	ForbidWarpShuffleFallbacks = []string{
		"LDS",
		"STS",
	}
)

Fallback opcode forbid lists for Disassembly.AssertOpcodes.

These lists capture legal-but-unoptimized fallback sequences that the compiler emits when it fails to lower to specialized hardware instructions. Auditing against these lists ensures that silent performance regressions fail the audit gate.

View Source
var (
	ErrNoDefinition        = errors.New("missing CUDA definition")
	ErrAmbiguousDefinition = errors.New("ambiguous CUDA definition")
)

Errors DefinitionLine reports, distinguished because a caller searching several files must tell them apart: a file that does not define the kernel is an ordinary miss to carry on past, while two definitions in one file are a refusal that another file's answer must not paper over.

View Source
var (
	// ErrRegCountExceeded reports that allocating cave scratch registers would
	// exceed the architecture's GPR limit.
	ErrRegCountExceeded = errors.New("cudasass: kernel register count exceeds architecture limit")

	// ErrUnsupportedDisplacedOp reports that a displaced entry or exit
	// instruction is not in the trampoline replay allowlist.
	ErrUnsupportedDisplacedOp = errors.New("cudasass: displaced instruction is not in the trampoline allowlist")

	// ErrDisplacedPCRelative reports that a displaced instruction is PC-relative
	// and cannot be relocated into the trampoline cave.
	ErrDisplacedPCRelative = errors.New("cudasass: displaced instruction is PC-relative")

	// ErrDisplacedWaitBarrier reports that a displaced instruction waits on a
	// scoreboard barrier set prior to the trampoline.
	ErrDisplacedWaitBarrier = errors.New("cudasass: displaced instruction waits on a pre-existing scoreboard barrier")

	// ErrNoExitInstruction reports that no EXIT instruction was found in the kernel.
	ErrNoExitInstruction = errors.New("cudasass: no EXIT instruction found")

	// ErrUnsupportedMachine reports that the ELF e_machine is not EM_CUDA.
	ErrUnsupportedMachine = errors.New("cudasass: unsupported ELF e_machine")

	// ErrKernelSymbolAbsent reports that the kernel symbol is missing from .symtab.
	ErrKernelSymbolAbsent = errors.New("cudasass: kernel symbol not found")

	// ErrMissingConstant0Offset reports that the kernel's .nv.constant0 section
	// is missing or too small for the cave's constant-bank descriptor offset.
	ErrMissingConstant0Offset = errors.New("cudasass: missing .nv.constant0 offset")

	// ErrUnsupportedFlightMode reports that the requested flight recorder mode
	// is not supported by the entry/exit trampoline patcher.
	ErrUnsupportedFlightMode = errors.New("cudasass: unsupported flight mode")
)
View Source
var (
	// ErrTextSectionAbsent means the image has no text section for the kernel.
	ErrTextSectionAbsent = errors.New("no text section for the kernel")
	// ErrSectionNotCode means the named section is not allocated executable
	// code, so its bytes are not instructions.
	ErrSectionNotCode = errors.New("section is not executable code")
	// ErrSectionNotInFile means the section occupies no file bytes, which a
	// NOBITS section does not.
	ErrSectionNotInFile = errors.New("section has no bytes in the file")
	// ErrPatchUnaligned means the target offset is not on a 16-byte
	// instruction boundary.
	ErrPatchUnaligned = errors.New("patch offset is not instruction-aligned")
	// ErrPatchOutOfRange means the target instruction lies outside the section.
	ErrPatchOutOfRange = errors.New("patch lies outside the section")
	// ErrOriginalMismatch means the bytes already at the target offset are not
	// the ones the plan was built from. This is the guard against a patch that
	// lands at the wrong offset, which is a failure no load test can catch
	// because a wrong-offset patch loads.
	ErrOriginalMismatch = errors.New("bytes at the patch offset are not the instruction the plan was built from")
	// ErrRelocationOverlap means a relocation applies to the bytes being
	// patched, so the loader will rewrite part of what was written.
	ErrRelocationOverlap = errors.New("a relocation applies to the patched bytes")
	// ErrMirroredText means the image carries a second copy of the patched
	// text in a form this path cannot update. See [CubinImage.Mirrors].
	ErrMirroredText = errors.New("the image carries a second copy of the patched text")
	// ErrLockNotHeld means a device load was requested without the GPU lock.
	ErrLockNotHeld = errors.New("GPU lock not held")
	// ErrNothingPatched means an image was offered for loading that no patch
	// reached, so loading it would qualify nothing.
	ErrNothingPatched = errors.New("no patch was applied")
)

Errors the patch path returns. Each is a refusal, not a warning: the path emits a patched image or it emits nothing.

Clauses lists every clause, in order.

View Source
var DefaultLowerings = []Lowering{

	{PTX: "ld.global.v4", SASS: []string{"LDG.E.128"}, VectorWidth: 4, ScalarSASS: []string{"LDG.E"}},
	{PTX: "st.global.v4", SASS: []string{"STG.E.128"}, VectorWidth: 4, ScalarSASS: []string{"STG.E"}},
	{PTX: "ld.global.v2", SASS: []string{"LDG.E.64"}, VectorWidth: 2, ScalarSASS: []string{"LDG.E"}},
	{PTX: "st.global.v2", SASS: []string{"STG.E.64"}, VectorWidth: 2, ScalarSASS: []string{"STG.E"}},
	{PTX: "ld.local", SASS: []string{"LDL"}, Exclusive: true, Spill: true},
	{PTX: "st.local", SASS: []string{"STL"}, Exclusive: true, Spill: true},

	{PTX: "shfl.sync", SASS: []string{"SHFL"}, Exclusive: true},
	{PTX: "vote.sync", SASS: []string{"VOTE"}, Exclusive: true},
	{PTX: "dp4a", SASS: []string{"IDP4A"}, Exclusive: true},
	{PTX: "dp2a", SASS: []string{"IDP2A"}, Exclusive: true},
	{PTX: "tex", SASS: []string{"TEX", "TLD"}, Exclusive: true},
	{PTX: "mma", SASS: []string{"HMMA", "IMMA", "OMMA", "QMMA"}, Exclusive: true},

	{PTX: "fma.rn.f32", SASS: []string{"FFMA"}},
	{PTX: "fma.rn.f64", SASS: []string{"DFMA"}},
	{PTX: "atom.global", SASS: []string{"ATOMG"}},
	{PTX: "atom.shared", SASS: []string{"ATOMS"}},
	{PTX: "red.global", SASS: []string{"REDG"}},
	{PTX: "ld.global", SASS: []string{"LDG"}},
	{PTX: "st.global", SASS: []string{"STG"}},
	{PTX: "ld.shared", SASS: []string{"LDS"}},
	{PTX: "st.shared", SASS: []string{"STS"}},
}

DefaultLowerings is the table [Compare] uses when LoweringOptions.Lowerings is nil.

It is deliberately short. An entry earns its place by naming a lowering whose failure is worth a report: a specialized unit that went unused, an instruction ptxas has no other reason to emit, or memory traffic that says where a value ended up. Opcodes that ptxas rearranges freely are absent, because an entry that fires on every kernel reports nothing.

Notably absent are the scalar mul and add opcodes. ptxas contracts them into FFMA and DFMA, so an entry for them would flag every kernel compiled with the default -fmad=true. A caller auditing for contraction adds them.

View Source
var ErrConstraint = errors.New("kernel violates its SASS constraint")

ErrConstraint is wrapped by the error ProveDisassembly and ProveCubin return when a kernel violates its constraint.

View Source
var ErrControlChanged = errors.New("plan changes bits outside the control field")

ErrControlChanged reports that a control-only plan changes more than the control field.

View Source
var ErrDegenerate = errors.New("cudasass: graph is degenerate: it has an indirect branch")

ErrDegenerate reports a control flow graph with an indirect branch, whose paths an analysis cannot enumerate.

View Source
var ErrNoISATables = fmt.Errorf("%w: native SASS ISA tables not generated; run go generate -run gensasstables ./x/isa/sass", cuda.ErrUnsupported)

ErrNoISATables reports that native SASS ISA decoder tables are not compiled into the binary, as in a release module archive; run "go generate -run gensasstables ./x/isa/sass" to generate isa_sm*.gen.go locally, or disassemble via DisassembleCUBIN or Parse. It wraps cuda.ErrUnsupported.

View Source
var ErrNoTargetOption = errors.New("cudasass: no -arch option in .note.nv.tkinfo")

ErrNoTargetOption reports a cubin whose .note.nv.tkinfo records no -arch option, so its feature-set suffix is unknown.

View Source
var ErrNotTextSection = errors.New("code section is not a .text section")

ErrNotTextSection means a listing has an instruction under a code section other than a kernel's .text.<kernel>, such as the .nv.capmerc.text.<kernel> section ptxas emits beside it. Parse returns it, wrapped with the section's name, rather than attribute the instruction to the kernel.

View Source
var ErrOutputLimit = cudatool.ErrOutputLimit

ErrOutputLimit means nvdisasm wrote more than the output budget. The truncated listing is not parsed.

View Source
var ErrUnsupportedOption = cudatool.ErrUnsupportedOption

ErrUnsupportedOption means the resolved nvdisasm does not accept an option the requested Options would emit, by name or by arity. Disassembler.Disassemble reports it instead of running a command line the tool would reject.

Functions

func AllowedDisplacedEntryOpcode

func AllowedDisplacedEntryOpcode(opcode string) bool

AllowedDisplacedEntryOpcode reports whether opcode's base mnemonic is in the displaced-entry trampoline replay allowlist (e.g. NOP, LDC, LDCU, S2R, S2UR, IADD).

func AuditSM100Function

func AuditSM100Function(fn Function) []string

AuditSM100Function checks static Blackwell sm_100a SASS invariants on fn and returns human-readable findings for any violations. An empty or nil slice means all invariants hold.

Checked invariants:

  • Every UTMMA instruction must be guarded by a leader predicate (@P0, @UP0, etc.) or preceded by an ELECT leader-election instruction in the function.
  • Every function containing UTMMA must also issue UTMACMDFLUSH (commit) and LDTM (TMEM -> register readback).
  • Every block-scaled UTMMA (.MXF4NVF4, .MXF8F6F4, .BLOCK_SCALE) must have UTMACP scale staging into TMEM in the function.

func AuthorizeLoad

func AuthorizeLoad(p PatchedImage, env func(string) string) error

AuthorizeLoad is the host-side gate every device load of a patched image passes. It loads nothing itself.

env is the environment lookup, normally os.Getenv. The GPU lock is required because a candidate binary of unknown validity can hang or fault the device, and the device is shared. The lock must be one an ancestor holds, as [cudalock.Inherited] checks: run the load under gpu-lock itself, not under "gpu-lock env GPU_LOCK_HELD=1", which replaces the holder's pid with a value that names no holder.

func BaseOpcode

func BaseOpcode(opcode string) string

BaseOpcode returns the root mnemonic without modifiers or architectures (e.g. IMAD.WIDE -> IMAD).

func CheckControlOnly

func CheckControlOnly(plans []MutationPlan, arch Arch) error

CheckControlOnly reports whether every plan changes only the control field of its instruction on arch.

func CheckPatchCubinArch

func CheckPatchCubinArch(arch Arch) error

CheckPatchCubinArch reports whether PatchCubinEntryExit supports arch.

It returns nil for SM121a, an error wrapping cuda.ErrHardwarePending for known architectures (including "sm_103" and SM103a) whose SASS opcodes, control-word bitfields, or relocation IDs have not yet been verified against nvdisasm/silicon, and an error wrapping cuda.ErrUnsupported for unknown architectures.

func CheckRegisterFile

func CheckRegisterFile(groups []WarpGroupRegs) error

CheckRegisterFile reports whether the warp groups of one CTA fit the register file: Σ 32·Warps·round8(RegsPer) ≤ RegisterFileSize, with registers counted at the per-thread allocation granularity of 8.

It checks the arithmetic only. Whether more than one CTA fits an SM, and any per-warp allocation unit beyond the granularity of 8, are left to the occupancy calculator.

func CheckWaits

func CheckWaits(d *Disassembly) error

CheckWaits returns a *WaitError if any function of d has an unbounded or unclassified wait, or a control flow graph that cannot be built, so that a loader can refuse a module whose kernels could hang on a dead peer.

func CompareWithWitness

func CompareWithWitness(before, after *Function) (Result, []WitnessPair)

CompareWithWitness compares two compilations of one function and returns the matched (or mismatched) value-graph root pairs as a witness.

Example
package main

import (
	"fmt"

	cudasass "github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	const listing = `.section .text.k
.text.k:
/*0000*/ LDC R2, c[0x0][0x160] ;
/*0010*/ LDC R3, c[0x0][0x164] ;
/*0020*/ FADD.FTZ.RN R4, R2, R3 ;
/*0030*/ FMUL.FTZ.RN R5, R2, 0x3f800000 ;
/*0040*/ FADD.FTZ.RN R6, R4, R5 ;
/*0050*/ STG.E [R0.64], R6 ;
/*0060*/ EXIT ;
`
	d, err := cudasass.ParseString(listing)
	if err != nil {
		panic(err)
	}
	orig := d.Functions[0]
	scrambled, err := cudasass.Scramble(orig, 7)
	if err != nil {
		panic(err)
	}

	res, pairs := cudasass.CompareWithWitness(orig, scrambled)
	fmt.Printf("scrambled verdict: %s (%d witness pairs)\n", res.Verdict, len(pairs))
	for _, p := range pairs {
		fmt.Printf("  root=%s equal=%v\n", p.Root, p.Equal)
	}

	// Mutate one rounding bit: FADD.FTZ.RN -> FADD.FTZ.RZ.
	mutant := *scrambled
	mutant.Instructions = append([]cudasass.Instruction(nil), scrambled.Instructions...)
	for i := range mutant.Instructions {
		if mutant.Instructions[i].Opcode == "FADD.FTZ.RN" {
			mutant.Instructions[i].Opcode = "FADD.FTZ.RZ"
			break
		}
	}
	mres, _ := cudasass.CompareWithWitness(orig, &mutant)
	fmt.Printf("mutant verdict: %s\n", mres.Verdict)
}
Output:
scrambled verdict: equal (1 witness pairs)
  root=exit:0.0 equal=true
mutant verdict: different

func ComputePressure

func ComputePressure(fn *Function, arch Arch) (map[uint64]RegisterPressure, error)

ComputePressure computes per-instruction live register counts across fn's CFG by backward dataflow to a fixed point, without invoking nvdisasm.

func Covered

func Covered(inst Instruction) (string, bool)

Covered returns the name of the form inst belongs to, and false if inst is outside the covered subset.

func DecodeBranchTarget

func DecodeBranchTarget(inst Instruction) (uint64, bool)

DecodeBranchTarget extracts the branch target address from a BRA instruction.

func DefinitionLine

func DefinitionLine(source, sym string) (int, error)

DefinitionLine returns the 1-based line of source that defines the kernel carried in a CUBIN as the symbol sym.

The CUBIN spells a mangled symbol and the source spells the name alone, so the symbol is first reduced to its qualified name; an extern "C" name passes through, and every instantiation of a template reduces to the one definition they were compiled from.

Reporting a line requires evidence that the name is defined there. A comment mentioning the kernel, a forward declaration and a launch site all name it without being its source location, and attributing a kernel to one of those misplaces every line the capture reports for it. Two definitions of the same name are ambiguous and are refused rather than resolved to the first.

func DisassembleCFG

func DisassembleCFG(cubin []byte, basicBlocks bool) (string, error)

DisassembleCFG invokes nvdisasm on cubin bytes to produce Graphviz DOT control flow graph text. If basicBlocks is true, basic blocks are generated instead of hyperblocks.

func EdgeIndex

func EdgeIndex(prev uint64, block int32) (index int, next uint64)

EdgeIndex returns the coverage map index of the transition into block from the location prev, and the location to pass for the next transition.

It is the AFL edge hash as cuFuzz's record_coverage_edge_count computes it: the index is (MAP_SIZE/2) + ((prev ^ block) % (MAP_SIZE/2)), with block sign-extended to 64 bits as C converts an int, and the next location is block >> 1, an arithmetic shift. The shift makes A→B and B→A different edges. Indices therefore lie in the upper half of the map.

Block IDs are the caller's. cuFuzz derives them from a hash of the function name and the block's position in NVBit's CFG_t, and a CFG block index can be used the same way.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	// The same two blocks in opposite orders are different edges.
	_, prev := sass.EdgeIndex(0, 5)
	ab, _ := sass.EdgeIndex(prev, 9)
	_, prev = sass.EdgeIndex(0, 9)
	ba, _ := sass.EdgeIndex(prev, 5)
	fmt.Println(ab, ba)
}
Output:
32779 32769

func ExtractDOTGraph

func ExtractDOTGraph(dot string, name string) (string, error)

ExtractDOTGraph extracts the digraph definition for the named kernel from Graphviz DOT text. If name is empty once unquoted, it names no kernel and the entire dot text is returned. Matching checks exact name, trimmed quoted name, and substring match against mangled symbols.

func IsSIMD

func IsSIMD(opcode string) bool

IsSIMD returns true if the opcode is a SIMD or Tensor Core instruction.

func IsScalarArithmetic

func IsScalarArithmetic(opcode string) bool

IsScalarArithmetic returns true if the opcode is a scalar arithmetic or logical operation.

func JoinPressure

func JoinPressure(disasm *Disassembly, pressureMap map[string]map[uint64]RegisterPressure) error

JoinPressure performs a total join between a parsed Disassembly (Pass 1) and a register pressure map from --life-range-mode count (Pass 2).

Every instruction present in Pass 2 must match an instruction in Pass 1. Every instruction in Pass 1 must match an entry in Pass 2, with the sole exception of alignment NOP padding at the end of a section, which is given 0 pressure.

func ListDOTGraphs

func ListDOTGraphs(dot string) []string

ListDOTGraphs returns the names of the function graphs in Graphviz DOT text.

nvdisasm prints a whole module as one digraph named "f" and puts each function in a "cluster_<function>" subgraph of it, so the top-level name identifies nothing a caller can ask for. Where those clusters are present they are the graphs, and the names returned are the functions'. A digraph with no clusters is reported under its own name.

Every name returned is one ExtractDOTGraph will extract. A name that unquotes to nothing is not reported: DOT permits an anonymous graph, and an empty name is how ExtractDOTGraph is asked for the whole document, so such a graph names nothing a caller can ask for.

func MatchKey

func MatchKey(name string) string

MatchKey reduces a kernel symbol to the name the PTX and the SASS for one kernel agree on.

nvcc writes the same Itanium-mangled symbol at both levels, so most pairs match on the symbol itself. The levels part company once the SASS has been through a demangler: cu++filt rewrites .text._Z10atomicDropPfPKfi as .text.atomicDrop(float *, const float *, int), which no longer resembles the PTX symbol. MatchKey strips either spelling down to the qualified function name, "atomicDrop" here, and leaves a name it does not recognize alone.

Template arguments are dropped, so MatchKey("_Z3fooIiEvPT_") and MatchKey("foo<int>(int*)") are both "foo". A demangled template kernel is still the one case MatchKey cannot rescue on its own: cu++filt writes the return type ahead of the name. The SASS section parser preserves the whole signature, but MatchKey does not remove that return type.

func Matches

func Matches(opcode, spelling string) bool

Matches reports whether opcode is an instance of spelling.

func NormalizeInstruction

func NormalizeInstruction(inst Instruction) string

NormalizeInstruction returns a normalized string representation of an instruction, stripping instruction address offsets, memory offset drift, and normalizing whitespace.

func NormalizeLine

func NormalizeLine(line string) string

NormalizeLine parses and normalizes a single SASS disassembly line.

func NormalizeOperands

func NormalizeOperands(opcode, operands string) string

NormalizeOperands normalizes operands by stripping memory offset drift, constant bank drift, branch target offsets, and normalizing spacing.

func OptimizeBasicBlockControl

func OptimizeBasicBlockControl(block []Bundle, lat Latencies) ([]Bundle, ControlOptStats, error)

OptimizeBasicBlockControl returns block with tightened control codes and what changed. It never changes an instruction's opcode, operands or order, and changes its encoding only in the control field.

The input must itself pass VerifyHazardSafety with lat; otherwise the block is refused, since the model would be checking a schedule it already considers wrong. Each change is made, checked with VerifyHazardSafety and a boundary check, and kept only if both pass. The passes, in order:

  • Scoreboard splitting: a variable-latency producer that shares a write barrier with another, whose first reader comes after an earlier wait on that barrier, is moved to a barrier the block neither sets nor waits on, and its first reader waits on the new barrier instead. The earlier wait then no longer waits for it. A producer with no reader in the block is not moved, since a successor block may wait on its barrier.
  • Stall tightening: the stall of an instruction is lowered to the smallest value, not below 1, that still passes both checks, when it and the instruction after it are fixed-latency, not a branch or fence, and of a class lat has a latency for. Other stalls are left alone because they may pace a functional unit, which the model does not know: in testdata/sm121a-loop-13.3.sass ptxas pads a DFMA chain with NOPs stalling 15 cycles each although the scoreboard already orders the chain.
  • Operand reuse: on FFMA, FADD, FMUL, IMAD, IADD and IADD3 whose yield bit is set, the reuse flag for source slot s is set when the next instruction is one of those, reads the same GPR in slot s and does not wait on a barrier, and this instruction does not write it. Slot 0 is bit 0, as observed on sm_121a; slots 1 and 2 as bits 1 and 2 are assumed.
  • Sticky tensor issue: in a run of two or more consecutive tensor-pipe instructions (see Bundle.Tensor) none of which waits on a barrier, the yield bit is set on every instruction but the last.

Encodings of instructions whose control code changed are rewritten with EncodeControl when the instruction carries one.

func ParamBase

func ParamBase(target string) (int, error)

ParamBase returns the bank offset of the parameter block for target, for a listing whose cubin is not at hand. CubinImage.ParamLayout reads it from the cubin.

func ParseCuobjdumpResUsage

func ParseCuobjdumpResUsage(text string) (map[string]KernelResource, error)

ParseCuobjdumpResUsage parses the text output of `cuobjdump -res-usage`. It returns a mapping of kernel symbol names to their reported resource usage.

func ParseLifeRangeCount

func ParseLifeRangeCount(r io.Reader) (map[string]map[uint64]RegisterPressure, error)

ParseLifeRangeCount parses nvdisasm output formatted with --life-range-mode count. It returns a map of kernel name to instruction address to RegisterPressure.

In count mode, nvdisasm formats trailing table columns:

/*0000*/ LDC R1, c[0x0][0x37c] ; // |   1   |        |        |         |

nvdisasm prints a header row naming the columns before each function's instructions, and leaves out a column for a register class the function does not use: an sm_121a kernel with no predicates is counted under "GPR | UGPR | UPRED". The header decides which count each cell is. A listing with no header is read in the order GPR, PRED, UGPR, UPRED. A blank cell represents zero, and a column name this package does not know is an error.

ParseLifeRangeCount keys kernels by the names Parse reads. It returns an error for a ".text." label or a ".section" directive Parse refuses as malformed, as it does for other input it cannot read, rather than keying the instructions that follow under a guessed name.

func PatchCubinArchGaps

func PatchCubinArchGaps(arch Arch) []string

PatchCubinArchGaps returns the list of unverified encoding/ABI items that prevent PatchCubinEntryExit from patching arch, or nil when arch is calibrated and supported (currently SM121a).

func PatchCubinEntryExit

func PatchCubinEntryExit(cubin []byte, kernelName string) ([]byte, error)

PatchCubinEntryExit injects 128-bit entry and pre-EXIT BRA trampolines into the cubin, creates/updates .nv.global __iket_flight_cfg, and adjusts .nv.info metadata. Kernel launch parameters in .nv.constant0 remain untouched.

func PatchCubinEntryExitWithConfig

func PatchCubinEntryExitWithConfig(image []byte, kernelName string, cfg PatchConfig) ([]byte, error)

PatchCubinEntryExitWithConfig injects entry and pre-EXIT BRA trampolines into the cubin with the provided initial PatchConfig in __iket_flight_cfg.

The cave is appended to .text.<kernelName> through cubin.File.ReplaceText, which updates the section and symbol sizes and lays out the sections after it. The kernel's .nv.capmerc.text.<kernelName> section, which the new code would leave stale, is stripped.

func SM103ACalibrationProbeSource

func SM103ACalibrationProbeSource() string

SM103ACalibrationProbeSource returns a self-contained CUDA C (.cu) probe kernel designed to exercise sm_103a PatchCubinEntryExit calibration (control-word bitfield layout, all 13 flight-cave/trampoline instruction families, and ELF64 relocation IDs for a __device__ global symbol) in a single compile/disassemble pass on CUDA 13.4+:

  1. control-word bitfield layout (nvdisasm -b SM103a -json);
  2. 12-bit opcodes and operand bitfields for all 13 flight-cave/trampoline instructions (BRA, NOP, EXIT, LDCU.64, UMOV, MOV, LDG.E, STG.E, ISETP, ATOMG.E.ADD, IMAD.WIDE, CS2R, S2UR);
  3. ELF64 relocation type IDs (32@lo / 32@hi) for UMOV materializing a __device__ global symbol address.

func TextSectionName

func TextSectionName(kernel string) string

TextSectionName returns the conventional text section name for a kernel.

func UnfencedBulkDestinations

func UnfencedBulkDestinations(fn *Function, target string) ([]uint64, error)

UnfencedBulkDestinations reports PCs of possible generic loads from a bulk async copy's global destination after a proxy-restricted wait. It recognizes the contiguous CUDA 13.5 sequence observed on sm_100a, sm_103a, and sm_121a, with both 64-bit addresses loaded from the same constant slot in the same basic block. The absence of an advisory does not imply ordering.

Example
f, err := os.Open("testdata/proxywait/sm_100a.read.sass")
if err != nil {
	panic(err)
}
defer f.Close()
dis, err := Parse(f)
if err != nil {
	panic(err)
}
pcs, err := UnfencedBulkDestinations(dis.Function("proxywait_destination_restricted"), "sm_100a")
fmt.Printf("%x %v\n", pcs, err)
Output:
[150] <nil>

func UnfencedBulkSources

func UnfencedBulkSources(fn *Function, target string) ([]uint64, error)

UnfencedBulkSources reports potential generic-to-async proxy ordering defects. It only considers an adjacent shared store and shared-to-global bulk copy that use the exact same address operand in one basic block. CUDA 13.5 controls for sm_100a, sm_103a, and sm_121a establish this pattern. An adjacent pair may not describe all synchronization in a kernel.

func VerifyHazardSafety

func VerifyHazardSafety(block []Bundle, lat Latencies) error

VerifyHazardSafety checks every register dependency within block against its control codes, using lat for fixed-latency results:

  • a fixed-latency result is read only after its latency has elapsed in accumulated stall counts, and is overwritten by a later fixed-latency instruction only if that write completes later;
  • a result guarded by a write barrier is read or overwritten only after some instruction at or before the reader waits on that barrier;
  • a source guarded by a read barrier is overwritten only after such a wait.

It returns a *HazardError for the first violation, and an error if a fixed-latency producer with a reader in the block has no entry in lat. Dependencies that cross the block boundary are not checked here; see OptimizeBasicBlockControl.

func Waves

func Waves(blocks, slots int) (ratio float64, rounds int)

Waves reports how a grid of blocks runs on a device that holds slots blocks at once, such as SMs times resident blocks per SM. The ratio is blocks/slots: 2.25 means two full waves and a last wave a quarter full. Rounds is the number of waves the device runs, the ratio rounded up. Both are zero when blocks or slots is not positive.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	// 300 blocks on 132 SMs holding one block each.
	ratio, rounds := sass.Waves(300, 132)
	fmt.Printf("%.2f waves in %d rounds\n", ratio, rounds)
}
Output:
2.27 waves in 3 rounds

func WriteFlightConfig

func WriteFlightConfig(image []byte, cfg PatchConfig) ([]byte, error)

WriteFlightConfig updates __iket_flight_cfg in place within a patched cubin. Only the 16 bytes of the configuration change.

Types

type AlignedAccess

type AlignedAccess struct {
	Address      uint64 // offset of the instruction in the function
	Opcode       string // e.g. "LDG.E.128.CONSTANT"
	Width        int    // bytes accessed, and the alignment the pointer needs
	ParamOrdinal int    // the pointer parameter

	// Guard is the offset of a branch that keeps every misaligned value
	// of the pointer away from the access, and Guarded reports that there
	// is one. See [AlignedAccesses] for what counts.
	Guard   uint64
	Guarded bool
}

An AlignedAccess is a global memory instruction whose address is a kernel pointer parameter plus terms that are all multiples of the access width. Such an access is aligned exactly when the pointer is: a pointer Width bytes aligned never faults on it, and any other pointer always does.

func AlignedAccesses

func AlignedAccesses(fn *Function, k elfinspect.Kernel) ([]AlignedAccess, error)

AlignedAccesses returns the global loads, stores and atomics of fn whose alignment requirement falls entirely on one pointer parameter of k, in address order.

The address of each access is traced back to an LDC of the parameter through IMAD.WIDE and IADD.64 steps whose immediate stride or increment is a multiple of the access width; a trace that leaves the access's chain of single-predecessor blocks, meets a predicated definition, or meets any other instruction ends without a result, and the access is not reported. It is therefore a list of accesses proven to need the alignment, not of every access that does.

An access is Guarded when some branch on a LOP3 of the parameter makes the access unreachable from the entry for every misaligned value of the parameter's low bits, whatever the other operands hold: the shape of `if ((p & 15) == 0) { vector path } else { scalar path }`.

k must come from the same cubin as fn; its ParamBank and Params map the constant bank offsets the SASS reads to parameter ordinals.

func (AlignedAccess) String

func (a AlignedAccess) String() string

type AppliedPatch

type AppliedPatch struct {
	Address    uint64 // the instruction's address within the section
	FileOffset uint64 // where the bytes were written in the file
	Before     Encoding
	After      Encoding
}

An AppliedPatch records one instruction replaced in the image.

type Arch

type Arch string

Arch names the architecture an encoding fact was observed on.

const (
	// SM103a identifies Blackwell Ultra (GB300/B300) arch-accelerated target sm_103a.
	SM103a Arch = "sm_103a"
)

Additional SM architecture constants for cubin patching and capability checks.

const SM121a Arch = "sm_121a"

SM121a is the only architecture this model is calibrated for.

func CubinArch

func CubinArch(image []byte) (Arch, error)

CubinArch returns the Arch encoded in image's CUDA ELF header, or an error if image is not a little-endian EM_CUDA ELF or encodes no SM number.

type ArchFeature

type ArchFeature struct {
	ID          string   `json:"id"`
	Name        string   `json:"name"`
	MinSM       int      `json:"min_sm"`
	Description string   `json:"description"`
	Opcodes     []string `json:"opcodes"`
}

ArchFeature describes one SM-level hardware feature and its SASS evidence.

func ArchFeatures

func ArchFeatures(arch string) []ArchFeature

ArchFeatures returns the hardware features available on the given compute capability. It returns nil for unrecognized architectures.

type ArchitectureDiff

type ArchitectureDiff struct {
	BaseInstructions   int
	TargetInstructions int
	InstructionDelta   int

	BaseBranches   int
	TargetBranches int
	BranchDelta    int

	BaseSizeBytes   int
	TargetSizeBytes int
	TotalSizeDelta  int

	BaseScalarCount   int
	TargetScalarCount int
	ScalarDelta       int

	BaseSIMDCount   int
	TargetSIMDCount int
	SIMDDelta       int

	Spills        SpillDiff
	Substitutions []OpcodeSubstitution
}

ArchitectureDiff summarizes architectural changes between two function versions.

type BarrierIssue

type BarrierIssue struct {
	Address uint64 // the barrier
	Opcode  string
	Proved  bool   // the mismatch is proved; otherwise it is undecided
	Reason  string // what was proved, or what is missing
}

A BarrierIssue is a CTA barrier that some threads of a block can reach in a way the others do not match.

func CheckBarriers

func CheckBarriers(fn *Function, block [3]int, maxThreads int) ([]BarrierIssue, error)

CheckBarriers returns the CTA barriers of fn whose participation the threads of a block, of shape block when it is known (EIATTR_REQNTID or a known launch) and zero otherwise, do not match. maxThreads bounds the threads of the block (EIATTR_MAX_THREADS), or is 0.

A barrier is reported as proved when two threads that every launch of that shape has meet it differently. Two cases are checked:

  • A BAR.SYNC or BAR.ARV whose immediate thread count is more than the block has, than maxThreads, or than 1024, can never complete. It is proved only if a thread that exists reaches it: its block is on every path from the entry, nothing earlier in the block can leave, and it is unguarded or its guard is an ISETP that holds for that thread. Otherwise it is unproved.
  • A BAR.SYNC of the whole CTA that one side of a branch runs and the other does not, followed by a BAR.SYNC with the same id that both sides then run. The branch is on every path from the entry and not in a loop, its condition is an ISETP of threadIdx.x (or a mask of it) against a constant, and two threads of the block go different ways. The side with the barrier runs it in every thread that takes it; the other side reaches the join without a barrier, a call or an exit. The threads of the first side wait at their barrier while the others arrive at the later one, so the two are matched with each other, which the kernel does not mean.

The same structure under a condition the analysis cannot evaluate, or with a block shape that is not known, is reported unproved.

A zero block means the shape is not known; otherwise a zero dimension counts as 1, so [3]int{256} is a block of 256 threads.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	// if (threadIdx.x < 64) __syncthreads(); __syncthreads();
	d, err := sass.ParseString(`
	.section	.text.k,"ax",@progbits
k:
.text.k:
        /*0000*/                   S2R R0, SR_TID.X ;
        /*0010*/                   ISETP.GT.U32.AND P0, PT, R0, 0x3f, PT ;
        /*0020*/              @!P0 BAR.SYNC.DEFER_BLOCKING 0x0 ;
        /*0030*/                   BAR.SYNC.DEFER_BLOCKING 0x0 ;
        /*0040*/                   EXIT ;
`)
	if err != nil {
		panic(err)
	}
	issues, err := sass.CheckBarriers(d.Function("k"), [3]int{128, 1, 1}, 0)
	if err != nil {
		panic(err)
	}
	for _, is := range issues {
		fmt.Println(is)
	}
}
Output:
0x20 BAR.SYNC.DEFER_BLOCKING: threadIdx.x=0 waits here while threadIdx.x=64 skips it under the guard @!P0 and arrives at the barrier at 0x30

func (BarrierIssue) String

func (b BarrierIssue) String() string

type BasicBlock

type BasicBlock struct {
	Start, End   uint64 // address of the first instruction, and one past the last
	Instructions []Instruction
}

A BasicBlock is a maximal straight-line run of instructions: control enters only at the first and leaves only after the last.

func BasicBlocks

func BasicBlocks(fn *Function) []BasicBlock

BasicBlocks reconstructs the basic blocks of fn.

A block ends after any branch, and begins at any address named as a branch target. Targets are taken from the operand text nvdisasm prints, which in an ELF section is a label reference such as `(.L_x_0), resolved through Function.Labels, and in a raw binary is a 0x-prefixed address. An operand that is neither, such as the barrier register B0 of a BSSY or the register of an indirect branch, names no target. Disassembler.ControlFlowGraph is nvdisasm's own answer and is what TestBasicBlockReconstructionAgainstNvdisasm compares against.

type Basis

type Basis string

A Basis says where the value of a Cell came from.

const (
	// Measured is a hardware counter read from a run of the kernel.
	Measured Basis = "measured"
	// Probed is a device attribute read from a live device of the
	// architecture, as cudadevicetable records it.
	Probed Basis = "probed"
	// Compiled is read from the kernel's CUBIN or its SASS.
	Compiled Basis = "compiled"
	// Planned comes from a plan or launch configuration the caller
	// supplied: a cudashared plan, Tensor Memory allocations, or the
	// launch's block size and dynamic shared bytes.
	Planned Basis = "planned"
	// Table is a datasheet value no device has confirmed.
	Table Basis = "table"
	// Unavailable means the value is not known. The cell's Value is zero
	// and is not a measurement; its Reason says why.
	Unavailable Basis = "unavailable"
)

The bases, strongest first. A value computed from several inputs takes the weakest of their bases.

type BlameArc

type BlameArc struct {
	WaiterPC          uint64
	WaiterOpcode      string
	ProducerPC        uint64
	ProducerOpcode    string
	Barrier           int
	Kind              string // "write" or "read"
	SharedRegs        []Register
	CoTenant          bool // true when producer shares the barrier but has no register overlap with waiter
	Uncertain         bool // true when the arc crosses a branch or basic-block boundary
	UncertaintyReason string
}

BlameArc links a waiting instruction (victim PC) to the scoreboard producer that armed the waited-on barrier.

func ScoreboardBlame

func ScoreboardBlame(fn *Function, arch Arch) ([]BlameArc, error)

ScoreboardBlame traces each instruction in fn that waits on a scoreboard barrier back to the producer(s) that armed that barrier in straight-line program order.

Arcs contained within a single basic block have Uncertain == false. Arcs that cross a branch or basic-block boundary are marked Uncertain == true because static straight-line order cannot prove which predecessor path executed.

Example
package main

import (
	"fmt"

	cudasass "github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	enc := func(ctrl cudasass.ControlCode) cudasass.Encoding {
		e, err := cudasass.EncodeControl(cudasass.Encoding{Lo: 0x7982}, ctrl, cudasass.SM121a)
		if err != nil {
			panic(err)
		}
		return e
	}

	fn := &cudasass.Function{
		Name: "kernel_math_stall",
		Instructions: []cudasass.Instruction{
			{Address: 0x0120, Opcode: "LDG.E.32", Operands: "R4, [R10.64]", Encoding: enc(cudasass.ControlCode{Stall: 1, Yield: true, WriteBarrier: 2, ReadBarrier: cudasass.NoBarrier})},
			{Address: 0x0130, Opcode: "FFMA", Operands: "R20, R21, R22, R20", Encoding: enc(cudasass.ControlCode{Stall: 1, Yield: true, WriteBarrier: cudasass.NoBarrier, ReadBarrier: cudasass.NoBarrier})},
			{Address: 0x0140, Opcode: "FFMA", Operands: "R8, R4, R6, R8", Encoding: enc(cudasass.ControlCode{Stall: 4, Yield: true, WriteBarrier: cudasass.NoBarrier, ReadBarrier: cudasass.NoBarrier, WaitMask: 1 << 2})},
		},
	}

	arcs, err := cudasass.ScoreboardBlame(fn, cudasass.SM121a)
	if err != nil {
		panic(err)
	}
	for _, a := range arcs {
		fmt.Println(a)
	}
}
Output:
0x0120 LDG.E.32 --(b2 write, regs=R4)--> 0x0140 FFMA

func (BlameArc) String

func (a BlameArc) String() string

type Bundle

type Bundle struct {
	Inst   Instruction // Inst.Encoding is never changed except for its control field
	Ctrl   ControlCode
	Defs   []Register
	Uses   []Register
	Class  OpcodeClass
	Tensor bool // issues to the tensor cores; see [ControlOptStats.StickyTensorBursts]
}

A Bundle is one instruction of a basic block, with the facts the control-code optimizer needs about it.

func Bundles

func Bundles(block BasicBlock, arch Arch) ([]Bundle, error)

Bundles decodes the control codes of block's instructions on arch and returns them as bundles. It reports an error for an opcode outside the modelled subset or an instruction with no encoding.

type CFG

type CFG struct {
	Function string
	Blocks   []BasicBlock // exactly BasicBlocks of the function
	Edges    []FlowEdge   // sorted by From, then To, then Kind

	// Indirect lists the blocks that end in an indirect branch (BRX, BRXU,
	// JMX, JMXU) whose targets the listing does not name, in order. Their
	// targets come from a register at run time, so Edges has no edge for
	// them, only the fall-through of a guarded one. A jump-table branch
	// that nvdisasm annotates with its targets, as in
	// BRXU UR4 -0x260 (*"BRANCH_TARGETS .L_x_1,.L_x_2"*), has a Taken
	// edge to each and is not listed here.
	Indirect []int

	// IsDegenerate reports that Indirect is not empty: the graph is missing
	// the edges of at least one branch, so it is not the complete set of
	// paths through the function.
	IsDegenerate bool
}

A CFG is the control flow graph of one function: its basic blocks and the edges between them. It corresponds to NVBit's CFG_t, whose blocks are the same partition and whose is_degenerate flag is IsDegenerate.

func NewCFG

func NewCFG(fn *Function) (*CFG, error)

NewCFG builds the control flow graph of fn over BasicBlocks.

Edges come from the last instruction of each block. A branch or exit whose guard is absent or @PT is unconditional; any other guard, or a predicate operand other than PT, also allows the fall-through. A guard of @!PT, or a predicate operand of !PT, never branches. A call has a Call edge to its target inside fn unless its guard never holds, and always falls through.

A direct branch whose target names no block of fn is an error rather than a missing edge.

Example
package main

import (
	"fmt"
	"log"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

const loopSASS = `
.section .text.loop,"ax",@progbits
.text.loop:
        /*0000*/                   ISETP.GE.AND P0, PT, R0, 0x10, PT ;
.L_x_0:
        /*0010*/                   IADD R0, R0, 0x1 ;
        /*0020*/               @!P0 BRA ` + "`" + `(.L_x_0) ;
        /*0030*/                   EXIT ;
`

func main() {
	d, err := sass.ParseString(loopSASS)
	if err != nil {
		log.Fatal(err)
	}
	g, err := sass.NewCFG(d.Function("loop"))
	if err != nil {
		log.Fatal(err)
	}
	for i, b := range g.Blocks {
		fmt.Printf("BB%d %#x-%#x successors %v\n", i, b.Start, b.End, g.Successors(i))
	}
	fmt.Println("degenerate:", g.IsDegenerate)
}
Output:
BB0 0x0-0x10 successors [1]
BB1 0x10-0x30 successors [1 2]
BB2 0x30-0x40 successors []
degenerate: false

func (*CFG) DOT

func (g *CFG) DOT() string

DOT renders g in Graphviz DOT. Each block is a node named BBn, for its index in Blocks, labelled with one line per instruction beginning with its offset in four or more hex digits, as nvdisasm's --print-instr-offsets-cfg prints them. Edges are labelled with their FlowKind. A degenerate graph says so in the graph label, and its indirect blocks are drawn dashed.

DisassembleCFG is nvdisasm's rendering of the same function, and ListDOTGraphs reads the name of either.

Example
package main

import (
	"fmt"
	"log"
	"strings"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

const loopSASS = `
.section .text.loop,"ax",@progbits
.text.loop:
        /*0000*/                   ISETP.GE.AND P0, PT, R0, 0x10, PT ;
.L_x_0:
        /*0010*/                   IADD R0, R0, 0x1 ;
        /*0020*/               @!P0 BRA ` + "`" + `(.L_x_0) ;
        /*0030*/                   EXIT ;
`

func main() {
	d, err := sass.ParseString(loopSASS)
	if err != nil {
		log.Fatal(err)
	}
	g, err := sass.NewCFG(d.Function("loop"))
	if err != nil {
		log.Fatal(err)
	}
	for _, line := range strings.Split(g.DOT(), "\n") {
		if strings.Contains(line, "->") {
			fmt.Println(strings.TrimSpace(line))
		}
	}
}
Output:
"BB0" -> "BB1" [label="fallthrough"];
"BB1" -> "BB1" [label="taken"];
"BB1" -> "BB2" [label="fallthrough"];

func (*CFG) Dominators

func (g *CFG) Dominators() []int

Dominators returns the immediate dominator of each block, computed from block 0, the function's entry, over every edge kind. The entry's immediate dominator is itself, and a block unreachable from the entry has -1.

func (*CFG) LoadsBeforeWait

func (g *CFG) LoadsBeforeWait(m Mnemonics) ([]Instruction, error)

LoadsBeforeWait returns the global-memory reads in g that can execute before the grid-dependency wait m.Wait, ordered by address.

A read is reported if some path from the function's entry reaches it without passing an instruction that matches m.Wait and always executes. A wait under a guard other than @PT does not count, because on the path where the guard is false the read goes ahead. A block no path reaches is never reported. A call is not assumed to wait.

Text order is not control flow: a read placed after the wait in the listing can still be reached before it by a branch around the wait, and LoadsBeforeWait reports it.

The reads recognized are LDG, LD, ATOM, ATOMG, LDGSTS, UBLKCP and UTMALDG. It returns ErrDegenerate if g has an indirect branch.

Example
package main

import (
	"fmt"
	"log"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	d, err := sass.ParseString(`.section .text.k,"ax",@progbits
.text.k:
        /*0000*/       LDG.E R2, desc[UR4][R2.64] ;
        /*0010*/   @P0 BRA ` + "`" + `(.L_x_0) ;
        /*0020*/       GRIDWAIT ;
.L_x_0:
        /*0030*/       LDG.E R3, desc[UR4][R4.64] ;
        /*0040*/       EXIT ;
`)
	if err != nil {
		log.Fatal(err)
	}
	g, err := sass.NewCFG(d.Function("k"))
	if err != nil {
		log.Fatal(err)
	}
	// A real check takes its spellings from MnemonicsFor.
	loads, err := g.LoadsBeforeWait(sass.Mnemonics{Wait: "GRIDWAIT"})
	if err != nil {
		log.Fatal(err)
	}
	for _, inst := range loads {
		fmt.Printf("%#04x %s %s\n", inst.Address, inst.Opcode, inst.Operands)
	}
}
Output:
0x0000 LDG.E R2, desc[UR4][R2.64]
0x0030 LDG.E R3, desc[UR4][R4.64]

func (*CFG) Loops

func (g *CFG) Loops() []Loop

Loops returns g's natural loops, one per header, ordered by header. Back edges into the same header form one loop. Blocks unreachable from the entry, such as the self-branch that pads the end of every kernel, are in no loop.

func (*CFG) Reducible

func (g *CFG) Reducible() bool

Reducible reports whether every cycle reachable from the entry is a natural loop. In an irreducible graph some cycle has two entries and no header, and CFG.Loops does not report it.

func (*CFG) Successors

func (g *CFG) Successors(b int) []int

Successors returns the blocks control can reach directly from block b, in increasing order and without repeats.

func (*CFG) Waits

func (g *CFG) Waits() []Wait

Waits returns the device-side waits of g, ordered by address.

A wait loop is a natural loop (CFG.Loops) with an exit whose condition depends on a load inside the loop from an address the loop does not also store to (compared as operand text), or on an mbarrier try-wait. The dependence is followed through the registers each instruction defines and uses, from the exit's predicate back to definitions inside the loop. A definition outside the loop is loop-invariant and ends the search.

A wait loop is bounded when some exit's condition also depends on a read of %globaltimer inside the loop (CS2R, CS2UR, S2R or S2UR of SR_GLOBALTIMERLO or SR_GLOBALTIMERHI), and has a cause code when a path from that exit stores to memory before it leaves the function. An exit through a predicated EXIT, RET or KILL inside the loop leaves at once, so it stores nothing. Without a deadline, a wait loop with an exit that reads no memory and depends on a definition inside the loop that depends on itself across iterations, such as a spin counter, is WaitCounted.

A call to a subroutine of the same function is followed: the dependence search continues from each of the subroutine's returns back through its body, and from its entry back to the instructions before the call, so a register the subroutine leaves alone on some path is still traced to its definition before the call. A load inside the subroutine counts even if the loop stores to the same operand text, which names other registers there. A cycle of dependences counts as carried only if it passes through the loop's own instructions, not one that stays inside a loop of the subroutine.

The analysis refuses to guess. A dependence through an opcode outside the covered subset (Classify), an mbarrier try-wait without a deadline (whose producer may be in the same CTA or not), a call the analysis cannot follow inside an unbounded loop, or a loop in a function whose graph is degenerate or irreducible is unclassified. A call cannot be followed if its target is outside the function, or if the subroutine calls one, reaches the call or overlaps the loop, is entered other than by a call, can leave the function or run off its end, never returns, or has an instruction outside the covered subset. (An indirect branch anywhere in the function makes its graph degenerate.) A loop that reads no memory and calls nothing is not a wait and is not reported.

BAR (other than BAR.ARV and BAR.RED, which do not wait) and DEPBAR are reported as WaitLocal, one per instruction.

type CaveAllocRequest

type CaveAllocRequest struct {
	Arch            Arch // Target architecture; empty defaults to SM121a.
	AttrRegCount    int  // Kernel's current EIATTR_REGCOUNT (0..255).
	NeedGPRs        int  // Scratch GPRs required above AttrRegCount.
	NeedPreds       int  // Scratch predicate registers (P0..P6) required.
	NeedUGPRs       int  // Scratch uniform registers (UR0..UR62) required.
	NeedBarriers    int  // Scratch scoreboard barrier indices (0..5) required.
	ThreadsPerBlock int  // Block size for occupancy estimation; defaults to 256 if <= 0.
	SharedMemBytes  int  // Static + dynamic shared memory per block for occupancy estimation.
}

CaveAllocRequest specifies the scratch resources a cave requires and the kernel's current resource configuration.

type CaveReloc

type CaveReloc struct {
	Offset uint64 // byte offset within .text.<kernel>
	Symbol string // target symbol name (e.g. FlightCfgSymbol)
	Type   uint32 // relocation type (e.g. RCudaAbs32Lo32, RCudaAbs32Hi32)
	Addend int64
}

CaveReloc describes a single Elf64_Rela relocation to emit in .rela.text.<kernel>.

type CaveResources

type CaveResources struct {
	Kernel            string
	Arch              Arch
	EntryAddress      uint64
	ExitSites         []ExitSite
	AttrRegCount      int
	NewAttrRegCount   int
	MaxUsedGPR        int            // Highest GPR index (0..254) observed, or -1 if none
	AllocatedGPRs     []Register     // Scratch GPRs allocated above max(AttrRegCount, MaxUsedGPR+1)
	FreePreds         []Register     // Unused P0..P6 across scanned instructions
	AllocatedPreds    []Register     // Scratch predicates allocated (from FreePreds or borrowed via PredSpill)
	PredSpill         *PredSpillPlan // Non-nil when P2R/R2P spill/restore is needed
	FreeUGPRs         []Register     // Unused UR0..UR62 across scanned instructions
	AllocatedUGPRs    []Register     // Scratch uniform registers allocated from FreeUGPRs
	FreeBarriers      []uint8        // Unused scoreboard barrier indices 0..5
	AllocatedBarriers []uint8        // Scratch barrier indices allocated from FreeBarriers
	BarriersScanned   bool           // True if at least one instruction carried a hardware Encoding
	Occupancy         OccupancyDelta
}

CaveResources describes the unused hardware resources found in a decoded kernel function and the concrete allocation for a cave.

func AllocateCaveResources

func AllocateCaveResources(fn *Function, req CaveAllocRequest) (*CaveResources, error)

AllocateCaveResources scans fn's decoded instructions (entry and each EXIT site) to find unused GPRs above req.AttrRegCount, unused predicates P0..P6, unused uniform registers UR0..UR62, and unused scoreboard barriers 0..5, returning a concrete allocation and SM occupancy-delta estimate.

It refuses architectures other than SM121a, negative counts, AttrRegCount above SM121aMaxGPRs (255), or GPR allocations that would exceed 255. If all predicates are live and NeedPreds > len(FreePreds), it produces a P2R/R2P spill/restore plan using an extra scratch GPR above AttrRegCount.

type Cell

type Cell struct {
	Name   string  `json:"name,omitempty"`   // set on detail cells
	Value  float64 `json:"value"`            // zero when Basis is Unavailable
	Unit   string  `json:"unit,omitempty"`   // "registers", "bytes", "columns", "instructions", "percent", "GB/s"
	Basis  Basis   `json:"basis"`            // where Value came from
	Source string  `json:"source,omitempty"` // the counter, section, attribute or plan Value was read from
	Reason string  `json:"reason,omitempty"` // why the value is unavailable
}

A Cell is one value of a HierarchyLevel with its basis.

func (Cell) Known

func (c Cell) Known() bool

Known reports whether the cell holds a value.

type Clause

type Clause int

A Clause is one part of a kernel's effect contract.

const (
	ClauseTarget    Clause = iota // the target the cubin was compiled for
	ClauseResources               // registers, static shared memory, local memory
	ClauseAlignment               // the alignment each pointer parameter needs
	ClauseAccess                  // what each pointer parameter is read or written through
	ClauseAsync                   // every asynchronous copy waited for before use
	ClauseWaits                   // every device-side wait ends: a deadline or a spin count
)

func (Clause) String

func (c Clause) String() string

type Contract

type Contract struct {
	Kernel      string
	CubinSHA256 [32]byte
	Target      Target // zero if [ReadTarget] failed; then Derived says why
	Layout      ParamLayout

	Registers   int // per thread, EIATTR_REGCOUNT
	SharedBytes int // static shared memory
	LocalOps    int // LDL and STL instructions: spills and local arrays

	// Effects are the kernel's global memory effects through its
	// parameters, or nil if extraction failed; then Err says why.
	// A *MissingWaitError is a race in the kernel, not a gap in the
	// analysis; an *UnprovedWaitError is a gap in the analysis.
	Effects *Effects
	Err     error

	// MaxGPR is the highest general register the instructions name, or -1.
	MaxGPR int

	// Waits are the kernel's device-side waits other than CTA-local
	// barriers ([CFG.Waits]). A kernel whose control flow graph cannot
	// be built has one unclassified wait saying why.
	Waits []Wait
	// contains filtered or unexported fields
}

A Contract is what one kernel's cubin and SASS require of a launch. It is read from the instructions, not declared, and it is keyed by the SHA-256 of the cubin: a kernel with the same name and parameters in another cubin has another contract.

func (*Contract) Complete

func (c *Contract) Complete() bool

Complete reports whether every clause of c is derived.

func (*Contract) Derived

func (c *Contract) Derived(cl Clause) (bool, string)

Derived reports whether clause cl of c was read from the instructions and, if not, why. Alignment and access are derived only when every global access resolves to a parameter or a module global: one access through a pointer loaded from memory leaves the parameter it came from unknown. Async is derived when extraction found every copy waited for before each shared read it may touch: a read proved apart from a copy in flight needs no wait, and one neither proved apart nor proved to overlap leaves the clause underived as unproved, not as a race. Waits is derived when no wait is unbounded or unclassified: an unbounded wait, like a missing copy wait, is a defect in the kernel, and the contract does not hold for it.

type ControlCode

type ControlCode struct {
	Stall         uint8 // cycles to stall before issuing the next instruction
	Yield         bool  // clearing this yields the warp; reuse is invalid when clear
	WriteBarrier  uint8 // scoreboard barrier this instruction sets on write, or NoBarrier
	ReadBarrier   uint8 // scoreboard barrier this instruction sets on read, or NoBarrier
	WaitMask      uint8 // barriers this instruction waits on, one bit each
	Reuse         uint8 // 3-bit operand-reuse cache flags (bits[124:122] when Yield and class has reuse slots)
	Batch         uint8 // 3-bit batch_t hint (bits[124:122] when class has no reuse slots or !Yield)
	IgnoredBit125 bool  // bit 125; nvdisasm 13.5 ignores it (same-PC flip gives byte-identical output, 4,301/4,301); cleared to 0 by EncodeControl
}

A ControlCode is the scheduling control field of one SASS instruction.

Control codes are part of correctness, not metadata. A reordering that preserves data dependencies but drops a barrier index, a wait mask or the yield flag is wrong, and the hardware does not check it.

func DecodeControl

func DecodeControl(e Encoding, arch Arch) (ControlCode, error)

DecodeControl returns the control code carried by e on arch.

It returns a ControlDecodeError for any architecture other than SM121a, checked before a missing encoding. A present encoding can carry an all-zero ControlCode; nil error distinguishes this known value from refusal. The field offsets were calibrated on sm_121a only, and an encoding fact is not generalized across SM versions: decoding sm_90 bits at sm_121a offsets yields a barrier index that is structurally well formed and meaningless.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	control, err := sass.DecodeControl(sass.Encoding{Lo: 1}, sass.SM121a)
	fmt.Println(control == (sass.ControlCode{}), err == nil)
	_, err = sass.DecodeControl(sass.Encoding{}, sass.SM121a)
	var refusal *sass.ControlDecodeError
	if errors.As(err, &refusal) {
		fmt.Println(refusal.Arch, refusal.MissingEncoding)
	}
}
Output:
true true
sm_121a true
Example (ReuseAndBatch)
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	iadd := sass.Encoding{Lo: 0x0000000607007c35, Hi: 0x041fe2000f8e0000}
	c1, _ := sass.DecodeControl(iadd, sass.SM121a)
	stg := sass.Encoding{Lo: 0x0000000502007986, Hi: 0x004fe2000c101904 | (uint64(5) << 58)}
	c2, _ := sass.DecodeControl(stg, sass.SM121a)
	fmt.Println(c1)
	fmt.Println(c2)
}
Output:
stall=1 yield wait=0x01 reuse=0x1
stall=1 yield wait=0x04 batch=0x5

func RecomputeControl

func RecomputeControl(a, c Instruction, arch Arch) (aAfter, cAfter ControlCode, err error)

RecomputeControl returns the control codes the two instructions must carry after a and c exchange places without surrounding block context, or an error if they cannot be recomputed from the pair alone.

A barrier index that an instruction sets travels with that instruction; a wait mask travels with the waiter. When stall counts differ, the stall each instruction needs depends on surrounding producers, readers, and block boundaries, which an isolated pair does not carry; use RecomputeSwap to recompute differing stall counts across a BasicBlock with SM121aLatencies.

func RecomputeSwap

func RecomputeSwap(b BasicBlock, i, j int, arch Arch) (firstAfter, secondAfter ControlCode, err error)

RecomputeSwap returns the control codes that positions min(i,j) and max(i,j) of b (which must be adjacent) carry after exchanging places on arch.

RecomputeSwap clears operand-reuse hints on the swapped pair, checks that any preceding instruction does not carry a reuse hint into position min(i,j), and verifies intra-block hazard safety against SM121aLatencies. When the pair's original stall counts differ or swapping them creates an intra-block hazard, RecomputeSwap searches for a hazard- and boundary-safe stall assignment.

func (ControlCode) String

func (c ControlCode) String() string

func (ControlCode) Valid

func (c ControlCode) Valid() error

Valid reports whether every field fits the width observed for it on sm_121a. It deliberately does not police the stall value: the accepted range is per-instruction, not per-architecture, so a range check belongs to the form being encoded. See ObservedStallRange.

func (ControlCode) Waits

func (c ControlCode) Waits(i int) bool

Waits reports whether the instruction waits on barrier i.

type ControlDecodeError

type ControlDecodeError struct {
	Arch Arch // requested architecture

	// MissingEncoding is true when arch is calibrated but no encoding was captured.
	MissingEncoding bool
}

A ControlDecodeError reports a refused static control-code decode. It does not report a measured hardware capability.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	_, err := sass.DecodeControl(sass.Encoding{Lo: 1}, "sm_90")
	var refusal *sass.ControlDecodeError
	if errors.As(err, &refusal) {
		fmt.Println(refusal.Arch, refusal.MissingEncoding)
	}
}
Output:
sm_90 false

func (*ControlDecodeError) Error

func (e *ControlDecodeError) Error() string

type ControlOptStats

type ControlOptStats struct {
	InstructionsScanned int
	StallCyclesSaved    int // static stall cycles removed from the block
	ReuseHintsAdded     int // operand reuse flags set
	SplitScoreboards    int // producers moved off a shared write barrier
	StickyTensorBursts  int // runs of tensor instructions whose yield bit was set
}

ControlOptStats summarizes what OptimizeBasicBlockControl changed.

type ControlOptions

type ControlOptions struct {
	Latencies Latencies

	// Samples, if not nil, maps instruction addresses to stall samples, as
	// a PC-sampling profiler reports them. Only blocks holding at least
	// MinSamples samples are optimized, hottest first.
	Samples    map[uint64]uint64
	MinSamples uint64
}

ControlOptions configures OptimizeFunctionControl.

type ControlPlan

type ControlPlan struct {
	Plans   []MutationPlan // one per instruction whose control code changed
	Stats   ControlOptStats
	Skipped []error // one per basic block left unchanged, with the reason
}

A ControlPlan is the result of OptimizeFunctionControl.

func OptimizeFunctionControl

func OptimizeFunctionControl(fn *Function, arch Arch, opts ControlOptions) (ControlPlan, error)

OptimizeFunctionControl runs OptimizeBasicBlockControl over the basic blocks of fn on arch and returns the changes as MutationPlan values for CubinImage.Apply. A block the model cannot analyse, or whose input schedule it rejects, is skipped and reported in Skipped.

In each plan, Before and After differ only in the control field and Control is the new control code.

type CubinAuditReport

type CubinAuditReport struct {
	Kernel string
	Arch   string

	// UsedGPRs is the per-thread register count ptxas reported, or, when
	// GPRsFromSASS is set, one more than the highest GPR the SASS names,
	// which is a lower bound.
	UsedGPRs       int
	GPRsFromSASS   bool
	MaxAllowedGPRs int

	StackFrame  int // bytes per thread, from ptxas; -1 if not reported
	SpillStores int // bytes, from ptxas; -1 if not reported
	SpillLoads  int // bytes, from ptxas; -1 if not reported

	STL int // local-memory store instructions in the SASS
	LDL int // local-memory load instructions in the SASS

	// TensorMMA counts HMMA, IMMA, QMMA, OMMA, HGMMA (wgmma) and the
	// UTC*MMA forms (tcgen05.mma).
	TensorMMA int

	// RedundantWaits counts waits that cannot delay anything: a DEPBAR or
	// tensor-memory wait identical to the previous one in its basic block
	// with no memory, tensor or barrier-setting instruction between, and,
	// on sm_121a where control codes decode, a wait on a scoreboard that
	// no instruction in the block has set since the last wait on it.
	RedundantWaits int

	// PeakLiveGPRs is the largest live-GPR count nvdisasm's life-range
	// analysis reported, or 0 if the listing has none.
	PeakLiveGPRs int

	Violations []string
}

A CubinAuditReport is what ProveDisassembly found for one kernel.

func ProveCubin

func ProveCubin(cubin []byte, ptxasLog string, c CubinConstraint) ([]CubinAuditReport, error)

ProveCubin disassembles cubin with nvdisasm and checks every kernel in it against c, taking register counts and spill sizes from ptxasLog, the output of ptxas -v for the same compilation (empty if unavailable). See ProveDisassembly.

func ProveDisassembly

func ProveDisassembly(d *Disassembly, rep *ptx.Report, c CubinConstraint) ([]CubinAuditReport, error)

ProveDisassembly checks every function in d against c and returns one report per function, and an error wrapping ErrConstraint if any report has a violation.

The checks are counts over the instruction stream, not a proof about executions: an STL in dead code is still an STL. A kernel ptxas reports spilling is a violation under ForbidSpills even if the SASS has no STL/LDL, and the reverse, since either source alone could be stale. rep may be nil; then spill sizes are unknown (-1), which ForbidSpills does not count as a spill, and register counts come from the SASS.

func (CubinAuditReport) OK

func (r CubinAuditReport) OK() bool

OK reports whether the report has no violations.

type CubinConstraint

type CubinConstraint struct {
	MaxGPRs          int  // 0 means no limit
	ForbidSpills     bool // no STL, no LDL, no spill bytes and no stack frame
	RequireTensorMMA bool // at least one tensor-core MMA instruction

	// MaxRedundantWaits bounds RedundantWaits; a negative value means no
	// limit.
	MaxRedundantWaits int
}

A CubinConstraint is a pass/fail limit for ProveDisassembly.

type CubinImage

type CubinImage struct {
	// contains filtered or unexported fields
}

A CubinImage is a CUBIN held for patching.

func OpenCubin

func OpenCubin(b []byte) (*CubinImage, error)

OpenCubin parses b as a CUBIN. The bytes are copied, so the caller's slice is never modified.

func (*CubinImage) Apply

func (im *CubinImage) Apply(kernel string, plans []MutationPlan) (PatchedImage, error)

Apply writes the plans into the kernel's text section and returns the patched image.

It refuses, before writing anything, if the section is missing, is not executable code, has no file bytes, if any target is unaligned or out of range, if a relocation applies to a target, or if the bytes already at a target are not the ones the plan was built from. The last of these is the check that makes a misplaced patch a failure here rather than a CUBIN that loads and is wrong.

func (*CubinImage) Contract

func (im *CubinImage) Contract(fn *Function, kernel string) (*Contract, error)

Contract reads the contract of kernel from im and fn, the kernel's disassembly. It fails only if the cubin does not describe kernel; a kernel whose effects cannot be extracted has a contract whose Contract.Derived says which clauses are missing.

func (*CubinImage) ContractFrom

func (im *CubinImage) ContractFrom(src Source, kernel string) (*Contract, error)

ContractFrom reads the contract of kernel in im using src to obtain its SASS.

func (*CubinImage) DecodeContract

func (im *CubinImage) DecodeContract(kernel string) (*Contract, error)

DecodeContract reads the contract of kernel in im natively without nvdisasm.

func (*CubinImage) FunctionIndex

func (im *CubinImage) FunctionIndex(name string) (int, error)

FunctionIndex returns the symbol-table index of the function symbol name whose section is .text.<name>: the index nvdisasm's --cuda-function-index selects (see Options.Functions). It is an error if there is no such symbol or more than one.

Example
package main

import (
	"encoding/hex"
	"fmt"
	"os"
	"strings"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	raw, err := os.ReadFile("testdata/asyncbuf.sm121a.cubin.hex")
	if err != nil {
		panic(err)
	}
	cubin, err := hex.DecodeString(strings.Join(strings.Fields(string(raw)), ""))
	if err != nil {
		panic(err)
	}
	im, err := sass.OpenCubin(cubin)
	if err != nil {
		panic(err)
	}
	// The index selects one kernel for nvdisasm (Options.Functions).
	for _, k := range []string{"double_buffer", "triple_buffer"} {
		i, err := im.FunctionIndex(k)
		fmt.Println(k, i, err)
	}
	_, err = im.FunctionIndex("missing")
	fmt.Println(err)
}
Output:
double_buffer 37 <nil>
triple_buffer 35 <nil>
function missing: no function symbol for .text.missing

func (*CubinImage) Mirrors

func (im *CubinImage) Mirrors(kernel string) []string

Mirrors returns the sections that carry a second copy of the kernel's text.

CUDA 13.4's ptxas emits, beside every `.text.<kernel>`, a `.nv.capmerc.text.<kernel>` in an undocumented form (0x102 bytes beside addk's 0x200 bytes of text in testdata/roundtrip). What it encodes has not been measured, and patching the text section alone leaves it unchanged. Which bytes execute was measured once, on the GB10 host, by flipping one byte at stride 16, reloading, launching and comparing the result: 40 of 53 flips in `.text.<kernel>` failed the launch and 0 of 25 in the capmerc section did, so under that driver and launch configuration the executed bytes come from `.text`. That says nothing about what the capmerc section is for, and nothing here repeats the measurement, so the presence of a mirror is reported and the load gate refuses.

func (*CubinImage) ParamLayout

func (im *CubinImage) ParamLayout(kernel string) (ParamLayout, error)

ParamLayout reads the parameter layout of kernel from its .nv.info section: the block's place in the bank from EIATTR_PARAM_CBANK, and each parameter from EIATTR_KPARAM_INFO or EIATTR_KPARAM_INFO_V2. A kernel with no parameters has a layout with none.

func (*CubinImage) SHA256

func (im *CubinImage) SHA256() [32]byte

SHA256 identifies the immutable bytes copied by OpenCubin.

Example
raw := symbolImage(0x21, 0, 0)
original := sha256.Sum256(raw)
image, _ := OpenCubin(raw)
// Mutating the caller's input does not change the copied image identity.
raw[len(raw)-1] ^= 1
fmt.Println(image.SHA256() == original)
Output:
true

func (*CubinImage) Symbols

func (im *CubinImage) Symbols(name string) ([]CubinSymbol, error)

Symbols returns ordinary symbol-table entries with exactly the given name, in table order, including duplicates and zero values. An empty result means no match; a missing table returns an error wrapping elf.ErrNoSymbols. Total decoded symbol names are limited to 8 MiB, including nonmatches. Reserved section indices remain raw and have no SectionName. This method reads no symbol payload and proves neither loading nor runtime semantics.

Example
// This constructed ELF is a host example, not a measured compiler image.
image, _ := OpenCubin(symbolImage(0x21, 0, 0))
rows, _ := image.Symbols("raw")
fmt.Println(len(rows), rows[0].Value, rows[0].Size, rows[0].Section)
Output:
1 0 4 SHN_UNDEF

type CubinSymbol

type CubinSymbol struct {
	Name        string
	Type        elf.SymType
	Binding     elf.SymBind
	Section     elf.SectionIndex
	SectionName string
	Value, Size uint64
}

CubinSymbol preserves raw ELF symbol metadata. Value and Size are compiler metadata, not runtime reservation capacity or readable payload evidence.

type DecodedField

type DecodedField struct {
	Name    string
	Hi, Lo  int // outermost bit bounds; Width is total bits across ranges
	Width   int
	Raw     uint64
	Operand string
	Symbol  string
}

A DecodedField is one bit-field extracted from a 128-bit SASS word.

type DecodedInst

type DecodedInst struct {
	Arch       string // table architecture ("SM90", "SM100", "SM120")
	Class      string // descriptor class identifier
	Alternate  bool
	Mnemonic   string // base mnemonic from OPCODES
	Opcode     string // full opcode with modifiers as printed by nvdisasm
	Predicate  string // guard predicate ("@P0", "@!UP0", or "" when unguarded)
	Operands   []DecodedOperand
	Fields     []DecodedField
	Control    ControlCode // populated when HasControl is true (calibrated on sm_121/sm_121a only)
	HasControl bool        // true only on sm_121/sm_121a; SM90, SM100, and SM120 were not swept
	Fixed      int
	Unnamed    int
	Candidates int
}

A DecodedInst is the native decode of one 128-bit SASS instruction word.

func Decode

func Decode(sm string, word [16]byte) (DecodedInst, error)

Decode decodes a 16-byte little-endian SASS instruction word (Lo in word[0:8], Hi in word[8:16]) for target sm ("sm_90", "sm_90a", "sm_100a", "sm_120", "sm_121", "sm_121a", ...). Unsupported targets wrap cuda.ErrUnsupported; builds without locally generated ISA tables wrap ErrNoISATables.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	const listing = "\t.target sm_121a\n\t.section .text.k,\"ax\",@progbits\nk:\n" +
		"\t/*0000*/ LDC R1, c[0x0][0x37c] ; /* 0x0000df00ff017b82 */\n" +
		"\t                                 /* 0x000fe40000000800 */\n"
	dis, err := sass.ParseString(listing)
	if err != nil {
		panic(err)
	}
	in := dis.Functions[0].Instructions[0]

	inst, err := sass.Decode("sm_121a", in.Encoding.Bytes())
	switch {
	case err == nil:
		fmt.Printf("%s %s\n", inst.Opcode, inst.Instruction(0, in.Encoding).Operands)
	case errors.Is(err, sass.ErrNoISATables):
		// Without locally generated ISA tables, fall back to the parsed listing.
		fmt.Printf("%s %s\n", in.Opcode, in.Operands)
	default:
		panic(err)
	}
}
Output:
LDC R1, c[0x0][0x37c]

func (DecodedInst) DefsUses

func (d DecodedInst) DefsUses() (defs, uses []Register)

DefsUses returns the registers d defines and uses from its decoded operand roles and widths.

func (DecodedInst) Instruction

func (d DecodedInst) Instruction(addr uint64, word Encoding) Instruction

Instruction formats d at hardware offset addr with raw encoding word.

type DecodedOperand

type DecodedOperand struct {
	Name     string
	Role     OperandRole
	Text     string
	Reg      Register
	HasReg   bool
	Width    int // consecutive 32-bit registers spanned (1, 2, or 4)
	Negated  bool
	Inverted bool
	Abs      bool
	Reuse    bool
	Imm      int64
	Raw      uint64
	BitWidth int
	// contains filtered or unexported fields
}

A DecodedOperand is one structured operand of a natively decoded SASS word.

type Demangler

type Demangler struct{ Path string }

Demangler selects cu++filt. Its zero value searches PATH.

func (Demangler) Demangle

func (d Demangler) Demangle(ctx context.Context, symbols []string) (Output, error)

Demangle runs cu++filt on newline-delimited symbols through stdin, so symbols cannot be interpreted as command options. Unrecognized names pass through according to cu++filt's behavior; success does not prove every name was mangled.

func (Demangler) Version

func (d Demangler) Version(ctx context.Context) (Output, error)

Version reports cu++filt's version. Unlike nvdisasm it uses the -v option.

type DepKind

type DepKind int

A DepKind names the reason one instruction must precede another.

const (
	RAW     DepKind = iota // read after write: the later reads what the earlier wrote
	WAR                    // write after read: the later overwrites what the earlier read
	WAW                    // write after write: both write the same register
	Memory                 // both touch memory and their order is observable
	Fence                  // one is a fence and the other touches memory
	Barrier                // the later waits on a scoreboard barrier the earlier sets
)

func (DepKind) String

func (k DepKind) String() string

type DeterminismFinding

type DeterminismFinding struct {
	PC     uint64
	Kind   string // "fp-atomic" or "grid-tainted-reduction"
	Opcode string
	Detail string
}

DeterminismFinding describes one static batch-size nondeterminism hazard found in a SASS function.

func (DeterminismFinding) String

func (f DeterminismFinding) String() string

type DeterminismReport

type DeterminismReport struct {
	Function string
	Pass     bool
	Findings []DeterminismFinding
}

DeterminismReport is the result of AuditDeterminism.

func AuditDeterminism

func AuditDeterminism(fn *Function) DeterminismReport

AuditDeterminism performs static taint analysis from grid-size reads (SR_NCTAID) into floating-point reduction order and checks for non-associative floating-point atomics/reductions (REDG/RED/ATOMG/ATOM).

Reads of SR_CTAID (block index) are not tainted, so kernels that use blockIdx to index disjoint output rows pass cleanly.

Example
package main

import (
	"fmt"

	cudasass "github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	const sass = `.section .text.rmsnorm_f16
.text.rmsnorm_f16:
/*0000*/ S2R R2, SR_CTAID.X ;
/*0010*/ FFMA R10, R8, R8, R10 ;
/*0020*/ EXIT ;

.section .text.splitk_moe_down_bf16
.text.splitk_moe_down_bf16:
/*0000*/ S2R R2, SR_NCTAID.Z ;
/*0010*/ IMAD R4, R2, 0x4, RZ ;
/*0020*/ FFMA R10, R4, R8, R10 ;
/*0030*/ REDG.E.ADD.BF16x2 [R12.64], R10 ;
/*0040*/ EXIT ;
`
	d, err := cudasass.ParseString(sass)
	if err != nil {
		panic(err)
	}
	for _, fn := range d.Functions {
		rep := cudasass.AuditDeterminism(fn)
		tag := "PASS"
		if !rep.Pass {
			tag = "FAIL"
		}
		fmt.Printf("[%s] %s (%d findings)\n", tag, rep.Function, len(rep.Findings))
		for _, f := range rep.Findings {
			fmt.Printf("  %s %s (%s)\n", f.Kind, f.Opcode, fmt.Sprintf("%#04x", f.PC))
		}
	}
}
Output:
[PASS] rmsnorm_f16 (0 findings)
[FAIL] splitk_moe_down_bf16 (2 findings)
  fp-atomic REDG.E.ADD.BF16x2 (0x0030)
  grid-tainted-reduction FFMA (0x0020)

type DeviceProperties

type DeviceProperties struct {
	Architecture            string // Architecture code (e.g. "sm_90", "sm_121")
	MaxThreadsPerBlock      int    // Maximum threads per thread block (CTA)
	WarpSize                int    // Warp size in threads (always 32)
	MaxWarpsPerSM           int    // Maximum concurrent warps per SM
	MaxBlocksPerSM          int    // Maximum concurrent thread blocks per SM
	MaxRegistersPerSM       int    // Total 32-bit registers available per SM
	MaxSharedMemoryPerSM    int    // Maximum shared memory per SM in bytes
	MaxSharedMemoryPerBlock int    // Default maximum shared memory per thread block in bytes
	MaxSharedMemoryOptin    int    // Opt-in maximum shared memory per block in bytes
	RegAllocationUnit       int    // Register allocation granularity in registers per warp
	SmemAllocationUnit      int    // Shared memory allocation granularity in bytes

	// TMEMColumnsPerSM is the Tensor Memory an SM holds, in 32-bit columns
	// of 128 lanes: 512 where tcgen05 exists, 0 elsewhere. A CTA allocates
	// a power of two from 32 to 512 columns with tcgen05.alloc, so TMEM
	// caps residency at TMEMColumnsPerSM / columns blocks per SM however
	// few registers and how little shared memory the kernel uses.
	TMEMColumnsPerSM int

	// MaxClusterSize is the largest thread block cluster a kernel may
	// launch with when it opts in to non-portable sizes; 0 where clusters
	// do not exist. The portable maximum is 8 everywhere clusters exist.
	MaxClusterSize int

	// Source names the device these values were read from, or is empty when
	// they were hand-entered from a datasheet and no device has confirmed
	// them. Every field above renders identically either way, which is the
	// problem: an occupancy figure computed from an unconfirmed capacity is
	// wrong in the way that reads as right. [LookupProbedDevice] refuses the
	// unconfirmed rows for callers that cannot afford one.
	//
	// It is filled dynamically from cudadevicetable when a probed record is
	// present, so it cannot be set by editing this file.
	Source string
}

DeviceProperties defines hardware execution limits and allocation granularities for a GPU Streaming Multiprocessor (SM).

func LookupDevice

func LookupDevice(arch string) (DeviceProperties, error)

LookupDevice returns device properties for the requested architecture string. It accepts formats like "sm_90", "sm90", "sm_103a", "sm_103f", "SM_80", "gb300", etc., dynamically consuming any probed architecture from cudadevicetable and falling back to predefined datasheet limits otherwise.

func LookupProbedDevice

func LookupProbedDevice(arch string) (DeviceProperties, error)

LookupProbedDevice returns device properties only for an architecture a real device has been probed for in cudadevicetable (either embedded in devices.json or supplied at runtime via devicetable.Register / $CUDADEVICETABLE_FACTS). Use it where a wrong value would flow onward silently -- an occupancy ceiling, a launch geometry, a headline ratio -- because it turns a plausible datasheet number into an error.

LookupDevice remains the right call for advisory output, which is honest about being advisory.

func (DeviceProperties) HasTMEM

func (d DeviceProperties) HasTMEM() bool

HasTMEM reports whether the architecture has Tensor Memory (tcgen05.alloc), which caps resident blocks per SM independently of registers and shared memory. It is true when TMEMColumnsPerSM > 0 or when devicetable's probed target for the architecture supports tcgen05 (for example sm_107, whose TMEM column count is not yet measured).

type DiffOp

type DiffOp int

DiffOp represents the diff operation on an instruction.

const (
	DiffMatch  DiffOp = iota // Instruction matches between base and target
	DiffAdd                  // Instruction was added in target
	DiffDelete               // Instruction was removed from base
)

func (DiffOp) String

func (op DiffOp) String() string

type Disassembler

type Disassembler struct {
	Path, TempDir  string
	MaxOutputBytes int64
	Timeout        time.Duration
}

Disassembler invokes nvdisasm. The zero value searches PATH and uses the operating system's temporary directory. TempDir selects a scratch parent. Methods do not load code onto a GPU. Tool option support is version dependent.

MaxOutputBytes and Timeout bound one Disassembler.Disassemble run; zero selects the defaults of 256 MiB of output and one minute. Output over the budget fails with an error wrapping ErrOutputLimit.

func (Disassembler) Capabilities

func (d Disassembler) Capabilities(ctx context.Context) (cudatool.Caps, error)

Capabilities reports what the selected nvdisasm accepts. The answer comes from the option sets recorded for the toolkit the executable belongs to, or from its own --help for a toolkit newer than any recorded one.

func (Disassembler) ControlFlowGraph

func (d Disassembler) ControlFlowGraph(ctx context.Context, cubin []byte, basicBlocks bool) (Output, error)

ControlFlowGraph disassembles a CUDA ELF image into a Graphviz DOT control flow graph. If basicBlocks is true, basic blocks are generated instead of hyperblocks. Instruction offsets are included in the graph nodes.

func (Disassembler) Disassemble

func (d Disassembler) Disassemble(ctx context.Context, cubin []byte, opts Options) (out Output, err error)

Disassemble validates a CUDA ELF image and disassembles a private file copy. Scratch files are removed before return. Output remains available on failure.

func (Disassembler) DisassembleFunctionWithPressure

func (d Disassembler) DisassembleFunctionWithPressure(ctx context.Context, cubin []byte, name string) (*Disassembly, error)

DisassembleFunctionWithPressure collects line information and live register counts for a single CUBIN function symbol.

func (Disassembler) DisassembleWithPressure

func (d Disassembler) DisassembleWithPressure(ctx context.Context, cubin []byte) (*Disassembly, error)

DisassembleWithPressure executes a dual-pass disassembly on a CUBIN ELF image: Pass 1 disassembles instructions with source, inline, and PTX line information. Pass 2 collects live register pressure (--life-range-mode count). The passes are joined on instruction offset, populating LiveGPR, LivePred, LiveUGPR, and LiveUPred on each instruction.

When pass 2 fails or its output cannot be parsed, as nvdisasm does on some driver-JIT cubins, DisassembleWithPressure returns the pass 1 disassembly with no live-register counts and records why in Disassembly.PressureErr.

func (Disassembler) Version

func (d Disassembler) Version(ctx context.Context) (Output, error)

Version queries the selected executable; both output streams are retained.

type Disassembly

type Disassembly struct {
	// Target is the explicit architecture declared by .target or a code-for
	// preamble. It is empty when declarations are missing, malformed,
	// conflicting, or exceed the parser's target declaration bounds.
	// It is not inferred from instruction spellings or binary encodings.
	Target    string
	Functions []*Function

	// PressureErr, when not nil, is why [Disassembler.DisassembleWithPressure]
	// could not read register life ranges. Every instruction's LiveGPR,
	// LivePred, LiveUGPR and LiveUPred is then zero because it was not
	// measured, not because nothing is live. It is not encoded as JSON.
	PressureErr error `json:"-"`
	// contains filtered or unexported fields
}

Disassembly represents a parsed collection of disassembled SASS functions.

func DecodeCUBIN

func DecodeCUBIN(cubin []byte) (*Disassembly, error)

DecodeCUBIN decodes all .text.<kernel> sections of a CUBIN ELF image in pure Go without invoking nvdisasm. It wraps ErrNoISATables when local ISA tables have not been generated via "go generate -run gensasstables ./x/isa/sass".

Example
package main

import (
	"bytes"
	"encoding/hex"
	"errors"
	"fmt"
	"os"
	"strings"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	raw, err := os.ReadFile("testdata/effects-sm90.cubin.hex")
	if err != nil {
		panic(err)
	}
	cubin, err := hex.DecodeString(strings.Join(strings.Fields(string(raw)), ""))
	if err != nil {
		panic(err)
	}
	dis, err := sass.DecodeCUBIN(cubin)
	if errors.Is(err, sass.ErrNoISATables) {
		sidecar, sErr := os.ReadFile("testdata/effects-sm90.sass")
		if sErr != nil {
			panic(sErr)
		}
		dis, err = sass.Parse(bytes.NewReader(sidecar))
	}
	if err != nil {
		panic(err)
	}
	fn := dis.Function("fill")
	fmt.Printf("target=%s kernel=%s first=%s\n", dis.Target, fn.Name, fn.Instructions[0].Opcode)
}
Output:
target=sm_90 kernel=fill first=LDC

func DecodeCUBINFunction

func DecodeCUBINFunction(cubin []byte, name string) (*Disassembly, error)

DecodeCUBINFunction is DecodeCUBIN restricted to the section .text.<name>: other sections are not decoded, so an instruction outside name that the tables cannot decode does not fail it.

Example
package main

import (
	"bytes"
	"encoding/hex"
	"errors"
	"fmt"
	"os"
	"strings"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	raw, err := os.ReadFile("testdata/effects-sm90.cubin.hex")
	if err != nil {
		panic(err)
	}
	cubin, err := hex.DecodeString(strings.Join(strings.Fields(string(raw)), ""))
	if err != nil {
		panic(err)
	}
	// Only fill is decoded, however many kernels the cubin holds.
	// Without native tables, NvdisasmSource.DisassembleFunction lists the
	// one kernel through nvdisasm; this example reads a listing instead.
	dis, err := sass.DecodeCUBINFunction(cubin, "fill")
	if errors.Is(err, sass.ErrNoISATables) {
		sidecar, sErr := os.ReadFile("testdata/effects-sm90.sass")
		if sErr != nil {
			panic(sErr)
		}
		dis, err = sass.Parse(bytes.NewReader(sidecar))
	}
	if err != nil {
		panic(err)
	}
	fn := dis.Function("fill")
	fmt.Printf("kernel=%s first=%s\n", fn.Name, fn.Instructions[0].Opcode)
}
Output:
kernel=fill first=LDC

func DecodeCUBINWithPressure

func DecodeCUBINWithPressure(cubin []byte) (*Disassembly, error)

DecodeCUBINWithPressure decodes cubin natively via DecodeCUBIN and joins whole-CFG live register counts from ComputePressure.

func DisassembleCUBIN

func DisassembleCUBIN(cubin []byte) (*Disassembly, error)

DisassembleCUBIN invokes nvdisasm on cubin bytes to produce a structured Disassembly.

func DisassembleWithPressure

func DisassembleWithPressure(cubin []byte) (*Disassembly, error)

DisassembleWithPressure invokes nvdisasm twice on cubin bytes to produce a structured Disassembly with line info and live register pressure joined.

func Parse

func Parse(r io.Reader) (*Disassembly, error)

Parse reads SASS disassembly text from r and returns a Disassembly.

A ".text.NAME:" label names the kernel NAME. Parse reads the label from left to right, skipping each terminated string or character literal as rule 1 below reads one; the first "//" outside a literal begins a comment that is not part of the label. The label's terminal colon is the first colon outside a literal and before that comment that is followed by nothing but blanks, "/* */" comments and a final "//" comment, where a blank is any Unicode white space. A ".text." line with no such colon names the kernel by its text before that comment. So these labels name k, k and f<S{": //"}>() in turn:

.text.k // note:
.text.k: // a: b
.text.f<S{": //"}>():

A ".section .text.NAME" directive names the kernel NAME. Its flags field, if it has one, is the first comma outside a literal that is followed by optional spaces or tabs, a terminated double-quoted literal holding only LLVM's section flag bytes (a, e, o, w, x, M, S, T, G, R, ?, c, d, l, s and y, or none), and then the end of the line, a "//" comment, or a comma, optional spaces or tabs and a section type: '@' or '%' followed by identifier bytes or a quoted literal, or a quoted literal alone. The fields after the comma that follows the type, such as an entry size or a group, are not read, even a quoted group made only of flag bytes. A directive with no flags field names the kernel by its whole text. So a comma or quote inside a literal, a comma and quoted literal that more of the name follows, and a comma and quoted literal holding any other byte that no type follows belong to the name. The first three of these directives name the kernel decltype(fp, "<char const [5]>") s1<int>(int), the fourth names the kernel k, "lit", and the last two name the kernel k:

.section .text.decltype(fp, "<char const [5]>") s1<int>(int),"ax",@progbits
.section .text.decltype(fp, "<char const [5]>") s1<int>(int), "ax", @progbits
.section .text.decltype(fp, "<char const [5]>") s1<int>(int)
.section .text.k, "lit"
.section .text.k,"axG",@progbits,"x"
.section .text.k,"ax",@progbits, "a"

Parse returns an error, rather than guess where the section's name ends, for a ".section" directive whose name, the text before its flags field, holds a literal left open as rule 1 below reads one; or ends, split at its commas outside every literal, in a quoted literal, a type and only metadata fields (each a quoted literal or text with no blank, quote or bracket), which is a flags field holding a byte LLVM does not read; or whose flags field is followed by a later comma that would itself begin a flags field where the text before that comma is a name Parse accepts. So Parse refuses

.section .text.k"x
.section .text.k,"axq",@progbits
.section .text.k,"axq",@progbits,"grp",comdat
.section .text.k, "a","ax",@progbits

A demangled name's string literals are arguments that a bracket outside every literal closes after them, so they are never read as such a flags field: the directive

.section .text.decltype(g(fp, "<char const [2]>", "<char const [3]>", 0)) s1<int>(int),"ax",@progbits

names the kernel decltype(g(fp, "<char const [2]>", "<char const [3]>", 0)) s1<int>(int).

A name that itself ends, outside every literal, in a comma and a quoted literal of flag bytes, with no second such field after it, is read as a shorter name and its flags: the directive

.section .text.k, "a"

names the kernel k, never k, "a". No such name is supported.

Parse returns an error, rather than guess where the kernel's name ends, for a ".text." line whose name, read from left to right, breaks this lexical rule:

  1. A double or single quote begins a literal that ends at the next unescaped copy of the same quote; a backslash escapes the byte after it. Nothing inside a literal counts below. An unterminated literal is refused.
  2. Only '(', '[' and '{' open a bracket, and only ')', ']' and '}' close one; '<' and '>' are ignored. A closing bracket that does not match the innermost open bracket, or a bracket left open, is refused.
  3. Every "::" is accepted. A run of three or more colons is refused.
  4. A single colon is accepted only (a) in "[abi:" followed by one or more letters, digits, '_' or '$' and then ']', as in "h[abi:cxx11](int)"; (b) in "auto:N", where "auto" begins the name or follows a byte other than a letter, digit, '_' or '$', and N is one or more digits followed by a byte other than those, as in "{lambda(auto:1)#1}"; (c) as a conditional's colon, paired with the latest '?' at the same (), [] or {} depth that no colon has paired, with text other than white space between them, as in "decltype(fp ? 1 : 2) f<int>(int)". Every other single colon is refused.
  5. "/*", "*/" and "//" are refused.

So ".text.k:junk", ".text.k: junk", ".text.k:\u00a0junk", ".text.k /* c */:" and ".text.k(a ? b) : c" are refused. Because '<' and '>' are not brackets, every "::" is accepted, a conditional pairs at any depth and "[abi:" and "auto:N" carry no condition on what precedes or encloses them, some constructed lines that are no C++ name are accepted and name a kernel by their whole name: ".text.k ? f<a : b>", ".text.f<1 >> 2, b ? 1 : 2>()", ".text.k ? junk : junk", ".text.k:: junk", ".text.k ::junk", ".text.f(a::)" and ".text.k [abi:cxx11]" among them.

A colon, comma, quote or "//" inside a terminated literal, as in SL8<L8{"a//b"}> or S<5>{": //"}, belongs to the name and ends neither a label nor a directive's name. These rules are lexical; Parse is not a C++ parser. It still refuses, or does not support:

  • a label holding a literal left open, refused whatever follows the open quote, since rule 1 cannot tell where the literal would end;
  • a directive whose name itself ends, outside every literal, in a comma and a quoted literal of flag bytes, which is read as a shorter name followed by flags, or in a comma, a quoted literal, a type and metadata fields, which is refused;
  • a directive name breaking rules 2 through 5: a ".section" directive's name is checked only for a literal left open, so it is otherwise read as its text before the flags field and is not refused.
Example (TextSection)
package main

import (
	"errors"
	"fmt"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	d, err := sass.ParseString(`	.section	.text.k,"ax",@progbits
        /*0000*/                   EXIT ;
`)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(d.Function("k").ELFSection)

	_, err = sass.ParseString(`	.section	.nv.capmerc.text.k,"",@progbits
        /*0000*/                   EXIT ;
`)
	fmt.Println(errors.Is(err, sass.ErrNotTextSection))
}
Output:
.text.k
true

func ParseString

func ParseString(sass string) (*Disassembly, error)

ParseString parses SASS disassembly text directly from a string.

Example
package main

import (
	"fmt"

	isasass "github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	sass := `
.section .text.LinearGEMV,"ax",@progbits
/* 0x7f001230 */   LDG.E.CONSTANT.F32 R4, [R2.64] ;    // Global load
/* 0x7f001250 */   FFMA R0, R4, R5, R0 ;               // Fused multiply-add
`

	d, err := isasass.ParseString(sass)
	if err != nil {
		panic(err)
	}

	fn := d.Function("LinearGEMV")
	fmt.Printf("Kernel: %s (instructions: %d)\n", fn.Name, len(fn.Instructions))
	first := fn.Instructions[0]
	fmt.Printf("First instruction: [0x%x] %s %s\n", first.Address, first.Opcode, first.Operands)
}
Output:
Kernel: LinearGEMV (instructions: 2)
First instruction: [0x7f001230] LDG.E.CONSTANT.F32 R4, [R2.64]

func (*Disassembly) AssertOpcodes

func (d *Disassembly) AssertOpcodes(kernelName string, require, forbid []string) error

AssertOpcodes checks that all required opcodes are present and forbidden opcodes are absent. Mnemonic matching is case-insensitive and prefix-aware (e.g. "IDP4A" matches "IDP4A.U8.U8"). Common fallback forbid lists like ForbidSIMDFallbacks, ForbidFMAFallbacks, and ForbidWarpShuffleFallbacks can be passed to catch optimization regressions.

Example
package main

import (
	"fmt"

	isasass "github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	sass := `
.section .text.QuantizedDotProduct,"ax",@progbits
/* 0010 */   LDG.E.CONSTANT.F32 R4, [R2.64] ;
/* 0020 */   IDP4A.U8.U8 R0, R4, R5, R0 ;
`

	d, err := isasass.ParseString(sass)
	if err != nil {
		panic(err)
	}

	// Verify the kernel uses hardware SIMD dot product and no scalar integer multiplication.
	err = d.AssertOpcodes("QuantizedDotProduct",
		[]string{"IDP4A"}, // Required
		[]string{"IMAD"},  // Forbidden
	)
	fmt.Println("Assert SIMD:", err == nil)

	// Attempting to assert a missing instruction reports a clear error.
	err = d.AssertOpcodes("QuantizedDotProduct", []string{"HMMA"}, nil)
	fmt.Println("Assert Tensor Core:", err)

}
Output:
Assert SIMD: true
Assert Tensor Core: cudasass: kernel "QuantizedDotProduct" missing required opcode "HMMA"

func (*Disassembly) Function

func (d *Disassembly) Function(name string) *Function

Function returns the function by name, or nil if not found.

func (*Disassembly) Sections

func (d *Disassembly) Sections() []Section

Sections returns one Section per kernel region of the parsed listing, in listing order.

This is the shape callers reach for when they want one kernel's SASS, and it is deliberately not derived by matching a banner at the call site: Name comes from the same header the instructions were parsed under, so a section can never name a kernel the disassembly does not contain. nvdisasm prints several spellings of a kernel's header -- a banner comment, ".section .text.<name>", ".global <name>", ".type <name>,@function" -- and a call site that picks one of them is choosing which spelling to be wrong about.

A Section is a region of the listing, not an occurrence of a name. nvdisasm spells one kernel's header more than once -- ".section .text.k4" and then ".text.k4:" as a label -- and those are one region, not two. Two regions for one name arise only where the listing genuinely separates them, with a banner or an intervening kernel, and then Disassembly.Function still merges the instructions while the regions stay distinct.

func (*Disassembly) Summary

func (d *Disassembly) Summary(kernelName string) (*OpcodeSummary, error)

Summary returns the opcode summary for the named function.

type DisassemblyDiff

type DisassemblyDiff struct {
	Functions    []FunctionDiff
	Architecture ArchitectureDiff
	Spills       SpillDiff
}

DisassemblyDiff represents the diff between two Disassembly objects.

func Diff

func Diff(base, target *Disassembly) (*DisassemblyDiff, error)

Diff compares two Disassembly objects and produces a DisassemblyDiff.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	baseSASS := `
.section .text.gemv,"ax",@progbits
/*0010*/ IMAD.WIDE R0, R1, R2, R0 ;
/*0020*/ EXIT ;
`
	targetSASS := `
.section .text.gemv,"ax",@progbits
/*0010*/ IDP4A.U8.U8 R0, R1, R2, R0 ;
/*0020*/ EXIT ;
`
	base, _ := sass.ParseString(baseSASS)
	target, _ := sass.ParseString(targetSASS)

	diff, _ := sass.Diff(base, target)
	fnDiff := diff.Function("gemv")
	fmt.Printf("SIMD delta: %+d\n", fnDiff.Architecture.SIMDDelta)
	for _, sub := range fnDiff.Architecture.Substitutions {
		fmt.Printf("Substituted: %s -> %s\n", sub.From, sub.To)
	}
}
Output:
SIMD delta: +1
Substituted: IMAD -> IDP4A

func (*DisassemblyDiff) Function

func (d *DisassemblyDiff) Function(name string) *FunctionDiff

Function returns the FunctionDiff for the named function, or nil if not found.

type Divergence

type Divergence struct {
	Kind        Kind
	Slot        string // exact producer slot ID, empty for aggregate findings
	IRLine      int    // terminal IR use, zero for aggregate findings
	SASSAddress uint64 // conversion generic-access PC, when attributed
	Kernel      string // kernel name, as the level that has the kernel spells it
	PTXOpcode   string // PTX opcode prefix involved, if any
	SASSOpcode  string // SASS opcode prefix involved, if any
	PTXCount    int    // matching PTX instructions
	SASSCount   int    // matching SASS instructions
	Detail      string // supporting measurement, such as peak live register count
}

A Divergence is one place where the SASS differs from what the PTX asked for.

func (Divergence) String

func (d Divergence) String() string

type Edge

type Edge struct {
	From, To int
	Kind     DepKind
	Reg      Register // the register involved, for RAW, WAR and WAW
}

An Edge records that instruction From must issue before instruction To. From and To are indices into the block the edge was computed over.

func Dependencies

func Dependencies(b BasicBlock, arch Arch) ([]Edge, error)

Dependencies returns the ordering edges within one basic block.

It reports an error naming the first unclassified opcode rather than returning a partial graph: an edge set that silently omits the dependencies of an instruction nobody modelled is indistinguishable from one that proves a swap is safe.

type EdgeCoverage

type EdgeCoverage struct {
	// contains filtered or unexported fields
}

An EdgeCoverage accumulates edge counts for many threads, each with its own previous location. Its zero value is empty and ready to use.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	var c sass.EdgeCoverage
	for thread := range uint64(3) {
		c.Record(thread, 5)
		c.Record(thread, 9)
	}
	i, _ := sass.EdgeIndex(2, 9)
	fmt.Println(c.Count(i), c.Bitmap()[i])
}
Output:
3 3

func (*EdgeCoverage) Bitmap

func (c *EdgeCoverage) Bitmap() []byte

Bitmap returns the map as CoverageMapSize bytes, each count reduced to cuFuzz's bucket: 0, 1 and 2 are themselves, then 3 for 3-511, 4 for 512-4095, 5 for 4096-16383, 6 for 16384-65535 and 7 above.

func (*EdgeCoverage) Count

func (c *EdgeCoverage) Count(index int) uint32

Count returns the number of transitions counted at index.

func (*EdgeCoverage) Record

func (c *EdgeCoverage) Record(thread uint64, block int32) int

Record records that thread entered block and returns the index it counted. A thread's first transition is from location 0.

func (*EdgeCoverage) RecordWarp

func (c *EdgeCoverage) RecordWarp(threads []uint64, block int32) int

RecordWarp records that the active lanes of one warp, threads[0] first, entered block together, as cuFuzz's injected function does: every lane advances its own previous location, and only the first lane's edge is counted, once. It returns that index, or -1 if threads is empty.

type Effects

type Effects struct {
	Function string
	Params   []ParamAccess // by Offset

	// Unresolved lists the addresses of global accesses whose base register
	// no parameter reaches: pointers loaded from memory, computed through
	// shared memory, or merged from two parameters on different paths.
	Unresolved []uint64

	// Globals counts the global accesses through the address of a module
	// global, such as a lookup table, rather than through a parameter.
	Globals int

	// AsyncCopies counts the global-to-shared copies (LDGSTS, UBLKCP,
	// UTMALDG) and Waits the instructions that wait for them (DEPBAR, and
	// the mbarrier waits SYNCS.PHASECHK and SYNCS.*TRYWAIT).
	AsyncCopies, Waits int
}

Effects are the global memory effects a kernel's instructions have through its parameters, and the asynchronous copies it issues.

func ExtractEffects

func ExtractEffects(fn *Function, l ParamLayout) (*Effects, error)

ExtractEffects reads fn's global memory effects through the parameters of layout l, and checks its asynchronous copies. Only the 8-byte parameters of l can hold a pointer; a layout with no Params, for a listing without its cubin, lets every word of the block from l.Base on hold one.

A forward dataflow over the control flow graph follows each parameter word from its constant bank load (LDC, LDCU, ULDC) through moves (MOV, UMOV, R2UR, and IMAD Rd, RZ, RZ, Rc) and address arithmetic (IADD3, IADD3.X, IADD.64, IMAD.WIDE, UIMAD.WIDE, LEA, LEA.HI.X, VIADD, UIADD3) into the address of each global load, store, atomic and asynchronous copy. A register defined any other way holds no parameter. Where two paths reach a block with the same parameter at different offsets, the offset becomes a register offset; with different parameters, the register holds none. A CALL to a subroutine in fn clears the registers that subroutine defines, and any other CALL clears every register.

Every asynchronous copy must be committed (LDGDEPBAR) and waited for (DEPBAR) before any shared memory read (LDS, LDSM) on every path that touches its bytes, or be waited for through an mbarrier. A subroutine that issues a copy returns with it outstanding at an unknown address, and so does a CALL to code outside fn. A DEPBAR is taken to wait for every committed group. A copy still in flight at a read is compared with it by address, followed symbolically from threadIdx.x, constant bank words and loop-carried uniform registers: a read whose bytes provably differ from the copy's in every pair of threads needs no wait. An address spilled to local memory (STL) and loaded back (LDL) keeps its value, unless a store that may touch the word comes between: an STL that overlaps it or whose address is not a known offset from the same base, a generic store or atomic (ST, ATOM, RED), or a CALL. The threads a copy or read may run in are those of its path: a comparison of threadIdx.x with a constant (ISETP, alone or combined by AND or OR with another predicate) that guards a branch, an exit or the instruction itself narrows the range of threadIdx.x past it, until the predicate is written again or a CALL. Only the first destination of an ISETP is followed. A read that provably touches the bytes its own thread's copy writes is a *MissingWaitError; one the analysis can decide neither way is an *UnprovedWaitError.

A proof across threads needs facts the analysis checks rather than assumes:

  • A value is the same in every thread only if it is built from constant bank words, CTA-wide special registers and such values, and where two paths define it differently, only if no branch that threads may take different ways reaches the join before its post-dominator. A branch is uniform when its predicate is computed from uniform values alone.
  • A DEPBAR completes only the waiting thread's copies. Another thread's copies count as complete only after a block-wide barrier (BAR.SYNC with no thread count) follows the wait; until then a read must be apart from every other thread's copy. This also keeps a thread from comparing its read against copies another thread issued in a different iteration of a loop.
  • A read on one side of a divergent branch, before its post-dominator, while another side issues a copy, is unproved: the reading thread's path does not hold the other thread's copy.

What remains assumed is what the rest of this analysis assumes: every path in the control flow graph can run. The clause covers reads of copied bytes; a copy that overwrites bytes another thread is still reading is not checked. Without the cubin, threadIdx.x is bounded by the hardware limit of 1024.

Example
package main

import (
	"fmt"
	"log"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

// A kernel that copies a float4 from in to out[1].
const copySASS = `
.section .text.copy4,"ax",@progbits
.text.copy4:
        /*0000*/                   LDC.64 R2, c[0x0][0x218] ;
        /*0010*/                   LDC.64 R4, c[0x0][0x210] ;
        /*0020*/                   LDG.E.128 R8, desc[UR4][R2.64] ;
        /*0030*/                   STG.E.128 desc[UR4][R4.64+0x10], R8 ;
        /*0040*/                   EXIT ;
`

func main() {
	d, err := sass.ParseString(copySASS)
	if err != nil {
		log.Fatal(err)
	}
	// copy4(float4 *out, const float4 *in) on sm_90.
	layout := sass.ParamLayout{Base: 0x210, Size: 16, Params: []sass.Param{{0, 0, 8}, {1, 8, 8}}}
	e, err := sass.ExtractEffects(d.Function("copy4"), layout)
	if err != nil {
		log.Fatal(err)
	}
	for _, p := range e.Params {
		fmt.Printf("param at %d: read=%v write=%v align=%d extent=%d\n", p.Offset, p.Read, p.Write, p.Align, p.Extent)
	}
}
Output:
param at 0: read=false write=true align=16 extent=32
param at 8: read=true write=false align=16 extent=16

type Encoding

type Encoding struct {
	Lo, Hi uint64
}

An Encoding is the raw hardware encoding of one SASS instruction, as nvdisasm prints it under Options.PrintHex.

An instruction on the architectures nvdisasm still disassembles occupies two 64-bit words. Lo is the word nvdisasm prints on the instruction's own line; Hi is the word it prints alone on the line below. In instruction memory the two appear in that order, each little-endian, which is what Encoding.Bytes returns and what nvdisasm's --binary mode reads back.

The zero Encoding means no encoding was captured, not an instruction whose encoding is zero: an all-zero 128-bit word is not a legal instruction, and nvdisasm rejects one with "Illegal instruction found".

func EncodeATOMGAdd

func EncodeATOMGAdd(rd, ra, rb uint8, offset int32, widthBits int, descUR uint8, pred string, c ControlCode) (Encoding, error)

EncodeATOMGAdd encodes a 128-bit sm_121a ATOMG.E.ADD.STRONG.GPU PT, Rd, desc[URz][Ra.64], Rb instruction.

func EncodeBRA

func EncodeBRA(pc, target uint64, pred string, c ControlCode) (Encoding, error)

EncodeBRA encodes a 128-bit BRA instruction on sm_121a.

func EncodeCS2RClockLo

func EncodeCS2RClockLo(rd uint8, pred string, c ControlCode) (Encoding, error)

EncodeCS2RClockLo encodes a 128-bit sm_121a CS2R.32 Rd, SR_CLOCKLO instruction.

func EncodeControl

func EncodeControl(e Encoding, c ControlCode, arch Arch) (Encoding, error)

EncodeControl returns e with its control field replaced by c, clearing bit 125 (which nvdisasm 13.5 ignores) to 0. It reports an error if c holds a value not observed to be legal on arch or on e's instruction class, rather than truncating it into the field.

func EncodeIMADWideImm

func EncodeIMADWideImm(rd, ra uint8, imm uint32, rc uint8, signed bool, pred string, c ControlCode) (Encoding, error)

EncodeIMADWideImm encodes a 128-bit sm_121a IMAD.WIDE Rd, Ra, imm32, Rc instruction.

func EncodeISETP

func EncodeISETP(cmp IStepCmp, pd, ra, rb, pc uint8, signed bool, pred string, c ControlCode) (Encoding, error)

EncodeISETP encodes a 128-bit sm_121a ISETP.<cmp>.<type>.AND Pd, PT, Ra, Rb, Pc instruction.

func EncodeLDCU64

func EncodeLDCU64(urd uint8, cbankOffset uint32, pred string, c ControlCode) (Encoding, error)

EncodeLDCU64 encodes a 128-bit sm_121a LDCU.64 URd, c[0x0][cbankOffset] instruction.

func EncodeLDG

func EncodeLDG(rd, ra uint8, offset int32, widthBits int, descUR uint8, pred string, c ControlCode) (Encoding, error)

EncodeLDG encodes a 128-bit sm_121a LDG.E / LDG.E.64 instruction. Pass descUR = URZNum when no uniform descriptor is used.

func EncodeMOVImm32

func EncodeMOVImm32(rd uint8, imm uint32, pred string, c ControlCode) (Encoding, error)

EncodeMOVImm32 encodes a 128-bit sm_121a MOV Rd, imm32 instruction.

func EncodeMOVUR

func EncodeMOVUR(rd, urs uint8, pred string, c ControlCode) (Encoding, error)

EncodeMOVUR encodes a 128-bit sm_121a MOV Rd, URs instruction.

func EncodeNOP

func EncodeNOP(pred string, c ControlCode) (Encoding, error)

EncodeNOP encodes a 128-bit sm_121a NOP instruction.

func EncodeS2R

func EncodeS2R(rd uint8, srName string, pred string, c ControlCode) (Encoding, error)

EncodeS2R encodes a 128-bit sm_121a S2R Rd, SR instruction using specialRegisters.

func EncodeS2UR

func EncodeS2UR(urd uint8, srName string, pred string, c ControlCode) (Encoding, error)

EncodeS2UR encodes a 128-bit sm_121a S2UR URd, SR instruction using specialRegisters.

func EncodeSTG

func EncodeSTG(ra, rb uint8, offset int32, widthBits int, descUR uint8, pred string, c ControlCode) (Encoding, error)

EncodeSTG encodes a 128-bit sm_121a STG.E / STG.E.64 instruction. Pass descUR = URZNum when no uniform descriptor is used.

func EncodeUMOVImm32

func EncodeUMOVImm32(urd uint8, imm uint32, pred string, c ControlCode) (Encoding, error)

EncodeUMOVImm32 encodes a 128-bit sm_121a UMOV URd, imm32 instruction.

func ReEncode

func ReEncode(inst Instruction, arch Arch) (Encoding, error)

ReEncode rebuilds inst's encoding from its disassembled text.

The opcode, guarding predicate and register operands come from the text. The control code does not: nvdisasm prints no control field, so it is decoded from inst's captured encoding and re-applied. That asymmetry is the central result of the gate rather than an implementation convenience -- see Verdict.ControlCodeIsOutOfBand.

ReEncode returns an error for any instruction outside the covered subset. It never falls back to copying the captured bytes, which would make the round trip vacuous.

func (Encoding) Bytes

func (e Encoding) Bytes() [16]byte

Bytes returns the encoding as it occupies instruction memory: Lo then Hi, each little-endian. The result is accepted by nvdisasm --binary, which reads a bare sequence of such encodings.

func (Encoding) Present

func (e Encoding) Present() bool

Present reports whether an encoding was captured. See Encoding for why the zero value cannot be a real instruction.

func (Encoding) String

func (e Encoding) String() string

String formats both words in the order nvdisasm prints them.

type EquivVerdict

type EquivVerdict int

A EquivVerdict is the outcome of comparing two functions.

const (
	Unknown   EquivVerdict = iota // the model cannot decide
	Equal                         // same values stored, same branches taken
	Different                     // some stored value, address, order or condition differs
)

func (EquivVerdict) String

func (v EquivVerdict) String() string

type Evidence

type Evidence struct {
	Kernel          string
	Registers       int
	StaticShared    int
	DynamicShared   int
	LocalMemory     int // Local stack frame bytes per thread from EIATTR_FRAME_SIZE
	ThreadsPerBlock int
	Occupancy       OccupancyReport
}

Evidence joins compiled static resource usage with a requested launch geometry. It serves as an explanatory bound and diagnostic aid, not an optimizer recommendation.

type EvidenceIdentity

type EvidenceIdentity struct {
	ArtifactDigest string `json:"artifact_digest"`
	Entry          string `json:"entry"`
	Target         string `json:"target"`
	CompilerKey    string `json:"compiler_key"`
	WorkloadKey    string `json:"workload_key"`
}

EvidenceIdentity binds derived SASS or occupancy evidence to an artifact, entry point, target architecture, compiler key, and workload key.

func (EvidenceIdentity) Validate

func (id EvidenceIdentity) Validate() error

Validate checks that all three SHA-256 digests are lowercase 64-hex-char strings and that Entry and Target are non-empty.

type EvidenceRecord

type EvidenceRecord struct {
	Available bool           `json:"available"`
	Number    *float64       `json:"number,omitempty"`
	Unit      string         `json:"unit,omitempty"`
	Basis     string         `json:"basis,omitempty"`
	Source    EvidenceSource `json:"source"`
	Reason    string         `json:"reason,omitempty"`
}

EvidenceRecord holds a cycle-free derived or unavailable evidence fact ready for admission into github.com/tmc/lib/nvidia/x/obs/diag.

func PeakGPREvidence

func PeakGPREvidence(pressure map[string]map[uint64]RegisterPressure, source EvidenceSource) (EvidenceRecord, error)

PeakGPREvidence derives peak live GPR count from ParseLifeRangeCount output. Only the exact entry is admitted. A missing or empty map is unavailable; a present zero count remains a real derived zero. This is not an allocated register count or compiler spill proof.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	digest := strings.Repeat("1", 64)
	source := sass.EvidenceSource{
		Identity: sass.EvidenceIdentity{ArtifactDigest: digest, Entry: "kernel", Target: "sm_90", CompilerKey: digest, WorkloadKey: digest},
		Producer: "compiled fixture", Locator: "kernel record",
	}
	rec, err := sass.PeakGPREvidence(nil, source)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(rec.Available, rec.Number == nil)
}
Output:
false true

type EvidenceSource

type EvidenceSource struct {
	Identity EvidenceIdentity `json:"identity"`
	Producer string           `json:"producer"`
	Locator  string           `json:"locator"`
}

EvidenceSource identifies the producer and locator of a derived SASS or occupancy fact.

type ExitSite

type ExitSite struct {
	Index     int    // Index in Function.Instructions
	Address   uint64 // Hardware PC address of the EXIT instruction
	Predicate string // Guarding predicate, if any (e.g. "@P0")
}

ExitSite records a decoded EXIT instruction in a kernel's .text section.

type FaultDiagnosis

type FaultDiagnosis struct {
	FaultPC      uint64
	Instruction  Instruction
	AddrOperands []string
	Slice        []FaultSliceStep
	ParamOrdinal int // -1 if no parameter load was reached
	ParamOffset  int // -1 if no parameter load was reached
	Field        *FieldLayout
}

FaultDiagnosis is the host-only reconstruction of a recorded fault PC.

func DiagnoseFaultPC

func DiagnoseFaultPC(fn *Function, faultPC uint64, k elfinspect.Kernel, layout []FieldLayout) (*FaultDiagnosis, error)

DiagnoseFaultPC maps a recorded fault PC in fn to the faulting instruction, its address operands, the backward def-use slice of its address registers, and the Go struct field from layout via k (EIATTR_PARAM_CBANK and EIATTR_KPARAM_INFO).

This is a host-only static analysis over a recorded fault PC; it does not execute code or read a live GPU fault.

Example
package main

import (
	"fmt"

	elfinspect "github.com/tmc/lib/nvidia/x/host/elf"
	cudasass "github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	const sass = `.section .text.paged_attn_decode_v2
.text.paged_attn_decode_v2:
/*0040*/ LDC.64 R2, c[0x0][0x178] ;
/*0240*/ LDG.E.S32 R4, [R10.64] ;
/*0290*/ IMAD.WIDE R6, R4, 0x80, R2 ;
/*02c0*/ LDG.E.128 R16, [R6.64+0x0] ;
/*02d0*/ EXIT ;
`
	d, err := cudasass.ParseString(sass)
	if err != nil {
		panic(err)
	}
	k := elfinspect.Kernel{
		Name:      "paged_attn_decode_v2",
		ParamBank: 0x160,
		Params: []elfinspect.Param{
			{Ordinal: 3, Offset: 0x18, Size: 8},
		},
	}
	layout := []cudasass.FieldLayout{
		{Ordinal: 3, Name: "PagedKVArgs.BlockTable", GoType: "cuda.Slice[uint8]"},
	}

	diag, err := cudasass.DiagnoseFaultPC(d.Functions[0], 0x02c0, k, layout)
	if err != nil {
		panic(err)
	}
	fmt.Printf("PC=%#04x op=%s addr=%v\n", diag.FaultPC, diag.Instruction.Opcode, diag.AddrOperands)
	fmt.Printf("param=#%d field=%s (%s)\n", diag.ParamOrdinal, diag.Field.Name, diag.Field.GoType)
}
Output:
PC=0x02c0 op=LDG.E.128 addr=[[R6.64+0x0]]
param=#3 field=PagedKVArgs.BlockTable (cuda.Slice[uint8])

func (*FaultDiagnosis) String

func (d *FaultDiagnosis) String() string

String formats a human-readable autopsy report.

type FaultSliceStep

type FaultSliceStep struct {
	PC          uint64
	Opcode      string
	Operands    string
	ParamOffset int // >= 0 if this instruction reads c[0x0][ParamOffset], else -1
}

FaultSliceStep is one instruction in the backward address-formation slice from a faulting memory instruction.

type FeatureAuditOptions

type FeatureAuditOptions struct {
	// SharedMemBytes is the kernel's per-CTA shared memory footprint (static
	// plus dynamic, when known). Values >= 16 KiB qualify a kernel with global
	// or shared transfers for TMA relevance gating.
	SharedMemBytes int

	// PMActivePct and PMTensorPct are optional CUPTI PM sampling means
	// (SM active % and tensor pipe active %). When SM active >= 50% and
	// tensor pipe <= 5%, missing tensor-core MMA is flagged even below the
	// static FMA instruction-count floor.
	PMActivePct *float64
	PMTensorPct *float64
}

FeatureAuditOptions supplies optional context for relevance gating in AuditFeatures.

type FeatureAuditReport

type FeatureAuditReport struct {
	SM                string         `json:"sm"`
	Kernel            string         `json:"kernel,omitempty"`
	Features          []FeatureEntry `json:"features"`
	Used              []FeatureEntry `json:"used,omitempty"`
	Available         []FeatureEntry `json:"available,omitempty"`
	Unused            []FeatureEntry `json:"unused,omitempty"`
	WideLoads         int            `json:"wide_loads"`
	NarrowLoads       int            `json:"narrow_loads"`
	TotalLoads        int            `json:"total_loads"`
	InstructionCounts map[string]int `json:"instruction_counts"`
}

FeatureAuditReport summarizes hardware-feature usage for one kernel on one SM.

func AuditFeatures

func AuditFeatures(arch string, fn *Function, opts FeatureAuditOptions) FeatureAuditReport

AuditFeatures audits a disassembled SASS function against the hardware features of arch, applying relevance gating so small utility kernels are not flagged as missing TMA or Tensor Core MMA.

type FeatureEntry

type FeatureEntry struct {
	Feature  ArchFeature   `json:"feature"`
	Status   FeatureStatus `json:"status"`
	Count    int           `json:"count"`
	Evidence string        `json:"evidence,omitempty"`
}

FeatureEntry records the audit verdict for one architecture feature in a kernel.

type FeatureStatus

type FeatureStatus string

FeatureStatus classifies how a kernel uses an architecture hardware feature.

const (
	// FeatureUsed means the kernel's SASS issues instructions for the feature.
	FeatureUsed FeatureStatus = "used"
	// FeatureAvailable means the target architecture provides the feature, the
	// kernel does not use it, and relevance gating does not indicate a gap.
	FeatureAvailable FeatureStatus = "available"
	// FeatureUnused means the target architecture provides the feature, the
	// kernel does not use it, and relevance gating indicates a likely gap.
	FeatureUnused FeatureStatus = "unused"
)

type FieldLayout

type FieldLayout struct {
	Ordinal int
	Name    string // e.g. "PagedKVArgs.BlockTable"
	GoType  string // e.g. "cuda.Slice[uint8]"
	Offset  int
	Size    int
}

FieldLayout maps a kernel parameter ordinal to a Go struct field.

type FlightCave

type FlightCave struct {
	Code             []byte
	EntryOffset      uint64      // offset within cave of entry sequence
	ExitOffset       uint64      // offset within cave of exit sequence
	ExitReplayOffset uint64      // offset within cave of replayed EXIT instruction
	Relocs           []CaveReloc // relocations relative to cave start (caller adds caveOffset)
}

FlightCave is the assembled sm_121a entry/exit trampoline code cave.

func AssembleFlightCave

func AssembleFlightCave(caveOffset uint64, entryDisplaced, exitDisplaced []byte) (FlightCave, error)

AssembleFlightCave builds the sm_121a entry and exit trampoline code cave for caveOffset in .text.<kernel>. Both entry and exit sequences:

  1. Materialize __iket_flight_cfg into R8:R9 via UMOV + ELF relocations,
  2. Load Mode at [R8.64+8], test Mode == 0, and uniform @P0 BRA bypass,
  3. Read SR_CLOCK and SR_CTAID.X, ATOMG.E.ADD the ring cursor, load Capacity at [RingPtr+16] and skip the stores when idx >= Capacity (writeIdx keeps counting), compute slotAddr = RingPtr + idx * 32 via IMAD.WIDE.U32, and STG.E the event,
  4. Drain store read barriers and replay the displaced entry/exit instruction.

type FlowEdge

type FlowEdge struct {
	From, To int // indices into CFG.Blocks
	Kind     FlowKind
}

A FlowEdge is a control transfer between two blocks of a CFG.

type FlowKind

type FlowKind int

A FlowKind names how control passes from one basic block to another.

const (
	FallThrough FlowKind = iota // control continues to the next block
	Taken                       // a direct branch transfers to the block
	Call                        // a call enters the block; control returns after the caller
)

func (FlowKind) String

func (k FlowKind) String() string

type Function

type Function struct {
	Name         string
	BaseAddress  uint64
	Instructions []Instruction

	// Symbols lists the function symbols nvdisasm declares inside this
	// function's section other than the function itself, in address order.
	// The compiler places the subroutines a kernel calls, such as its
	// division slowpath, after the kernel's own code in the same section,
	// and their instructions are in Instructions like any other.
	Symbols []Symbol

	// ELFSection is the ELF section the instructions were read from, as
	// the listing names it: ".text.<Name>" when a header spelled it, and ""
	// when every header was a spelling that names no section, such as
	// cuobjdump's "Function : <Name>". [Parse] refuses a listing that
	// opens any other code section, so no other value occurs.
	ELFSection string

	// Labels maps each code label in the function, such as ".L_x_0", to the
	// address of the instruction that follows it. A label with no instruction
	// after it in the function, such as the one nvdisasm uses to size it, is
	// omitted.
	Labels map[string]uint64
}

Function represents a disassembled GPU kernel with its instruction sequence.

func DecodeFunction

func DecodeFunction(sm string, fn *Function) (*Function, error)

DecodeFunction reconstructs fn's instructions solely from their 128-bit Encoding words using Decode for target sm, discarding any prior text.

func Scramble

func Scramble(fn *Function, seed int64) (*Function, error)

Scramble returns a copy of fn with internal general-purpose registers bijectively renamed and independent instructions reordered within basic blocks. The returned function is semantically equivalent to fn under CompareWithWitness.

func (*Function) ClusterCancelCount

func (f *Function) ClusterCancelCount() int

ClusterCancelCount counts static cluster launch control cancel instructions. A count describes the function's code, independent of what executed.

func (*Function) Summary

func (f *Function) Summary() *OpcodeSummary

Summary returns opcode frequency statistics for this function.

func (*Function) SymbolAt

func (f *Function) SymbolAt(addr uint64) string

SymbolAt returns the name of the symbol whose code contains the function-relative address: the last of Symbols at or before it, or the function's own name when no symbol precedes it.

func (*Function) WaterfallTrace

func (f *Function) WaterfallTrace(opts WaterfallOptions) (*WaterfallTrace, error)

WaterfallTrace builds a Chrome Trace Event JSON structure for fn, with one track per warp slot and instruction durations taken from the control word's stall field.

Example
package main

import (
	"fmt"

	cudasass "github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	enc := func(ctrl cudasass.ControlCode) cudasass.Encoding {
		e, err := cudasass.EncodeControl(cudasass.Encoding{Lo: 0x7982}, ctrl, cudasass.SM121a)
		if err != nil {
			panic(err)
		}
		return e
	}

	fn := &cudasass.Function{
		Name: "mxfp4_gemv",
		Instructions: []cudasass.Instruction{
			{Address: 0x0000, Opcode: "LDG.E.128", Operands: "R4, [R2.64]", Encoding: enc(cudasass.ControlCode{Stall: 6, Yield: true, WriteBarrier: 2, ReadBarrier: cudasass.NoBarrier})},
			{Address: 0x0010, Opcode: "IADD3", Operands: "R10, R10, 0x10, RZ", Encoding: enc(cudasass.ControlCode{Stall: 2, Yield: true, WriteBarrier: cudasass.NoBarrier, ReadBarrier: cudasass.NoBarrier})},
			{Address: 0x0020, Opcode: "FFMA", Operands: "R8, R4, R10, R8", Encoding: enc(cudasass.ControlCode{Stall: 4, Yield: true, WriteBarrier: cudasass.NoBarrier, ReadBarrier: cudasass.NoBarrier, WaitMask: 1 << 2})},
		},
	}

	tr, err := fn.WaterfallTrace(cudasass.WaterfallOptions{Arch: cudasass.SM121a, WarpSlots: 2})
	if err != nil {
		panic(err)
	}
	fmt.Printf("function=%s slots=%d model=%q events=%d\n",
		tr.Metadata.Function, tr.Metadata.WarpSlots, tr.Metadata.TimingModel, len(tr.TraceEvents))
	for _, ev := range tr.TraceEvents {
		if ev.Phase == "X" {
			fmt.Printf("  slot=%d ts=%d dur=%d %s\n", ev.TID, ev.TS, ev.Dur, ev.Name)
		}
	}
}
Output:
function=mxfp4_gemv slots=2 model="stall-field order (not latency)" events=7
  slot=0 ts=0 dur=6 0x0000 LDG.E.128
  slot=1 ts=0 dur=2 0x0010 IADD3
  slot=0 ts=6 dur=4 0x0020 FFMA

func (*Function) WriteWaterfallJSON

func (f *Function) WriteWaterfallJSON(w io.Writer, opts WaterfallOptions) error

WriteWaterfallJSON writes the Chrome Trace Event JSON for f to w.

type FunctionDiff

type FunctionDiff struct {
	Name         string
	Base         Function
	Target       Function
	Changes      []InstructionDiff
	Architecture ArchitectureDiff
	Spills       SpillDiff
}

FunctionDiff represents the diff between two kernel functions.

func DiffFunctions

func DiffFunctions(baseFn, targetFn Function) FunctionDiff

DiffFunctions compares two functions and returns their structured diff.

func (FunctionDiff) AddedCount

func (f FunctionDiff) AddedCount() int

AddedCount returns the number of instructions added in target.

func (FunctionDiff) DeletedCount

func (f FunctionDiff) DeletedCount() int

DeletedCount returns the number of instructions removed from base.

func (FunctionDiff) MatchedCount

func (f FunctionDiff) MatchedCount() int

MatchedCount returns the number of matching instructions.

type GlobalTimerHoistViolation

type GlobalTimerHoistViolation struct {
	Line        int
	PC          string
	Instruction string
	PrevLine    int
	PrevPC      string
	PrevInst    string
	BarrierLine int
	BarrierPC   string
	BarrierInst string
	Reason      string
}

GlobalTimerHoistViolation describes a SASS %globaltimer read (CS2R/CS2UR/S2R/S2UR SR_GLOBALTIMER*) that ptxas scheduled across or without a required ordering barrier (BAR.SYNC, MEMBAR, DEPBAR, WARPSYNC).

type GlobalTimerScheduleReport

type GlobalTimerScheduleReport struct {
	TimerReads   int
	BarrierInsts int
	SyncBarriers int // BAR*, WARPSYNC*
	MemBarriers  int // MEMBAR*
	DepBarriers  int // DEPBAR*
	RingCommits  int // ATOMG*, ATOM*, REDG*
	Violations   []GlobalTimerHoistViolation
}

GlobalTimerScheduleReport summarizes the %globaltimer (CS2R/CS2UR/S2R/S2UR SR_GLOBALTIMER*) and barrier (BAR, MEMBAR, DEPBAR, WARPSYNC) schedule observed in a SASS listing.

func VerifyGlobalTimerSchedule

func VerifyGlobalTimerSchedule(sass string) (GlobalTimerScheduleReport, error)

VerifyGlobalTimerSchedule checks a ptxas/nvdisasm SASS listing of an IKET-instrumented kernel or region for CS2R/CS2UR SR_GLOBALTIMER schedule hoisting or sinking across BAR.SYNC, MEMBAR, DEPBAR, or WARPSYNC barriers.

Specifically, it verifies that:

  1. The listing contains at least one SR_GLOBALTIMER read.
  2. No BAR/DEPBAR/WARPSYNC synchronization barrier precedes the first SR_GLOBALTIMER read in a timed region (start timer sunk below barrier).
  3. Consecutive SR_GLOBALTIMER sample reads are separated by at least one ordering barrier (BAR, MEMBAR, DEPBAR, or WARPSYNC), preventing ptxas from hoisting a range-end CS2R/CS2UR SR_GLOBALTIMER above the work or barrier it bounds.
  4. Every BAR/DEPBAR/WARPSYNC barrier is followed by a post-barrier SR_GLOBALTIMER read before the subsequent ring-buffer atomic reservation (ATOMG/ATOM), system fence (MEMBAR.*.SYS), or end of listing (end timer hoisted above barrier).
  5. No SR_GLOBALTIMER read is sunk between a ring-buffer seal fence (MEMBAR.*.SYS) and its following global seal store (STG).
Example
package main

import (
	"fmt"

	isasass "github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	sass := `
		/*0520*/ CS2R R6, SR_GLOBALTIMERLO ;
		/*0890*/ STS [R14], R37 ;
		/*0f20*/ BAR.SYNC.DEFER_BLOCKING 0x0 ;
		/*0f50*/ CS2UR UR12, SR_GLOBALTIMERLO ;
		/*11d0*/ @P3 ATOMG.E.ADD.64.STRONG.GPU PT, R20, desc[UR8][R20.64+0x20], R22 ;
		/*1390*/ MEMBAR.SC.SYS ;
		/*13d0*/ STG.E.STRONG.SYS desc[UR8][R16.64+0x3c], R21 ;
	`
	rep, err := isasass.VerifyGlobalTimerSchedule(sass)
	fmt.Printf("timers=%d sync_bars=%d mem_bars=%d commits=%d violations=%d err=%v\n",
		rep.TimerReads, rep.SyncBarriers, rep.MemBarriers, rep.RingCommits, len(rep.Violations), err)
}
Output:
timers=2 sync_bars=1 mem_bars=1 commits=1 violations=0 err=<nil>

type HazardError

type HazardError struct {
	Kind     DepKind
	From, To int // indices into the block
	Reg      Register
	Reason   string
}

A HazardError reports a register dependency a control-code schedule does not honour.

func (*HazardError) Error

func (e *HazardError) Error() string

type Hierarchy

type Hierarchy struct {
	Schema int              `json:"schema"`
	Kernel string           `json:"kernel"`
	Arch   string           `json:"arch"`
	Levels []HierarchyLevel `json:"levels"`
}

A Hierarchy records how one kernel uses each level of the memory hierarchy: registers, shared memory, Tensor Memory, L2 and device memory, in that order. Every value carries its Basis; none is defaulted.

func BuildHierarchy

func BuildHierarchy(in HierarchyInput) (*Hierarchy, error)

BuildHierarchy joins the CUBIN, SASS, plans, counters and device tables of one kernel into a Hierarchy.

Example

ExampleBuildHierarchy joins a kernel's compiled resources, its launch and the counters of one run into a record of each memory level it uses. A value nothing supplied is printed as unavailable, with the reason below.

package main

import (
	"log"
	"os"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	h, err := sass.BuildHierarchy(sass.HierarchyInput{
		Name:   "matvec",
		Arch:   "sm_121",
		Kernel: &sass.KernelResource{Name: "matvec", Registers: 40, StaticSharedMem: 1024},
		Launch: &sass.Launch{Threads: 256, Source: "example"},
		Counters: map[string]float64{
			"lts__t_sectors.sum":                         1 << 16,
			"lts__t_sector_hit_rate.pct":                 75,
			"lts__t_sectors_srcunit_tex_lookup_miss.sum": 1 << 14,
			"gpu__time_duration.sum":                     8000,
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	if err := h.WriteText(os.Stdout); err != nil {
		log.Fatal(err)
	}
}
Output:
kernel matvec on sm_121
LEVEL          CAPACITY                  DECLARED                    MOVED
Register       65536 registers (probed)  10240 registers (compiled)  unavailable [1]
  per_thread   40 registers (compiled)
  stack_frame  0 bytes (compiled)
Shared         102400 bytes (probed)  1024 bytes (planned)  unavailable [2]
  static       1024 bytes (compiled)
  dynamic      0 bytes (planned)
TensorMemory   0 columns (table)        unavailable [3]  unavailable [4]
L2             25165824 bytes (probed)  unavailable [5]  2097152 bytes (measured)
  hit_rate     75 percent (measured)
DRAM           unavailable [6]  unavailable [7]  524288 bytes (measured)
  ceiling      273 GB/s (table)
  ceiling_pct  24.01 percent (table)
[1] Register moved: no counter reports register-file traffic
[2] Shared moved: no shared-memory traffic counter is read
[3] TensorMemory declared: no SASS or tensor-memory allocation supplied
[4] TensorMemory moved: the device has no tensor memory
[5] L2 declared: a kernel declares no L2 storage
[6] DRAM capacity: cudadevicetable records no device-memory size
[7] DRAM declared: a kernel declares no device-memory storage

func (*Hierarchy) Level

func (h *Hierarchy) Level(level fmt.Stringer) *HierarchyLevel

Level returns the row for level, or nil if h has none.

func (*Hierarchy) MarshalJSON

func (h *Hierarchy) MarshalJSON() ([]byte, error)

MarshalJSON is ordinary JSON marshaling; it exists so that a Hierarchy that fails Validate cannot be written.

func (*Hierarchy) UnmarshalJSON

func (h *Hierarchy) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes h and validates it.

func (*Hierarchy) Validate

func (h *Hierarchy) Validate() error

Validate reports whether h has every level once, in order, and whether every cell names its basis: a known value names its source and an unavailable one its reason.

func (*Hierarchy) WriteText

func (h *Hierarchy) WriteText(w io.Writer) error

WriteText writes h as a fixed-width table, one row per level. An unavailable cell is printed as "unavailable" with a numbered note giving its reason, and every other cell names its basis.

type HierarchyInput

type HierarchyInput struct {
	Name string // kernel name
	Arch string // target architecture, such as "sm_121" or "sm_100a"

	// Kernel holds the resources read from the kernel's CUBIN by
	// InspectCubin. Nil means no CUBIN was read.
	Kernel *KernelResource

	Launch     *Launch
	SharedPlan any
	TMEM       []TMEMRegion

	// SASS is the kernel's disassembly. Its tcgen05 instructions say
	// whether the kernel uses Tensor Memory.
	SASS *Function

	// Counters are the hardware counters of one launch, keyed by their
	// Nsight Compute names. Nil means none were collected.
	Counters   map[string]float64
	DurationNs float64

	// MemoryCeiling, when set, is the bandwidth device-memory traffic is
	// compared to; otherwise the cudadevicetable value is.
	MemoryCeiling *MemoryCeiling
}

HierarchyInput is what BuildHierarchy reads. Each field is optional except Arch and Name; a level whose input is absent reports its cells unavailable rather than assuming a value.

type HierarchyLevel

type HierarchyLevel struct {
	Level    string `json:"level"` // the cudalayout.StorageLevel name
	Capacity Cell   `json:"capacity"`
	Declared Cell   `json:"declared"`
	Moved    Cell   `json:"moved"`

	// Use is "used" or "unused" when the SASS says whether the kernel
	// touches the level, and empty when nothing says. It is set only for
	// Tensor Memory, which a kernel can use without declaring a size.
	Use string `json:"use,omitempty"`

	Details []Cell            `json:"details,omitempty"`
	Regions []HierarchyRegion `json:"regions,omitempty"`
}

A HierarchyLevel is one row of a Hierarchy: how much of a level an SM or device has, how much one CTA of the kernel declares, and how many bytes the kernel moved through it.

type HierarchyRegion

type HierarchyRegion struct {
	Name       string `json:"name"`
	Offset     int64  `json:"offset"`
	Size       int64  `json:"size"`
	Unit       string `json:"unit"`
	FirstStage int    `json:"first_stage,omitempty"`
	LastStage  int    `json:"last_stage,omitempty"`
	Dynamic    bool   `json:"dynamic,omitempty"`
	Basis      Basis  `json:"basis"`
}

A HierarchyRegion is one named range of a level's declared storage: a shared memory region of a cudashared plan, or a Tensor Memory allocation.

type IStepCmp

type IStepCmp uint8

IStepCmp selects the integer comparison in EncodeISETP.

const (
	CmpLT IStepCmp = 1
	CmpEQ IStepCmp = 2
	CmpLE IStepCmp = 3
	CmpGT IStepCmp = 4
	CmpNE IStepCmp = 5
	CmpGE IStepCmp = 6
)

type Instruction

type Instruction struct {
	Address     uint64   // Hardware PC address (e.g. 0x7f001230)
	Predicate   string   // Instruction predicate, e.g. "@P0", "@!PT"
	Opcode      string   // Mnemonic and modifiers, e.g. "FFMA", "LDG.E.CONSTANT.F32", "STS.32"
	Operands    string   // Register and memory operands, e.g. "R0, R4, R5, R0"
	SourceFile  string   // Source file name from line-info comments, e.g. "kernels.cu"
	SourceLine  int      // Source line number from line-info comments
	InlinedFile string   // Inlined call site file name, if inlined
	InlinedLine int      // Inlined call site line number, if inlined
	PTXLine     int      // PTX line number from .nv_debug_ptx_txt comments, if present
	LiveGPR     int      // Live General Purpose Registers from register life-range analysis
	LivePred    int      // Live Predicate registers
	LiveUGPR    int      // Live Uniform GPRs (sm_70+)
	LiveUPred   int      // Live Uniform Predicate registers (sm_70+)
	Encoding    Encoding // Raw instruction encoding, when [Options.PrintHex] was requested
	Comment     string   // Optional disassembly comment
	Raw         string   // Full raw disassembly line
}

Instruction represents a single decoded hardware SASS instruction.

func ParseInstructionLine

func ParseInstructionLine(line string) (Instruction, bool)

ParseInstructionLine parses a single SASS instruction line. Supports both nvdisasm formats:

/* 0x7f001230 */   LDG.E.CONSTANT.F32 R4, [R2.64] ;   // comment
/*0030*/                   LDG.E.CONSTANT.F32 R4, [R2.64];

A trailing encoding comment written by --print-instruction-encoding sets Instruction.Encoding.Lo. The matching high word is on the next line, which is not an instruction line; only Parse sees it, so an instruction parsed through this function alone carries a half encoding.

func (Instruction) Pressure

func (i Instruction) Pressure() RegisterPressure

Pressure returns the live register pressure at this instruction.

func (Instruction) Role

func (i Instruction) Role() InstructionRole

Role returns the semantic execution role of the instruction.

type InstructionDiff

type InstructionDiff struct {
	Op     DiffOp
	Inst   Instruction
	Base   *Instruction
	Target *Instruction
}

InstructionDiff represents a single instruction diff entry.

func (InstructionDiff) String

func (d InstructionDiff) String() string

String returns a unified-diff style formatted representation of the instruction diff.

type InstructionRole

type InstructionRole string

InstructionRole classifies a SASS instruction into its primary execution or memory-hierarchy role for stall attribution, roofline analysis, and spill auditing.

const (
	RoleUnknown     InstructionRole = "unknown"
	RoleALU         InstructionRole = "alu"
	RoleTensorMMA   InstructionRole = "tensor_mma"
	RoleGlobalMem   InstructionRole = "global_mem"
	RoleLocalMem    InstructionRole = "local_mem"
	RoleSharedMem   InstructionRole = "shared_mem"
	RoleConstantMem InstructionRole = "constant_mem"
	RoleTextureMem  InstructionRole = "texture_mem"
	RoleBarrier     InstructionRole = "barrier"
	RoleBranch      InstructionRole = "branch"
	RoleWarpShuffle InstructionRole = "warp_shuffle"
	RoleSpecialReg  InstructionRole = "special_reg"
)

func ClassifyRole

func ClassifyRole(sassOrOpcode string) InstructionRole

ClassifyRole returns the InstructionRole for a SASS opcode or full SASS instruction text (such as "LDG.E.128", "LDL", "/*0010*/ @P0 STL [R1], R2 ;").

Local-memory instructions (LDL, STL, LDLK, STLK, and LD/ST with .LOCAL) return RoleLocalMem, distinct from RoleGlobalMem (LDG, STG, LDGSTS, RED, ATOM, ATOMG) so register spills are never conflated with global-memory traffic.

type JSONDisassembly

type JSONDisassembly struct {
	Metadata  map[string]json.RawMessage
	Functions []JSONFunction
}

JSONDisassembly retains metadata and function records from nvdisasm's JSON output. Unlike Disassembly it preserves gaps and does not infer instruction addresses for architectures with a different instruction width.

func ParseJSON

func ParseJSON(r io.Reader) (*JSONDisassembly, error)

ParseJSON reads nvdisasm's [metadata, functions] format. It rejects missing required fields and trailing data; unknown fields are allowed for toolkit evolution. Metadata is retained verbatim, not interpreted as a version gate.

Example
d, err := ParseJSON(strings.NewReader(jsonFixture))
if err != nil {
	panic(err)
}
fmt.Println(d.Functions[0].Name, len(d.Functions[0].Instructions))
Output:
kernel 3

type JSONFunction

type JSONFunction struct {
	Name         string            `json:"function-name"`
	Start        uint64            `json:"start"`
	Length       uint64            `json:"length"`
	Attributes   []string          `json:"other-attributes"`
	Instructions []JSONInstruction `json:"sass-instructions"`
}

JSONFunction is a CUDA function in the nvdisasm JSON schema.

type JSONInstruction

type JSONInstruction struct {
	Predicate  string            `json:"predicate"`
	Opcode     string            `json:"opcode"`
	Operands   string            `json:"operands"`
	Extra      string            `json:"extra"`
	Attributes map[string]string `json:"other-attributes"`
	Flags      []string          `json:"other-flags"`
}

JSONInstruction preserves empty opcodes representing instruction-slot gaps.

type KernelResource

type KernelResource struct {
	Name               string             // Kernel function name
	RegisterAllocation RegisterAllocation // Parsed presence, or caller-supplied analytical inputs
	Registers          int                // Physical 32-bit registers allocated per thread (from global .nv.info EIATTR_REGCOUNT)
	// StaticSharedMem is the physical static shared memory allocation charged per CTA in bytes.
	//
	// On sm_121a and modern architectures, the driver charges an extra 1024 bytes
	// (driver/hardware reservation) whenever a kernel declares shared memory:
	//
	//   Declared tile    ptxas -v          cuobjdump -res-usage / ELF .nv.shared size
	//   64 B             64 bytes smem     SHARED:1088
	//   4096 B           4096 bytes smem   SHARED:5120
	//   8192 B           8192 bytes smem   SHARED:9216
	//   none declared    (no line)         SHARED:0 (no .nv.shared section)
	//
	// StaticSharedMem records the actual ELF section size (e.g. 1088, 5120, 9216),
	// which is what cuOccupancyMaxActiveBlocksPerMultiprocessor charges against the SM.
	// (The same 1024 B arithmetic appears in MaxSharedMemoryOptin: 101376 B = 102400 - 1024 B,
	// though whether this shares the identical hardware reservation mechanism is unproven).
	StaticSharedMem  int
	StackFrameBytes  int // Local stack frame size per thread in bytes (EIATTR_FRAME_SIZE)
	ConstantBankSize int // Constant memory parameter bank 0 size in bytes (.nv.constant0 / EIATTR_PARAM_CBANK)

	// TMEMColumns is the Tensor Memory one CTA allocates with
	// tcgen05.alloc, in columns; 0 when it allocates none. No ELF
	// attribute records it, so InspectCubin leaves it 0 and a caller
	// reads it from the PTX.
	TMEMColumns int

	// ClusterSize is the number of CTAs in the kernel's thread block
	// cluster; 0 or 1 without one.
	ClusterSize int

	// CTAPair reports that the kernel issues tcgen05 MMAs with
	// cta_group::2, which pairs each CTA with a peer CTA of its cluster.
	CTAPair bool
}

KernelResource records static hardware resource allocations for a compiled CUDA kernel.

func InspectArtifact

func InspectArtifact(cm *nvrtc.CompiledModule) ([]KernelResource, error)

InspectArtifact reports kernel resources in a compiled CUBIN. PTX and LTOIR have no final register allocation and must be linked or loaded first.

func InspectCubin

func InspectCubin(cubin []byte) ([]KernelResource, error)

InspectCubin parses a CUBIN ELF image and extracts resource usage for all kernels.

func InspectCubinReader

func InspectCubinReader(r io.ReaderAt, size int64) ([]KernelResource, error)

InspectCubinReader parses a CUBIN ELF image from an io.ReaderAt.

func ParseELF

func ParseELF(f *elf.File) ([]KernelResource, error)

ParseELF inspects an open CUBIN ELF file and extracts resource usage for all kernels.

func (KernelResource) Calculate

func (k KernelResource) Calculate(arch string, threadsPerBlock, dynamicSmemBytes int) (OccupancyReport, error)

Calculate determines theoretical occupancy on the named GPU architecture.

Example (TensorMemory)
package main

import (
	"fmt"
	"log"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	// A tcgen05 GEMM that allocates 256 TMEM columns per CTA fits two CTAs
	// on an SM of 512 columns, whatever its registers allow.
	kernel := sass.KernelResource{Name: "umma_gemm", Registers: 64, TMEMColumns: 256}
	report, err := kernel.Calculate("sm_103a", 128, 0)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(report)
}
Output:
sm_103: 8/64 warps (12.5%, 2 blocks/SM) limited by tensor_memory

func (KernelResource) CalculateDevice

func (k KernelResource) CalculateDevice(dev DeviceProperties, threadsPerBlock, dynamicSmemBytes int) OccupancyReport

CalculateDevice determines theoretical occupancy on a specific device specification. Its SM90 register bound accounts for four register sub-partitions. This static model does not establish runtime placement, dynamic register redistribution, or achieved occupancy.

func (KernelResource) Evidence

func (k KernelResource) Evidence(arch string, threadsPerBlock, dynamicSmemBytes int) (Evidence, error)

Evidence computes the theoretical occupancy report for the named architecture and returns Evidence combining the compiled resource usage and occupancy.

Example
package main

import (
	"fmt"
	"log"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	kernel := sass.KernelResource{
		Name:            "gemv_q8",
		Registers:       48,
		StaticSharedMem: 2048,
		StackFrameBytes: 0,
	}

	ev, err := kernel.Evidence("sm_121", 256, 1024)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s: %d regs, %d bytes local, %d warps/SM\n",
		ev.Kernel, ev.Registers, ev.LocalMemory, ev.Occupancy.TheoreticalWarps)
}
Output:
gemv_q8: 48 regs, 0 bytes local, 40 warps/SM

func (KernelResource) EvidenceDevice

func (k KernelResource) EvidenceDevice(dev DeviceProperties, threadsPerBlock, dynamicSmemBytes int) Evidence

EvidenceDevice computes the theoretical occupancy report for a specific device and returns Evidence.

func (KernelResource) OccupancyEvidence

func (k KernelResource) OccupancyEvidence(source EvidenceSource, threads, dynamicShared int, resourcesKnown bool) (EvidenceRecord, error)

OccupancyEvidence derives a theoretical occupancy ceiling from compiled resources and launch geometry. ResourcesKnown must describe all required resource metadata; absent metadata is not an observed zero allocation.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	digest := strings.Repeat("1", 64)
	source := sass.EvidenceSource{
		Identity: sass.EvidenceIdentity{ArtifactDigest: digest, Entry: "kernel", Target: "sm_90", CompilerKey: digest, WorkloadKey: digest},
		Producer: "compiled fixture", Locator: "kernel record",
	}
	k := sass.KernelResource{Name: "kernel", Registers: 32}
	rec, err := k.OccupancyEvidence(source, 128, 0, true)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(rec.Available, rec.Unit)
}
Output:
true ratio

type KernelResourceInfo

type KernelResourceInfo struct {
	Name               string             // Kernel symbol or function name
	RegisterAllocation RegisterAllocation // Whether the register attribute was present
	Registers          int                // 32-bit registers allocated per thread (EIATTR_REGCOUNT)
	RegCount           int                // Alias for Registers
	SharedMemBytes     int                // Static shared memory in bytes (EIATTR_SHARED_SIZE_SYSMEM or .nv.shared)
	FrameSizeBytes     int                // Per-thread stack frame size in bytes (EIATTR_FRAME_SIZE)
	FrameSize          int                // Alias for FrameSizeBytes
	MaxRegCount        int                // Compiler register ceiling (EIATTR_MAXREG_COUNT)
	ReqNTID            [3]int             // Required CTA dimensions [x, y, z] (EIATTR_REQ_NTID)
	ConstantBankSize   int                // Constant bank 0 parameter size in bytes (EIATTR_PARAM_CBANK)
}

KernelResourceInfo represents static resource usage for a CUDA kernel parsed from a compiled CUBIN ELF image. Rows may include device helpers; they do not by themselves prove CUDA entry callability.

func ReadKernelInfo

func ReadKernelInfo(r io.ReaderAt) ([]KernelResourceInfo, error)

ReadKernelInfo parses a CUBIN ELF image from an io.ReaderAt and extracts resource rows discovered from ELF functions and CUDA sections. Check RegisterAllocation before interpreting a numeric zero; names alone do not establish CUDA entry callability.

func ReadKernelInfoBytes

func ReadKernelInfoBytes(cubin []byte) ([]KernelResourceInfo, error)

ReadKernelInfoBytes parses a CUBIN ELF image from a byte slice.

func (KernelResourceInfo) Calculate

func (k KernelResourceInfo) Calculate(arch string, threadsPerBlock int) (OccupancyResult, error)

Calculate determines theoretical occupancy for this kernel on the named GPU architecture.

type Kind

type Kind int

A Kind classifies a divergence between what the PTX asked for and what the SASS delivered.

const (
	// Erased is a PTX opcode with no SASS instruction it lowers to.
	Erased Kind = iota + 1
	// Unsourced is a SASS opcode that ptxas emits only for a PTX opcode the
	// kernel never used.
	Unsourced
	// Spill is an unsourced local memory access: the register allocator's, not
	// the kernel's.
	Spill
	// Padding is a kernel whose interior NOP fraction exceeds the reporting
	// threshold.
	Padding
	// MissingSASS is a PTX kernel with no function in the disassembly.
	MissingSASS
	// MissingPTX is a disassembled function with no kernel in the PTX.
	MissingPTX
	// WidthCollapse is a vector operation lowered to equivalent scalar traffic.
	WidthCollapse
	// SharedConversion is a shared-space address conversion present in a kernel
	// or slot that was expected to have direct shared access.
	SharedConversion
)

func (Kind) String

func (k Kind) String() string

type Latencies

type Latencies struct {
	// Result is the number of cycles after issue before a non-branch
	// instruction may read the result.
	Result map[string]uint8
	// Branch is the number of cycles after issue before a branch may read
	// the result, typically a predicate. An opcode absent here uses Result.
	Branch map[string]uint8
	// Pair overrides Result for one {producer, reader} pair of base
	// opcodes.
	Pair map[[2]string]uint8
}

Latencies gives the result latency of fixed-latency instructions, by base opcode (see BaseOpcode).

func MeasuredLatencies

func MeasuredLatencies(sm string) (Latencies, error)

MeasuredLatencies returns the hardware-measured Latencies table for target sm. Only GB10 ("sm_121" / "sm_121a") has silicon measurements today; other known SM architectures wrap cuda.ErrHardwarePending, and unknown target strings wrap cuda.ErrUnsupported.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/tmc/lib/nvidia/x/cuda"
	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	lat, err := sass.MeasuredLatencies("sm_121a")
	if err != nil {
		panic(err)
	}
	_, err90 := sass.MeasuredLatencies("sm_90a")
	fmt.Printf("LDG=%d sm_90a_pending=%v\n", lat.Result["LDG"], errors.Is(err90, cuda.ErrHardwarePending))
}
Output:
LDG=37 sm_90a_pending=true

func ObservedLatencies

func ObservedLatencies() Latencies

ObservedLatencies returns, for each fixed-latency producer seen with a reader in the same basic block of this package's sm_121a fixtures (ptxas 13.3 and 13.4; testdata/*.sass and testdata/roundtrip), the smallest producer-to-reader separation ptxas emitted.

These are not hardware measurements. A separation ptxas emitted is an upper bound on the true latency if ptxas was right, so using it keeps an optimized schedule no tighter than one ptxas itself produced for that producer. The bound is weaker for a reader class not seen with that producer; where one pair was seen tighter than the rest (IMAD feeding IMAD), it is a Pair entry and the producer's Result is the larger value seen with every other reader.

func SM121aLatencies

func SM121aLatencies() Latencies

SM121aLatencies returns the Latencies table populated from MeasuredSM121aLatencyRecords.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	lat := sass.SM121aLatencies()
	fmt.Printf("FFMA=%d MUFU=%d\n", lat.Result["FFMA"], lat.Result["MUFU"])
}
Output:
FFMA=4 MUFU=18

type Launch

type Launch struct {
	Threads       int    // threads per block
	DynamicShared int    // dynamic shared memory bytes per block
	Source        string // where the configuration was read, such as "occupancy_config"
}

A Launch is the launch configuration of the kernel.

type Legality

type Legality struct {
	Legal     bool
	Undecided bool
	Reasons   []string
}

A Legality is the verdict on one proposed reordering.

Legal is true only if every check ran and passed. A check that could not be decided sets Undecided and leaves Legal false: a reordering this model cannot reason about is refused, never permitted by default.

func CanSwap

func CanSwap(b BasicBlock, i, j int, arch Arch, policy NumericalPolicy) Legality

CanSwap reports whether the instructions at positions i and j of b, which must be adjacent, may exchange places.

Legality is decided statically, on host, with no device. A true verdict is a claim about data dependencies, memory ordering and control codes only; it is not a claim that the resulting sequence is faster, and not a claim that it loads, which is what the step 4 feasibility gate decides.

func (Legality) String

func (l Legality) String() string

type LiveSet

type LiveSet map[Register]bool

A LiveSet is a set of registers live at one point.

func Liveness

func Liveness(b BasicBlock, liveOut LiveSet, arch Arch) ([]LiveSet, error)

Liveness returns the set of registers live immediately after each instruction of b, given the registers live on exit from the block.

This is a within-block backward pass: liveOut is the caller's claim about what the block's successors read, and Liveness does not compute it. A caller that passes nil is asserting the block's successors read nothing, which is true only for a block ending in EXIT.

A write kills a register only if the instruction always executes: it is unguarded or guarded by @PT or @UPT. Any other guard makes the write a may-def. On the path where the guard is false the old value survives, so a register live after a guarded write is still live before it. This includes @!PT and @!UPT, which never execute and so write nothing, and a guard this package cannot parse, which is never taken to be unconditional. The registers an instruction reads, including its guard, are live before it whatever its guard, which over-approximates liveness for an instruction that never executes.

It reports an error for the same reason Dependencies does: an unclassified opcode makes every set after it wrong, and a liveness set that is quietly wrong is worse than none, because it is what a reordering is checked against.

Example (Predicated)

A guarded write may not happen, so the value it would overwrite stays live before it.

package main

import (
	"fmt"
	"log"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	b := sass.BasicBlock{Instructions: []sass.Instruction{
		{Address: 0x0, Opcode: "NOP"},
		{Address: 0x10, Predicate: "@P0", Opcode: "IADD", Operands: "R4, R2, UR6"},
	}}
	r4 := sass.Register{Class: sass.GPR, Num: 4}
	live, err := sass.Liveness(b, sass.LiveSet{r4: true}, sass.SM121a)
	if err != nil {
		log.Fatal(err)
	}
	for i, s := range live {
		fmt.Printf("after %d: %v\n", i, s.Registers())
	}
}
Output:
after 0: [R2 R4 P0 UR6]
after 1: [R4]

func (LiveSet) Contains

func (s LiveSet) Contains(r Register) bool

Contains reports whether r is in the set.

func (LiveSet) Registers

func (s LiveSet) Registers() []Register

Registers returns the set's members sorted by class then number, so that output is stable.

type Loop

type Loop struct {
	Header int   // index into CFG.Blocks
	Blocks []int // the loop's blocks, header included, sorted
}

A Loop is a natural loop of a CFG: a header block and the blocks that reach a back edge into it without passing through it. A back edge is an edge whose target dominates its source, so code that ptxas places after the function's exit and branches back from is not a loop unless it is part of a cycle through its target.

type Lowering

type Lowering struct {
	// PTX is the PTX opcode prefix the kernel asked for.
	PTX string

	// SASS lists the opcode prefixes ptxas may emit for PTX. The lowering is
	// satisfied if any of them occurs.
	SASS []string

	// Exclusive reports that ptxas emits these SASS opcodes only for this PTX
	// opcode. Finding them in a kernel whose PTX does not use PTX is then a
	// divergence. It is false for opcodes ptxas also emits on its own account:
	// IMAD for address arithmetic, DFMA for a contracted mul.f64 and add.f64.
	Exclusive bool

	// Spill reports that the SASS opcodes are local memory traffic, so that an
	// unsourced occurrence is a register spill ptxas introduced rather than an
	// access the kernel wrote. Only meaningful with Exclusive.
	Spill bool

	// VectorWidth is the number of scalar accesses PTX stands for: 4 for
	// ld.global.v4, 2 for ld.global.v2. It only labels the report.
	VectorWidth int

	// ScalarSASS lists the scalar SASS forms ptxas would emit if it declined
	// to keep the vector form. Unlike SASS these are matched exactly rather
	// than by prefix, because the scalar spelling is a prefix of the vector
	// one: nvdisasm writes a 32-bit load as "LDG.E" and a 128-bit load as
	// "LDG.E.128", so a prefix match on the scalar form counts the vector
	// loads this field exists to find the absence of.
	ScalarSASS []string
}

A Lowering records the SASS opcodes ptxas emits for a PTX opcode.

PTX and SASS prefixes are matched by cudaptx.OpcodeSummary.Count and cudasass.OpcodeSummary.Count respectively, so a prefix names whole opcode fields: "ld.global" covers "ld.global.nc.f32" and "LDG" covers "LDG.E.CONSTANT.F32".

type LoweringOptions

type LoweringOptions struct {
	// Lowerings is the PTX to SASS opcode table. Nil means [DefaultLowerings].
	Lowerings []Lowering

	// MaxNOPFraction is the interior NOP fraction of a kernel above which
	// [Padding] is reported. Zero means [DefaultMaxNOPFraction]; a negative
	// value disables the check.
	MaxNOPFraction float64

	// InferredSharedSlots lists slot or kernel names whose SASS must not contain
	// shared-space address conversions. Labels do not prove slot attribution.
	InferredSharedSlots []string

	// CheckSharedConversions, when true, verifies that no shared-space address
	// conversions (cvta.shared in PTX, or conversion instructions in SASS) exist.
	CheckSharedConversions bool
}

LoweringOptions configures [Compare]. The zero LoweringOptions is usable.

type LoweringReport

type LoweringReport struct {
	Stats       []Stats
	Slots       []SlotEvidence // checked per-slot coverage; nil for aggregate comparisons
	Divergences []Divergence
}

A LoweringReport is the result of comparing a PTX module with its SASS.

func CompareLowering

func CompareLowering(m *isaptx.Module, d *Disassembly, opts *LoweringOptions) (*LoweringReport, error)

Compare pairs the kernels of m with the functions of d and reports where the lowering diverged from the PTX. The error is non-nil only for unusable input; divergences are in the report, and LoweringReport.Err turns them into one error.

Example

Two kernels call atomicAdd on the same address with the same arguments, and compile to the same atom.global.add.f32 in PTX. One of them reads the value the atomic returns; the other throws it away, and ptxas substitutes a reduction. Nothing in the PTX says which kernel got which.

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/tmc/lib/nvidia/x/isa/ptx"
	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func parse(ptxFile, sassFile string) (*ptx.Module, *sass.Disassembly) {
	pf, err := os.Open(ptxFile)
	if err != nil {
		log.Fatal(err)
	}
	defer pf.Close()
	m, err := ptx.Parse(pf)
	if err != nil {
		log.Fatal(err)
	}
	sf, err := os.Open(sassFile)
	if err != nil {
		log.Fatal(err)
	}
	defer sf.Close()
	d, err := sass.Parse(sf)
	if err != nil {
		log.Fatal(err)
	}
	return m, d
}

func main() {
	m, d := parse("testdata/lowering.sm90.ptx", "testdata/lowering.sm90.sass")

	r, err := sass.CompareLowering(m, d, nil)
	if err != nil {
		log.Fatal(err)
	}
	for _, div := range r.Divergences {
		fmt.Println(div)
	}
}
Output:
_Z10atomicDropPfPKfi: erased: 1 atom.global, no ATOMG

func VerifyCompiledSharedConversions

func VerifyCompiledSharedConversions(result *nvvm.Result, sass []byte) (*LoweringReport, error)

VerifyCompiledSharedConversions uses the actual CompileWithOptions-retained input origins and checks its copied PTX digest. The first supported contract requires exactly one inferred input. SASS remains caller-paired text; native artifact association and debug-location qualification require a real receipt.

Example
_, err := VerifyCompiledSharedConversions(&nvvm.Result{}, []byte("not compiled SASS"))
fmt.Println(err != nil)
Output:
true

func VerifyInferredSharedConversions

func VerifyInferredSharedConversions(ir []byte, inference *nvvm.InferenceReport, ptx, sass []byte) (*LoweringReport, error)

VerifyInferredSharedConversions derives slot attribution from actual inference origins and observed compiler locations in caller-paired PTX/SASS text. It validates original IR identity but does not attest that a compiler emitted the supplied texts. Missing, ambiguous, elided or unsupported coverage returns an error and a partial report. The legacy verifier remains kernel-aggregate.

Example
_, inference, _ := nvvm.InferAddressSpaces([]byte(slotIR))
report, err := VerifyInferredSharedConversions([]byte(slotIR), inference, []byte(slotPTX), []byte(slotSASS(slotPTX)))
fmt.Println(err, report.Slots[0].Verified, report.Divergences[0].Slot)
Output:
<nil> true @kernel/%b

func VerifyNoSharedConversions

func VerifyNoSharedConversions(m *isaptx.Module, d *Disassembly, slots ...string) (*LoweringReport, error)

VerifyNoSharedConversions checks matched kernels for PTX shared conversions and the bounded observed SM121 SASS conversion mechanism. Unsupported SASS returns an error and a partial report; it cannot establish conversion absence. Slots are descriptive caller labels, not evidence of per-slot attribution. This textual check does not attest a machine-code encoding or other targets.

Example
package main

import (
	"fmt"
	"log"
	"strings"

	"github.com/tmc/lib/nvidia/x/isa/ptx"
	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	m, err := ptx.Parse(strings.NewReader(".version 8.0\n.target sm_121\n.address_size 64\n.entry kernel() { ret; }\n"))
	if err != nil {
		log.Fatal(err)
	}
	d, err := sass.Parse(strings.NewReader("code for sm_121\nFunction : kernel\n/*0000*/ LDS R1, [R0];\n/*0010*/ EXIT;\n"))
	if err != nil {
		log.Fatal(err)
	}
	r, err := sass.VerifyNoSharedConversions(m, d, "%sharedSlot")
	if err != nil {
		log.Fatal(err)
	}
	// This supported direct-access fragment contains no recognized conversion.
	hasSharedConv := false
	for _, div := range r.Divergences {
		if div.Kind == sass.SharedConversion {
			hasSharedConv = true
		}
	}
	fmt.Println("shared conversions found:", hasSharedConv)
}
Output:
shared conversions found: false

func (*LoweringReport) Err

func (r *LoweringReport) Err() error

Err returns an error naming every divergence, or nil if there are none.

Example

A report turns into one error, for use as a gate.

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/tmc/lib/nvidia/x/isa/ptx"
	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func parse(ptxFile, sassFile string) (*ptx.Module, *sass.Disassembly) {
	pf, err := os.Open(ptxFile)
	if err != nil {
		log.Fatal(err)
	}
	defer pf.Close()
	m, err := ptx.Parse(pf)
	if err != nil {
		log.Fatal(err)
	}
	sf, err := os.Open(sassFile)
	if err != nil {
		log.Fatal(err)
	}
	defer sf.Close()
	d, err := sass.Parse(sf)
	if err != nil {
		log.Fatal(err)
	}
	return m, d
}

func main() {
	m, d := parse("testdata/lowering.sm90.ptx", "testdata/lowering.sm90.rr24.sass")

	r, err := sass.CompareLowering(m, d, &sass.LoweringOptions{
		Lowerings: []sass.Lowering{
			{PTX: "st.local", SASS: []string{"STL"}, Exclusive: true, Spill: true},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(r.Err())
}
Output:
cudalowering: _Z7spillerPfPKfi: spill: 5 STL, no st.local

func (*LoweringReport) String

func (r *LoweringReport) String() string

type Matching

type Matching struct {
	Pairs         []Pair
	UnmatchedPTX  []*ptx.Kernel
	UnmatchedSASS []*Function
}

A Matching is the result of pairing a PTX module with a disassembly. A kernel that appears at one level only is listed as unmatched rather than dropped: a comparison that quietly pairs nothing cannot report a divergence.

func Match

func Match(m *ptx.Module, d *Disassembly) *Matching

Match pairs the kernels of m with the functions of d.

Only .entry kernels with a body are considered. A .func device function is usually inlined into its callers and has no SASS function of its own, so pairing it would report an absence that means nothing.

Names are matched first as written, then through MatchKey. A key that names more than one kernel on either side is not used, so two kernels are never paired on an ambiguous name.

type MathFingerprint

type MathFingerprint struct {
	SHFLTotal      int            `json:"shfl_total"`
	SHFLModes      map[string]int `json:"shfl_modes,omitempty"`
	DivRNCount     int            `json:"div_rn_count"`
	RecipFMACount  int            `json:"recip_fma_count"`
	RsqrtApprox    int            `json:"rsqrt_approx"`
	FMULCount      int            `json:"fmul_count"`
	FFMACount      int            `json:"ffma_count"`
	ContractionPct float64        `json:"contraction_pct"`
	Source         string         `json:"source"`
}

MathFingerprint records static precision-related instructions in one kernel. ContractionPct is the share of multiply and fused multiply-add instructions that are fused. It does not establish which expressions the compiler fused.

func FingerprintMath

func FingerprintMath(f *Function, p *ptx.Kernel) MathFingerprint

FingerprintMath counts math instructions in f, falling back to p when SASS is unavailable. Where p is available, it also identifies explicit div.rn. SASS reciprocal/FMA sequences alone do not identify a rounding mode.

type MeasuredLatencyRecord

type MeasuredLatencyRecord struct {
	Opcode          string
	Reader          string  // "" for general result latency, or specific consumer base opcode
	MedianCycles    float64 // dependent-chain (2N - N)/N median cycles
	MinCycles       float64
	MaxCycles       float64
	HotColdCycles   float64 // binary-patched hot minus cold NOP median cycles per instruction
	IssueCycles     float64 // independent-chain issue cycles per instruction
	SchedulerCycles uint8   // integer stall bound for VerifyHazardSafety and RecomputeSwap
	Label           string  // "MEASURED"
	Device          string
	Driver          string
	Toolkit         string
	GPULockLease    string
}

A MeasuredLatencyRecord records one hardware latency and throughput measurement on NVIDIA GB10 (sm_121a).

func MeasuredSM121aLatencyRecords

func MeasuredSM121aLatencyRecords() []MeasuredLatencyRecord

MeasuredSM121aLatencyRecords returns a copy of the GB10 hardware latency measurements.

type MemoryCeiling

type MemoryCeiling struct {
	GBps   float64
	Source string
}

A MemoryCeiling is a device-memory bandwidth measured on the device the kernel ran on.

type MissingWaitError

type MissingWaitError struct {
	Function string
	Copy     uint64 // address of the copy
	Use      uint64 // address of the shared read
}

A MissingWaitError reports a shared memory read that an asynchronous copy reaches on some path with no wait for it in between, where the read touches bytes the copy writes. Extraction fails: the kernel has a race, not a contract.

func (*MissingWaitError) Error

func (e *MissingWaitError) Error() string

type Mnemonics

type Mnemonics struct {
	Arch    Arch
	Toolkit string // the CUDA toolkit whose ptxas the control was compiled with
	Wait    string // griddepcontrol.wait
	Trigger string // griddepcontrol.launch_dependents
	NCLoad  string // ld.global.nc, a non-coherent global load
}

Mnemonics are the SASS spellings ptxas uses on one architecture for the instructions a programmatic dependent launch is checked by. They differ by architecture: ptxas 13.5 spells griddepcontrol.wait ACQBULK on sm_121a, so a check that looks for GRIDDEPCONTROL there matches nothing and cannot fail.

Each spelling is a base opcode, or an opcode followed by the modifiers it must carry, such as "LDG.E.CONSTANT". An instruction matches a spelling when its opcode is the spelling or the spelling followed by more modifiers.

MnemonicsFor returns spellings that a compiled control kernel showed. A Mnemonics built by hand has had no such check.

func MnemonicsFor

func MnemonicsFor(arch Arch) (Mnemonics, error)

MnemonicsFor returns the spellings ptxas uses on arch. It returns an error if no control kernel compiled for arch has been recorded.

type Mode

type Mode int

Mode selects one mutually exclusive nvdisasm output form.

const (
	Text Mode = iota
	JSON
	ControlFlow
	BasicBlockFlow
	RegisterLife
)

type Mutation

type Mutation struct {
	Index       int         // index into the function's instruction slice
	Replacement Instruction // the instruction to put there
}

A Mutation proposes replacing one instruction of a function.

Replacement carries text only: opcode, predicate and operands. Its Encoding field is ignored, because the replacement's schedule is not the caller's to choose -- CheckMutation takes the control code from the instruction being replaced, which is the whole reason the mutation class is restricted to those that leave the schedule correct.

type MutationPlan

type MutationPlan struct {
	Function string
	Index    int
	Address  uint64
	FormFrom string
	FormTo   string
	Before   Encoding
	After    Encoding
	Control  ControlCode // carried unchanged from Before, or the new code in a plan from [OptimizeFunctionControl]
}

A MutationPlan is a mutation that passed every patch-time gate. It is the only thing CubinImage.Apply accepts.

func CheckMutation

func CheckMutation(fn *Function, arch Arch, m Mutation, liveOut LiveSet) (MutationPlan, error)

CheckMutation decides whether m may be applied to fn, and returns the plan if it may.

liveOut is the caller's claim about which registers the containing basic block's successors read. It is required: a mutation is checked against liveness, and a liveness set that was guessed is worse than none. nil is accepted only for a block that ends in EXIT, where it is the true answer.

The gates, in order, each fail closed:

  • both the original and the replacement are of a covered form;
  • the original re-encodes byte-identically, so its bits are understood;
  • the replacement's encoding carries the original's control code exactly;
  • the basic block's RAW, WAR, WAW, memory, fence and barrier edges are unchanged by the substitution;
  • no register the replacement newly defines is live at that point, and no register it stops defining is live at that point. A register rename can change an edge, and a rename onto a register that aliases something live changes the program without changing any edge inside the block, which is the case this check and not the edge comparison catches.

type NativeSource

type NativeSource struct{}

NativeSource decodes CUBINs in pure Go using DecodeCUBIN.

func (NativeSource) DisassembleCUBIN

func (NativeSource) DisassembleCUBIN(cubin []byte) (*Disassembly, error)

DisassembleCUBIN decodes cubin natively without invoking nvdisasm.

type NumericalPolicy

type NumericalPolicy struct {
	// AllowFloatReassociation permits swapping instructions that accumulate
	// in floating point. It must come from the kernel's declared policy, not
	// from an observation that the result happened to match.
	AllowFloatReassociation bool
}

A NumericalPolicy states whether floating-point accumulation order may be changed for the kernel under analysis.

Reordering is not semantics-preserving in general. The default zero value forbids it, because a kernel that has not declared a policy has not permitted the change.

type NvdisasmSource

type NvdisasmSource struct {
	Disassembler Disassembler
}

NvdisasmSource disassembles CUBINs by running nvdisasm with hex encodings.

func (NvdisasmSource) DisassembleCUBIN

func (s NvdisasmSource) DisassembleCUBIN(cubin []byte) (*Disassembly, error)

DisassembleCUBIN invokes nvdisasm with Options.PrintCode and Options.PrintHex and parses its output.

func (NvdisasmSource) DisassembleFunction

func (s NvdisasmSource) DisassembleFunction(cubin []byte, name string) (*Disassembly, error)

DisassembleFunction is NvdisasmSource.DisassembleCUBIN restricted to the function name: nvdisasm lists only the section of its function symbol (CubinImage.FunctionIndex). The listing of one function is the same whether or not the others are listed, and its size does not grow with them.

type OccupancyDelta

type OccupancyDelta struct {
	Before          OccupancyEstimate
	After           OccupancyEstimate
	ThreadsPerBlock int
	SharedMemBytes  int
	DeltaWarps      int     // After.TheoreticalWarps - Before.TheoreticalWarps
	DeltaBlocks     int     // After.ActiveBlocks - Before.ActiveBlocks
	DeltaOccupancy  float64 // After.Occupancy - Before.Occupancy
}

OccupancyDelta compares SM theoretical occupancy before and after bumping AttrRegCount.

func EstimateOccupancyDelta

func EstimateOccupancyDelta(arch Arch, oldRegCount, newRegCount, threadsPerBlock, sharedMemBytes int) (OccupancyDelta, error)

EstimateOccupancyDelta computes the theoretical SM occupancy before and after bumping AttrRegCount from oldRegCount to newRegCount on arch. If threadsPerBlock <= 0, it defaults to 256 threads per block.

type OccupancyEstimate

type OccupancyEstimate struct {
	RegCount         int     // Registers per thread
	ActiveBlocks     int     // Resident thread blocks per SM
	TheoreticalWarps int     // Resident warps per SM
	MaxWarps         int     // Architecture maximum warps per SM
	Occupancy        float64 // TheoreticalWarps / MaxWarps
}

OccupancyEstimate describes SM theoretical occupancy for one register count.

type OccupancyReport

type OccupancyReport struct {
	Available         bool    // Numeric fields are usable only when true
	UnavailableReason string  // Why compiled metadata prevents a calculation
	Architecture      string  // Target GPU architecture (e.g. "sm_90", "sm_121")
	TheoreticalWarps  int     // Theoretical active warps per SM
	MaxWarps          int     // Architecture maximum warps per SM
	Occupancy         float64 // Theoretical occupancy ratio [0.0, 1.0]
	ActiveBlocks      int     // Resident thread blocks (CTAs) per SM
	LimitingFactor    string  // Primary bottleneck: one of the Limit constants
	BlockLimit        int     // Ceiling imposed by max blocks per SM
	WarpLimit         int     // Ceiling imposed by max warps per SM
	RegLimit          int     // Ceiling imposed by register file capacity
	SmemLimit         int     // Ceiling imposed by shared memory capacity
	TMEMLimit         int     // Ceiling imposed by Tensor Memory columns
}

OccupancyReport records theoretical occupancy and hardware bottleneck analysis for a kernel configuration.

func (OccupancyReport) String

func (r OccupancyReport) String() string

String returns a concise human-readable summary of the occupancy report.

type OccupancyResult

type OccupancyResult struct {
	Architecture     string  // Architecture code (e.g. "sm_90", "sm_121")
	Arch             string  // Architecture alias
	TheoreticalWarps int     // Theoretical active warps per SM
	ActiveWarps      int     // Theoretical active warps per SM (alias)
	MaxWarps         int     // Architecture maximum warps per SM
	Occupancy        float64 // Theoretical occupancy ratio [0.0, 1.0]
	ActiveBlocks     int     // Resident thread blocks (CTAs) per SM
	LimitingFactor   string  // Primary bottleneck: "registers", "shared_memory", "block_size", "blocks", "none"
	BlockLimit       int     // Ceiling imposed by max blocks per SM
	WarpLimit        int     // Ceiling imposed by max warps per SM
	RegLimit         int     // Ceiling imposed by register file capacity
	SmemLimit        int     // Ceiling imposed by shared memory capacity
}

OccupancyResult describes the theoretical SM occupancy for a kernel configuration.

func CalculateOccupancy

func CalculateOccupancy(arch string, regCount, sharedMemBytes, threadsPerBlock int) (OccupancyResult, error)

CalculateOccupancy computes theoretical active warps and thread blocks per SM on the given GPU architecture based on register, shared memory, and block size constraints.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	res, err := sass.CalculateOccupancy("sm_90", 40, 0, 256)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s: %d/%d warps (%.0f%%) limited by %s\n",
		res.Architecture, res.TheoreticalWarps, res.MaxWarps, res.Occupancy*100, res.LimitingFactor)
}
Output:
sm_90: 48/64 warps (75%) limited by registers

func (OccupancyResult) String

func (r OccupancyResult) String() string

String returns a concise human-readable summary of the occupancy result.

type OpTableClaim

type OpTableClaim struct {
	Opcode         string
	Pipe           string // e.g. "fma_pipe", "lsu_pipe", "alu_pipe"
	ScoreboardType string // e.g. "fixed", "variable-barrier"
	MinWaitNeeded  int    // claimed minimum wait cycles (0 if variable/unknown)
}

OpTableClaim holds descriptor-table scheduling claims for one base opcode, supplied by the caller (for example from an external descriptor parser). This package embeds no vendor descriptor text.

type OpTableComparison

type OpTableComparison struct {
	Opcode               string
	Pipe                 string
	ScoreboardType       string
	TableMinWait         int
	ObservedPtxasLatency int // from ObservedLatencies(); 0 if absent
	HasObservedLatency   bool
	ObservedMinStall     int // min stall field seen in fn (-1 if unseen)
	ObservedMaxStall     int // max stall field seen in fn (-1 if unseen)
	ObservedBarriers     int // count of instructions arming wr/rd barrier in fn
	SiliconStatus        string
	SiliconErr           error
	Mismatch             string
}

OpTableComparison compares a descriptor-table claim for one opcode against what cudasass observed in its calibrated sm_121a tables and a disassembled function. Silicon measurements are not performed on the host.

func CompareOpTables

func CompareOpTables(fn *Function, arch Arch, claims []OpTableClaim) ([]OpTableComparison, error)

CompareOpTables dumps descriptor-table claims alongside cudasass's observed ptxas latencies and control-field observations from fn (when non-nil).

This is the host-only half of table-vs-silicon comparison: SiliconStatus is always "unmeasured (host-only)" and SiliconErr wraps cudaerrors.ErrHardwarePending.

Example
package main

import (
	"fmt"

	cudasass "github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	enc := func(ctrl cudasass.ControlCode) cudasass.Encoding {
		e, err := cudasass.EncodeControl(cudasass.Encoding{Lo: 0x7982}, ctrl, cudasass.SM121a)
		if err != nil {
			panic(err)
		}
		return e
	}

	fn := &cudasass.Function{
		Name: "sample",
		Instructions: []cudasass.Instruction{
			{Address: 0x0000, Opcode: "FFMA", Operands: "R8, R4, R6, R8", Encoding: enc(cudasass.ControlCode{Stall: 5, Yield: true, WriteBarrier: cudasass.NoBarrier, ReadBarrier: cudasass.NoBarrier})},
			{Address: 0x0010, Opcode: "LDG.E.32", Operands: "R4, [R2.64]", Encoding: enc(cudasass.ControlCode{Stall: 2, Yield: true, WriteBarrier: 2, ReadBarrier: cudasass.NoBarrier})},
		},
	}

	claims := []cudasass.OpTableClaim{
		{Opcode: "FFMA", Pipe: "fma_pipe", ScoreboardType: "fixed", MinWaitNeeded: 5},
		{Opcode: "LDG", Pipe: "lsu_pipe", ScoreboardType: "variable-barrier", MinWaitNeeded: 0},
	}

	rows, err := cudasass.CompareOpTables(fn, cudasass.SM121a, claims)
	if err != nil {
		panic(err)
	}
	for _, r := range rows {
		fmt.Println(r)
	}
}
Output:
FFMA     pipe=fma_pipe   sb=fixed            table_min_wait=5  ptxas_obs=5   sass_obs=5..5 (barriers=0)    silicon=unmeasured (host-only)
LDG      pipe=lsu_pipe   sb=variable-barrier table_min_wait=0  ptxas_obs=n/a sass_obs=2..2 (barriers=1)    silicon=unmeasured (host-only)

func (OpTableComparison) String

func (c OpTableComparison) String() string

type OpcodeClass

type OpcodeClass struct {
	Defs       int  // destination operands, after any leading predicate destinations
	Loads      bool // reads memory
	Stores     bool // writes memory
	Fence      bool // orders memory operations around it
	Branch     bool // transfers control
	Indirect   bool // branch target comes from a register; see [CFG.IsDegenerate]
	FloatAccum bool // accumulates in floating point; see [Legality]
	// contains filtered or unexported fields
}

An OpcodeClass records how one opcode's operands map to definitions and uses, and which reordering rules apply to it.

The table is deliberately small. A def/use model guessed from an opcode's spelling is the failure this lane exists to avoid: an opcode absent from the table is reported as unclassified, and every analysis below refuses to decide rather than assuming the common case.

func Classify

func Classify(opcode string) (OpcodeClass, bool)

Classify returns the class of an opcode, and false if it is not in the covered subset. Callers must not substitute a default for false.

type OpcodeSubstitution

type OpcodeSubstitution struct {
	From      string
	To        string
	Count     int
	FromCount int
	ToCount   int
}

OpcodeSubstitution records a substitution between instruction opcodes (e.g. IMAD -> IDP4A).

type OpcodeSummary

type OpcodeSummary struct {
	Total      int
	Counts     map[string]int
	Predicated int
}

OpcodeSummary records instruction counts and mnemonics for a kernel.

func (*OpcodeSummary) Count

func (s *OpcodeSummary) Count(prefix string) int

Count returns the number of instructions whose opcode matches the prefix. Matching is case-insensitive. For example, Count("IDP4A") matches "IDP4A", "IDP4A.U8.U8", "idp4a.s8.s8", and the Blackwell sm_12x variant "IDP.4A.S8.S8".

type OperandRole

type OperandRole uint8

OperandRole classifies how a decoded instruction uses one operand slot.

const (
	OperandOther      OperandRole = iota
	OperandDef                    // register or predicate written by the instruction
	OperandUse                    // register or predicate read by the instruction
	OperandAddress                // bracketed memory address ([R2.64+0x10], desc[UR4][R2.64], tmem[UR6])
	OperandCBank                  // constant-bank operand (c[0x0][0x380])
	OperandImmediate              // integer, bitset, or floating-point immediate
	OperandTarget                 // PC-relative branch or call target
	OperandBarrier                // convergence barrier or scoreboard token (B0, SB0)
	OperandSpecialReg             // special register (SR_TID.X, SR_GLOBALTIMERLO, ...)
)

func (OperandRole) String

func (r OperandRole) String() string

type Options

type Options struct {
	Mode                       Mode
	LifeRangeMode              string // "count", "narrow", or "wide" for RegisterLife mode
	Functions                  []int  // symbol indices to disassemble; all functions when empty
	PrintCode                  bool
	PrintHex                   bool
	PrintRaw                   bool
	SeparateFunctions          bool
	SortSections               bool
	NoDataflow                 bool
	NoVLIW                     bool
	PrintInstructionOffsetsCFG bool
	SourceLines                bool
	InlineLines                bool
	PTXLines                   bool
}

Options selects disassembly output. Line annotations require Text mode and corresponding debug sections in the input; absent sections yield no annotations.

type Output

type Output = cudatool.Output

Output contains command identity and diagnostics, including on command failure.

type Pair

type Pair struct {
	PTX  *ptx.Kernel
	SASS *Function
}

A Pair binds a PTX kernel to the SASS function it lowered to.

type Param

type Param struct {
	Ordinal int // position in the kernel's signature
	Offset  int // byte offset in the parameter block
	Size    int // bytes
}

A Param is one kernel parameter as the cubin records it.

type ParamAccess

type ParamAccess struct {
	Offset      int // the parameter's byte offset in the parameter block
	Read, Write bool
	Accesses    int // instructions that reach it

	// Align is the alignment the accesses require of the parameter: a
	// w-byte access at constant offset c needs gcd(w, c), which every valid
	// base satisfies, and a w-byte access at a register offset needs w,
	// on the assumption that the compiler chose w for an aligned base.
	Align int

	// Extent is one past the highest byte reached when every access is at
	// a constant offset from the parameter, and -1 otherwise.
	Extent int64

	// MinAlign is the smallest alignment any one access requires.
	MinAlign int

	// Checked is nonzero when the kernel tests the parameter's low bits
	// at run time, masking with Checked-1 into a predicate, as a kernel
	// does that takes a vector path only for aligned pointers.
	Checked int
}

A ParamAccess is the global memory one parameter's value reaches.

func (ParamAccess) Required

func (p ParamAccess) Required() int

Required returns the alignment a launch must give the parameter. A kernel that checks the alignment at run time needs only what its narrowest access does: which accesses its check guards is not followed, so the requirement is the one every path meets.

type ParamLayout

type ParamLayout struct {
	Base   int     // bank offset of the parameter block
	Size   int     // bytes in the parameter block
	Params []Param // in ordinal order
}

A ParamLayout is where a kernel's parameters sit in constant bank 0. Parameter p is read from c[0x0][Base+p.Offset].

func (ParamLayout) Param

func (l ParamLayout) Param(off int) (Param, bool)

Param returns the parameter whose bytes include block offset off.

type PatchConfig

type PatchConfig struct {
	RingPtr uint64 // device pointer to ring buffer
	Mode    uint32 // 0 = off, 1 = entry_exit only, 2 = full
	Mask    uint32 // filter mask
}

PatchConfig specifies the initial or runtime values for __iket_flight_cfg.

func ParsePatchConfig

func ParsePatchConfig(b []byte) (PatchConfig, error)

ParsePatchConfig parses a 16-byte slice into a PatchConfig.

func ReadFlightConfig

func ReadFlightConfig(image []byte) (PatchConfig, error)

ReadFlightConfig reads the current __iket_flight_cfg from a patched cubin.

func (PatchConfig) Bytes

func (c PatchConfig) Bytes() []byte

Bytes serializes PatchConfig into a 16-byte little-endian byte slice.

type PatchedImage

type PatchedImage struct {
	Bytes            []byte
	Kernel           string
	Section          string
	Patches          []AppliedPatch
	UnpatchedMirrors []string // second copies of the text this path did not update
}

A PatchedImage is the output of the patch path.

Bytes is a complete CUBIN of exactly the input's length: the path overwrites instructions in place and moves nothing, so every section offset, alignment and program header in the original still describes the result.

func (PatchedImage) Loadable

func (p PatchedImage) Loadable() error

Loadable reports whether the image may be offered to a device.

It fails closed on the mirror: an image whose text has a second, unpatched copy is refused, because whether the device executes the copy this path wrote is exactly what a load does not answer.

type PredSpillPlan

type PredSpillPlan struct {
	Required     bool        // True when all needed predicates could not be satisfied from FreePreds
	ScratchPreds []Register  // Predicate registers borrowed by the cave
	SaveGPR      Register    // Scratch GPR above AttrRegCount holding saved PR bits
	Mask         uint8       // Bitmask of borrowed predicates (bit i for Pi)
	SpillInst    Instruction // P2R instruction saving PR into SaveGPR
	RestoreInst  Instruction // R2P instruction restoring PR from SaveGPR
}

PredSpillPlan describes how to spill and restore live predicate registers around a cave using P2R and R2P when fewer than NeedPreds predicates are free.

type PublishIssue

type PublishIssue struct {
	Address uint64
	Opcode  string
}

PublishIssue identifies a possible single-thread publication of preceding CTA writes. Whether the atomic is a publication is a kernel contract and cannot be determined from its opcode.

func CheckPublish

func CheckPublish(fn *Function, block [3]int) ([]PublishIssue, error)

CheckPublish finds leader atomics preceded by a global fence but missing the store, whole-CTA barrier, fence ordering. It follows forward branches with predicates determined by threadIdx.x. Calls, loops, and unknown predicates are outside its scope. A zero block shape checks the leader predicate against the architectural range of threadIdx.x without asserting that the launch had multiple threads.

func (PublishIssue) String

func (p PublishIssue) String() string

type RegionSASSAttribution

type RegionSASSAttribution struct {
	Region          string
	Invocations     int
	TotalDurNs      uint64
	TotalInsts      int
	TensorCoreInsts int // HMMA, IMMA, OMMA, UTMMA, QSPC
	GlobalMemInsts  int // LDG, STG, LDGSTS, UTMALDG
	SharedMemInsts  int // LDS, STS, LDSM
	LocalSpillInsts int // LDL, STL
	BarrierInsts    int // BAR, BSYNC, WARPSYNC, DEPBAR, MEMBAR
	DynamicSpillOps uint64
	BoundClass      string // "spill_bound", "barrier_heavy", "tensor_core", "memory_io", "alu"
}

RegionSASSAttribution correlates an [iket.RegionSummary] with static SASS instruction counts and local-memory register spill indicators.

func AttributeRegionSASS

func AttributeRegionSASS[T interface {
	Validate() error
	SummarizeRegions() ([]S, error)
}, S any](trace T, regionSASS map[string]string) ([]RegionSASSAttribution, error)

AttributeRegionSASS correlates the summarized regions of trace with static SASS snippets in regionSASS, counting instruction categories and dynamic local-memory register spill operations and classifying each region's bound. Returned attributions are ordered lexicographically by Region.

Example
package main

import (
	"fmt"

	isasass "github.com/tmc/lib/nvidia/x/isa/sass"
	"github.com/tmc/lib/nvidia/x/obs/iket/ikettrace"
)

func main() {
	trace := &ikettrace.Trace{
		StringTable: []string{"gemm_mainloop", "spill_epilogue"},
		LocationTable: []ikettrace.Location{
			{CTAID: [3]int{0, 0, 0}, WarpID: 0},
		},
		Launches: []ikettrace.Launch{
			{
				KernelName: "sm90_gemm",
				GridDimX:   1, GridDimY: 1, GridDimZ: 1,
				BlockDimX: 128, BlockDimY: 1, BlockDimZ: 1,
				Ranges: []ikettrace.Range{
					{WarpLocIdxs: []int{0}, StartTs: 1000, EndTs: 1800, RangeNameIdx: 0},
					{WarpLocIdxs: []int{0}, StartTs: 1800, EndTs: 2600, RangeNameIdx: 0},
					{WarpLocIdxs: []int{0}, StartTs: 2600, EndTs: 3500, RangeNameIdx: 1},
				},
			},
		},
	}

	regionSASS := map[string]string{
		"gemm_mainloop": `
			/*0000*/ LDSM.16.M88.4 R4, [R8];
			/*0010*/ HMMA.16816.F32 R16, R4, R12, R16;
			/*0020*/ HMMA.16816.F32 R20, R4, R14, R20;
		`,
		"spill_epilogue": `
			/*0100*/ STL.E.64 [R1+0x20], R16;
			/*0110*/ LDL.E.64 R16, [R1+0x20];
			/*0120*/ STG.E.128 [R2.64], R16;
		`,
	}

	attrs, err := isasass.AttributeRegionSASS(trace, regionSASS)
	if err != nil {
		panic(err)
	}
	for _, a := range attrs {
		fmt.Printf("%s: calls=%d dur=%dns insts=%d tc=%d spill=%d dyn_spill=%d class=%s\n",
			a.Region, a.Invocations, a.TotalDurNs, a.TotalInsts, a.TensorCoreInsts, a.LocalSpillInsts, a.DynamicSpillOps, a.BoundClass)
	}
}
Output:
gemm_mainloop: calls=2 dur=1600ns insts=3 tc=2 spill=0 dyn_spill=0 class=tensor_core
spill_epilogue: calls=1 dur=900ns insts=3 tc=0 spill=2 dyn_spill=2 class=spill_bound

type Register

type Register struct {
	Class RegisterClass
	Num   int
}

A Register names one register operand.

func DefsUses

func DefsUses(i Instruction) (defs, uses []Register, ok bool)

DefsUses returns the registers instruction i defines and uses.

Each register of a multi-register operand is reported: LDG.E.64 R2 defines R2 and R3, LDS.128 R8 defines R8 through R11, and an address [R4.64] uses R4 and R5. A predicate written as a carry-out (IADD3 Rd, P0, ...) or ahead of the destination (LOP3.LUT P0, Rd, ...) is a definition, not a use.

It reports false if i's opcode is outside the covered subset. A caller that treats an unclassified instruction as defining nothing will reorder across a definition it could not see, so the boolean is not advisory.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	inst := sass.Instruction{Opcode: "LDG.E.64", Operands: "R2, desc[UR4][R6.64]"}
	defs, uses, _ := sass.DefsUses(inst)
	fmt.Println(defs)
	fmt.Println(uses)
}
Output:
[R2 R3]
[UR4 UR5 R6 R7]

func (Register) Sink

func (r Register) Sink() bool

Sink reports whether r discards writes and so is never a definition.

func (Register) String

func (r Register) String() string

type RegisterAllocation

type RegisterAllocation string

RegisterAllocation describes whether compiled register-allocation metadata was present. It neither authenticates its producer nor proves callability.

Example
caller := KernelResource{Registers: 0}
parsedMissing := KernelResource{RegisterAllocation: RegisterAllocationAbsent}
explicitZero := KernelResource{RegisterAllocation: RegisterAllocationPresent}
fmt.Println(caller.CalculateDevice(SM90, 128, 0).Available)
fmt.Println(parsedMissing.CalculateDevice(SM90, 128, 0).Available)
fmt.Println(explicitZero.CalculateDevice(SM90, 128, 0).Available)
Output:
true
false
true
const (
	// RegisterAllocationCallerSupplied preserves the existing struct-literal
	// API: values, including zero, are analytical inputs supplied by the caller.
	RegisterAllocationCallerSupplied RegisterAllocation = ""
	// RegisterAllocationPresent means a supported allocation field was decoded.
	RegisterAllocationPresent RegisterAllocation = "present"
	// RegisterAllocationInvalid means allocation records conflict or cannot be decoded.
	RegisterAllocationInvalid RegisterAllocation = "invalid"
	// RegisterAllocationAbsent means no supported allocation field was decoded.
	RegisterAllocationAbsent RegisterAllocation = "absent"
)

type RegisterClass

type RegisterClass int

A RegisterClass distinguishes the register files a SASS operand can name.

const (
	GPR   RegisterClass = iota // R0-R254
	Pred                       // P0-P6
	UGPR                       // UR0-UR62
	UPred                      // UP0-UP6
)

func (RegisterClass) String

func (c RegisterClass) String() string

type RegisterPressure

type RegisterPressure struct {
	GPR   int // Live General Purpose Registers (GPR)
	Pred  int // Live Predicate registers (PRED)
	UGPR  int // Live Uniform GPRs (UGPR, sm_70+)
	UPred int // Live Uniform Predicate registers (UPRED, sm_70+)
}

RegisterPressure records live register counts at a specific instruction.

type Result

type Result struct {
	Function string
	Verdict  EquivVerdict
	// Reason says why the verdict is Unknown, or where the functions
	// first differ: the two expressions and their instructions.
	Reason string
	// Before and After are the addresses of the instructions where a
	// difference shows, when EquivVerdict is Different.
	Before, After uint64
	// Assumes lists the registers both functions read before writing
	// when EquivVerdict is Equal: they are equal only if both compilations
	// find the same values there, which the hardware does not promise.
	Assumes []string
}

A Result is the comparison of one function.

func CompareAll

func CompareAll(before, after *Disassembly) []Result

CompareAll compares the functions of two disassemblies by name. A function present on one side only is Different.

func CompareEquiv

func CompareEquiv(before, after *Function) Result

CompareEquiv compares two compilations of one function.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	const urForm = `	code for sm_90a
		Function : scale_idx
        /*0000*/                   LDC R1, c[0x0][0x28] ;
        /*0010*/                   ULDC.64 UR4, c[0x0][0x208] ;
        /*0020*/                   S2R R0, SR_TID.X ;
        /*0030*/                   S2UR UR6, SR_CTAID.X ;
        /*0040*/                   ULDC.64 UR8, c[0x0][0x210] ;
        /*0050*/                   UIMAD UR7, UR6, 0x80, URZ ;
        /*0060*/                   IADD3 R10, R0, UR7, RZ ;
        /*0070*/                   SHF.R.S32.HI R11, RZ, 0x1f, R10 ;
        /*0080*/                   LEA R2, P0, R10, UR8, 0x2 ;
        /*0090*/                   LEA.HI.X R3, R10, UR9, R11, 0x2, P0 ;
        /*00a0*/                   LDG.E R12, desc[UR4][R2.64] ;
        /*00b0*/                   PRMT R13, R12, 0x0123, RZ ;
        /*00c0*/                   STG.E desc[UR4][R2.64], R13 ;
        /*00d0*/                   EXIT ;
`
	const gprForm = `	code for sm_90a
		Function : scale_idx
        /*0000*/                   LDC R1, c[0x0][0x28] ;
        /*0010*/                   ULDC.64 UR4, c[0x0][0x208] ;
        /*0020*/                   S2R R0, SR_TID.X ;
        /*0030*/                   S2R R6, SR_CTAID.X ;
        /*0040*/                   LDC.64 R8, c[0x0][0x210] ;
        /*0050*/                   IMAD R7, R6, 0x80, RZ ;
        /*0060*/                   IADD3 R10, R0, R7, RZ ;
        /*0070*/                   IMAD.WIDE R2, R10, 0x4, R8 ;
        /*0080*/                   LDG.E R12, desc[UR4][R2.64] ;
        /*0090*/                   UPRMT UR13, R12, 0x0123, URZ ;
        /*00a0*/                   STG.E desc[UR4][R2.64], UR13 ;
        /*00b0*/                   EXIT ;
`
	const badPRMT = `	code for sm_90a
		Function : scale_idx
        /*0000*/                   LDC R1, c[0x0][0x28] ;
        /*0010*/                   ULDC.64 UR4, c[0x0][0x208] ;
        /*0020*/                   S2R R0, SR_TID.X ;
        /*0030*/                   S2R R6, SR_CTAID.X ;
        /*0040*/                   LDC.64 R8, c[0x0][0x210] ;
        /*0050*/                   IMAD R7, R6, 0x80, RZ ;
        /*0060*/                   IADD3 R10, R0, R7, RZ ;
        /*0070*/                   IMAD.WIDE R2, R10, 0x4, R8 ;
        /*0080*/                   LDG.E R12, desc[UR4][R2.64] ;
        /*0090*/                   PRMT R13, R12, 0x0122, RZ ;
        /*00a0*/                   STG.E desc[UR4][R2.64], R13 ;
        /*00b0*/                   EXIT ;
`
	dUR, err := sass.ParseString(urForm)
	if err != nil {
		panic(err)
	}
	dGPR, err := sass.ParseString(gprForm)
	if err != nil {
		panic(err)
	}
	dBad, err := sass.ParseString(badPRMT)
	if err != nil {
		panic(err)
	}

	fmt.Println("UR vs GPR:", sass.CompareEquiv(dUR.Functions[0], dGPR.Functions[0]).Verdict)
	fmt.Println("wrong PRMT:", sass.CompareEquiv(dUR.Functions[0], dBad.Functions[0]).Verdict)
}
Output:
UR vs GPR: equal
wrong PRMT: different

func (Result) String

func (r Result) String() string

type RoundTripResult

type RoundTripResult struct {
	Address    uint64
	Opcode     string
	Form       string   // the covered form, empty if uncovered
	Want, Got  Encoding // the captured encoding and the re-encoded one
	Identical  bool
	Difference Encoding // bits that differ, zero when Identical
	Err        string   // why re-encoding did not run at all
}

A RoundTripResult is one instruction's outcome in the feasibility gate.

type SM100Correlation

type SM100Correlation struct {
	PTXLine     int
	PTXOpcode   string
	SASSKind    SM100Kind
	SASSOpcodes []string
	CTAGroup    int
	BlockScaled bool
	ScaleVec    int
	TMEMSourceA bool
	Matched     bool
}

SM100Correlation links a PTX sm_100a/sm_103a instruction to its lowered SASS instruction(s).

type SM100InstInfo

type SM100InstInfo struct {
	Kind        SM100Kind
	Mnemonic    string
	CTAGroup    int    // 1 or 2 (.CTA_GROUP_1 / .CTA_GROUP_2 / .2CTA)
	BlockScaled bool   // .MXF4NVF4, .MXF8F6F4, .BLOCK_SCALE
	ScaleVec    int    // 2 or 4 when .SCALE_VEC_2X / .SCALE_VEC_4X / .2X / .4X is present
	TMEMSourceA bool   // true if operand A is sourced from TMEM ([TMEM:...]) rather than shared memory
	DataType    string // e.g., "F16", "BF16", "E4M3", "MXF4NVF4"
	TMEMCols    int    // width/columns for LDTM/STTM (e.g., 32, 64, 128)
}

SM100InstInfo holds decoded attributes of a Blackwell/Rubin sm_100a/sm_103a/sm_107a SASS instruction.

func ClassifySM100Inst

func ClassifySM100Inst(inst Instruction) (SM100InstInfo, bool)

ClassifySM100Inst classifies a SASS instruction if it belongs to the Blackwell sm_100a tensor-memory (TMEM / tcgen05) or cluster execution family.

type SM100Kind

type SM100Kind string

SM100Kind classifies a Blackwell sm_100a tensor-memory or cluster SASS instruction.

const (
	SM100None      SM100Kind = ""
	SM100UTMMA     SM100Kind = "UTMMA"        // tcgen05.mma -> UTCHMMA (kind::f16), UTCOMMA (block-scaled kind::mxf4nvf4)
	SM100UTMALDG   SM100Kind = "UTMALDG"      // TMA global -> TMEM / shared load
	SM100UTMASTG   SM100Kind = "UTMASTG"      // TMA shared -> global store
	SM100UTMACP    SM100Kind = "UTMACP"       // tcgen05.cp shared -> TMEM copy (e.g. block scales) -> UTCCP
	SM100UTMAFlush SM100Kind = "UTMACMDFLUSH" // tcgen05.commit / fence -> UTCBAR
	SM100LDTM      SM100Kind = "LDTM"         // tcgen05.ld TMEM -> register load
	SM100STTM      SM100Kind = "STTM"         // tcgen05.st register -> TMEM store
	SM100ELECT     SM100Kind = "ELECT"        // elect.sync single-thread leader election
	SM100Alloc     SM100Kind = "UTCATOMSWS"   // tcgen05.alloc / tcgen05.dealloc: TMEM column allocator
)

type SM100LoweringReport

type SM100LoweringReport struct {
	Kernel       string
	Target       string
	PTX          SM100PTXSummary
	SASS         SM100Summary
	Correlations []SM100Correlation
	SpillLoads   int
	SpillStores  int
	AuditIssues  []string
	Divergences  []string
}

SM100LoweringReport holds the PTX-to-SASS correlation and audit results for a Blackwell sm_100a/sm_103a kernel.

func CompareSM100PTXAndSASS

func CompareSM100PTXAndSASS(ptxSrc, sassSrc string) (*SM100LoweringReport, error)

CompareSM100PTXAndSASS parses PTX and SASS sources for a Blackwell sm_100a kernel, correlates each PTX tcgen05.* / elect.sync operation to its lowered SASS instruction(s), and checks CTA group width, block-scaling, TMEM load/store counts, static SASS invariants, and register spills.

func (*SM100LoweringReport) Err

func (r *SM100LoweringReport) Err() error

Err returns nil if the report has no divergences or audit issues, or a single joined error describing all findings.

func (*SM100LoweringReport) OK

func (r *SM100LoweringReport) OK() bool

OK reports whether all PTX-to-SASS correlations, SASS invariants, and zero-spill checks succeeded without divergence.

func (*SM100LoweringReport) String

func (r *SM100LoweringReport) String() string

String formats a human-readable summary of the PTX-to-SASS correlation report.

type SM100PTXSummary

type SM100PTXSummary struct {
	Target           string
	Total            int
	Alloc            int // tcgen05.alloc
	Dealloc          int // tcgen05.dealloc
	Cp               int // tcgen05.cp
	MMA              int // tcgen05.mma
	MMACTAGroup1     int // tcgen05.mma.cta_group::1
	MMACTAGroup2     int // tcgen05.mma.cta_group::2
	MMABlockScaled   int // tcgen05.mma with kind::mxf4nvf4, kind::mxf8f6f4, or .block_scale
	MMAScaleVec2X    int // tcgen05.mma with .scale_vec::2X
	MMAScaleVec4X    int // tcgen05.mma with .scale_vec::4X (sm_103a K=128 NVFP4)
	MMATMEMSourceA   int // tcgen05.mma with TMEM-resident matrix A ([tmem])
	Commit           int // tcgen05.commit
	Wait             int // tcgen05.wait
	Ld               int // tcgen05.ld
	St               int // tcgen05.st
	Elect            int // elect.sync
	ClusterTryCancel int // clusterlaunchcontrol.try_cancel
	TMALoad          int // cp.async.bulk.tensor, global to shared
	TMAStore         int // cp.async.bulk.tensor, shared to global
	LocalLd          int // ld.local
	LocalSt          int // st.local
}

SM100PTXSummary records counts of Blackwell sm_100a/sm_103a/sm_100f/sm_103f PTX instructions (tcgen05.*, elect.sync, clusterlaunchcontrol.try_cancel, and local memory traffic).

type SM100Summary

type SM100Summary struct {
	Total        int
	UTMMA        int
	UTMALDG      int
	UTMASTG      int
	UTMACP       int
	UTMACMDFLUSH int
	LDTM         int
	STTM         int
	ELECT        int
	UTCATOMSWS   int // Tensor Memory allocator operations
	CTAGroup1    int
	CTAGroup2    int
	BlockScaled  int
	ScaleVec2X   int
	ScaleVec4X   int
	TMEMSourceA  int
	ByKind       map[SM100Kind]int
}

SM100Summary holds instruction counts and attributes for Blackwell/Rubin sm_100a/sm_103a/sm_107a tensor-memory and cluster instructions in a disassembled function.

func SummarizeSM100Function

func SummarizeSM100Function(fn Function) SM100Summary

SummarizeSM100Function aggregates counts and attributes of Blackwell sm_100a tensor-memory and cluster SASS instructions in fn.

func (SM100Summary) Count

func (s SM100Summary) Count(kind SM100Kind) int

Count returns the number of instructions of the given SM100Kind.

type Section

type Section struct {
	Name string
	Text []byte

	// ELFSection is the ELF section the region's instructions were read
	// from, as the listing names it: ".text.<Name>" for nvdisasm's
	// ".section" and label headers, and "" for a header that names no
	// section, such as cuobjdump's "Function : <Name>".
	ELFSection string
}

A Section is the region of a disassembly listing that belongs to one kernel.

Text is the listing region verbatim, from the kernel's banner comment (or, where nvdisasm printed none, from its first header line) through the line before the next kernel or trailing banner. It is a region of a listing, not a standalone file: the listing's preamble is not repeated into it, so Text re-parses through ParseString but is not by itself a complete nvdisasm output.

type SharedAccess

type SharedAccess struct {
	Address uint64
	Opcode  string
	Width   int // bytes one thread touches
	Verdict SharedVerdict

	// For SharedOutOfBounds: the thread that goes past the limit and the
	// least offset in the window its access can start at.
	Thread int
	Offset int64

	// Reason says why the verdict is SharedUnknown.
	Reason string
}

A SharedAccess is the verdict on one instruction that reads or writes shared memory.

func CheckSharedBounds

func CheckSharedBounds(fn *Function, lim SharedLimit) ([]SharedAccess, error)

CheckSharedBounds returns the verdict on each shared memory access of fn, in address order, against lim.

An address is followed as a symbolic value of threadIdx.x and constants, as for the asynchronous copy check: anything else, such as a value loaded from memory, a parameter, blockIdx or a register that paths disagree on, leaves it unknown. A register a guarded instruction writes is known to an access under the same guard later in the block, as ptxas writes a short if. An address of threadIdx.x and masks of it, such as (4*threadIdx.x) ^ 0x3fc, is evaluated for each thread; otherwise a mask and(X, M) is taken to range over [0, M].

An access is in bounds if every thread's address, over every threadIdx.x below blockDim.x, stays in [0, lim.Bytes). Threads that definitely exit at a dominating EXIT are excluded, and so are threads that a comparison of threadIdx.x with a constant keeps off every path to the access, such as a branch around it taken when threadIdx.x > 31, or that fail its guard. It is out of bounds only if a thread that exists in every launch the limit allows runs it and touches a byte at or past the maximum window size: its block is on every path from the entry to an exit, nothing earlier in the block can leave, and the instruction is unguarded or its guard is an ISETP of the block that holds for that thread. A thread can still fail to reach it by faulting or hanging first. The threads that exist are threadIdx.x = 0, and all of [0, lim.BlockX) when BlockX is set. LDSM and STSM of one or two matrices read the addresses of only some threads, so they are never out of bounds.

The window includes the 1 KB the system reserves at its start on sm_90 and later, so an access that underflows into it is in bounds here.

The accesses are LDS, STS, ATOMS, LDSM, STSM and the shared side of LDGSTS. Bulk copies (UBLKCP, UTMALDG) and mbarrier operations (SYNCS) are not checked.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	// s[threadIdx.x + 1] = v for float s[256], in a block of 256 threads.
	d, err := sass.ParseString(`
	.section	.text.k,"ax",@progbits
k:
.text.k:
        /*0000*/                   S2R R0, SR_TID.X ;
        /*0010*/                   S2UR UR5, SR_CgaCtaId ;
        /*0020*/                   UMOV UR4, 0x400 ;
        /*0030*/                   ULEA UR4, UR5, UR4, 0x18 ;
        /*0040*/                   LEA R2, R0, UR4, 0x2 ;
        /*0050*/                   STS [R2+0x4], R3 ;
        /*0060*/                   EXIT ;
`)
	if err != nil {
		panic(err)
	}
	// .nv.shared.k is 0x800: 1 KB reserved, then the 1 KB array.
	acc, err := sass.CheckSharedBounds(d.Function("k"), sass.SharedLimit{Bytes: 0x800, BlockX: 256})
	if err != nil {
		panic(err)
	}
	for _, a := range acc {
		fmt.Println(a)
	}
	// If the launch may add more shared memory, the same access is
	// undecided: it fits some of the allowed window sizes.
	acc, err = sass.CheckSharedBounds(d.Function("k"), sass.SharedLimit{Bytes: 0x800, MaxBytes: 0x900, BlockX: 256})
	if err != nil {
		panic(err)
	}
	fmt.Println(acc[0].Verdict)
}
Output:
0x50 STS: thread 255 touches 4 bytes at window offset 0x800 or above
unknown

func (SharedAccess) String

func (a SharedAccess) String() string

type SharedLimit

type SharedLimit struct {
	// Bytes is the minimum size of the window a launch allocates, counted
	// from its start. On sm_90 and
	// later the window starts with 1 KB the system reserves, which
	// .nv.shared.<kernel> includes, and the kernel's static and then
	// dynamic shared memory follow it.
	Bytes int64

	// MaxBytes is the maximum size of the window. Zero means the size
	// is exactly Bytes.
	MaxBytes int64

	// BlockX is blockDim.x when the launch fixes it, as EIATTR_REQNTID
	// or a known launch does, or 0. A thread with threadIdx.x = BlockX-1
	// exists only when it is known.
	BlockX int

	// MaxBlockX bounds blockDim.x when BlockX is 0; zero means 1024.
	MaxBlockX int
}

A SharedLimit bounds the shared memory window of one CTA.

type SharedVerdict

type SharedVerdict int

A SharedVerdict says what is known of one shared memory access.

const (
	SharedUnknown     SharedVerdict = iota // neither bound is shown
	SharedInBounds                         // every thread stays below SharedLimit.Bytes
	SharedOutOfBounds                      // some thread that runs the access goes past it
)

func (SharedVerdict) String

func (v SharedVerdict) String() string

type SlotEvidence

type SlotEvidence struct {
	Slot, OriginalSHA256, PreparedSHA256, PTXSHA256, SASSSHA256 string
	Verified                                                    bool
	Reason                                                      string
	Uses                                                        []SlotUseEvidence
}

SlotEvidence describes bounded textual coverage, not compiler or GPU attestation. Verified requires every use to have a direct shared witness and no conversion.

Example
var evidence SlotEvidence
fmt.Println(evidence.Verified)
Output:
false

type SlotUseEvidence

type SlotUseEvidence struct {
	IRLine                   int
	Value                    string
	PTXLines                 []int
	SharedPCs, ConversionPCs []uint64
}

SlotUseEvidence records observed text locations for an actual producer use.

Example
var evidence SlotUseEvidence
fmt.Println(len(evidence.SharedPCs), len(evidence.ConversionPCs))
Output:
0 0

type Source

type Source interface {
	DisassembleCUBIN(cubin []byte) (*Disassembly, error)
}

A Source disassembles a CUBIN image into functions and instructions.

var Native Source = NativeSource{}

Native is the default pure-Go Source.

type SourceDirective

type SourceDirective struct {
	File string         // file named by the directive, as nvdisasm spelled it
	Line int            // line within File
	Kind SourceFileKind // what File is: a CUDA source, or the PTX text

	// InlinedFile and InlinedLine are the call site the directive attributes
	// File:Line to, when it carries an "inlined at" annotation. nvdisasm emits
	// one annotation per inlining level; only the first, the immediate call
	// site, is reported here. InlinedFile is empty exactly when InlinedLine is
	// zero.
	InlinedFile string
	InlinedLine int
}

A SourceDirective is one parsed nvdisasm line directive:

//## File "kernels.cu", line 42
//## File "util.cuh", line 7 inlined at "kernels.cu", line 42

The directive establishes a location for every instruction that follows it, up to the next directive or the next function, which is nvdisasm's own convention.

func ParseSourceDirective

func ParseSourceDirective(line string) (SourceDirective, bool)

ParseSourceDirective parses an nvdisasm line directive. It reports false for any other line, including a line that merely contains one: a directive is recognised only at the start of the line, after leading space.

type SourceFileKind

type SourceFileKind int

A SourceFileKind classifies the file named in an nvdisasm line directive.

nvdisasm spells a real source file and its own PTX cross-reference tier with the same syntax, so the name alone does not say which one a directive means. Every consumer that joins on (file, line) has to tell them apart, and doing it by comparing against a literal at each call site is how one call site drifts from the rest.

const (
	// CUDASource is a CUDA source or header file that took part in the
	// compilation. Its line numbers index that file.
	CUDASource SourceFileKind = iota

	// PTXText is nvdisasm's pseudo-file ".nv_debug_ptx_txt", which holds the
	// PTX text embedded in the CUBIN rather than any file on disk. Its line
	// numbers index that embedded text and run far past the end of any real
	// source: a module of a few thousand source lines routinely names PTX
	// lines past 140000. Fusing those numbers into a source file's namespace
	// attributes instructions to lines that file does not have.
	PTXText
)

func (SourceFileKind) String

func (k SourceFileKind) String() string

type SpillDiff

type SpillDiff struct {
	AddedSTS     int // Local-memory STL instructions added
	RemovedSTS   int // Local-memory STL instructions removed
	AddedLDS     int // Local-memory LDL instructions added
	RemovedLDS   int // Local-memory LDL instructions removed
	TotalAdded   int // Total local-memory operations added (AddedSTS + AddedLDS)
	TotalRemoved int // Total local-memory operations removed (RemovedSTS + RemovedLDS)
}

SpillDiff counts local-memory accesses added and removed. These counts alone do not establish compiler spills. The historical STS and LDS field names count STL and LDL respectively; shared-memory STS and LDS are excluded.

func (SpillDiff) Delta

func (s SpillDiff) Delta() int

Delta returns the net change in local-memory operations.

type StallProfile

type StallProfile struct {
	Reason   string  // the stall reason the sampler named, e.g. "long_scoreboard"
	Percent  float64 // percentage of samples, or StallSampleUnavailable
	Measured bool    // whether a sampler produced Percent
	Source   string  // the sampler that measured it; empty when absent
}

A StallProfile is a measured stall percentage for one instruction.

This package measures nothing. It disassembles, models dependencies and re-encodes, all on host, and none of that observes a warp stalling. A profile therefore reaches this package only from a sampler that ran on the device, carrying the sampler's name in Source; a profile with no Source is absent, never zero.

func InstructionStalls

func InstructionStalls(inst Instruction) ([]StallProfile, bool)

InstructionStalls returns the stall profiles this package holds for inst, and false when it holds none.

It always returns false. The function exists so that a caller asking for stall percentages receives an explicit absence rather than discovering there is no accessor and reaching for the control code's ControlCode.Stall, which is a static issue delay in cycles chosen by ptxas, not a measured fraction of sampled warps.

func (StallProfile) Valid

func (p StallProfile) Valid() error

Valid reports whether the profile is internally consistent. It rejects both a measurement with no source and an absence carrying a plausible number, because a synthesized percentage is indistinguishable from a measured one once it is past this check.

type StallRange

type StallRange struct{ Min, Max uint8 }

StallRange is the range of stall values observed to be accepted for one instruction form on sm_121a.

The stall field is four bits wide, but the accepted range is not the field width and is not the same for every instruction. Sweeping all sixteen values of the field, nvdisasm accepts every one of them on NOP and rejects 0 and 12-15 on IADD Rd, Ra, URb -- and ptxas itself emits NOP with stall 0. A range measured on one instruction is therefore a fact about that instruction, not about the architecture, and is recorded per form.

func ObservedStallRange

func ObservedStallRange(form string) (StallRange, bool)

ObservedStallRange returns the stall range swept for a covered form, and false if that form has not been swept. Callers must not substitute the range of another form: the two measured so far disagree.

type Stats

type Stats struct {
	Kernel           string
	PTXInstructions  int
	SASSInstructions int
	NOPs             int // NOP instructions, trailing alignment padding included
	InteriorNOPs     int // NOPs ahead of the kernel's last real instruction
	PeakGPR          int // 0 unless the disassembly carries live register counts
}

Stats counts one matched kernel at both levels. It is reported whether or not the kernel diverged, so that a quiet comparison still shows what it read.

type Symbol

type Symbol struct {
	Name    string
	Address uint64
}

A Symbol is a function symbol declared inside another function's section, at the address of its first instruction.

type TMEMRegion

type TMEMRegion struct {
	Name    string `json:"name"`
	Offset  uint32 `json:"offset"`
	Columns uint32 `json:"columns"`
}

A TMEMRegion is one Tensor Memory allocation a CTA holds, as cudatmem.Allocation reports it: TMEMRegion{"acc", a.Offset(), a.Columns()}.

type Target

type Target struct {
	SM     int    // 103 for sm_103a
	Suffix string // "", "f" or "a"
}

A Target is the compilation target of a cubin: an SM number and the feature-set suffix, "" for the baseline, "f" for family-specific or "a" for architecture-specific code.

func ParseTarget

func ParseTarget(s string) (Target, error)

ParseTarget parses an sm_XY, sm_XYf or sm_XYa name.

func ReadTarget

func ReadTarget(r io.ReaderAt) (Target, error)

ReadTarget returns the target the cubin in r was compiled for.

The ELF header's e_flags record the SM number but not the suffix: ptxas 13.5 writes the same e_flags for sm_103, sm_103f and sm_103a. The suffix is read from the "-arch sm_XYs" option ptxas records in the .note.nv.tkinfo note. ReadTarget returns an error wrapping ErrNoTargetOption, naming the tools whose notes carry no option, if no note records that option, and an error if two notes record different targets.

The header's SM may be later than the option's. A CUDA 13.5 driver on a compute capability 12.1 device holds an sm_120 or sm_120f image with its e_flags SM rewritten to 121 and no other byte changed, and that is the image a capture of the loaded module records. ReadTarget accepts such an image only if the option's target runs on the header's compute capability (see Target.RunsOn), which rules out architecture-specific code and other major versions, and returns the option's target, not the header's. Any other disagreement is an error.

func (Target) Major

func (t Target) Major() int

Major and Minor return the compute capability the target names.

func (Target) Minor

func (t Target) Minor() int

func (Target) RunsOn

func (t Target) RunsOn(major, minor int) bool

RunsOn reports whether code compiled for t may run on a device of compute capability major.minor, by the rules NVIDIA documents:

  • Architecture-specific code ("a") runs only on the exact compute capability it was compiled for (CUDA C++ Programming Guide, section 5.1.2.1, "Architecture-Specific Features").
  • Family-specific code ("f") runs on later members of the same family (section 5.1.2.2 and its Table 31, "Family-Specific Compatibility": compute_100f on 10.0, 10.3 and 10.7, compute_103f on 10.3 and 10.7, compute_120f on 12.0 and 12.1). Every row of that table is the same major version at an equal or higher minor version.
  • Baseline code runs on devices of the same major version at an equal or higher minor version (nvcc documentation, section 5.3, "Application Compatibility": sm_80 code runs on all CC 8.x GPUs).

Binary code never runs across major versions.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	t, _ := sass.ParseTarget("sm_103a")
	fmt.Println(t.RunsOn(10, 3), t.RunsOn(10, 0), t.RunsOn(12, 1))
}
Output:
true false false

func (Target) String

func (t Target) String() string

String returns the target's sm_XY name, such as "sm_103a".

type TimerKind

type TimerKind string

A TimerKind names a way a timer read can sit in the wrong place relative to the work it brackets.

const (
	// EndReadBeforeWait is a timer read issued while the result of an
	// instruction issued after the previous timer read is still pending on
	// its scoreboard: the interval ends before that work completes.
	EndReadBeforeWait TimerKind = "end_read_before_wait"

	// StartReadBeforeWait is a timer read issued while the result of an
	// earlier instruction is still pending, where the wait for that result
	// falls before the next timer read: the interval includes the tail of
	// work issued before it began.
	StartReadBeforeWait TimerKind = "start_read_before_wait"

	// StoreUnfenced is a global or generic store or reduction issued between
	// two timer reads with no MEMBAR between it and the later read: the
	// interval covers the store's issue, not its completion.
	StoreUnfenced TimerKind = "store_unfenced"
)

type TimerReport

type TimerReport struct {
	Function string

	// Reads lists the address of every timer read, in address order.
	// ClockReads and GlobalTimerReads count the SR_CLOCK* and
	// SR_GLOBALTIMER* reads among them.
	Reads            []uint64
	ClockReads       int
	GlobalTimerReads int

	// Unchecked, when not empty, is why the placement could not be checked,
	// such as a listing without encodings or an architecture whose control
	// codes are not calibrated. Violations is then nil and means nothing.
	Unchecked string

	// PartialWaits counts DEPBAR.LE SBn, k waits with k > 0. Such a wait
	// retires only the oldest producers on SBn; the check retires none, so
	// a violation through SBn may not be real.
	PartialWaits int

	Violations []TimerViolation
}

A TimerReport is the timer placement of one function.

func CheckTimers

func CheckTimers(fn *Function, arch Arch) TimerReport

CheckTimers checks where fn reads SR_CLOCKLO, SR_CLOCKHI and SR_GLOBALTIMER* (by S2R, CS2R, S2UR or CS2UR) relative to the scoreboard waits of the work between them, using the control codes of arch.

The check is a forward may-analysis over NewCFG: a violation is reported if it occurs on some path. Only write scoreboards are followed; a read scoreboard releases source registers and says nothing about completion. Timer reads are not producers. A wait is a wait-mask bit or DEPBAR.LE SBn, 0x0; see TimerReport.PartialWaits for other DEPBARs. Asynchronous copies and TMA, which complete through mbarriers rather than scoreboards, are not followed, nor are shared and local stores.

The check needs every instruction's encoding (nvdisasm -hex) and an architecture DecodeControl accepts; otherwise the report is unchecked.

func (TimerReport) Checked

func (r TimerReport) Checked() bool

Checked reports whether the function has a timer read and its placement was checked. A function that is not checked has no verdict, clean or not.

type TimerViolation

type TimerViolation struct {
	Kind TimerKind

	// Read is the timer read the violation is reported at: the closing read
	// for EndReadBeforeWait and StoreUnfenced, the opening read for
	// StartReadBeforeWait.
	Read uint64

	// Producer is the instruction whose result (or, for StoreUnfenced,
	// whose store) the interval does not bracket.
	Producer uint64

	// Wait is the instruction that waits on Producer's scoreboard, and End
	// the timer read that closes the interval, for StartReadBeforeWait only.
	Wait, End uint64
}

A TimerViolation is one misplaced timer read.

type Toolchain

type Toolchain struct {
	Tool    string // tki_toolName, e.g. "ptxas"
	Version string // tki_toolVersion, e.g. "Cuda compilation tools, release 13.0, V13.0.88"
	Count   int    // notes in the image carrying this exact stamp
}

Toolchain names a compiler that produced part of a CUDA ELF image, read from the .note.nv.tkinfo note ptxas stamps into every cubin it writes.

Version carries the release, so two images built months apart are distinguishable by it. Tool is "ptxas" in every image measured.

func ReadToolchains

func ReadToolchains(r io.ReaderAt) ([]Toolchain, error)

ReadToolchains returns the distinct toolchain stamps in a CUDA ELF image, sorted by tool and version, each with the number of notes that carry it.

A single-element result is an image built by one compiler; more than one element is an image assembled from several, which is the condition this exists to detect. An image with no stamp yields no elements and no error: not every ELF is a cubin, and not every cubin is stamped.

It reads r with debug/elf alone, through elfinspect.OpenCubin: no CUDA driver is loaded and no external tool is run. Both paths where the note has been observed are covered, a bare cubin and a host object or executable that carries .note.nv.tkinfo sections of its own. Cubins reachable only inside a compressed .nv_fatbin payload are not decompressed and so are not reported.

A CUDA 12 cubin carries its toolkit version in e_version, as documented on [checkCUBIN], where debug/elf accepts only EV_CURRENT; the image is opened with elfinspect.OpenCubin, which reads it. Any other image with an e_version but EV_CURRENT is reported by that field.

Example

ExampleReadToolchains reads the compiler stamp out of a CUDA ELF image.

package main

import (
	"bytes"
	"encoding/hex"
	"fmt"

	isasass "github.com/tmc/lib/nvidia/x/isa/sass"
	"log"
	"os"
	"strings"
)

func main() {
	text, err := os.ReadFile("testdata/tkinfo-ptxas-13.0-sm121.cubin.hex")
	if err != nil {
		log.Fatal(err)
	}
	cubin, err := hex.DecodeString(strings.TrimSpace(string(text)))
	if err != nil {
		log.Fatal(err)
	}
	stamps, err := isasass.ReadToolchains(bytes.NewReader(cubin))
	if err != nil {
		log.Fatal(err)
	}
	for _, s := range stamps {
		fmt.Println(s)
	}
}
Output:
ptxas: Cuda compilation tools, release 13.0, V13.0.88

func (Toolchain) String

func (t Toolchain) String() string

String returns the stamp as "tool: version", with a count when it is not 1.

type UnprovedWaitError

type UnprovedWaitError struct {
	Function string
	Copy     uint64 // address of the copy
	Use      uint64 // address of the shared read
}

An UnprovedWaitError reports a shared memory read that an asynchronous copy reaches on some path with no wait for it in between, where the analysis can show neither that they touch different bytes nor that they touch the same ones. It is a gap in the analysis, not a race: the kernel may be correct. But ClauseAsync is not derived, so Contract.Complete reports false, as it does for a *MissingWaitError; only a proof that the addresses are disjoint, or a wait, clears it.

Example

A copy whose shared tile comes from memory can be neither proved apart from the read nor proved to overlap it. The async clause is then unproved, not a race, and the contract is still incomplete.

package main

import (
	"encoding/hex"
	"errors"
	"fmt"
	"os"
	"strings"

	"github.com/tmc/lib/nvidia/x/isa/sass"
)

func main() {
	raw, err := os.ReadFile("testdata/asyncbuf.sm121a.cubin.hex")
	if err != nil {
		panic(err)
	}
	cubin, err := hex.DecodeString(strings.Join(strings.Fields(string(raw)), ""))
	if err != nil {
		panic(err)
	}
	im, err := sass.OpenCubin(cubin)
	if err != nil {
		panic(err)
	}
	listing, err := os.ReadFile("testdata/asyncbuf.sm121a.sass")
	if err != nil {
		panic(err)
	}
	dis, err := sass.ParseString(string(listing))
	if err != nil {
		panic(err)
	}
	for _, k := range []string{"double_buffer", "double_buffer_same", "indirect_buffer"} {
		c, err := im.Contract(dis.Function(k), k)
		if err != nil {
			panic(err)
		}
		var mw *sass.MissingWaitError
		var uw *sass.UnprovedWaitError
		finding := "none"
		switch {
		case errors.As(c.Err, &mw):
			finding = "missing wait"
		case errors.As(c.Err, &uw):
			finding = "unproved wait"
		}
		ok, _ := c.Derived(sass.ClauseAsync)
		fmt.Printf("%s: async=%v %s complete=%v\n", k, ok, finding, c.Complete())
	}
}
Output:
double_buffer: async=true none complete=true
double_buffer_same: async=false missing wait complete=false
indirect_buffer: async=false unproved wait complete=false

func (*UnprovedWaitError) Error

func (e *UnprovedWaitError) Error() string

type Verdict

type Verdict struct {
	Arch     Arch
	Function string
	Results  []RoundTripResult

	// ControlCodeIsOutOfBand records that the disassembled text does not
	// determine the encoding, so a re-encoder must carry control codes
	// separately. This is true on sm_121a and is a property of nvdisasm's
	// output, not of this package.
	ControlCodeIsOutOfBand bool
}

A Verdict is the outcome of the step 4 feasibility gate on one function.

A negative verdict is a complete and successful outcome for this lane. It must be recorded, and it blocks steps 5 and 6; see Verdict.Blocks.

func RoundTrip

func RoundTrip(fn *Function, arch Arch) Verdict

RoundTrip runs the feasibility gate over fn: for every instruction it re-encodes from the text and compares with the captured bytes.

func (Verdict) Blocks

func (v Verdict) Blocks() bool

Blocks reports whether steps 5 and 6 of lane 34 must not run. It is the negation of Verdict.Feasible, stated separately because it is the scheduling fact the lane prompt turns on.

func (Verdict) Counts

func (v Verdict) Counts() (covered, identical, uncovered int)

Counts returns how many instructions were covered, how many of those round-tripped byte-identically, and how many were outside the subset.

func (Verdict) CoveredForms

func (v Verdict) CoveredForms() []string

CoveredForms returns the distinct forms the gate re-encoded, sorted.

func (Verdict) Failures

func (v Verdict) Failures() []RoundTripResult

Failures returns the covered instructions that did not round-trip.

func (Verdict) Feasible

func (v Verdict) Feasible() bool

Feasible reports whether every covered instruction round-tripped byte-identically.

It is false when nothing was covered: a gate that covered no instruction has demonstrated nothing, and reporting that as success is the failure mode the gate exists to prevent.

func (Verdict) String

func (v Verdict) String() string

String renders the verdict in the form the handoff records.

type Wait

type Wait struct {
	Function string
	Address  uint64 // the loop header's first instruction, or the barrier
	Class    WaitClass
	Reason   string // why the wait has its class, for a reader to check

	Loads  []uint64 // in-loop loads an exit condition depends on
	Timers []uint64 // in-loop %globaltimer reads a deadline exit depends on
	Causes []uint64 // stores on a deadline exit's path, before it leaves
}

A Wait is one device-side wait in a function: a wait loop, or a hardware barrier instruction.

type WaitClass

type WaitClass int

A WaitClass says whether a device-side wait can end without the write it waits for.

const (
	// WaitUnclassified means the analysis could not decide. It is never
	// counted as bounded.
	WaitUnclassified WaitClass = iota

	// WaitUnbounded is a loop that leaves only when memory it reads
	// changes: if the writer dies, the loop never ends.
	WaitUnbounded

	// WaitBoundedNoCause is a wait with a deadline exit whose path stores
	// nothing, so the host cannot tell a timeout from a normal exit.
	WaitBoundedNoCause

	// WaitBounded is a wait with a deadline exit whose path stores a cause
	// code.
	WaitBounded

	// WaitCounted is a wait without a deadline exit but with an exit that
	// depends on a value the loop carries from one iteration to the next
	// without reading memory, such as a spin count. It ends, but after a
	// number of iterations, not a time.
	WaitCounted

	// WaitLocal is a hardware barrier inside one CTA, such as BAR.SYNC or
	// DEPBAR, which cannot wait on a peer.
	WaitLocal
)

func (WaitClass) String

func (c WaitClass) String() string

type WaitError

type WaitError struct {
	Waits []Wait
}

A WaitError lists the unbounded and unclassified waits CheckWaits found.

func (*WaitError) Error

func (e *WaitError) Error() string

type WarpGroupRegs

type WarpGroupRegs struct {
	Warps   int
	RegsPer int // registers per thread
}

A WarpGroupRegs is the register budget of one group of warps in a CTA, such as a producer or consumer warpgroup after setmaxnreg.

type WaterfallEvent

type WaterfallEvent struct {
	Phase string         `json:"ph"`
	PID   int            `json:"pid"`
	TID   int            `json:"tid"`
	TS    uint64         `json:"ts,omitempty"`
	Dur   uint64         `json:"dur,omitempty"`
	ID    uint64         `json:"id,omitempty"`
	Name  string         `json:"name"`
	Cat   string         `json:"cat,omitempty"`
	Args  map[string]any `json:"args,omitempty"`
}

WaterfallEvent is one Chrome Trace Event in a WaterfallTrace.

type WaterfallMetadata

type WaterfallMetadata struct {
	Function    string `json:"function"`
	Arch        Arch   `json:"arch"`
	TimingModel string `json:"timing_model"`
	WarpSlots   int    `json:"warp_slots"`
}

WaterfallMetadata documents the timing model of a WaterfallTrace.

type WaterfallOptions

type WaterfallOptions struct {
	// Arch selects the control-code encoding table. Currently only [SM121a] is supported.
	Arch Arch

	// WarpSlots is the number of warp tracks to emit. Values <= 0 default to 1.
	WarpSlots int
}

WaterfallOptions configures Function.WaterfallTrace.

type WaterfallTrace

type WaterfallTrace struct {
	Metadata    WaterfallMetadata `json:"metadata"`
	TraceEvents []WaterfallEvent  `json:"traceEvents"`
}

WaterfallTrace is a Chrome Trace Event JSON document representing a SASS function's instructions in stall-field order.

Timing values (ts, dur) are derived from the 4-bit stall field in each instruction's control word, not hardware latency tables.

type WitnessPair

type WitnessPair struct {
	Root       string
	BeforePC   uint64
	AfterPC    uint64
	BeforeExpr string
	AfterExpr  string
	Class      int
	Equal      bool
}

A WitnessPair is one root in the value-graph bisimulation between two compilations of a function.

func (WitnessPair) String

func (w WitnessPair) String() string

Directories

Path Synopsis
internal
gensasstables command
Command gensasstables compiles extracted SASS instruction tables from a local sassgen cache directory into compact numeric Go tables for package sass.
Command gensasstables compiles extracted SASS instruction tables from a local sassgen cache directory into compact numeric Go tables for package sass.

Jump to

Keyboard shortcuts

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