plan9asm

package module
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: Apache-2.0 Imports: 18 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

plan9asm

Build Status GitHub release Coverage Status GoDoc XGo

github.com/xgo-dev/plan9asm

Plan 9 assembly parser and LLVM IR translator, extracted as an independent module.

Repository layout

  • github.com/xgo-dev/plan9asm: parser + lowering library.
  • cmd/plan9asm: package/file oriented helper (list, transpile), moved from llgo-stdlib-opt/chore/plan9asm.
  • cmd/plan9asmll: stdlib-oriented converter/test tool (.s -> .ll, optional llc compile).

Current status

  • Library parser/lowering targets: 386, amd64, arm, arm64, wasm.
  • Tool targets (cmd/plan9asmll -all-targets):
    • darwin/amd64, darwin/arm64
    • linux/386, linux/amd64, linux/arm, linux/arm64
    • windows/386, windows/amd64, windows/arm64
    • js/wasm, wasip1/wasm
  • The package-oriented cmd/plan9asm and coverage-oriented cmd/plan9asmscan support the same five Plan 9 assembly architectures.
  • 386 currently reuses the x86 lowering path from amd64 backend logic.
  • arm64 does not include arm (32-bit). They are separate architectures.
  • Instruction coverage is tracked for all five LLGo Plan 9 assembly GOARCH targets by architecture, level, family, opcode, and operand form against Go's official opcode/encoder sources, positive GOROOT assembly, and executable real-world regressions. See Plan 9 assembly instruction coverage.

LLVM backend

  • LLVM 22 is the only supported object-code toolchain; LLVM 23 and older releases are intentionally rejected instead of used as fallbacks.
  • TranslateModule builds an in-memory llvm.Module (github.com/xgo-dev/llvm).
  • Translate keeps compatibility and returns textual IR from that module.
  • Root module dependency stays small (goplus/llvm).
  • golang.org/x/tools/go/packages is used only in cmd/plan9asmll submodule.
  • cmd/plan9asm does not depend on llgo/internal/build or llgo/internal/packages.

Quick test

go test ./...

Some tests require local LLVM 22 tools (llc, clang) and skip when unavailable.

The executable cases under testdata/conformance use the native Go assembler as an oracle, then compile and run the same assembly through plan9asm/LLVM. Run them with:

go test . -run 'Test.*Conformance'

The separate cross-version instruction coverage gate compares Go's assembler corpus and encoder forms against the checked-in baseline:

scripts/check-go-asm-coverage.sh

On a Linux/amd64 host with the Debian cross GCC toolchains and QEMU user-mode emulators installed, run the cross-architecture link and execution smoke test:

PLAN9ASM_CROSS_EXEC=1 go test . -run '^TestCrossLinuxRuntimeMatrix$' -count=1 -v

cmd/plan9asmll usage

Show flags:

go run -C cmd/plan9asmll . -h

List selected asm files only:

go run -C cmd/plan9asmll . -patterns=std -goos=linux -goarch=386 -list-only

Convert one target (.s -> .ll):

go run -C cmd/plan9asmll . \
  -patterns=std \
  -goos=linux -goarch=amd64 \
  -out _out/plan9asmll/linux-amd64 \
  -report /tmp/plan9asmll-linux-amd64.json

Convert and compile (.ll -> .o) via llc:

go run -C cmd/plan9asmll . \
  -all-targets \
  -patterns=std \
  -compile \
  -out _out/plan9asmll/all-targets \
  -report /tmp/plan9asmll-all-targets.json

Run only x86 (386) targets:

go run -C cmd/plan9asmll . \
  -patterns=std \
  -targets=linux/386,windows/386 \
  -compile \
  -out _out/plan9asmll/x86 \
  -report /tmp/plan9asmll-x86.json

Output behavior

  • Every asm file is printed with explicit status (OK or FAIL).
  • On failure, tool prints:
    • the primary reason line,
    • unsupported opcode set (if detected),
    • per-hit location as file line number + source line.
  • -keep-going=true (default) continues through all files and summarizes at the end.

Notes

  • The stdlib asm corpus depends on your local Go toolchain version (go tool dist list, GOROOT content).
  • If -compile is enabled, LLVM 22's llc-22 (or a version-verified llc) must be discoverable in PATH or set via -llc.
  • Design notes and migration details are in doc/llvm-module-migration.md.

cmd/plan9asm usage

List packages/files containing .s:

go run -C cmd/plan9asm . list -goos=linux -goarch=amd64 std

transpile package mode uses positional patterns (go build/test style) and supports multiple patterns.

Transpile package selected .s files:

go run -C cmd/plan9asm . transpile \
  -dir _out/plan9asm/runtime-linux-amd64 \
  -goos=linux -goarch=amd64 \
  runtime

Transpile one .s file:

go run -C cmd/plan9asm . transpile \
  -i /path/to/file.s \
  -o /tmp/file.ll \
  -goos=linux -goarch=amd64

Native Darwin/ARM64 assembly

TranslateNativeARM64Source emits native assembly directly from a bounded Plan 9 subset for raw callbacks and trampolines. It preserves explicitly written register interfaces without synthesizing LLVM function signatures or using Go assembler objects. The driver invokes the native assembler, binds the returned DATA globals, and supplies imported symbols and library link arguments.

ForeignARM64Functions is a routing hint for files containing only local TEXT; it does not establish a C ABI. Unsupported frames, flags, instructions, operands, and references produce errors. Go-declared functions retain typed LLVM translation; unresolved local signatures require explicit metadata instead of a void() guess.

See the native backend contract for the exact source, instruction, data and runtime boundaries. The former TranslateNativeARM64Object API has been removed; callers pass source to TranslateNativeARM64Source instead.

Documentation

Overview

Package plan9asm provides an experimental translator from Go/Plan 9 assembly syntax (the `.s` files used in the Go standard library) into LLVM IR.

Scope (initial):

  • Focus on a small subset sufficient for leaf functions used as building blocks (CRC/byte ops/syscall stubs), without depending on Go's assembler.
  • The first implementation targets amd64-like integer ops and a simplified ABI model for tests. It is not yet a drop-in replacement for the full Go assembler.

This package is intentionally self-contained (no dependency on llgo's SSA pipeline) so it can be iterated independently and unit tested by compiling the produced `.ll` with llc/clang.

Index

Constants

This section is empty.

Variables

View Source
var ErrProbeNeedsContext = errors.New("instruction probe needs function context")

ErrProbeNeedsContext means an instruction cannot be judged in isolation. The full-file corpus compiler remains authoritative for these forms.

Functions

func ForeignARM64Functions added in v0.6.0

func ForeignARM64Functions(src []byte) map[string]bool

ForeignARM64Functions is the Darwin/ARM64 compatibility routing helper.

func ForeignNativeFunctions added in v0.6.1

func ForeignNativeFunctions(src []byte, goarch string) map[string]bool

ForeignNativeFunctions identifies files containing only file-local TEXT symbols. This is a routing hint, NOT an inference of a C function signature. The native backend validates frames, flags, instructions, and references independently. Files with package-visible TEXT must use the typed backend and explicit Go declarations. Unsupported native forms must not fall back to signature guessing.

func InstructionFamily added in v0.5.2

func InstructionFamily(arch Arch, opcode string) string

InstructionFamily groups opcodes by architectural function. The family is deliberately independent of current plan9asm support so unsupported forms remain visible in the same family as their supported peers.

func ProbeInstruction added in v0.5.2

func ProbeInstruction(arch Arch, goarch string, ins Instr) error

ProbeInstruction runs one instruction through the real lowering pipeline. It is intended for coverage tooling; executable conformance tests are still required before a form is considered semantically verified.

func SupportsNativeTarget added in v0.6.1

func SupportsNativeTarget(goos, goarch string) bool

SupportsNativeTarget reports implemented instruction/object-format pairs.

func Translate

func Translate(file *File, opt Options) (string, error)

Translate converts a parsed Plan 9 asm File into LLVM IR text (`.ll`).

The generated text is produced from an llvm.Module to keep textual emission consistent with the LLVM printer.

func TranslateModule

func TranslateModule(file *File, opt Options) (llvm.Module, error)

TranslateModule converts a parsed Plan 9 asm File into an llvm.Module.

Caller owns the returned module and should call Dispose when finished.

func TranslateNativeModule added in v0.6.1

func TranslateNativeModule(ctx llvm.Context, src []byte, opts NativeOptions) (mod llvm.Module, err error)

TranslateNativeModule represents each raw native entry as an address-only naked LLVM function. The void() carrier is NOT a Go/C signature: all inputs, results, calls and returns live in physical registers inside inline assembly. Call sites retain their own ABI. No typed IR call is generated for a carrier. DATA contains real LLVM references, as do inline-asm symbol operands, so module linking, renaming and dead-code elimination can track their dependencies. The caller owns the returned module; errors never return a partial module.

Types

type Arch

type Arch string
const (
	ArchAMD64 Arch = "amd64"
	ArchARM   Arch = "arm"
	ArchARM64 Arch = "arm64"
	ArchWASM  Arch = "wasm"
)

type DataStmt

type DataStmt struct {
	// Addr retains a symbol-address initializer, including its (SB) suffix.
	Addr    string
	Sym     string
	Off     int64
	Width   int64
	Value   uint64
	Payload []byte
}

DataStmt models a minimal Plan 9 DATA directive:

DATA sym+off(SB)/width, $value

Width is in bytes. Integer values are encoded little-endian into the global. String payloads are copied byte-for-byte and zero-padded to Width, matching cmd/asm's DATA string semantics.

type ExtendOp

type ExtendOp string

ExtendOp is an ARM64 register-extension modifier (for example UXTB, SXTW). The prefix U/S selects zero- or sign-extension; the suffix B/H/W/X selects the source width (8/16/32/64 bits).

const (
	ExtendUXTB ExtendOp = "UXTB"
	ExtendUXTH ExtendOp = "UXTH"
	ExtendUXTW ExtendOp = "UXTW"
	ExtendUXTX ExtendOp = "UXTX"
	ExtendSXTB ExtendOp = "SXTB"
	ExtendSXTH ExtendOp = "SXTH"
	ExtendSXTW ExtendOp = "SXTW"
	ExtendSXTX ExtendOp = "SXTX"
)

type File

type File struct {
	Arch  Arch
	Funcs []Func

	// Data and Globl capture a minimal subset of the Plan 9 DATA/GLOBL directives
	// used by some stdlib asm (e.g. hash/crc32/crc32_amd64.s).
	//
	// These are emitted as LLVM globals by the translator so loads like:
	//   MOVOA r2r1<>+0(SB), X0
	// can be translated without relying on an overlay/alt package.
	Data  []DataStmt
	Globl []GloblStmt
}

File is a parsed Plan 9 asm source file (subset).

func Parse

func Parse(arch Arch, src string) (*File, error)

Parse parses a subset of Go/Plan 9 assembly syntax.

Currently supported:

  • TEXT directives (function start)
  • MOVQ/ADDQ/SUBQ/XORQ/MOVL, CPUID, XGETBV, BYTE, RET
  • Operands: immediate ($imm), register (AX/BX/CX/DX), and name+off(FP)

Also supported at a minimal level:

  • #include is ignored
  • #define NAME <body> with optional single-line continuation via '\' and macro invocation when the entire statement is just NAME.

type FrameLayout

type FrameLayout struct {
	Params  []FrameSlot
	Results []FrameSlot
}

type FrameSlot

type FrameSlot struct {
	Offset int64
	Type   LLVMType
	Index  int // index into LLVM function arguments (for Params) or results tuple (for Results)
	// Field is the index of the extracted field within the argument aggregate.
	// It is used for classic Go asm slots like b_base+0(FP) when the Go-level
	// parameter is passed as a struct (string/slice header).
	//
	// When Field < 0, the slot refers directly to %arg(Index).
	Field int
}

type Func

type Func struct {
	// Sym is the symbol name from the TEXT directive with (SB) trimmed.
	// It may contain the Plan 9 middle dot (·).
	Sym string

	// FrameSize and ArgSize retain the numeric $frame-args values from TEXT.
	// WebAssembly's Go ABI uses FrameSize to address FP operands through the
	// linear-memory stack and to restore SP on return. A missing -args suffix
	// leaves ArgSize at zero.
	FrameSize int64
	ArgSize   int64

	Instrs []Instr
}

type FuncSig

type FuncSig struct {
	Name  string
	Args  []LLVMType
	Ret   LLVMType // use Void for void-return
	Attrs string   // optional function attributes group (e.g. "#0")

	// WASMContext is the physical closure-environment parameter carried in
	// WebAssembly's CTXT pseudo-register. It precedes Args in the LLVM entry but
	// is not part of the Go function signature, so FrameSlot.Index continues to
	// address Args without an offset. The zero value means that the entry does
	// not consume an incoming CTXT value.
	WASMContext LLVMType

	// WASMNative keeps the function's declared WebAssembly signature when
	// Options.WASMABI selects the official Go stack ABI. It is used for the
	// small set of runtime exports and assembly helpers that intentionally do
	// not use the resumable (PC_B) -> unwind convention.
	WASMNative bool

	// ArgRegs optionally specifies which architectural registers correspond to
	// Args for arm64 asm that passes values in non-sequential registers.
	//
	// When empty, args are assumed to map to R0..R7 in order (ABIInternal-ish).
	//
	// This is used for intra-asm tailcalls like:
	//   B helper<>(SB)
	// where helper expects inputs in a custom register assignment.
	ArgRegs []Reg

	// Frame provides a minimal stack-frame model for resolving name+off(FP)
	// references in Go/Plan9 assembly into LLVM function args/returns.
	//
	// This is intentionally limited to the classic Go assembler convention used
	// by stdlib .s files (e.g. internal/cpu/cpu_x86.s).
	Frame FrameLayout
}

func InferWASMAssemblyFuncSig added in v0.5.2

func InferWASMAssemblyFuncSig(fn Func, name string) (FuncSig, error)

InferWASMAssemblyFuncSig derives the native WebAssembly signature of a file-local helper from its operand-stack and virtual-register use. Official Go uses these helpers for bytealg routines such as memeqbody and memchr; they have no Go declaration, so their signature cannot come from go/types.

type GloblStmt

type GloblStmt struct {
	Sym   string
	Flags string
	Size  int64
}

GloblStmt models a minimal Plan 9 GLOBL directive:

GLOBL sym(SB), flags, $size

Flags are preserved as raw text for now (e.g. "RODATA").

type GoFunction

type GoFunction struct {
	TextSymbol     string
	ResolvedSymbol string
}

GoFunction records the original TEXT symbol and its resolved LLVM symbol.

type GoModuleOptions

type GoModuleOptions struct {
	FileName string
	GOOS     string
	GOARCH   string
	// Sizes is the type layout used to type-check the package. When nil,
	// TranslateGoModule uses the standard gc layout for GOARCH. Callers with a
	// custom data model, such as Emscripten wasm32 versus Memory64, must pass
	// the same Sizes instance used by go/types.
	Sizes types.Sizes
	// FrameSizes describes the stack-frame layout encoded in FP offsets. It
	// defaults to Sizes. This is separate because LLGo's C-compatible wasm32
	// mode uses 32-bit values while translating assembly emitted for Go's
	// 64-bit GOARCH=wasm frame layout.
	FrameSizes     types.Sizes
	TargetTriple   string
	WASMABI        WASMABI
	X87Mode        X87Mode
	AnnotateSource bool

	ResolveSym func(sym string) string
	KeepFunc   func(textSym, resolved string) bool
	ManualSig  func(resolved string) (FuncSig, bool)
}

GoModuleOptions configures TranslateGoModule.

GOARCH is required and currently accepts only "amd64", "386", and "arm64". If ResolveSym is nil, the default resolver only strips ABI suffixes.

type GoModuleTranslation

type GoModuleTranslation struct {
	Module     llvm.Module
	Signatures map[string]FuncSig
	Functions  []GoFunction
}

GoModuleTranslation is the result of TranslateGoModule.

Callers own Module and must call Module.Dispose when finished with it.

func TranslateGoModule

func TranslateGoModule(pkg GoPackage, src []byte, opt GoModuleOptions) (*GoModuleTranslation, error)

TranslateGoModule binds Go declarations to a Plan 9 asm file and translates the result into an LLVM module in one call.

The package must provide go/types information for the declarations referenced by the assembly. Methods and variadic functions are not supported.

type GoPackage

type GoPackage struct {
	Path    string
	Types   *types.Package
	Imports map[string]*types.Package
	Syntax  []*ast.File
}

GoPackage provides the Go declarations and syntax needed to bind a Plan 9 asm file to real Go symbols.

type Instr

type Instr struct {
	Op   Op
	Args []Operand
	Raw  string
}

type InstructionDescriptor added in v0.5.2

type InstructionDescriptor struct {
	Arch     Arch     `json:"arch"`
	Goarch   string   `json:"goarch"`
	Family   string   `json:"family"`
	Opcode   string   `json:"opcode"`
	Operands []string `json:"operands"`
	Form     string   `json:"form"`
}

InstructionDescriptor is the stable identity used by coverage reports. Opcode-only coverage is insufficient: an opcode can accept one operand form while rejecting another valid Go assembly form.

func DescribeInstruction added in v0.5.2

func DescribeInstruction(arch Arch, goarch string, ins Instr) InstructionDescriptor

DescribeInstruction classifies an instruction without claiming that its lowering is implemented. Use ProbeInstruction to check lowering support.

type LLVMType

type LLVMType string
const (
	Void LLVMType = "void"
	I1   LLVMType = "i1"
	I8   LLVMType = "i8"
	I16  LLVMType = "i16"
	I32  LLVMType = "i32"
	I64  LLVMType = "i64"
	Ptr  LLVMType = "ptr"
)

type MemRef

type MemRef struct {
	Base     Reg
	Sym      string // optional symbol-based address, including the (SB) suffix
	Off      int64
	OffRaw   string   // unresolved symbolic displacement, used by generated wasm go_asm.h offsets
	Index    Reg      // optional; empty if not present
	IndexExt ExtendOp // optional ARM64 index extension (UXTW, SXTW, UXTX, or SXTX)
	Scale    int64    // optional; defaults to 1 when Index is present
	Segment  Reg      // optional x86 segment override (FS or GS)
}

type NativeData added in v0.6.0

type NativeData struct {
	Name string
	Size uint32
}

NativeData describes a Go global whose storage is supplied by native assembly.

func TranslateNativeARM64Source added in v0.6.1

func TranslateNativeARM64Source(src []byte, imports map[string]string, pkgPath string) (string, []NativeData, error)

TranslateNativeARM64Source is the Darwin/ARM64 compatibility entry point.

func TranslateNativeSource added in v0.6.1

func TranslateNativeSource(src []byte, opts NativeOptions) (string, []NativeData, error)

TranslateNativeSource translates checked Plan 9 source directly to native assembly, without Go object files, implicit frames, or signature inference.

type NativeOptions added in v0.6.1

type NativeOptions struct {
	GOOS, GOARCH string
	PackagePath  string
	Imports      map[string]string
}

NativeOptions selects a bounded physical-register backend. It does not describe Go ABI entries: callers must already obey the target native calling convention.

type Op

type Op string
const (
	OpTEXT   Op = "TEXT"
	OpMRS    Op = "MRS"
	OpMOVQ   Op = "MOVQ"
	OpMOVL   Op = "MOVL"
	OpADDQ   Op = "ADDQ"
	OpSUBQ   Op = "SUBQ"
	OpXORQ   Op = "XORQ"
	OpMOVD   Op = "MOVD"
	OpCPUID  Op = "CPUID"
	OpXGETBV Op = "XGETBV"
	OpBYTE   Op = "BYTE"
	OpWORD   Op = "WORD"
	OpCALL   Op = "CALL"
	OpJMP    Op = "JMP"
	OpRET    Op = "RET"
	OpLABEL  Op = "LABEL"
)

type Operand

type Operand struct {
	Kind OperandKind

	Imm    int64    // OpImm
	ImmRaw string   // OpImm unresolved symbolic placeholder, including leading '$'
	Reg    Reg      // OpReg
	Ext    ExtendOp // OpRegExtend
	// OpRegShift
	ShiftOp     ShiftOp
	ShiftAmount int64
	ShiftReg    Reg

	FPName   string // OpFP (e.g. "a", "ret")
	FPOffset int64  // OpFP

	Ident string // OpIdent (e.g. system register name in MRS)

	Sym string // OpSym / OpLabel

	// OpMem: a minimal memory addressing mode.
	// Examples:
	//   (SI)
	//   16(SI)
	//   -8(SI)(R8*1)
	//   (R0)(R6)
	Mem MemRef

	RegList []Reg // OpRegList (e.g. (R4, R8))
}

Operand models a minimal subset of Plan 9 asm operands.

Supported:

  • Immediate: $123
  • Register: AX, BX, ...
  • FP slot: name+offset(FP) (used in classic Go stack ABI syntax)

func (Operand) String

func (o Operand) String() string

type OperandKind

type OperandKind int
const (
	OpInvalid OperandKind = iota
	OpImm
	OpReg
	OpRegExtend
	OpRegShift
	OpFP
	OpFPAddr
	OpIdent
	OpSym
	OpLabel
	OpMem
	OpRegList
)

type Options

type Options struct {
	TargetTriple string

	// ResolveSym maps the TEXT symbol (with (SB) trimmed) into the final linker
	// symbol name to emit in LLVM IR. If nil, the symbol is used as-is.
	ResolveSym func(sym string) string

	// Sigs maps resolved symbol name -> signature.
	Sigs map[string]FuncSig

	// Goarch is used for a few arch-specific translations (e.g. x86 CPUID).
	Goarch string

	// WASMABI selects the WebAssembly physical ABI. Its zero value preserves
	// the direct ABI used by existing plan9asm callers.
	WASMABI WASMABI

	// X87Mode controls explicit x87 instruction lowering for GOARCH=386. Auto
	// uses hardware, matching the Go 386 target contract. Software retains the
	// portable LLVM fallback for custom targets without x87 hardware.
	X87Mode X87Mode

	// AnnotateSource emits source asm lines as IR comments before lowering each
	// instruction, for translation debugging.
	AnnotateSource bool
}

type Reg

type Reg string
const (
	AX Reg = "AX"
	BX Reg = "BX"
	CX Reg = "CX"
	DX Reg = "DX"
	SI Reg = "SI"
	DI Reg = "DI"
	SP Reg = "SP"
	BP Reg = "BP"
	PC Reg = "PC"
	FS Reg = "FS"
	GS Reg = "GS"

	AL Reg = "AL"
	AH Reg = "AH"
	BL Reg = "BL"
	BH Reg = "BH"
	CL Reg = "CL"
	CH Reg = "CH"
	DL Reg = "DL"
	DH Reg = "DH"

	ZR Reg = "ZR"
)

type ShiftOp

type ShiftOp string
const (
	ShiftLeft   ShiftOp = "<<"
	ShiftRight  ShiftOp = ">>"
	ShiftArith  ShiftOp = "->"
	ShiftRotate ShiftOp = "@>"
)

type WASMABI added in v0.5.2

type WASMABI uint8

WASMABI selects the physical ABI used for WebAssembly Plan 9 assembly. Direct is LLGo's existing native LLVM calling convention. Go uses the official linear-memory stack, mutable register globals, PC_B resume input, and an i32 unwind result.

const (
	WASMABIDirect WASMABI = iota
	WASMABIGo
)

type X87Mode added in v0.5.1

type X87Mode uint8

X87Mode selects how explicit x87 instructions in 386 Plan 9 assembly are lowered. Hand-written assembly may use x87 mnemonics regardless of GO386; the Go-supported Pentium MMX-or-newer baseline has an x87 unit, so the default emits hardware instructions. Software mode is reserved for custom targets that explicitly cannot execute x87 instructions.

const (
	X87Auto X87Mode = iota
	X87Hardware
	X87Software
)

Directories

Path Synopsis
cmd
plan9asmcorpus command
plan9asmdiscover command
Command plan9asmdiscover finds public Go modules that contain Plan 9 assembly.
Command plan9asmdiscover finds public Go modules that contain Plan 9 assembly.
plan9asmscan command

Jump to

Keyboard shortcuts

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