backend

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2026 License: Apache-2.0 Imports: 5 Imported by: 0 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.

Documentation

Overview

Package backend must be free of Wasm-specific concept. In other words, this package must not import internal/wasm package.

Index

Constants

View Source
const (
	// ABIArgKindReg represents an argument passed in a register.
	ABIArgKindReg = iota
	// ABIArgKindStack represents an argument passed in the stack.
	ABIArgKindStack
)
View Source
const LeafStackCheckHeadroomBytes = 128

LeafStackCheckHeadroomBytes is slack kept below MARGIN when eliding a leaf function's prologue stack-bounds check (both ISAs). A leaf makes no calls of any kind (so maxRequiredStackSizeForCalls stays 0) and thus its whole frame sits within the MARGIN its caller already reserved below it (invariant point 3 above). This headroom additionally covers the return-address push of any Go-exiting trampoline (interrupt check, memory.grow, ...) the leaf might still invoke -- those exit to Go rather than recursing on the wasm stack, so they consume only a few bytes of it.

View Source
const StackBoundsCheckMarginBytes = 512

StackBoundsCheckMarginBytes (H7 in OPTIMIZATIONS.md) is a constant amount of extra slack that every wasm function prologue's stack-bounds check demands, beyond what the function itself (its own frame plus the deepest transient call it makes) actually needs. It costs nothing at runtime: the prologue check (insertStackBoundsCheck, both ISAs) is a pure comparison against native.executionContext.stackBottomPtr -- it does not change how much stack a frame physically consumes, only how early/how large the underlying stack buffer grows. Reserving MARGIN is implemented by biasing the stored stackBottomPtr check-limit up by MARGIN (see call_engine.go) rather than by adding MARGIN into every function's requiredStackSize() immediate; requiredStackSize() (isa/amd64/machine.go, isa/arm64/ machine.go) therefore excludes MARGIN, which keeps that hot-path prologue immediate small. This just shifts *which side* of the check inequality carries MARGIN and *when* the existing stack-grow mechanism fires; it adds no instructions and no per-call cost to ordinary wasm execution.

What it buys: CompileGoFunctionTrampoline, for a host-function signature whose entire Go argument/result slice (plus its small fixed bookkeeping overhead) fits within MARGIN, can skip its own stack-bounds check/ grow-call sequence entirely -- see the goSliceSizeAligned/goCallStackSize comparisons against this constant at the CompileGoFunctionTrampoline call sites in isa/amd64/abi_go_call.go and isa/arm64/abi_go_call.go. That removes ~4 instructions (an add/sub, a cmp, a conditional branch, and the reverse add/sub) from the hot path of every such host call.

Invariant that makes this safe (stated once here; both ISAs rely on it). MARGIN is reserved by biasing the stored stackBottomPtr check-limit up by MARGIN (set in call_engine.go), not by adding MARGIN into requiredStackSize() (isa/amd64/machine.go and isa/arm64/machine.go, which therefore exclude it) -- only which side of the check inequality below carries MARGIN has moved; the inequality itself, and everything the rest of this proof derives from it, is unchanged:

  1. Every wasm function's prologue check verifies that frameBase - stackBottomPtr >= maxRequiredStackSizeForCalls + frameSize() + MARGIN + <fixed per-ISA bookkeeping, 32 bytes on both amd64 and arm64: return-address + saved-frame-pointer/unwind slots>. (frameBase is the value of RBP/SP right after the prologue has pushed the caller's frame-pointer/return-address bookkeeping, i.e. exactly where the check itself runs.)

  2. native frames are fixed-size: once a function's prologue check passes, its body only ever uses up to frameSize() bytes for its own spill/clobbered-register area (a compile-time constant, allocated once), plus up to maxRequiredStackSizeForCalls bytes transiently for whichever single call it is currently making (outgoing stack args + that callee's own entry bookkeeping). Nothing else in a wasm frame's body consumes stack -- there is no dynamic (loop- or data-dependent) stack growth within a single frame.

  3. Consequently, at the point of any call this function makes -- whether to another wasm function or to a go-call trampoline -- the callee's own frame base is guaranteed to sit at least MARGIN bytes above stackBottomPtr, regardless of call depth. If the callee is itself a wasm function, it independently re-establishes the very same invariant via its own prologue check before making any further calls of its own, so the property holds transitively no matter how deep the call chain gets before a host call actually happens.

    Derivation (amd64 constants; arm64 differs only in which fixed constant plays which role, not in the shape of the argument): let actualFrameBytes be a frame's real physical stack usage at the call site (<= frameSize(), since clobbered int registers are pushed 8 bytes each while frameSize() conservatively charges 16), and let stackSlotSize be the outgoing stack-argument bytes for this particular call (<= maxRequiredStackSizeForCalls - 16, see prepareCall in isa/{amd64,arm64}/machine.go). Then the callee's frame base, measured from stackBottomPtr, is: calleeBase - stackBottomPtr = (callerFrameBase - stackBottomPtr) - actualFrameBytes - stackSlotSize - 16 >= requiredStackSize - frameSize() - stackSlotSize - 16 (check passed) = maxRequiredStackSizeForCalls + MARGIN + 32 - stackSlotSize - 16 + (frameSize()-actualFrameBytes) >= MARGIN + 32 + (frameSize()-actualFrameBytes) (since maxRequiredStackSizeForCalls - stackSlotSize >= 16) >= MARGIN. Without MARGIN (i.e. today, pre-H7) this same derivation bottoms out at exactly 32 bytes of guaranteed slack at any callee's entry -- enough for the callee's own prologue bookkeeping, but never enough to let a callee skip its own check. Adding MARGIN is what turns that bound into something a small trampoline can actually rely on.

  4. The stack-grow path (nativeapi.ExitCodeGrowStack), on the rare occasion some deeper frame's own prologue check does trip, allocates a fresh (larger) buffer and relocates every live frame onto it (cloneStack/adjustClonedStack). This doesn't threaten the invariant: the invariant is a per-check property (each frame's prologue check re-verifies it against the *current* stackBottomPtr/buffer every time that frame is entered), not something that has to be preserved by the relocation itself. A relocated frame's saved registers, return addresses, and frame-pointer chain are adjusted to the new buffer by adjustClonedStack, but MARGIN plays no part in that adjustment -- it only ever matters at the moment a prologue check (or an elided go-call trampoline standing in for one) runs.

MARGIN's value (512 bytes) is picked to cover the Go argument/result slice of the overwhelming majority of host function signatures: on amd64 the trampoline's own check would otherwise ask for goSliceSizeAligned+8, so MARGIN=512 covers any signature whose (params, results) max, rounded up to 8-byte slots and 16-byte aligned, is <=504 bytes -- i.e. up to 62 8-byte parameters/results on the larger side of the signature (arm64's goCallStackSize+16 gives the same bound). Real host functions -- including the largest WASI syscalls such as fd_write/path_open, which have at most ~9 params -- use a small handful of slots, so 512 bytes covers them with a wide safety margin; only deliberately pathological, huge-arity signatures fall back to the full check (still correct, just not elided).

Variables

This section is empty.

Functions

func ABIInfoFromUint64

func ABIInfoFromUint64(info uint64) (argIntRealRegs, argFloatRealRegs, retIntRealRegs, retFloatRealRegs byte, stackSlotSize uint32)

func GoFunctionCallRequiredStackSize

func GoFunctionCallRequiredStackSize(sig *ssa.Signature, argBegin int) (ret, retUnaligned int64)

GoFunctionCallRequiredStackSize returns the size of the stack required for the Go function call. argBegin is the index of the first argument in the signature which is not either execution context or module context.

Types

type ABIArg

type ABIArg struct {
	// Index is the index of the argument.
	Index int
	// Kind is the kind of the argument.
	Kind ABIArgKind
	// Reg is valid if Kind == ABIArgKindReg.
	// This VReg must be based on RealReg.
	Reg regalloc.VReg
	// Offset is valid if Kind == ABIArgKindStack.
	// This is the offset from the beginning of either arg or ret stack slot.
	Offset int64
	// Type is the type of the argument.
	Type ssa.Type
}

ABIArg represents either argument or return value's location.

func (*ABIArg) String

func (a *ABIArg) String() string

String implements fmt.Stringer.

type ABIArgKind

type ABIArgKind byte

ABIArgKind is the kind of ABI argument.

func (ABIArgKind) String

func (a ABIArgKind) String() string

String implements fmt.Stringer.

type CompiledBlockOffset

type CompiledBlockOffset struct {
	BlockID ssa.BasicBlockID
	Offset  int64
}

CompiledBlockOffset pairs an ssa.BasicBlockID with its resolved, function-body-relative start offset in the compiled executable.

type Compiler

type Compiler interface {
	// SSABuilder returns the ssa.Builder used by this compiler.
	SSABuilder() ssa.Builder

	// Compile executes the following steps:
	// 	1. Lower()
	// 	2. RegAlloc()
	// 	3. Finalize()
	// 	4. Encode()
	//
	// Each step can be called individually for testing purpose, therefore they are exposed in this interface too.
	//
	// The returned byte slices are the machine code and the relocation information for the machine code.
	// The caller is responsible for copying them immediately since the compiler may reuse the buffer.
	Compile(ctx context.Context) (_ []byte, _ []RelocationInfo, _ error)

	// Lower lowers the given ssa.Instruction to the machine-specific instructions.
	Lower()

	// RegAlloc performs the register allocation after Lower is called.
	RegAlloc()

	// Finalize performs the finalization of the compilation, including machine code emission.
	// This must be called after RegAlloc.
	Finalize(ctx context.Context) error

	// Buf returns the buffer of the encoded machine code. This is only used for testing purpose.
	Buf() []byte

	// TakeBuf returns the encoded machine-code buffer and relinquishes ownership:
	// the next Compile/Finalize allocates a fresh buffer instead of reusing this
	// one. This lets the caller retain the buffer without copying it (it would
	// otherwise be overwritten when the next function is compiled).
	TakeBuf() []byte

	BufPtr() *[]byte

	// Format returns the debug string of the current state of the compiler.
	Format() string

	// Init initializes the internal state of the compiler for the next compilation.
	Init()

	// AllocateVReg allocates a new virtual register of the given type.
	AllocateVReg(typ ssa.Type) regalloc.VReg

	// ValueDefinition returns the definition of the given value.
	ValueDefinition(ssa.Value) SSAValueDefinition

	// VRegOf returns the virtual register of the given ssa.Value.
	VRegOf(value ssa.Value) regalloc.VReg

	// TypeOf returns the ssa.Type of the given virtual register.
	TypeOf(regalloc.VReg) ssa.Type

	// MatchInstr returns true if the given definition is from an instruction with the given opcode, the current group ID,
	// and a refcount of 1. That means, the instruction can be merged/swapped within the current instruction group.
	MatchInstr(def SSAValueDefinition, opcode ssa.Opcode) bool

	// MatchInstrOneOf is the same as MatchInstr but for multiple opcodes. If it matches one of ssa.Opcode,
	// this returns the opcode. Otherwise, this returns ssa.OpcodeInvalid.
	//
	// Note: caller should be careful to avoid excessive allocation on opcodes slice.
	MatchInstrOneOf(def SSAValueDefinition, opcodes []ssa.Opcode) ssa.Opcode

	// AddRelocationInfo appends the relocation information for the function reference at the current buffer offset.
	AddRelocationInfo(funcRef ssa.FuncRef, isTailCall bool)

	// AddSourceOffsetInfo appends the source offset information for the given offset.
	AddSourceOffsetInfo(executableOffset int64, sourceOffset ssa.SourceOffset)

	// SourceOffsetInfo returns the source offset information for the current buffer offset.
	SourceOffsetInfo() []SourceOffsetInfo

	// EmitByte appends a byte to the buffer. Used during the code emission.
	EmitByte(b byte)

	// Emit4Bytes appends 4 bytes to the buffer. Used during the code emission.
	Emit4Bytes(b uint32)

	// Emit8Bytes appends 8 bytes to the buffer. Used during the code emission.
	Emit8Bytes(b uint64)

	// GetFunctionABI returns the ABI information for the given signature.
	GetFunctionABI(sig *ssa.Signature) *FunctionABI

	// CompiledBlockOffsets returns the resolved block offsets for the most
	// recently compiled function; see the Machine method of the same name.
	CompiledBlockOffsets() []CompiledBlockOffset

	// FrameSize returns the most recently compiled function's frame size;
	// see the Machine method of the same name.
	FrameSize() int64

	// SetHasEHContext forwards to the Machine method of the same name; it
	// must be called after Lower() and before RegAlloc() for the current
	// function.
	SetHasEHContext(v bool)
}

Compiler is the backend of native which takes ssa.Builder and Machine, use the information there to emit the final machine code.

func NewCompiler

func NewCompiler(ctx context.Context, mach Machine, builder ssa.Builder) Compiler

NewCompiler returns a new Compiler that can generate a machine code.

type FunctionABI

type FunctionABI struct {
	Initialized bool

	Args, Rets                 []ABIArg
	ArgStackSize, RetStackSize int64

	ArgIntRealRegs   byte
	ArgFloatRealRegs byte
	RetIntRealRegs   byte
	RetFloatRealRegs byte
}

FunctionABI represents the ABI information for a function which corresponds to a ssa.Signature.

func (*FunctionABI) ABIInfoAsUint64

func (a *FunctionABI) ABIInfoAsUint64() uint64

func (*FunctionABI) AlignedArgResultStackSlotSize

func (a *FunctionABI) AlignedArgResultStackSlotSize() uint32

func (*FunctionABI) Init

func (a *FunctionABI) Init(sig *ssa.Signature, argResultInts, argResultFloats []regalloc.RealReg)

Init initializes the abiImpl for the given signature.

type Machine

type Machine interface {
	// StartLoweringFunction is called when the compilation of the given function is started.
	// The maxBlockID is the maximum ssa.BasicBlockID in the function.
	StartLoweringFunction(maxBlockID ssa.BasicBlockID)

	// LinkAdjacentBlocks is called after finished lowering all blocks in order to create one single instruction list.
	LinkAdjacentBlocks(prev, next ssa.BasicBlock)

	// StartBlock is called when the compilation of the given block is started.
	// The order of this being called is the reverse post order of the ssa.BasicBlock(s) as we iterate with
	// ssa.Builder BlockIteratorReversePostOrderBegin and BlockIteratorReversePostOrderEnd.
	StartBlock(ssa.BasicBlock)

	// EndBlock is called when the compilation of the current block is finished.
	EndBlock()

	// FlushPendingInstructions flushes the pending instructions to the buffer.
	// This will be called after the lowering of each SSA Instruction.
	FlushPendingInstructions()

	// DisableStackCheck disables the stack check for the current compilation for debugging/testing.
	DisableStackCheck()

	// SetCurrentABI initializes the FunctionABI for the given signature.
	SetCurrentABI(abi *FunctionABI)

	// SetCompiler sets the compilation context used for the lifetime of Machine.
	// This is only called once per Machine, i.e. before the first compilation.
	SetCompiler(Compiler)

	// LowerSingleBranch is called when the compilation of the given single branch is started.
	LowerSingleBranch(b *ssa.Instruction)

	// LowerConditionalBranch is called when the compilation of the given conditional branch is started.
	LowerConditionalBranch(b *ssa.Instruction)

	// LowerInstr is called for each instruction in the given block except for the ones marked as already lowered
	// via Compiler.MarkLowered. The order is reverse, i.e. from the last instruction to the first one.
	//
	// Note: this can lower multiple instructions (which produce the inputs) at once whenever it's possible
	// for optimization.
	LowerInstr(*ssa.Instruction)

	// Reset resets the machine state for the next compilation.
	Reset()

	// InsertMove inserts a move instruction from src to dst whose type is typ.
	InsertMove(dst, src regalloc.VReg, typ ssa.Type)

	// InsertReturn inserts the return instruction to return from the current function.
	InsertReturn()

	// InsertLoadConstantBlockArg inserts the instruction(s) to load the constant value into the given regalloc.VReg.
	InsertLoadConstantBlockArg(instr *ssa.Instruction, vr regalloc.VReg)

	// Format returns the string representation of the currently compiled machine code.
	// This is only for testing purpose.
	Format() string

	// RegAlloc does the register allocation after lowering.
	RegAlloc()

	// PostRegAlloc does the post register allocation, e.g. setting up prologue/epilogue, redundant move elimination, etc.
	PostRegAlloc()

	// ResolveRelocations resolves the relocations after emitting machine code.
	//  * refToBinaryOffset: the map from the function reference (ssa.FuncRef) to the executable offset.
	//  * importedFns: the max index of the imported functions at the beginning of refToBinaryOffset
	//  * executable: the binary to resolve the relocations.
	//  * relocations: the relocations to resolve.
	//  * callTrampolineIslandOffsets: the offsets of the trampoline islands in the executable.
	ResolveRelocations(
		refToBinaryOffset []int,
		importedFns int,
		executable []byte,
		relocations []RelocationInfo,
		callTrampolineIslandOffsets []int,
	)

	// Encode encodes the machine instructions to the Compiler.
	Encode(ctx context.Context) error

	// CompileGoFunctionTrampoline compiles the trampoline function  to call a Go function of the given exit code and signature.
	CompileGoFunctionTrampoline(exitCode nativeapi.ExitCode, sig *ssa.Signature, needModuleContextPtr bool) []byte

	// CompileStackGrowCallSequence returns the sequence of instructions shared by all functions to
	// call the stack grow builtin function.
	CompileStackGrowCallSequence() []byte

	// CompileThrowTransferRegisterRestore returns a tiny callable blob
	// (execCtx in the ISA's conventional first-argument register in,
	// callee-saved registers restored from
	// native.executionContext.savedRegisters, plain return out) used by
	// the throw-time control transfer (afterThrowTransferEntrypoint /
	// (*callEngine).handleThrow) in place of a Go-call trampoline's own
	// post-exit register-restore tail, which a throw transfer bypasses
	// entirely (it jumps straight into an arbitrary landing pad, never
	// through goCallReturnAddress).
	CompileThrowTransferRegisterRestore() []byte

	// CompileEntryPreamble returns the sequence of instructions shared by multiple functions to
	// enter the function from Go.
	CompileEntryPreamble(signature *ssa.Signature) []byte

	// LowerParams lowers the given parameters.
	LowerParams(params []ssa.Value)

	// LowerReturns lowers the given returns.
	LowerReturns(returns []ssa.Value)

	// ArgsResultsRegs returns the registers used for arguments and return values.
	ArgsResultsRegs() (argResultInts, argResultFloats []regalloc.RealReg)

	// CallTrampolineIslandInfo returns the interval of the offset where the trampoline island is placed, and
	// the size of the trampoline island. If islandSize is zero, the trampoline island is not used on this machine.
	CallTrampolineIslandInfo(numFunctions int) (interval, islandSize int, err error)

	// CompiledBlockOffsets returns the resolved, function-body-relative
	// start offsets of every ssa.BasicBlock compiled in the most recent
	// Compile(), in final code-layout order. Valid only after Encode()
	// (i.e. after Finalize()) has run for the current function and
	// before the next Reset(); a block eliminated by dead-block
	// elimination is simply absent from the result. Used by the engine
	// to build the per-function exception side table (offsets of
	// try_table body ranges and catch-clause landing pads) from the
	// same block-position bookkeeping the backend already maintains
	// for branch-target resolution.
	CompiledBlockOffsets() []CompiledBlockOffset

	// FrameSize returns the most recently compiled function's total
	// fixed-frame size (clobbered-register + spill-slot area, in
	// bytes), i.e. what SP is offset by from FP/the frame's base
	// throughout the function's steady-state execution. On amd64,
	// where the exception unwinder recovers a frame's FP (RBP) but not
	// its SP directly (see backend/isa/amd64/stack.go:UnwindStackForThrow),
	// the engine uses this to compute SP = FP - FrameSize for the
	// matched catching frame before transferring control to its
	// landing pad. Valid after Finalize(), like CompiledBlockOffsets.
	FrameSize() int64

	// SetHasEHContext records, for the function about to be compiled,
	// whether it contains a try_table with catch clauses and therefore
	// needs the reserved per-frame execCtx/moduleCtx slots (see
	// EhCtxSlotOffsets). It must be called after SSA lowering and
	// before RegAlloc()/PostRegAlloc() (which reserve the frame space
	// and emit the two prologue stores respectively). When false (the
	// default, re-established by Reset()), the frame layout and prologue
	// are byte-for-byte identical to before P3.0 -- non-EH functions
	// pay nothing. This is the P3.0 "fixed frame slot" enabling
	// primitive: it only reserves space and stores execCtx/moduleCtx;
	// nothing reads the slots yet, so runtime behavior is unchanged.
	SetHasEHContext(v bool)

	// EhCtxSlotOffsets returns the SP-relative, compile-time-constant
	// byte offsets of the reserved per-frame slots that setupPrologue
	// stores execCtx and moduleCtx into (from the entry-ABI registers:
	// rax/rbx on amd64, x0/x1 on arm64). Because these slots are carved
	// out of the very bottom of the spill-slot region before the
	// register allocator hands out any of its own slots, the offsets are
	// fixed regardless of how many spill slots the function ends up
	// needing, and they are SP-relative hence relocation-safe across a
	// stack grow. Only meaningful for functions where SetHasEHContext(true)
	// was set; a later phase reloads execCtx/moduleCtx from here in
	// self-sufficient landing pads.
	EhCtxSlotOffsets() (execCtxOffset, moduleCtxOffset int64)
}

Machine is a backend for a specific ISA machine.

type RelocationInfo

type RelocationInfo struct {
	// Offset represents the offset from the beginning of the machine code of either a function or the entire module.
	Offset int64
	// Target is the target function of the call instruction.
	FuncRef ssa.FuncRef
	// IsTailCall indicates whether the call instruction is a tail call.
	IsTailCall bool
}

RelocationInfo represents the relocation information for a call instruction.

type SSAValueDefinition

type SSAValueDefinition struct {
	V ssa.Value
	// Instr is not nil if this is a definition from an instruction.
	Instr *ssa.Instruction
	// RefCount is the number of references to the result.
	RefCount uint32
}

SSAValueDefinition represents a definition of an SSA value.

func (*SSAValueDefinition) IsFromInstr

func (d *SSAValueDefinition) IsFromInstr() bool

IsFromInstr returns true if this definition is from an instruction.

type SourceOffsetInfo

type SourceOffsetInfo struct {
	// SourceOffset is the source offset in the original source code.
	SourceOffset ssa.SourceOffset
	// ExecutableOffset is the offset in the compiled executable.
	ExecutableOffset int64
}

SourceOffsetInfo is a data to associate the source offset with the executable offset.

Directories

Path Synopsis
isa
Package regalloc performs register allocation.
Package regalloc performs register allocation.

Jump to

Keyboard shortcuts

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