Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion quest/m2/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export.md);

## Required

- [MIR's codec as fast as THIR's](/quest/m2/ts-mir-codec.md) - the codec from MIR no slower than from THIR in any engine
- [Lower bodies from MIR](/quest/m2/ts-mir.md) - the MIR spike's prototype becomes the only lowering, and the THIR one goes
- [Cheaper byte slices](/quest/m2/ts-byte-views.md) - splitting a `&[u8]` stops making a `Uint8Array` view per split
- [Wide-integer fast paths](/quest/m2/ts-wide-fast.md) - a fused `from_halves` and an unboxed limb product, kept only if measured faster
Expand Down
17 changes: 0 additions & 17 deletions quest/m2/ts-mir-codec.md

This file was deleted.

11 changes: 5 additions & 6 deletions quest/m2/ts-mir.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,11 @@ still needs:
copied out of a field and then passed on.
- `?` on an `Option` returned through a `next` whose item can be `undefined`, and the
other THIR special cases the prototype mirrors (`for` loops by the iterator protocol,
`from_be_bytes` of bytes made in place, ranges stepped in place): keep each only
where `just ts bench` measures it.
`from_be_bytes` of bytes made in place): keep each only where `just ts bench`
measures it. Ranges stepped in place stay: a `for` over `0..n` read through
`rt.Range.next` or as a number-or-`rt.DONE` was up to 1.3x slower in V8.
- A signed `%` by a constant leaves its overflow check's operands as statements
(`4 === -1;`), which `tsc` rejects.
- Size: the task fixture's bundle is 35% larger gzipped than THIR's, the codec's 9%.
Likely wins, each to measure: a coroutine resume function structured where the
graph allows (a dispatch at each loop header the resume enters, rather than a
Expand All @@ -44,7 +47,3 @@ take a raw pointer. A nightly bump that changes them should fail loudly, as each
now.

Public API: the translator's whole output, and the `--lower` option, which goes.

## Required

- [MIR's codec as fast as THIR's](/quest/m2/ts-mir-codec.md) - the codec from MIR no slower than from THIR in any engine
27 changes: 23 additions & 4 deletions ts/fixtures/lang/expected/shapes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -378,16 +378,35 @@ export function loops(data: Uint8Array, out: rt.ByteVec): void {
count = rt.u8.add(count, 1);
}
out.push(count);
const lo = rt.i32.neg(rt.usize.rem(data.length, 4) | 0);
let r: rt.Range<rt.i32> = new rt.Range(lo, rt.i32.add(lo, 3));
const first = rt.iter.toOption(r.next());
r.end = r.start;
const second = rt.iter.toOption(r.next());
if (first !== undefined) {
const x = first;
out.extendFromSlice(rt.i32.toBeBytes(x));
}
if (second !== undefined) {
const x2 = second;
out.extendFromSlice(rt.i32.toBeBytes(x2));
}
for (let k = lo; k < 2; k++) {
out.push(k & 0xff);
}
for (let k2 = rt.i8.sub(124, (lo << 24) >> 24); k2 < 127; k2++) {
out.push(k2 & 0xff);
}
out.push(firstRepeat(data));
out.extendFromSlice(rt.u16.toBeBytes(tailBreak(data)));
out.push(armLoop(data));
out.extendFromSlice(rt.u32.toBeBytes(position$u8(data, 0) as rt.u32));
const settle = (x: rt.u8): rt.u8 => {
const settle = (x3: rt.u8): rt.u8 => {
while (true) {
if (x < 10) {
return x;
if (x3 < 10) {
return x3;
}
x = rt.u8.div(x, 3);
x3 = rt.u8.div(x3, 3);
}
};
out.push(settle(rt.u8.mul(data.length & 0xff, 7)));
Expand Down
20 changes: 20 additions & 0 deletions ts/fixtures/lang/src/shapes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,26 @@ pub fn loops(data: &[u8], out: &mut Vec<u8>) {
}
out.push(count);

// Ranges stepped by hand: signed across zero, up to the type's end, and an item read
// after the range changed.
let lo = -((data.len() % 4) as i32);
let mut r = lo..lo + 3;
let first = r.next();
r.end = r.start;
let second = r.next();
if let Some(x) = first {
out.extend_from_slice(&x.to_be_bytes());
}
if let Some(x) = second {
out.extend_from_slice(&x.to_be_bytes());
}
for k in lo..2 {
out.push(k as u8);
}
for k in 124 - lo as i8..i8::MAX {
out.push(k as u8);
}

out.push(first_repeat(data));
out.extend_from_slice(&tail_break(data).to_be_bytes());
out.push(arm_loop(data));
Expand Down
37 changes: 32 additions & 5 deletions ts/src/lower/mir/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,15 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> {
{
let iter_ty = gargs.skip_binder().type_at(0);
let recv = self.operand_frozen(&args[0].node, span, &mut pre);
if self.range_nexts.contains(&dest.local)
&& let Some(name) = self.var(dest.local)
{
let name = name.to_string();
self.assigned[dest.local] = true;
self.range_next(name, recv, &mut pre);
self.emit(pre, None, false, out);
return;
}
if let Some(name) = self.var(dest.local) {
let name = name.to_string();
self.next_names.insert(name);
Expand Down Expand Up @@ -221,11 +230,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> {
done(Expr::undefined(), true)
}
// A range of numbers steps in place, with nothing between it and the loop.
("Iterator", "next")
if let ty::Adt(adt, range_args) = targ(0)?.kind()
&& Std::of(tcx, adt.did()) == Some(Std::Range)
&& Int::of(range_args.type_at(0)).is_some_and(|i| !i.big()) =>
{
("Iterator", "next") if super::small_range(tcx, targ(0)?) => {
let range = self.alias_place(&args[0].node)?;
let start = range.clone().member("start");
let next = Expr::Cond(
Expand Down Expand Up @@ -427,6 +432,28 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> {
}
}

/// `name = recv.next()` of a range of numbers, stepped in place rather than through
/// `rt.Range`'s generic steps, into the item alone and a flag for whether there was
/// one: a number that is sometimes `rt.DONE` is slower in V8. Past the end, `name` is
/// left as it was, since only `Some` reads it.
fn range_next(&mut self, name: String, recv: Expr, out: &mut Vec<Stmt>) {
let range = self.path(recv, "range", out);
let start = range.clone().member("start");
let flag = self.b.fresh(&format!("{name}Some"));
let more = start.clone().binary("<", range.member("end"));
out.push(StmtKind::Expr(Expr::ident(&flag).assign(more)).at(None));
let step = Expr::ident(&name).assign(Expr::Postfix(Box::new(start), "++"));
out.push(
StmtKind::If {
cond: Expr::ident(&flag),
then: vec![StmtKind::Expr(step).at(None)],
els: Vec::new(),
}
.at(None),
);
self.range_flags.insert(name, flag);
}

/// The value at `place`, after setting `place` to `value`.
fn swap_out(&mut self, place: Expr, value: Expr, base: &str, out: &mut Vec<Stmt>) -> Expr {
let name = self.b.fresh(base);
Expand Down
36 changes: 33 additions & 3 deletions ts/src/lower/mir/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,11 @@ pub struct Fx<'m, 'b, 'a, 'tcx> {
next_results: FxHashSet<Local>,
/// Their names, which a switch on their variant tests against `rt.DONE`.
next_names: FxHashSet<String>,
/// Next results of a range of numbers stepped in place: each holds only the item, so
/// JS keeps it a number, and a flag holds whether there was one.
range_nexts: FxHashSet<Local>,
/// Their names, and their flags' names, which a switch on their variant tests.
range_flags: FxHashMap<String, String>,
}

impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> {
Expand Down Expand Up @@ -219,6 +224,8 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> {
var_parts: FxHashMap::default(),
next_results: FxHashSet::default(),
next_names: FxHashSet::default(),
range_nexts: FxHashSet::default(),
range_flags: FxHashMap::default(),
};
fx.analyze();
fx
Expand Down Expand Up @@ -576,14 +583,14 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> {
else {
continue;
};
let ty::FnDef(def_id, _) = *func.ty(&mir.local_decls, tcx).kind() else {
let ty::FnDef(def_id, gargs) = *func.ty(&mir.local_decls, tcx).kind() else {
continue;
};
let Some(local) = destination.as_local() else {
continue;
};
if crate::lower::iter::is_next(tcx, def_id) && self.defs[local] == 1 {
nexts.push(local);
nexts.push((local, gargs.skip_binder().type_at(0)));
}
if crate::lower::library::key(tcx, def_id).is_some_and(|(o, n)| o == "Try" && n == "branch")
&& let [arg] = &**args
Expand All @@ -597,7 +604,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> {
branches.insert(from, (at, local));
}
}
for local in nexts {
for (local, iter_ty) in nexts {
let branch = branches.get(&local).copied();
let mut uses = Uses {
local,
Expand All @@ -624,6 +631,8 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> {
continue;
}
self.next_results.insert(to);
} else if local != mir::RETURN_PLACE && small_range(tcx, iter_ty) {
self.range_nexts.insert(local);
}
self.next_results.insert(local);
}
Expand Down Expand Up @@ -761,6 +770,17 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> {
out.push(StmtKind::Declare { name, ty }.at(None));
}
}
let mut flags: Vec<String> = self.range_flags.values().cloned().collect();
flags.sort();
for name in flags {
out.push(
StmtKind::Declare {
name,
ty: Type::Builtin("boolean"),
}
.at(None),
);
}
out.extend(entry);
out.extend(body);
drop_self_assignments(&mut out);
Expand Down Expand Up @@ -841,6 +861,9 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> {
_ => args.type_at(0),
};
let item = self.b.t.ty(item, self.span);
if self.range_nexts.contains(&local) {
return item;
}
return Type::Union(vec![item, Type::Rt("Done", Vec::new())]);
}
let ty = match (self.checked.contains(&local), ty.kind()) {
Expand Down Expand Up @@ -2126,3 +2149,10 @@ fn inert(e: &Expr) -> bool {
e => e.is_path(),
}
}

/// Whether `ty` is a `Range` of numbers that fit a JS number, which steps in place.
pub(super) fn small_range<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool {
matches!(ty.kind(), ty::Adt(adt, args)
if crate::lower::library::Std::of(tcx, adt.did()) == Some(crate::lower::library::Std::Range)
&& crate::lower::num::Int::of(args.type_at(0)).is_some_and(|i| !i.big()))
}
10 changes: 10 additions & 0 deletions ts/src/lower/mir/place.rs
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,16 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> {
return self.err(span, format!("no variant of `{ty}` has discriminant {value}"));
};
match Std::of(tcx, adt.did()) {
Some(Std::Option)
if let Expr::Ident(n) = scrut
&& let Some(flag) = self.range_flags.get(n) =>
{
let flag = Expr::ident(flag);
match index.index() {
0 => flag.not(),
_ => flag,
}
}
Some(Std::Option) if matches!(scrut, Expr::Ident(n) if self.next_names.contains(n)) => {
match index.index() {
0 => scrut.clone().binary("===", Expr::Rt("DONE")),
Expand Down
2 changes: 1 addition & 1 deletion ts/src/lower/mir/rvalue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> {
let v = self.operand(op, span, out);
match elem_ty.kind() {
ty::Uint(ty::UintTy::U8) => {
let array = Expr::New(Box::new(Expr::ident("Uint8Array")), vec![Expr::lit(n.to_string())]);
let array = Expr::rt("bytes", vec![Expr::lit(n.to_string())]);
match &v {
Expr::Lit(text) if text == "0" => array,
_ => array.member("fill").call(vec![v]),
Expand Down