ir

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Jul 6, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package ir is the compiler's mid-level intermediate representation: a statement-level CFG of BasicBlocks holding IR nodes. It is a Go port of sonolus.py's sonolus/backend (ir.py, place.py, optimize/flow.py, finalize.py).

The IR is CFG-shaped and mutable (suited to SSA + optimization passes). It is distinct from snode.SNode, which is the final immutable node tree. finalize.go bridges the two: CFGToSNode lowers an optimized CFG into an snode.SNode.

Index

Constants

View Source
const (
	BlockEntityMemory  = 4000
	BlockEntityData    = 4001
	BlockEntityShared  = 4002
	BlockEntityInfo    = 4003
	BlockEntityDespawn = 4004
	BlockEntityInput   = 4005
	BlockEntityScore   = 4006
	BlockEntityLife    = 4007
	BlockTempMemory    = 10000
)

Canonical block ID constants referenced by all packages. Values must match the blockTables above.

View Source
const (
	BlockRuntimeEnvironment = 1000
	BlockRuntimeUpdate      = 1001 // RuntimeCanvas in Preview mode
	BlockRuntimeTouch       = 1002
	BlockEngineRom          = 3000
	TouchFieldStride        = 9
)

Runtime memory block IDs used by the Sonolus engine across all modes.

View Source
const (
	// Arithmetic
	OpAdd      = resource.RuntimeFunctionAdd
	OpSubtract = resource.RuntimeFunctionSubtract
	OpMultiply = resource.RuntimeFunctionMultiply
	OpDivide   = resource.RuntimeFunctionDivide
	OpPower    = resource.RuntimeFunctionPower
	OpMod      = resource.RuntimeFunctionMod
	OpRem      = resource.RuntimeFunctionRem
	OpNegate   = resource.RuntimeFunctionNegate
	OpAbs      = resource.RuntimeFunctionAbs
	OpSign     = resource.RuntimeFunctionSign

	// Comparison
	OpEqual     = resource.RuntimeFunctionEqual
	OpNotEqual  = resource.RuntimeFunctionNotEqual
	OpLess      = resource.RuntimeFunctionLess
	OpLessOr    = resource.RuntimeFunctionLessOr
	OpGreater   = resource.RuntimeFunctionGreater
	OpGreaterOr = resource.RuntimeFunctionGreaterOr

	// Logic
	OpAnd = resource.RuntimeFunctionAnd
	OpOr  = resource.RuntimeFunctionOr
	OpNot = resource.RuntimeFunctionNot

	// Min / Max / Clamp
	OpMax   = resource.RuntimeFunctionMax
	OpMin   = resource.RuntimeFunctionMin
	OpClamp = resource.RuntimeFunctionClamp

	// Math
	OpLog   = resource.RuntimeFunctionLog
	OpCeil  = resource.RuntimeFunctionCeil
	OpFloor = resource.RuntimeFunctionFloor
	OpRound = resource.RuntimeFunctionRound
	OpFrac  = resource.RuntimeFunctionFrac
	OpSin   = resource.RuntimeFunctionSin
	OpCos   = resource.RuntimeFunctionCos
	OpTan   = resource.RuntimeFunctionTan
	OpSinh  = resource.RuntimeFunctionSinh
	OpCosh  = resource.RuntimeFunctionCosh
	OpTanh  = resource.RuntimeFunctionTanh
	OpAsin  = resource.RuntimeFunctionArcsin
	OpAcos  = resource.RuntimeFunctionArccos
	OpAtan  = resource.RuntimeFunctionArctan
	OpAtan2 = resource.RuntimeFunctionArctan2
	OpRad   = resource.RuntimeFunctionRadian
	OpDeg   = resource.RuntimeFunctionDegree

	// Interpolation / remapping
	OpLerp         = resource.RuntimeFunctionLerp
	OpLerpClamped  = resource.RuntimeFunctionLerpClamped
	OpRemap        = resource.RuntimeFunctionRemap
	OpRemapClamped = resource.RuntimeFunctionRemapClamped

	// Control flow
	OpIf                       = resource.RuntimeFunctionIf
	OpWhile                    = resource.RuntimeFunctionWhile
	OpSwitch                   = resource.RuntimeFunctionSwitch
	OpSwitchInteger            = resource.RuntimeFunctionSwitchInteger
	OpSwitchWithDefault        = resource.RuntimeFunctionSwitchWithDefault
	OpSwitchIntegerWithDefault = resource.RuntimeFunctionSwitchIntegerWithDefault

	// Memory
	OpGet        = resource.RuntimeFunctionGet
	OpGetShifted = resource.RuntimeFunctionGetShifted
	OpSet        = resource.RuntimeFunctionSet
	OpSetShifted = resource.RuntimeFunctionSetShifted

	// Block / execution
	OpExecute  = resource.RuntimeFunctionExecute
	OpBlock    = resource.RuntimeFunctionBlock
	OpJumpLoop = resource.RuntimeFunctionJumpLoop
)

Canonical short aliases for runtime functions used throughout the compiler. These replace bare resource.RuntimeFunction* literals and the previously duplicated op* / rf* aliases in ir/optimize, ir/finalize, and snode.

ir/finalize.go and ir/optimize use these directly. snode keeps its own independent aliases (with the same names) because ir imports snode, so snode cannot import ir without a cycle.

View Source
const DefaultTempMemoryBlock = BlockTempMemory

DefaultTempMemoryBlock is the memory block temps are allocated into by default (sonolus.py play-mode TemporaryMemory). This is an alias for BlockTempMemory defined in blocks.go.

Variables

This section is empty.

Functions

func CFGToSNode

func CFGToSNode(gen *IDGen, entry *BasicBlock) (snode.SNode, error)

CFGToSNode lowers an (optimized) CFG into a single snode.SNode tree, encoding inter-block control flow as a Block(JumpLoop(...)) of per-block Execute nodes. Port of sonolus.py finalize.cfg_to_engine_node.

func Cond

func Cond(v float64) *float64

Cond returns a pointer to a branch condition value, for use with ConnectTo.

func FloorMod

func FloorMod(a, b float64) float64

FloorMod computes a floored modulo (result has the sign of the divisor), matching Python's % and the runtime RuntimeFunctionMod semantics. Used by frontend constant folding (value.go) and SCCP (sccp.go).

func IEEERem

func IEEERem(a, b float64) float64

IEEERem computes IEEE 754 remainder, matching the runtime RuntimeFunctionRem semantics. Used by frontend constant folding and SCCP for compile-time evaluation.

func Lower

func Lower(n Node) (snode.SNode, error)

Lower converts a single IR node into an snode.SNode. Port of finalize.ir_to_engine_node.

func Pure

func Pure(op Op) bool

Pure reports whether an operation is pure (side-effect-free and deterministic in its arguments). The classification is generated from sonolus.py's Op.pure.

func SideEffects

func SideEffects(op Op) bool

SideEffects reports whether an operation has observable side effects. The classification is generated from sonolus.py's Op.side_effects.

func Walk

func Walk(n Node, visit func(Node))

Walk traverses the IR tree depth-first, calling visit for each node. Nodes are visited bottom-up: children first, then the node itself. Unlike Map, Walk does not reconstruct nodes — it is intended for read-only analysis (use counting, liveness collection, etc.).

Nil nodes are visited as-is (visit(nil) is called). Callers that collect nodes into a slice should guard against nil entries.

Types

type BasicBlock

type BasicBlock struct {
	Phis       []*Phi
	Statements []Node
	Test       Node // defaults to Const(0)
	Incoming   []*FlowEdge
	Outgoing   []*FlowEdge
}

BasicBlock is a CFG node: phi nodes, a list of statements, a branch test expression, and incoming/outgoing edges. Port of sonolus.py BasicBlock.

func AllocateTestBlocks

func AllocateTestBlocks(entry *BasicBlock, blockID int) (*BasicBlock, error)

AllocateTestBlocks is the exported test-only wrapper around allocateTempBlocks. It assigns each distinct TempBlock a slot in the given memory block (no reuse, deterministic first-seen order).

Production code must use optimize.AllocateLive instead. This function is exported solely for unit tests that need a pre-SSA, pre-optimize allocation, because those tests call the frontend tracer directly and the result contains unresolved TempBlocks.

func NewBlock

func NewBlock() *BasicBlock

NewBlock creates an empty block with a default test of Const(0).

func Preorder

func Preorder(entry *BasicBlock) []*BasicBlock

Preorder returns reachable blocks in a BFS preorder that visits outgoing edges in sortedOutgoing order. Mirrors sonolus.py traverse_cfg_preorder.

func ReversePostorder

func ReversePostorder(entry *BasicBlock) []*BasicBlock

ReversePostorder returns reachable blocks in reverse-postorder (the order used for block numbering in finalization and dominance).

func (*BasicBlock) ConnectTo

func (b *BasicBlock) ConnectTo(other *BasicBlock, cond *float64)

ConnectTo adds an edge from b to other with the given condition (nil = default).

type BlockPlace

type BlockPlace struct {
	Block  Node
	Index  Node // nil is treated as Const(0)
	Offset int
}

BlockPlace addresses block[index + offset]. Block and Index are themselves IR nodes (typically Const for concrete block ids / indices, but may be expressions). Mirrors sonolus.py BlockPlace.

func Cell

func Cell(block, index int) BlockPlace

Cell is a convenience for a fixed block[index] location with constant ids.

func NewBlockPlace

func NewBlockPlace(block, index Node, offset int) BlockPlace

NewBlockPlace builds a BlockPlace addressing block[index + offset].

func TempCell

func TempCell(t *TempBlock) BlockPlace

TempCell returns the place for a size-1 temp block.

type BlockSet

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

BlockSet answers block read/write questions for a given mode. It satisfies the optimizer's BlockOracle interface structurally.

func Blocks

func Blocks(mode Mode) BlockSet

Blocks returns the block model for a mode.

func (BlockSet) RuntimeConstant

func (b BlockSet) RuntimeConstant(id int) bool

RuntimeConstant reports whether the block holds runtime-constant data.

func (BlockSet) Writable

func (b BlockSet) Writable(id int, callback string) bool

Writable reports whether the block may be written in the given callback. Unknown blocks are assumed writable (conservative: not safe to inline reads).

type Const

type Const float64

Const is a numeric literal (sonolus.py IRConst). Non-finite values lower to ROM reads during finalization.

type FlowEdge

type FlowEdge struct {
	Src  *BasicBlock
	Dst  *BasicBlock
	Cond *float64
}

FlowEdge is a directed CFG edge with a branch condition. Cond semantics (matching sonolus.py): nil = unconditional / default / true branch; 0 = false branch; other numbers = switch cases.

type Get

type Get struct {
	Place Place
}

Get reads a memory place (sonolus.py IRGet).

func GetPlace

func GetPlace(p Place) Get

GetPlace reads a memory place.

type IDGen

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

IDGen generates monotonic node identifiers for a single compilation. Each compilation entry point creates one IDGen and threads it through the frontend tracer, optimizer pipeline, and finalizer. This eliminates shared mutable state, making concurrent compilations safe.

func NewIDGen

func NewIDGen() *IDGen

NewIDGen returns a fresh ID generator starting at 1.

func (*IDGen) ImpureInstr

func (g *IDGen) ImpureInstr(op Op, args ...Node) Instr

ImpureInstr builds an operation node that may have side effects.

func (*IDGen) Next

func (g *IDGen) Next() int

Next returns the next monotonic ID from this generator.

func (*IDGen) PureInstr

func (g *IDGen) PureInstr(op Op, args ...Node) Instr

PureInstr builds a side-effect-free operation node.

func (*IDGen) SetPlace

func (g *IDGen) SetPlace(p Place, value Node) Set

SetPlace writes a value to a memory place.

type Instr

type Instr struct {
	ID   int
	Op   Op
	Args []Node
	Pure bool
}

Instr is an operation applied to argument nodes. Pure marks side-effect-free operations (sonolus.py distinguishes IRPureInstr from IRInstr); the flag is for optimization passes and does not affect lowering. ID is a monotonic identifier used by liveness analysis.

type Mode

type Mode int

Mode is a Sonolus engine mode; each has its own memory block layout.

const (
	ModePlay Mode = iota
	ModeWatch
	ModePreview
	ModeTutorial
)

func (Mode) String

func (m Mode) String() string

String returns the canonical mode name ("play", "watch", "preview", "tutorial").

type Node

type Node interface {
	// contains filtered or unexported methods
}

Node is any IR node that can be lowered to an snode.SNode.

func Map

func Map(n Node, fn func(Node) Node) Node

Map transforms the IR tree bottom-up. For each node, children are mapped first (with recursive calls to Map), then a structurally-equivalent node is reconstructed with the new children (preserving Instr.ID, Set.ID, and Instr.Pure), and finally fn is called on that result. fn may return a different node to replace the original.

type Op

Op is an IR/runtime operation. It shares the runtime function vocabulary with the final node list.

type Phi

type Phi struct {
	Var    *TempBlock
	Target Place
	Args   map[*BasicBlock]Place
}

Phi is an SSA phi node placed at a control-flow merge. Var is the original variable (the temp block) it was created for; Target is the SSA value it defines (assigned during SSA renaming); Args maps each predecessor block to the SSA value flowing in along that edge.

INVARIANT: During SSA form (between ToSSA and FromSSA), Target and all Args values are of concrete type SSAPlace. After FromSSA, phis are removed — they should never appear in post-SSA passes. Unchecked type assertions to ir.SSAPlace in ssa.go, sccp.go, and inlining.go depend on this invariant.

type Place

type Place interface {
	Node
	// contains filtered or unexported methods
}

Place is an addressable memory location: a BlockPlace or an SSAPlace. Port of sonolus.py place.py.

type SSAPlace

type SSAPlace struct {
	Name string
	Num  int
}

SSAPlace is an SSA value (sonolus.py SSAPlace). It must be removed by register allocation before finalization.

func (SSAPlace) String

func (p SSAPlace) String() string

type Set

type Set struct {
	ID    int
	Place Place
	Value Node
}

Set writes value to a memory place (sonolus.py IRSet). ID is a monotonic identifier used by liveness analysis.

type TempBlock

type TempBlock struct {
	Name string
	Size int
}

TempBlock is a virtual scratch block backing a local variable (sonolus.py TempBlock). It is identified by pointer: each local gets one TempBlock that is shared by all its accesses. TempBlock-backed places must be resolved to a concrete memory block by allocateTempBlocks before finalization.

func NewTemp

func NewTemp(name string) *TempBlock

NewTemp creates a size-1 scratch block named name.

Directories

Path Synopsis
Package optimize holds CFG optimization passes, ported from sonolus.py's sonolus/backend/optimize.
Package optimize holds CFG optimization passes, ported from sonolus.py's sonolus/backend/optimize.

Jump to

Keyboard shortcuts

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