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
31 changes: 16 additions & 15 deletions BACKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,18 +75,14 @@ Notes; finished-work narrative does not.
specialised method goes from the allocations in the program, so a dead `new_Parent` no longer keeps it on the erased
class (a generic parent which nothing allocates directly keeps a specialised class table with the method).

- **Build the local-player analysis fewer times, or incrementally.** An optimised Lua build of castle fight
constructs `LocalPlayerContextAnalyzer` four times: for the compile-time state function the splitter optimises
(`FunctionSplitter`, once per split target with locals), for `ImInliner.doInlining` and once per
`ImOptimizer.runLocalOptimizationSweep` (two sweeps). With a fifth (`LuaOldGenericsCasts`, since removed) they
took about 4 s of the compiler thread (7% of its samples). Each one is the
whole program, because the fact about a variable or a function depends on every caller and every writer.
Keeping the analysis of the first sweep for the second is not output-neutral: it changed about 40,000 lines of the
castle fight script (different local merges), so a construction per sweep stays until the analysis can retract a
fact (the propagation is a least fixpoint, so a rewrite which removes a flow cannot be undone in place) or the passes
report which functions they changed. What is left of a construction is the walk itself: the first touch of every IM
node (`indexElement`, `isInert`, `markReturns`) is about half of the samples, so the cost follows the size of the IM
and a flatter IM would help more than another rewrite of the analysis.
- **The inliner's Lua register model still splits locals by locality.** No local optimisation reads the
local-player analysis any more (copy propagation and the local merger preserve what each client computes), so an
optimised build constructs it once, in `ImInliner.doInlining`, where it refuses to inline client-local functions and
feeds the register budget, and again lazily in the late arithmetic-helper phase when a helper call is left. The budget
(`ImInliner.pressureOf`) still counts client-local and synchronised locals as separate register classes, as the
merger used to keep them; that over-estimates now, which is safe. Counting per type lets more helpers fit: measured on
castle fight, the late phase then inlines some and re-runs the local optimisations (+3.2 s), and the main inliner's
decisions change (+0.17% instructions). Decide it with a runtime measurement of the helpers it would inline.

- **Fewer whole-program passes between the optimiser's phases.** The garbage removal and the flatten each walk the
whole program, and a build runs them many times (castle fight: the removal 3 to 8 times with 11 to 29 rounds, the
Expand All @@ -100,11 +96,10 @@ Notes; finished-work narrative does not.
keeps: `modification counts: ImFunction` in `jass_im.parseq`). Left:
(1) more removals which remove nothing: one which the test suite shows to find nothing becomes an `assertNoGarbage`,
as the second removal, the one in `optimize` and the one in front of the empty package initialisers did (the one in
front of the first local optimisation is a candidate); (2) `LocalPlayerContextAnalyzer`, built again for the whole program after each
pass which is not local-player aware (see "Build the local-player analysis fewer times" above); (3) the flatten after the tuples
front of the first local optimisation is a candidate); (2) the flatten after the tuples
are eliminated is the one which does work (about 565 to 800 functions of castle fight): the producers of
statement expressions (`EliminateTuples`, `SimpleRewrites`, the inliner) could emit statements as the removal does;
(4) a chain of assignments to unread variables (`v1 = v0; v2 = v1; ...`, nothing reads the last) takes a round for
(3) a chain of assignments to unread variables (`v1 = v0; v2 = v1; ...`, nothing reads the last) takes a round for
each link, and a round costs the functions which changed (a walk of each, the rewrite of its statement list, its
locals), so the cost grows with the square of the length. Measured in a unit test (the checks of unit-test mode on,
one removal): a chain inside one function takes 0.24 s for 1,000 links, 1.5 s for 4,000 and 16.7 s for 16,000; with
Expand Down Expand Up @@ -218,6 +213,12 @@ Notes; finished-work narrative does not.
build-time or memory benefit, or evidence of a substantially smaller correct implementation; speculative future
benefits and raw class counts are insufficient.

- **Fuzz an optimiser change against client-local code.** `LocalPlayerFuzzTests` compiles random programs full of
`GetLocalPlayer()` and UI-state branches without and with optimisations and compares, client by client, what the Lua
does. CI runs 25 programs; before changing what a pass does around client-local values, run a campaign
(`WURST_FUZZ_PROGRAMS=3000`, a fresh `WURST_FUZZ_SEED`, `-PtestTimeoutMillis=3600000`) and plant a bug in the pass
to see the campaign catch it.

- **Making the grammars SLL-clean is not worth it.** The SLL-first parse (`AntlrTokenPipeline`) parses a file again
with the full LL prediction when SLL does not accept it, which also happens to a few valid files (`blizzard.j`,
the standard library's `util/Cinematic.wurst`). In an unoptimised build of a large map that second parse was 2 of
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,7 @@ private void optimize() {
// run some basic optimizations first:
func.flatten(tr);
new ConstantAndCopyPropagation().optimizeFunc(func);
// The merge asks the locality analysis only about locals and the values assigned to them (the function has
// no parameters), and the compile-time state usually has none, so the analysis is made only when it has some.
LocalPlayerContextAnalyzer localPlayerContextAnalyzer = func.getLocals().isEmpty()
? null
: new LocalPlayerContextAnalyzer(tr.getImProg());
new LocalMerger().optimizeFunc(func, localPlayerContextAnalyzer, tr);
new LocalMerger().optimizeFunc(func, tr);
Set<ImVar> usedVars = UsedVariables.calculate(func);
func.getLocals().removeIf(v -> !usedVars.contains(v));
func.flatten(tr);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import de.peeeq.datastructures.GraphInterpreter;
import de.peeeq.wurstscript.intermediatelang.optimizer.ControlFlowGraph.Node;
import de.peeeq.wurstscript.jassIm.*;
import de.peeeq.wurstscript.translation.imoptimizer.OptimizerPass;
import de.peeeq.wurstscript.translation.imtranslation.Flatten;
import de.peeeq.wurstscript.translation.imtranslation.ImHelper;
import de.peeeq.wurstscript.translation.imtranslation.ImTranslator;
Expand All @@ -14,16 +15,19 @@

import java.util.*;

public class LocalMerger implements LocalPlayerAwareOptimizerPass {
/**
* Gives locals whose live ranges are disjoint one variable. It needs no locality analysis: a merged local holds on
* every client the values the separate locals held, so a value which depends on the local player shares a variable
* with a synchronised one like any other.
*/
public class LocalMerger implements OptimizerPass {
private int totalLocalsMerged = 0;
private LocalPlayerContextAnalyzer localPlayerContextAnalyzer;
private ImTranslator translator;

@Override
public int optimize(ImTranslator trans, LocalPlayerContextAnalyzer analyzer) {
public int optimize(ImTranslator trans) {
ImProg prog = trans.getImProg();
translator = trans;
localPlayerContextAnalyzer = analyzer;
totalLocalsMerged = 0;
optimizeFunctions(prog.getFunctions());
List<ImClass> classes = prog.getClasses();
Expand Down Expand Up @@ -65,19 +69,14 @@ void optimizeFunc(ImFunction func) {
mergeLocals(liveness.liveOut, liveness.liveAtEntry, func);
}

void optimizeFunc(ImFunction func, LocalPlayerContextAnalyzer analyzer) {
localPlayerContextAnalyzer = analyzer;
optimizeFunc(func);
}

/**
* Entry point for callers which optimise one function outside {@link #optimize}: the translator
* identifies the Lua operator intrinsics whose unused calls may be dropped. Without one, every
* call is kept as a side effect.
*/
public void optimizeFunc(ImFunction func, LocalPlayerContextAnalyzer analyzer, ImTranslator trans) {
public void optimizeFunc(ImFunction func, ImTranslator trans) {
translator = trans;
optimizeFunc(func, analyzer);
optimizeFunc(func);
}

private boolean canMerge(ImType a, ImType b) { return a.equalsType(b); }
Expand Down Expand Up @@ -119,13 +118,6 @@ private void mergeLocals(Map<ImStmt, Set<ImVar>> livenessInfo, Set<ImVar> liveAt
if (!canMerge(color.getType(), v.getType())) {
continue;
}
// A merged local would hold both values while the analysis, made before this pass, still answers for
// each: keeping them apart keeps it true for the passes which use it after this one.
if (localPlayerContextAnalyzer != null
&& localPlayerContextAnalyzer.isLocalPlayerDependent(v)
!= localPlayerContextAnalyzer.isLocalPlayerDependent(color)) {
continue;
}

boolean conflict = false;
for (ImVar neigh : interference.get(v)) {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -198,9 +198,7 @@ public boolean functionUsesLocalPlayer(ImFunction function) {
* directly, or returns a value derived from one by data flow. Control taint is deliberately not
* consulted. A function reachable from a client-local branch has a tainted return fact, but
* inlining substitutes its body at the call site, where it runs under exactly the control the
* call already had, so nothing crosses a boundary. The passes which do move code
* ({@link LocalMerger}, ...) run after inlining and re-analyse the inlined program, where that control is
* explicit.
* call already had, so nothing crosses a boundary.
*/
public boolean functionInliningIsLocalPlayerSensitive(ImFunction function) {
if (function == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
import de.peeeq.wurstscript.WLogger;
import de.peeeq.wurstscript.intermediatelang.optimizer.ConstantAndCopyPropagation;
import de.peeeq.wurstscript.intermediatelang.optimizer.DispatchCheckDeduplicator;
import de.peeeq.wurstscript.intermediatelang.optimizer.LocalPlayerAwareOptimizerPass;
import de.peeeq.wurstscript.intermediatelang.optimizer.LocalPlayerContextAnalyzer;
import de.peeeq.wurstscript.intermediatelang.optimizer.LocalMerger;
import de.peeeq.wurstscript.intermediatelang.optimizer.RedundantFieldStores;
import de.peeeq.wurstscript.intermediatelang.optimizer.SideEffectAnalyzer;
Expand All @@ -31,8 +29,6 @@ public class ImOptimizer {
static {
localPasses.add(new SimpleRewrites());
localPasses.add(new LocalMerger());
// After the pass which uses the local-player analysis: a pass which does not use it discards it, and none
// after this one needs it again in the same sweep.
localPasses.add(new ConstantAndCopyPropagation());
localPasses.add(new RedundantFieldStores());
localPasses.add(new GlobalsInliner());
Expand Down Expand Up @@ -92,27 +88,12 @@ public void localOptimizations() {

private int runLocalOptimizationSweep() {
int optCount = 0;
LocalPlayerContextAnalyzer localPlayerContextAnalyzer = null;
for (OptimizerPass pass : localPasses) {
if (pass instanceof DispatchCheckDeduplicator && trans.isLuaTarget()) {
// The dispatch checks it merges are made by the class elimination, which Lua does not run.
continue;
}
int count;
if (pass instanceof LocalPlayerAwareOptimizerPass localPlayerAwarePass) {
if (localPlayerContextAnalyzer == null) {
localPlayerContextAnalyzer =
new LocalPlayerContextAnalyzer(trans.getImProg());
}
LocalPlayerContextAnalyzer analyzer = localPlayerContextAnalyzer;
count = timeTaker.measure(
pass.getName(),
() -> localPlayerAwarePass.optimize(trans, analyzer));
} else {
count = timeTaker.measure(pass.getName(), () -> pass.optimize(trans));
// A general mutating pass may invalidate dependency edges.
localPlayerContextAnalyzer = null;
}
int count = timeTaker.measure(pass.getName(), () -> pass.optimize(trans));
optCount += count;
totalCount.put(pass.getName(), totalCount.getOrDefault(pass.getName(), 0) + count);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,6 @@
* got some are passed through the local merger once more: the temporaries share a slot with each
* other and with dead locals of their type, and a function with many casts does not grow towards
* Lua's limit of 200 locals. Merging only renames variables, so the operands stay variables.
* The merger runs here without a locality analysis, so a client-local value and a synchronized one
* may share a local. Elsewhere it keeps them apart only so that the analysis made before it stays
* true for the passes which use it afterwards; this is the last pass, so nothing uses one after it.
*/
public final class LuaOldGenericsCasts {

Expand Down Expand Up @@ -75,7 +72,7 @@ public void visit(ImCast cast) {
}
prog.flatten(translator);
for (ImFunction function : touched) {
new LocalMerger().optimizeFunc(function, null, translator);
new LocalMerger().optimizeFunc(function, translator);
}
}
}
Loading
Loading