Skip to content

Commit df254ba

Browse files
committed
Cheaper direct calls and real heap figures from Runtime.
1 parent 242471c commit df254ba

5 files changed

Lines changed: 54 additions & 33 deletions

File tree

‎src/jit.ts‎

Lines changed: 3 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,6 @@ export type Compiled = (t: JThread, f: Frame) => number;
2929
const THRESHOLD = 500;
3030
const BACKEDGE_THRESHOLD = 2000;
3131
const MAX_CODE = 6000;
32-
// compiled frames nested on one JS stack before calls go through the run loop
33-
const MAX_DIRECT = 120;
3432
const MAX_FALLBACKS = 5000;
3533
// callees inlined as regions: bytecode outside throw-only blocks (HotSpot's
3634
// MaxInlineSize), nesting, and bytecode inlined into one compiled method
@@ -191,20 +189,6 @@ const runtime = {
191189
f.sp = sp;
192190
return f;
193191
},
194-
// the pushed frame of a direct call to compiled m, or null when the call
195-
// goes through the run loop: the stack is too deep or the monitor is taken
196-
enter(t: JThread, m: JMethod, recv: JObject | null): Frame | null {
197-
if (t.frames.length - t.base >= MAX_DIRECT || t.frames.length >= t.stackLimit) return null;
198-
let lock: JObject | null = null;
199-
if (m.isSynchronized) {
200-
lock = m.isStatic ? t.vm.mirror(m.cls) : recv!;
201-
if (!t.vm.tryMonitorEnter(t, lock)) return null;
202-
}
203-
const f = t.directFrame(m);
204-
f.lock = lock;
205-
t.frames.push(f);
206-
return f;
207-
},
208192
// A call that is not direct: a native's result, PUSHED once a native that
209193
// must wait is on the stack, or INTERPRET for the run loop to make the call.
210194
slowCall(t: JThread, m: JMethod, args: any[]): any {
@@ -295,7 +279,6 @@ const runtime = {
295279
},
296280
// raises exc from the run loop, once every compiled caller has spilled
297281
*rethrow(exc: JObject): Generator<never, void, unknown> { throw new JavaThrow(exc); },
298-
MAX_DIRECT,
299282
};
300283

301284
// ---- analysis ----------------------------------------------------------------
@@ -1187,7 +1170,7 @@ function genInvoke(
11871170
const res = (v: string) => (ret === "V" ? "" : `s${base}=${v};`);
11881171
// compiled callee: direct call
11891172
const recv = target.isStatic ? "null" : args[0];
1190-
parts.push(`if(tm.jit!==null&&(cf=rt.enter(t,tm,${recv}))!==null){`);
1173+
parts.push(`if(tm.jit!==null&&(cf=t.enter(tm,${recv}))!==null){`);
11911174
parts.push(`r=tm.jit(t,cf${args.map((x) => "," + x).join("")});if(r!==0){t.unpool(cf);${exit(pc, base, EXIT_SUSPEND)}}`);
11921175
parts.push(`${res("t.ret")}}`);
11931176
// a native callee runs here; anything else goes through the interpreter
@@ -1233,14 +1216,14 @@ function genPolymorphic(g: Gen, pc: number, next: number, d: number, target: JMe
12331216
const cell = K([null, null]);
12341217
const push = target.ret === "V" ? "" : `s${base}=t.ret;`;
12351218
return `if(${args[0]}!==null&&${args[0]}===${cell}[0]){f.pc=${pc};tm=${cell}[1];` +
1236-
`if(tm.jit!==null&&tm.cls.state===${INITIALIZED}&&(cf=rt.enter(t,tm,null))!==null){` +
1219+
`if(tm.jit!==null&&tm.cls.state===${INITIALIZED}&&(cf=t.enter(tm,null))!==null){` +
12371220
`r=tm.jit(t,cf${args.map((x) => "," + x).join("")});if(r!==0){t.unpool(cf);${exit(pc, base, EXIT_SUSPEND)}}${push}}` +
12381221
`else{${call(pc, d)}}}else{rt.vhTarget(t,${cell},${args[0]},${K(link.appendix)});${code}}`;
12391222
}
12401223
}
12411224
const push = target.ret === "V" ? "" : `s${base}=t.ret;`;
12421225
return `f.pc=${pc};${select}` +
1243-
`if(tm.jit!==null&&tm.cls.state===${INITIALIZED}&&(cf=rt.enter(t,tm,${callArgs[0] ?? "null"}))!==null){` +
1226+
`if(tm.jit!==null&&tm.cls.state===${INITIALIZED}&&(cf=t.enter(tm,${callArgs[0] ?? "null"}))!==null){` +
12441227
`r=tm.jit(t,cf${callArgs.map((x) => "," + x).join("")});if(r!==0){t.unpool(cf);${exit(pc, base, EXIT_SUSPEND)}}` +
12451228
`${push}}else{${call(pc, d)}}`;
12461229
}

‎src/natives/lang.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// java.lang natives: Object, System, Thread, Throwable, String, Runtime, ...
22

33
import { isHidden } from "./stackwalk.ts";
4-
import { gcStats } from "./management.ts";
4+
import { gcStats, javaHeap } from "./management.ts";
55
import { assertionsEnabled } from "../assertions.ts";
66
import { normalize } from "../fs.ts";
77
import { ACC_INTERFACE, JArray, JClass, JObject, MAX_HEAP, newArrayData } from "../runtime.ts";
@@ -316,8 +316,11 @@ export const natives: Natives = {
316316
// Runtime
317317
"java/lang/Runtime.availableProcessors()I": () => 1,
318318
// free <= total <= max, as callers that compute available memory expect
319-
"java/lang/Runtime.freeMemory()J": () => BigInt(Math.min(512 << 20, MAX_HEAP) / 2),
320-
"java/lang/Runtime.totalMemory()J": () => BigInt(Math.min(512 << 20, MAX_HEAP)),
319+
"java/lang/Runtime.freeMemory()J": () => {
320+
const h = javaHeap();
321+
return BigInt(h ? h.committed - h.used : Math.min(512 << 20, MAX_HEAP) / 2);
322+
},
323+
"java/lang/Runtime.totalMemory()J": () => BigInt(javaHeap()?.committed ?? Math.min(512 << 20, MAX_HEAP)),
321324
"java/lang/Runtime.maxMemory()J": () => BigInt(MAX_HEAP),
322325
// Collects where the engine allows it (node --expose-gc), in a new JS job:
323326
// a WeakRef read earlier in a job keeps its target alive until the job ends.

‎src/natives/management.ts‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -49,12 +49,21 @@ export function gcStats(vm: JVM): GcStats {
4949
return s;
5050
}
5151

52-
function jsHeap(): { used: number; committed: number } {
52+
// The JS heap as Java sees it, with used <= committed <= -Xmx; primitive
53+
// arrays are typed arrays, outside the JS heap. Null where the engine cannot tell.
54+
export function javaHeap(): { used: number; committed: number } | null {
55+
let used: number, committed: number;
5356
const node = (globalThis as any).process?.memoryUsage?.();
54-
if (node) return { used: node.heapUsed, committed: node.heapTotal };
5557
const chrome = (globalThis as any).performance?.memory;
56-
if (chrome) return { used: chrome.usedJSHeapSize, committed: chrome.totalJSHeapSize };
57-
return { used: 0, committed: 0 };
58+
if (node) {
59+
used = node.heapUsed + node.arrayBuffers;
60+
committed = node.heapTotal + node.arrayBuffers;
61+
} else if (chrome) {
62+
used = chrome.usedJSHeapSize;
63+
committed = chrome.totalJSHeapSize;
64+
} else return null;
65+
committed = Math.min(Math.max(used, committed), MAX_HEAP);
66+
return { used: Math.min(used, committed), committed };
5867
}
5968

6069
function* beans(t: JThread): NativeGen {
@@ -94,11 +103,9 @@ function* poolUsage(t: JThread, self: JObject): NativeGen {
94103
return yield* heapUsage(t);
95104
}
96105

97-
// MemoryUsage needs used <= committed <= max; node's heap does not know -Xmx
98106
function* heapUsage(t: JThread): NativeGen {
99-
const h = jsHeap();
100-
const committed = Math.min(Math.max(h.used, h.committed), MAX_HEAP);
101-
return yield* usage(t, 0, Math.min(h.used, committed), committed, MAX_HEAP);
107+
const h = javaHeap() ?? { used: 0, committed: 0 };
108+
return yield* usage(t, 0, h.used, h.committed, MAX_HEAP);
102109
}
103110

104111
function liveThreads(vm: JVM): JThread[] {

‎src/thread.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,9 @@ export const STATUS_NEW = 0, STATUS_RUNNABLE = 5, STATUS_TERMINATED = 2;
101101
export const STATUS_SLEEPING = 0x00e1, STATUS_WAITING = 0x0191, STATUS_TIMED_WAITING = 0x01a1;
102102
export const STATUS_PARKED = 0x0291, STATUS_PARKED_TIMED = 0x02a1, STATUS_BLOCKED = 0x0401;
103103

104+
// compiled frames nested on one JS stack before calls go through the run loop
105+
const MAX_DIRECT = 120;
106+
104107
let nextId = 1;
105108

106109
export class JThread {
@@ -139,8 +142,16 @@ export class JThread {
139142
// it spilled.
140143
private pool: (Frame | null)[] = [];
141144

142-
directFrame(m: JMethod): Frame {
145+
// The pushed frame of a direct call to compiled m, or null when the call
146+
// goes through the run loop: the stack is too deep or the monitor is taken.
147+
enter(m: JMethod, recv: JObject | null): Frame | null {
143148
const d = this.frames.length;
149+
if (d - this.base >= MAX_DIRECT || d >= this.stackLimit) return null;
150+
let lock: JObject | null = null;
151+
if (m.isSynchronized) {
152+
lock = m.isStatic ? this.vm.mirror(m.cls) : recv!;
153+
if (!this.vm.tryMonitorEnter(this, lock)) return null;
154+
}
144155
// filled without holes, which would make V8 store it as a dictionary
145156
while (this.pool.length <= d) this.pool.push(this.pooled(m, this.pool.length));
146157
const f = this.pool[d] ?? (this.pool[d] = this.pooled(m, d));
@@ -150,9 +161,10 @@ export class JThread {
150161
f.sp = 0;
151162
f.locals = null as any;
152163
f.stack = null as any;
153-
f.lock = null;
164+
f.lock = lock;
154165
f.needLock = false;
155166
f.direct = true;
167+
this.frames.push(f);
156168
return f;
157169
}
158170

‎test/java/RuntimeMemory.java‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// Runtime's memory figures follow what the program holds.
2+
public class RuntimeMemory {
3+
static long used(Runtime rt) {
4+
return rt.totalMemory() - rt.freeMemory();
5+
}
6+
7+
public static void main(String[] args) {
8+
Runtime rt = Runtime.getRuntime();
9+
long before = used(rt);
10+
long[] held = new long[8 << 20];
11+
long after = used(rt);
12+
System.out.println("used grows by 32 MB holding 64 MB " + (after - before >= 32 << 20));
13+
System.out.println("free <= total <= max " + (rt.freeMemory() <= rt.totalMemory() && rt.totalMemory() <= rt.maxMemory()));
14+
System.out.println(held.length);
15+
}
16+
}

0 commit comments

Comments
 (0)