---
title: "Control flow in TypeShade: branches, loops and kernels"
description: "How familiar TypeScript conditionals and loops map to the TypeShade GPU execution model."
url: https://typeshade.dev/guide/language/control-flow/
language: en
---

# Control flow: familiar syntax, explicit GPU execution

TypeShade uses familiar TypeScript conditional and loop syntax, but the code executes on the GPU. Understand control flow in terms of compilable computation, not the full dynamic behavior of the JavaScript runtime.

## 1. TypeScript control flow

Syntax such as `if`/`else` and `for` is familiar, but every condition and loop in TypeShade must be lowerable to GPU code. Matching syntax does not imply that all JavaScript runtime semantics are available.

## 2. Branches

TypeShade chooses between paths with the `if` statement and with the conditional expression.

### The `if` statement

Use `if`/`else` to express calculation paths. Inside a branch, keep values and resources within the TypeShade GPU model.

```ts
@compute([64, 1, 1])
export function paint(gid: builtin<"global_invocation_id">) {
  if (camera.pos.x > 0) {
    pixels[gid.x] = 1
  } else {
    pixels[gid.x] = 0
  }
}
```

### The conditional expression

A value chosen by a condition is written `c ? a : b`. WGSL has no `?:` operator. For a scalar or a vector, the WGSL emit is `select(b, a, c)`, with the false value first and the condition last. WGSL evaluates both values. Writing `select(f, t, c)` yourself is a call, not a conditional: it evaluates `f`, `t` and `c`, in that order, whichever value it picks, so write `c ? t : f` when only one arm should run.

### Costly arms

An arm that calls a function of the file, reads a texture or holds eight or more operations is lowered to a variable and an `if` by the compiler, so only the arm taken runs ([Rule 7.2](https://typeshade.dev/reference/rules/7-2/)). A cheap arm stays `select`. GLSL ES 3.00 keeps `?:` for the cheap arm and takes the same `if` for the costly one. A struct or an array is chosen through a variable and an `if` on both targets.

## 3. Loops

A loop is written as a statement or as an array method.

### Loop statements

Write a `for` loop, a `while` loop, or `for...of` over an array. A `for` loop may count to a value known only at run time, such as a uniform field or the length of an array.

```ts
for (let i = 0; i < 4; i++) {
  pixels[i] = pixels[i] + camera.pos.x
}
```

### Array methods

An array's `map`, `forEach`, `some`, `every`, `reduce`, `fill`, `findIndex`, `findLastIndex`, `indexOf`, `lastIndexOf` and `includes` compile too, each to a counted loop, and `map` takes an array with a fixed length.

## 4. Kernel functions

A kernel function holds loops that the compiler may run on the GPU. The sections below state what makes one, which loops run, how the workgroup is sized and what the compiler reports.

### What a kernel function is

An exported function that is not an entry point and takes an array with no size, `array<T>`, or a 2D storage texture, `texture_storage_2d<F, A>`, is a kernel function ([Rule 8.22](https://typeshade.dev/reference/rules/8-22/)). So is one that returns an array with no size that its body makes ([Rule 8.23](https://typeshade.dev/reference/rules/8-23/)). A sampled texture alone makes none, so an exported helper that reads one stays a helper. The array or the texture a kernel function takes is the caller's, read and written in place. The body writes the elements of the array but cannot assign the array whole ([`TS8018`](https://typeshade.dev/reference/errors/ts8018/)), and `return xs` gives back the same array with no copy. No qualifier is written on the parameter; `@inout` and `@out` are refused ([`TS8073`](https://typeshade.dev/reference/errors/ts8073/)). A method that changes its object, called on an element of the array, is a write to that element, as an argument of a parameter that its function writes is, for the proof of the loops ([Rule 8.29](https://typeshade.dev/reference/rules/8-29/)).

Each `for` at the top of its body is a loop the compiler may run on the GPU, one invocation per iteration, and a host file awaits the function like any import. No `compute` call, binding or `global_invocation_id` is written.

```ts
export function render(k: vec4, size: u32, out: array<f32>) {
  for (let i: u32 = 0; i < size * size; i++) {
    const p = vec2(f32(i % size), f32(i / size)) / f32(size)
    out[i] = k.x * sin(p.x * k.y) + k.z * cos(p.y * k.w)
  }
}
```

### Loops that run on the GPU

The compiler runs a loop on the GPU when it proves that no iteration touches what another one does. The loop is a counted `for`, or a `for...of`, that steps by a constant and that nothing returns from or breaks out of.

Each write lands on a name declared inside the loop, on an outer array or a texture at an index made from the loop's own, on an integer array the loop combines into at any index, on a variable the loop combines with `+=`, `*=`, `min`, `max`, `&`, `|` or `^`, which the GPU and the CPU fold in one tree order, on an array the loop only appends to with `push`, or on a `Map` or a `Set` the loop adds to.

The loop reads an array it writes only where it writes it. It never reads a variable it combines, an array it appends to or a `Map` or a `Set` it adds to. It calls no function that writes a module variable or a binding, and has no barrier, no workgroup memory and no `console` call.

### Workgroup size

`@workgroup_size([128])` before `export function scale(…) { … }` states the workgroup size of its loops on WebGPU, which is 64 without it. A loop that reduces always runs in workgroups of 256, so `@workgroup_size` on a function with such a loop is refused ([`TS8077`](https://typeshade.dev/reference/errors/ts8077/)).

### The last workgroup

The last workgroup of a dispatch holds the lanes past the loop's last iteration, and none of them returns early. A workgroup wholly past the end returns as one. In the workgroup that holds the last iteration, such a lane runs that iteration again with every write masked. So every lane of a workgroup runs the same control flow, the form that completed on a D3D12 device where an early return hung.

Where that lane would read what another lane writes, it skips the iteration under the same flag. The results do not change on any tier.

### Array methods in a kernel function

The methods of an array but `map` work on a kernel function's array too: `forEach`, `reduce`, `some`, `every`, `fill`, `findIndex`, `findLastIndex`, `indexOf`, `lastIndexOf` and `includes` ([Rule 8.18](https://typeshade.dev/reference/rules/8-18/)). Each is the loop it stands for, written into the function where the call is, with the function handed over as the loop's body. The proof reads it as it reads a `for` loop, so both loops below run on the GPU: `forEach` writes `out` at its own index, and `reduce` with `+` is a reduction.

```ts
export function stats(xs: array<f32>, out: array<f32>): f32 {
  xs.forEach((x, i) => {
    out[i] = x * 2.
  })
  const s = xs.reduce((a, x) => a + x * x, 0.)
  return sqrt(s)
}
```

A `reduce` adds in the tree order of a reduction on every tier, and TypeScript adds from left to right, so an `f32` sum may differ in the last places. The determinism report lists it as `order` (Rule 7.2). `some`, `every` and `includes` are an `|` and an `&` over every element. `findIndex`, `indexOf` and their `Last` forms are a `min` or a `max` of the index, which give the answer of the first element that decides. A function handed over runs for every element, so one that writes what it captures is refused.

### Refused loops

A loop the proof refuses runs on the CPU, and the program is correct either way. The proof never looks at a loop in an entry, a helper or a fragment shader, which stays per-invocation code. The compiler marks a refused loop with the warning [`TS8070`](https://typeshade.dev/reference/errors/ts8070/): its first sentence names the line and the names in your code, and its second gives the remedy. At the pinned compiler the warnings read:

| Rule | Warning |
| --- | --- |
| `R1` | `This loop runs on the CPU because it is an open loop, a while or a for that is not counted, whose trip count is known only when it ends. A counted for loop runs on the GPU.` |
| `R1` | `This loop runs on the CPU because "stride /= 2" does not step through a range of indices. Step by adding a constant.` |
| `R2` | `This loop runs on the CPU because line 9 returns from inside it, so whether an iteration runs depends on the ones before it. Record the result in an array and read it after the loop.` |
| `R3` | `This loop runs on the CPU because line 49 writes "nearest", which the next iteration reads. Declare it inside the loop, or combine it with one of += *= min max & \| ^.` |
| `R3` | `This loop runs on the CPU because line 4 writes "b[idx[i]]", an element two iterations can share. Write at an index made from "i".` |
| `R4` | `This loop runs on the CPU because line 9 reads "out[i - 1]", which another iteration writes. Read from an array the loop does not write.` |
| `R5` | `This loop runs on the CPU because line 7 calls "tally", which writes "calls". Return the value from "tally" and combine it in the loop instead.` |
| `R6` | `This loop runs on the CPU because line 5 calls console.log, whose lines would print in another order on the GPU. Log after the loop.` |

### Upload layout

An ordinary WebGPU kernel call can upload only live fields of a read-only object array. Flat `f32`, `i32` and `u32` fields keep declaration order. Every declared host field is still validated, with property-read order preserved. Written inputs, `Buffer`s, inputs inside a `fuse` body and unproved inputs keep the full layout; so do modules built with `typeshade({ fuse: true })`. Entry bindings, reflection, manifests and raw bytes keep their external layout. CPU and WebGL2 retain their representation. Smaller uploads do not guarantee a faster complete call; physical-device measurements remain necessary.

## 5. Collecting results

A loop in a kernel function collects results into an array with `push`, or into a `Map` or a `Set`.

### Appending with `push`

A loop appends to an array parameter with `out.push(v)`, as a statement, any number of times in an iteration and in any branch. The array starts empty in the function. The elements land in the order a sequential run of the loop appends them, on every tier, and `out.length` after the loop is the count appended.

```ts
export function strong(xs: array<f32>, t: f32, out: array<u32>): u32 {
  for (let i: u32 = 0; i < xs.length; i++) {
    if (xs[i] > t) {
      out.push(i)
    }
  }
  return out.length
}
```

### Capacity and count

The host array is the capacity. The call writes the first elements up to that capacity and leaves the rest as they were. The count the function returns may exceed the capacity, so a host that sees `n > out.length` can call again with more room. On WebGPU the loop runs in three dispatches: each iteration counts its pushes, one workgroup scans the counts into offsets, and each iteration stores its pushes at its offset. WebGL2 runs no loop that pushes.

host.ts

```ts
const out = new Uint32Array(1024) // the capacity
const n = await strong(xs, 0.5, out) // out holds the first indices, in ascending order
```

### `Map` and `Set`

A parameter may also be ECMAScript's `Set<K>` or `Map<K, V>`, with `K` a `u32`, an `i32`, an `f32` or a [key type](https://typeshade.dev/guide/language/string-keys-record/). A loop adds to it with `s.add(k)` or `m.set(k, v)`. The host passes JavaScript's own `Set` or `Map`, and when the call resolves it holds the entries a sequential run leaves: each key once, in the order first added, with the value set last.

```ts
export function labels(pixels: array<u32>, seen: Set<u32>): u32 {
  for (let i: u32 = 0; i < pixels.length; i++) {
    if (pixels[i] !== 0) {
      seen.add(pixels[i])
    }
  }
  return seen.size
}
```

A later loop reads it with `has`, `get` and `size`, and reads `m.get(k)!` only where `m.has(k)` guards it. Collection loops run on WebGPU and the CPU tier. WebGL2 cannot run them. String keys convert to ids before the loops and back afterward, preserving insertion order. An unknown host string is a `TypeError`. Open `Map<string, V>` and `Set<string>` stay refused. [kernel-set-unique](https://typeshade.dev/guide/examples/kernel-set-unique/) and [host-set-unique](https://typeshade.dev/guide/examples/host-set-unique/) show both.

## 6. Chains of kernel calls

A host can run several kernel calls as one plan. The sections below state how calls fuse, what the report says, how the plan takes its workgroup counts and constants, which resources it uses and which kernels the library supplies.

### Fusing calls

A host can call several kernel functions inside `device.fuse()` without a registration import ([Rule 11.13](https://typeshade.dev/reference/rules/11-13/)). `fuse()` from `typeshade/fuse` remains supported for the default owner. The Vite plugin includes the facts needed to combine eligible calls by default; `typeshade({ fuse: false })` omits them to reduce the generated size. On WebGPU, calls that read what the call before them wrote at the same index run as one dispatch, in one submission. Inside the body, every array a call writes must be a `Buffer` of scalars: a call that writes a host array, or that takes a `Buffer` of structs or a `Uniform`, is a `TypeError`. A method that changes its object, called on an element of an array, counts as a write to that element in the facts the plan reads, as an argument of a parameter that its function writes does (Rule 8.29).

### The fuse report

The report the scope returns names each group, and says why two calls run apart. An entry call in the body forms a group of its own, and so does a loop that pushes onto an array. A call taking a `Map` or `Set` also forms its own group, reporting `b takes a Map or a Set` or its CPU fallback reason. Each group also names the `tier` it ran on, and a group that ran on a later tier than the plan’s says why in `why`, as in `b runs on the CPU, …`. Each group’s `dispatches` counts the dispatch commands it made on WebGPU or the draw calls it made on WebGL2, and is 0 on the CPU tier; it is a count of commands, not a workgroup shape. A report from the runtime also carries `webgpuScratch`, four counters of the WebGPU buffers the plan’s scratch arrays took: `allocations` and `allocatedBytes` for new buffers, and `reuses` and `reusedBytes` for buffers borrowed from the owner’s pool. A report with no `webgpuScratch` means the counts are unknown, not 0. `mergeReports` adds several reports into one. It keeps each group’s `tier` and `dispatches`, and it sums the scratch counters only when every report records them. `FuseReport` and `mergeReports` come from `typeshade/runtime` too, so a host that only reads reports ships no planner.

### Indirect workgroup counts

An entry call may take its workgroup count from an array an earlier call wrote. `entry(bindings, { indirect, offset })` reads the three counts at element `offset` of a `Buffer<u32>` when the call runs. A chain of calls then needs no read between them, and in a scope the group of such a call reports `indirect: true`.

### Constants on an entry

Inside `device.fuse()`, an imported compute entry takes the same optional `{ constants }` third argument as a direct call. Its runtime-sized storage arrays may be `Buffer`s of scalars of that owner. The call remains a group of its own in the plan’s submission and keeps the owner’s fp64 flavor. On WebGPU its `workgroupShapes` reports the selected dimensions, such as `[[32, 1, 1]]`. Selecting constants adds no submission, fence or readback. The [host-compute example](https://typeshade.dev/guide/examples/host-compute/) returns the report and reads its output after the plan.

### Devices and owners

`createDevice()` from `typeshade/runtime` opens an owner of the calls. `device.array()` makes the `Buffer`s of scalars its calls take, and `device.fuse()` runs a body's calls as one plan on that device. A kernel call or an entry call runs on the device of its owned resources (its `Buffer`s and the textures a device made), else on the device in use (`device.use()`), else on the default owner. Mixing owners is refused before execution, and each `Buffer` keeps its owner for its life. `device.release(b)` gives an array back to the device's pool for the next `array()` of the same element and length.

host.ts

```ts
import { createDevice } from 'typeshade/runtime'
import 'typeshade/fuse'

const dev = await createDevice({ prefer: ['webgpu', 'cpu'] })
const a = dev.array(new Float32Array(n))
const out = dev.array(n, 'f32')
await dev.fuse(() => {
  relu(out, a)
})
dev.release(a) // the next array(n, 'f32') takes it from the pool
const values = await out.read()
await dev.dispose()
```

### Chunks

A kernel that iterates inside one dispatch can run long enough for a GPU watchdog to reset the device. Cut its loop into chunks. `device.chunkSize(key, max)` gives the units of the next chunk under the device's time budget, `createDevice({ timeBudgetMs })`, and `device.fuse(body, { chunk: { key, units } })` runs and times that chunk alone. The report gains a `chunk` row, and `device.chunkRates` holds what the device measured.

### Library kernels

`typeshade/algorithms` and `typeshade/random` are kernel functions written in TypeShade, and they fuse with yours in one scope. [Algorithms](https://typeshade.dev/guide/language/algorithms/) and [Random numbers](https://typeshade.dev/guide/language/random/) list them.

## 7. Where JavaScript control flow stops

- Write `filter`, `find` and the other array methods that change a length or can give `undefined` as a loop. `findIndex` and `indexOf` give -1 where nothing matches.
- Do not rely on general runtime objects.
- Keep conditions and loop ranges based on GPU-compilable values.
- A control-flow pattern valid in TypeScript is not automatically valid under TypeShade shader semantics.

[Next: Resources](https://typeshade.dev/guide/language/resources/)
