# Compiler and bytecode VM

> How eaxPLC compiles Structured Text to bytecode, lays out memory for variables and function blocks, and executes it in a zero-allocation stack VM.

Product: eaxPLC · Type: Explanation · Editions: Free, Pro
Source: https://eaxware.com/docs/eaxplc/explanation/compiler-and-vm/
Verified against commit d7a6b29.

## 1. Structured Text Compilation Pipeline

**Diagram: From Structured Text to code that runs** (data flow)

The project's Structured Text goes through the lexer and the parser, then the bytecode compiler, which checks it and takes the variables' offsets from the layout manager. A parse or compile error refuses the text and nothing that runs changes. The bytecode runs on the VM; on amd64 it is also compiled to machine code, elsewhere to a native plugin built in the background.

**Parts**

- **ST text** (file or document): the project
- **Lexer** (service or process): tokens
- **Parser** (service or process): the syntax tree
- **Bytecode compiler** (service or process): checks, then the code; offsets from the layout manager
- **Refused** (outcome): nothing changes
- **Bytecode** (file or document): the project's program
- **Bytecode VM** (service or process): every CPU, the fallback
- **Machine code (JIT)** (service or process): from the first scan
- **Native plugin** (service or process): built in the background

**Connections**

- **ST text → Lexer** (data or telemetry)
- **Lexer → Parser** (data or telemetry)
- **Parser → Bytecode compiler** (data or telemetry)
- **Parser → Refused** (refusal): parse error
- **Bytecode compiler → Refused** (refusal): compile error
- **Bytecode compiler → Bytecode** (data or telemetry)
- **Bytecode → Bytecode VM** (data or telemetry): always. The VM runs the bytecode on every CPU, and it keeps running when a machine-code or plugin build fails.
- **Bytecode → Machine code (JIT)** (data or telemetry): amd64. On amd64, in the executor mode auto or jit, the deploy compiles the bytecode to machine code, which runs from the first scan.
- **Bytecode → Native plugin** (data or telemetry): other CPUs. On other CPUs where a plugin can be loaded (executor mode auto), or in the mode native, the bytecode is transpiled to Go and built as a plugin in the background; it is swapped in at a cycle boundary once loaded, and the VM runs until then.

A deploy, a test and a check take the same path, so a check accepts exactly what a deploy accepts.

### 1.1 Lexer (`pkg/compiler/lexer.go`)
- Tokenizes Structured Text keywords (`PROGRAM`, `VAR`, `END_VAR`, `IF`, `THEN`, `ELSIF`, `ELSE`, `END_IF`).
- Parses radix/base literals:
  - `16#1A2F` (Hexadecimal)
  - `2#1100_0011` (Binary with optional underscores)
  - `8#755` (Octal)
- Parses IEC time literals:
  - `T#500ms`, `T#2s`, `T#1h30m`

### 1.2 Layout Manager (`pkg/compiler/layout_manager.go`)
- Allocates the variables without an `AT` address upwards from the `%M` base, which follows the CPU tier's memory partition (`%M` after `%I` and `%Q`: offset `2048` on the base 6144-byte image), into the extended area if needed, and skips every byte the program addresses directly. Offsets are kept across compiles and never reused.
- Enforces strict 8-byte alignment for composite Function Blocks to prevent unaligned memory faults on ARM/x86 architectures.
- Memory Footprint Table:
  - Standard types: `BOOL` (1 byte), `BYTE`/`USINT`/`SINT` (1 byte), `INT`/`UINT`/`WORD` (2 bytes), `DINT`/`UDINT`/`DWORD`/`REAL`/`TIME` (4 bytes), `LINT`/`LREAL` (8 bytes).
  - Function Blocks:
    - `TON`, `TOF`, `TP`, `RTC`, `CTU`, `CTD`, `CTUD`: 24 Bytes (8-byte aligned)
    - `SR`, `RS`, `SEMA`, `R_TRIG`, `F_TRIG`: 8 Bytes
    - `BLINK`, `GEN`, `FREQ_MEASURE`, `RAMP_REAL`, `RAMP_INT`, `HYSTERESIS`, `LIMITALARM`, `LIN_TRAFO`, `DERIVATIVE`, `INTEGRAL`, `STATISTICS_INT`, `STATISTICS_REAL`, `VARIANCE`: 32 Bytes
    - `PID`, `PD`, `PID_FIXCYCLE`, `CHARCURVE`: 64 Bytes

---

## 2. Bytecode Opcode Reference

| Opcode | Mnemonic | Description |
| :--- | :--- | :--- |
| `0` | `OpNop` | No operation |
| `1` | `OpLoadX` | Load 1-bit boolean from memory bit address onto stack |
| `2` | `OpStoreX` | Store top-of-stack boolean into memory bit address |
| `7` | `OpLoadD` | Load 32-bit value (`DINT`, `DWORD`, `REAL`, `TIME`) from memory offset |
| `8` | `OpStoreD` | Store top-of-stack 32-bit value into memory offset |
| `12` | `OpPushU32` | Push 32-bit immediate literal onto stack |
| `14` | `OpAddI` | Integer addition: `stack[sp-2] + stack[sp-1]` |
| `15` | `OpSubI` | Integer subtraction: `stack[sp-2] - stack[sp-1]` |
| `16` | `OpMulI` | Integer multiplication: `stack[sp-2] * stack[sp-1]` |
| `17` | `OpDivI` | Integer division: `stack[sp-2] / stack[sp-1]` |
| `18` | `OpModI` | Modulo operation |
| `19` | `OpAnd` | Bitwise / logical AND |
| `20` | `OpOr` | Bitwise / logical OR |
| `21` | `OpNot` | Logical NOT |
| `22` | `OpEq` | Equality comparison (`=`) |
| `25` | `OpGt` | Greater than comparison (`>`) |
| `33` | `OpJmp` | Unconditional jump to bytecode instruction index |
| `34` | `OpJmpFalse`| Jump if top of stack is `0` (false) |
| `36` | `OpCallTon` | Execute `TON` On-Delay timer block at struct offset |
| `45` | `OpCallBlink`| Execute `BLINK` asymmetrical pulse train block at struct offset |
| `47` | `OpCallGen` | Execute `GEN` waveform generator block at struct offset |
| `52` | `OpCallPid` | Execute `PID` closed-loop controller at struct offset |
| `91` | `OpHalt` | End of program scan cycle |

---

## 3. Zero-Allocation Stack VM (`pkg/compiler/vm.go`)

- Fixed 256-entry `uint64` evaluation stack (`[256]uint64`).
- Stack pointer `sp` tracks depth.
- Direct pointer casting to function block structures inside process memory:
  ```go
  case OpCallGen:
      genState := (*fb.GEN)(mem.GetPtr(int(inst.Offset)))
      genState.Update(genState.MODE, genState.BASE, genState.PERIOD, genState.CYCLES, genState.AMPLITUDE, genState.RESET, nowMs)
  ```
- Evaluates instructions in under 10 nanoseconds per opcode with zero garbage collection overhead.

---

## 4. Arrays of Function Block Instances

### 4.1 Syntax
An array may hold instances of a library block (`TON`, `CTU`, `PID` ...) or of a user `FUNCTION_BLOCK`. Its elements are called, read and written like named instances:

```text
VAR
    v     : ARRAY[1..400] OF FB_Valve;
    g     : ARRAY[1..2, 1..3] OF FB_Valve;   (* 2-D: an array of arrays *)
    t     : ARRAY[0..7] OF TON;
    em    : FB_EM;                           (* holds valves : ARRAY[1..3] OF FB_Valve *)
    i, j  : INT;
END_VAR

FOR i := 1 TO 400 DO
    v[i](Open := Cmd[i], Pos => Pos[i]);     (* inputs :=, outputs => *)
END_FOR;
FOR i := 1 TO 2 DO FOR j := 1 TO 3 DO g[i, j](); END_FOR; END_FOR;
t[i](IN := Run, PT := T#2s);
em.valves[i](Open := TRUE);                  (* through a member *)
v[i].inner(...);                             (* a block inside an element *)
Done := v[3].Cmd;                            (* read an output *)
v[3].Open := TRUE;                           (* write an input *)
```

- `ARRAY[a..b, c..d] OF X` is an array of arrays: `g[i, j]` and `g[i][j]` are the same element.
- A call is valid on an indexed or member expression (`FBCallStmt.Instance`), not only on a bare name.

### 4.2 Semantics
- **State per element.** Every element is a full instance with its own storage in the process image. Each element starts with the block's initial values, and keeps its state from scan to scan.
- **Index evaluated once.** The instance address of a call is computed once per call: the index expressions are evaluated and range-checked once, whatever the number of inputs and outputs. A side effect in an index happens once.
- **Out of range is a fault.** An index outside the declared bounds stops the scan with `ErrIndexRange` ("array index out of range"), exactly like any other out-of-range array index. Nothing is clamped or wrapped.
- **Whole-block copies** into an indexed element (`v[i] := proto;`) work (`OpAddr`, `OpSwap`).

### 4.3 Code generation: one body, a base register
- A **user FB body is compiled once per type** and shared by all the elements of every array of that type. It runs on a **base register** (instructions flagged `FlagBase` address the instance relative to the base).
- **Named instances are unchanged.** Each keeps its own body at fixed addresses.
- **VM:** `OpCallSub` saves the base and sets it to the element's address. `OpRet` restores it. `OpCallSub` carries `Imm = size<<32 | pc`, the instance size and the body's entry. The base register and its call stack sit at the end of the VM struct, off the interpreter's hot fields, so a program without arrays of FBs runs at its old speed.
- **JIT (amd64):** the base lives in `jitCtx`. At the call, the JIT checks once that the whole instance lies inside the image. Based accesses, `OpAddr`, `OpSwap` and the inline `R_TRIG`/`F_TRIG` then run without a check per access. The transpiler's region functions take the base as a parameter.
- **JIT verifier.** Because based accesses are not bounds-checked one by one, `assembleJIT` first verifies the bytecode. It refuses:
  - a base-relative access without an element offset outside a shared FB body;
  - a body that is also called as a fixed instance;
  - a body called without its instance size;
  - any based access that reaches past the instance (loads, stores, strings, library and nested block calls).

  A refused program runs on the interpreter, as with any other JIT assemble error.
- **Code size.** 400 `FB_Valve` elements in a `FOR` loop compile to 56 instructions (the same as for 10 elements). 400 named instances compile to 12 003.

### 4.4 Cost per scan: VM vs JIT
`BenchmarkFBArrayVsNamed` (`pkg/compiler/fb_array_jit_test.go`) runs one scan of 400 pharma-line actuators, written as an array in a `FOR` loop and as 400 named instances:

| Executor | Array vs named instances |
| :--- | :--- |
| VM (interpreter) | about **36 % slower**: the loop, the index check and the base switch per call cost more than fixed addresses |
| JIT | about **2.8× faster**: one compact shared body stays in the instruction cache, instead of 400 copies |

On 2026-10-17, with other load on the workstation, a re-run gave: array 314 µs vs named 216 µs on the VM (+45 %), and array 42 µs vs named 119 µs on the JIT (2.8×).

Choose by executor: on the JIT, an array of instances is both smaller and faster. On the interpreter, it is smaller but slower per scan.

### 4.5 Cross-reference and the AI guard
- **Cross-reference.** A call of an element is recorded on the array, as a partial reference. An array of FBs carries `fb_type` (the elements' type), and the editor's completion uses it: `v[i].`, `g[i, j].` and `em.valves[k].` offer the type's members, and `v[i](` offers its parameters.
- **AI guard.** A safety target on an element's member (`V[3].Cmd`, `g[1, 2].Cmd`) also protects that member in the shared body of the FB type, for every element, because the body runs for all of them.
  - Safety targets take one or more integer indexes per name.
  - `g[1][2].Cmd`, `g[1,2].Cmd` and `G[1, 2].cmd` are the same target. It is stored with its indexes in one spelling (`g[1, 2].Cmd`), and listing two spellings of it in the list set on the PLC is refused as a duplicate. In the list eaxScada signs, a tag on an element (`…/plc-01/g/1/2/Cmd`) becomes the target `g[1][2].Cmd`, and two tags on one element sign one target.
- **A target listed twice.** Two entries are the same target when their names differ only in letter case (`EStop`, `ESTOP`) or their indexes only in spelling (`g[1][2].Cmd`, `g[ 1,2 ].Cmd`, `g[01, 2].Cmd`).
  - In the list set on the PLC (Project Settings, `POST /api/deploy/safety-targets`) the save is refused with *`g[1, 2].Cmd` is listed twice* and the list in force does not change. A list file edited by hand with a duplicate is invalid: the PLC then has no list and refuses every AI-made program until an engineer saves the list again.
  - In the list eaxScada signs, the same spelling twice is refused (*listed twice*). Two spellings of one element are accepted as signed; the PLC applies that target once, in its stored spelling.
  - A target in both lists applies once and is shown as a local target: the signed list only adds targets, it never replaces or removes a local one.
- **A write that matches two targets** (a target and a part of it, `Safety1` and `Safety1.Out`; or the member two elements share in the FB body, `V[1].Cmd` and `V[2].Cmd`) is refused once per written symbol, naming one of the targets it matches. Removing one of the two targets leaves the symbol protected while the other still covers it.
- **Targets in a program with several PROGRAMs.**
  - A variable of a program other than the main one is listed with its program: `Line2.Speed`, `Line2.Valve.Q`, `Line2.Arr[3]`.
  - An unscoped name (`Speed`) is the main program's variable.
  - When another PROGRAM also declares that name, the list does not say which variable it protects: an AI-made deploy is refused with `ai_safety_target_ambiguous`, naming the programs and the scoped spellings to list (`Line2.Speed`, or the main program's `Main.Speed`), until the list scopes it.
  - While an AI-made program runs, the scan pin protects every copy of an unscoped name: the main program's and each other PROGRAM's variable of that name.
  - `POST /api/deploy/ai-status` says it before the deploy: `refused: true`, `code: "ai_safety_target_ambiguous"` and `ambiguous`, one line per ambiguous target.
