|
| 1 | +/* Static immutability facts the backend uses to drop run-time immutability |
| 2 | + * checks (see computeConstructionFacts). Pure functions of the IR module. */ |
| 3 | +import type { IrExpr, IrModule, IrStmt } from "../ir/ir.js"; |
| 4 | +import { everyExprChild, everyStmtChild } from "../ir/traverse.js"; |
| 5 | +import { |
| 6 | + computeCycleMutability, |
| 7 | + constructorEscapePoint, |
| 8 | + constructorThisAliases, |
| 9 | + fieldKey, |
| 10 | + type CycleMutability, |
| 11 | +} from "./cycle-mutability.js"; |
| 12 | + |
| 13 | +/** Fields that are never written once their object can be observed outside |
| 14 | + * its own construction (cycle-mutability.ts derives the facts from every |
| 15 | + * store in the IR, including typed-ref commits from checked-dynamic code, |
| 16 | + * and disables them for library builds and dynamic islands). |
| 17 | + * |
| 18 | + * Outside constructors, a reference read from such a field stays valid for |
| 19 | + * as long as its owner object is alive: nothing can replace it and release |
| 20 | + * the old value. Constructors themselves may still write their own |
| 21 | + * `this`'s fields, so the facts do not apply while one runs. */ |
| 22 | +export class ImmutableFields { |
| 23 | + constructor( |
| 24 | + private readonly mutability: CycleMutability, |
| 25 | + private readonly unitOfClass: (className: string) => string, |
| 26 | + ) {} |
| 27 | + |
| 28 | + /** `obj.field` on a class instance is construction-only. */ |
| 29 | + classField(className: string, field: string): boolean { |
| 30 | + return this.unit(this.unitOfClass(className), field); |
| 31 | + } |
| 32 | + |
| 33 | + /** `obj.field` on a record is never written after the literal. */ |
| 34 | + recordField(shapeId: string, field: string): boolean { |
| 35 | + return this.unit(`record:${shapeId}`, field); |
| 36 | + } |
| 37 | + |
| 38 | + private unit(unit: string, field: string): boolean { |
| 39 | + return ( |
| 40 | + !this.mutability.all && |
| 41 | + !this.mutability.units.has(unit) && |
| 42 | + !this.mutability.fields.has(fieldKey(unit, field)) |
| 43 | + ); |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +export function computeImmutableFields(mod: IrModule): ImmutableFields | null { |
| 48 | + if (mod.lib !== undefined) return null; |
| 49 | + const baseOf = new Map((mod.classes ?? []).map((c) => [c.name, c.base ?? null] as const)); |
| 50 | + const roots = new Map<string, string>(); |
| 51 | + const rootOf = (name: string): string => { |
| 52 | + const known = roots.get(name); |
| 53 | + if (known !== undefined) return known; |
| 54 | + let cur = name; |
| 55 | + for (let base = baseOf.get(cur); base !== null && base !== undefined; base = baseOf.get(cur)) |
| 56 | + cur = base; |
| 57 | + roots.set(name, cur); |
| 58 | + return cur; |
| 59 | + }; |
| 60 | + const unitOfClass = (name: string): string => `object:${rootOf(name)}`; |
| 61 | + const mutability = computeCycleMutability(mod, unitOfClass); |
| 62 | + return mutability.all ? null : new ImmutableFields(mutability, unitOfClass); |
| 63 | +} |
| 64 | + |
| 65 | +/** Stores that provably target an object no other code can reach yet. |
| 66 | + * |
| 67 | + * A published object (@scriptc/threads `publish`) rejects every write, so |
| 68 | + * the emitter guards each store into a type the program may publish. A |
| 69 | + * store into the constructor's own `this` cannot target a published object |
| 70 | + * when nothing outside the construction can hold `this` at that point: |
| 71 | + * |
| 72 | + * - the constructor runs on a fresh object: it is only reached through |
| 73 | + * `new` (or a construct thunk) for its class or a subclass, never by a |
| 74 | + * direct call on an existing object (`%C.constructor` called anywhere but |
| 75 | + * as the direct super call of a subclass constructor disqualifies C and |
| 76 | + * every ancestor, which that call reaches with the same receiver); |
| 77 | + * - no ancestor constructor, which runs before this body continues, lets |
| 78 | + * `this` escape, and the store lies in a top-level statement before the |
| 79 | + * first one in which this constructor lets it escape |
| 80 | + * (cycle-mutability's constructorEscapePoint: `this`, or a constant alias |
| 81 | + * of it, may only be a field-store target, a field-read receiver, the |
| 82 | + * direct base constructor's receiver, or stored into one of its own |
| 83 | + * fields; closures and class references capturing it count as escapes). |
| 84 | + * A subclass constructor's code only runs after this body returns. |
| 85 | + * |
| 86 | + * Library builds keep every guard: their constructors can be invoked by an |
| 87 | + * embedder in ways the module does not show. */ |
| 88 | +export interface ConstructionFacts { |
| 89 | + /** `fieldSet` statements whose target is a still-private `this`. */ |
| 90 | + privateStores: Set<IrStmt>; |
| 91 | +} |
| 92 | + |
| 93 | +export function computeConstructionFacts(mod: IrModule): ConstructionFacts { |
| 94 | + const facts: ConstructionFacts = { privateStores: new Set() }; |
| 95 | + if (mod.lib !== undefined) return facts; |
| 96 | + const classes = new Map((mod.classes ?? []).map((c) => [c.name, c] as const)); |
| 97 | + const ctorClass = new Map([...classes.keys()].map((name) => [`%${name}.constructor`, name])); |
| 98 | + const fnByName = new Map(mod.functions.map((fn) => [fn.name, fn] as const)); |
| 99 | + const thisOf = (name: string): string | null => |
| 100 | + fnByName.get(`%${name}.constructor`)?.params[0]?.localId ?? null; |
| 101 | + const isThisRef = (e: IrExpr, thisId: string | null): boolean => { |
| 102 | + if (thisId === null) return false; |
| 103 | + if (e.kind === "varRef") return e.localId === thisId; |
| 104 | + if (e.kind === "upcast") return isThisRef(e.value, thisId); |
| 105 | + if (e.kind === "seqExpr") return isThisRef(e.result, thisId); |
| 106 | + return false; |
| 107 | + }; |
| 108 | + |
| 109 | + // Constructors reached with a receiver that may not be fresh. |
| 110 | + const reused = new Set<string>(); |
| 111 | + const markReused = (name: string): void => { |
| 112 | + for (let c: string | undefined = name; c !== undefined && classes.has(c);) { |
| 113 | + if (reused.has(c)) break; |
| 114 | + reused.add(c); |
| 115 | + c = classes.get(c)!.base; |
| 116 | + } |
| 117 | + }; |
| 118 | + for (const fn of mod.functions) { |
| 119 | + const own = ctorClass.get(fn.name); |
| 120 | + const thisId = own !== undefined ? thisOf(own) : null; |
| 121 | + const baseCtor = |
| 122 | + own !== undefined && classes.get(own)!.base !== undefined |
| 123 | + ? `%${classes.get(own)!.base}.constructor` |
| 124 | + : null; |
| 125 | + const expr = (e: IrExpr): boolean => { |
| 126 | + if (e.kind === "call") { |
| 127 | + const target = ctorClass.get(e.callee); |
| 128 | + if ( |
| 129 | + target !== undefined && |
| 130 | + !(e.callee === baseCtor && e.args.length > 0 && isThisRef(e.args[0]!, thisId)) |
| 131 | + ) |
| 132 | + markReused(target); |
| 133 | + } else if (e.kind === "closure") { |
| 134 | + const target = ctorClass.get(e.fnName); |
| 135 | + if (target !== undefined) markReused(target); |
| 136 | + } |
| 137 | + return everyExprChild(e, expr, stmt); |
| 138 | + }; |
| 139 | + const stmt = (s: IrStmt): boolean => everyStmtChild(s, expr, stmt); |
| 140 | + fn.body.every(stmt); |
| 141 | + } |
| 142 | + |
| 143 | + // The first escaping statement of each constructor (body length: none). |
| 144 | + // A class without a constructor function of its own (runtime roots) is |
| 145 | + // treated as escaping at once. |
| 146 | + const points = new Map<string, number>(); |
| 147 | + const escapePoint = (name: string): number => { |
| 148 | + const known = points.get(name); |
| 149 | + if (known !== undefined) return known; |
| 150 | + const fn = fnByName.get(`%${name}.constructor`); |
| 151 | + const base = classes.get(name)?.base; |
| 152 | + const thisId = thisOf(name); |
| 153 | + const point = |
| 154 | + fn === undefined || thisId === null || classes.get(name)?.runtime === true |
| 155 | + ? 0 |
| 156 | + : constructorEscapePoint(fn, thisId, base !== undefined ? `%${base}.constructor` : null, { |
| 157 | + selfStores: true, |
| 158 | + }); |
| 159 | + points.set(name, point); |
| 160 | + return point; |
| 161 | + }; |
| 162 | + const ancestorEscapes = (name: string): boolean => { |
| 163 | + for (let c = classes.get(name)?.base; c !== undefined; c = classes.get(c)?.base) { |
| 164 | + const fn = fnByName.get(`%${c}.constructor`); |
| 165 | + if (!classes.has(c) || fn === undefined || escapePoint(c) < fn.body.length) return true; |
| 166 | + } |
| 167 | + return false; |
| 168 | + }; |
| 169 | + |
| 170 | + for (const [name] of classes) { |
| 171 | + const fn = fnByName.get(`%${name}.constructor`); |
| 172 | + if (fn === undefined || reused.has(name) || ancestorEscapes(name)) continue; |
| 173 | + const point = escapePoint(name); |
| 174 | + if (point === 0) continue; |
| 175 | + const aliases = constructorThisAliases(fn, thisOf(name)!); |
| 176 | + const isOwn = (e: IrExpr): boolean => |
| 177 | + (e.kind === "varRef" && aliases.has(e.localId)) || |
| 178 | + (e.kind === "upcast" && isOwn(e.value)) || |
| 179 | + (e.kind === "seqExpr" && isOwn(e.result)); |
| 180 | + const expr = (e: IrExpr): boolean => everyExprChild(e, expr, stmt); |
| 181 | + const stmt = (s: IrStmt): boolean => { |
| 182 | + if (s.kind === "fieldSet" && isOwn(s.obj)) facts.privateStores.add(s); |
| 183 | + return everyStmtChild(s, expr, stmt); |
| 184 | + }; |
| 185 | + for (let i = 0; i < point; i++) stmt(fn.body[i]!); |
| 186 | + } |
| 187 | + return facts; |
| 188 | +} |
| 189 | + |
| 190 | +/** Module constants whose value never changes once initialized: immutable, |
| 191 | + * not TDZ-checked (every read follows the initialization), no import-cycle |
| 192 | + * init flag, and at most one assignment in the whole module. Such a global |
| 193 | + * owns its value for the rest of the program, so a read of it can be |
| 194 | + * borrowed across any later operand or call. */ |
| 195 | +export function stableGlobals(mod: IrModule): Set<string> { |
| 196 | + const candidates = new Set( |
| 197 | + (mod.globals ?? []) |
| 198 | + .filter((g) => !g.mutable && g.tdz !== true && g.initFlag === undefined) |
| 199 | + .map((g) => g.id), |
| 200 | + ); |
| 201 | + const assigned = new Set<string>(); |
| 202 | + const expr = (e: IrExpr): boolean => { |
| 203 | + if (e.kind === "assignExpr" && candidates.has(e.localId)) candidates.delete(e.localId); |
| 204 | + return everyExprChild(e, expr, stmt); |
| 205 | + }; |
| 206 | + const stmt = (s: IrStmt): boolean => { |
| 207 | + if (s.kind === "assign" && candidates.has(s.localId)) { |
| 208 | + if (assigned.has(s.localId)) candidates.delete(s.localId); |
| 209 | + assigned.add(s.localId); |
| 210 | + } |
| 211 | + return everyStmtChild(s, expr, stmt); |
| 212 | + }; |
| 213 | + for (const fn of mod.functions) fn.body.every(stmt); |
| 214 | + return candidates; |
| 215 | +} |
0 commit comments