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
20 changes: 0 additions & 20 deletions BACKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,26 +222,6 @@ Notes; finished-work narrative does not.
were simply the easiest thing to emit. Method: read the emitted script of a real map next to what
hand-written Lua would be, list every compiler-introduced call, allocation or table write on an
ordinary path, and fix the root (AGENTS.md §3, §7).
- **Lua enum nil tests on gameplay paths, given a common.j constant through a parameter.** A native's
nil-safety wrapper turns a null enum argument into the handle of id 0, and skips that test where the call
passes a common.j constant. On the optimised Lua of a large real map (Oct 2026), that removed 305 of the
471 tests given a constant: 293 in setup code (`InitCustomTeams`, `config`) and 12 elsewhere. The 166
left include every gameplay one: `IsUnitType` 46, `GetUnitState` 29, `GetPlayerState` 13,
`SetUnitState` 12. They reach the native through a standard library parameter that only forwards the
enum (`unit.getState(unitstate state)` calls `GetUnitState(this, state)`), and the constant appears only
once the inliner has removed that function, after the lowering has chosen the test. Two candidate roots;
choose one:
1. In the lowering, move the `p = ConvertX(0)` normalisation of such a parameter to the function's direct
callers, where a constant needs none. This is only sound when every call of the function is seen (not
referenced, not a method implementation, not run by ExecuteFunc, name not preserved), nothing assigns
the parameter and nothing else reads it. Parameters which only forward to each other (mutually
recursive helpers) must also reach a native, or the callers pay for a test nothing needs. A
return-default guard (a null unit) must never move. A prototype of about 100 lines took the map from
494 enum tests to 25 (2 still given a constant), for about −2,900 static Lua instructions.
2. Decide after inlining, where the code reads `t = UNIT_STATE_MAX_LIFE; if t == nil then ...`: the fact
that a common.j constant global is never nil would fold the test there. That belongs to the optimiser,
which is outside this repository's scope.

## Blocked on a decision

- **Is the generated AST the right shape for the passes?** Generated nodes are single-parent mutable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import de.peeeq.datastructures.GraphInterpreter;
import de.peeeq.datastructures.NodeWorklist;
import de.peeeq.wurstscript.WurstOperator;
import de.peeeq.wurstscript.intermediatelang.optimizer.ControlFlowGraph.Node;
import de.peeeq.wurstscript.jassIm.*;
import de.peeeq.wurstscript.translation.imoptimizer.OptimizerPass;
Expand All @@ -16,7 +17,8 @@
import java.util.*;

/**
* Replaces a read of a local by the constant or the other local it is known to hold. It needs no locality analysis:
* Replaces a read of a local by the constant or the other local it is known to hold, and propagates nullness
* established by branches. It needs no locality analysis:
* a read which is replaced reads the same value on every client, and no computation moves, so a value which depends
* on the local player is propagated like any other.
*/
Expand All @@ -30,7 +32,7 @@ public int optimize(ImTranslator trans) {
totalPropagated = 0;
for (ImFunction func : ImHelper.calculateFunctionsOfProg(prog)) {
if (!func.isNative() && !func.isBj()) {
optimizeFunc(func);
optimizeFunc(func, prog);
}
}
return totalPropagated;
Expand All @@ -47,6 +49,18 @@ static class Value {
final int component;
final @Nullable ImConst constantValue;
final @Nullable ImTupleExpr constantTuple;
final boolean nonNull;

/** A branch proves non-nullness without proving which value the local holds. */
private Value() {
copyVar = null;
component = -1;
constantValue = null;
constantTuple = null;
nonNull = true;
}

private static final Value NON_NULL = new Value();

public Value(ImVar copyVar) {
this(copyVar, -1);
Expand All @@ -58,6 +72,7 @@ public Value(ImVar results, int component) {
this.component = component;
this.constantValue = null;
this.constantTuple = null;
this.nonNull = false;
if(results.isGlobal()) {
throw new IllegalArgumentException("copyVar must not be a Global.");
}
Expand All @@ -68,13 +83,15 @@ public Value(ImConst constantValue) {
this.component = -1;
this.constantValue = constantValue;
this.constantTuple = null;
this.nonNull = false;
}

public Value(ImTupleExpr tupleExpr) {
this.copyVar = null;
this.component = -1;
this.constantValue = null;
this.constantTuple = tupleExpr;
this.nonNull = false;

for(ImExpr e : tupleExpr.getExprs()) {
if(tryValue(e) == null) {
Expand Down Expand Up @@ -108,7 +125,9 @@ public boolean equals(@Nullable Object obj) {
}

public boolean equalValue(Value other) {
if (copyVar != null && other.copyVar != null) {
if (nonNull || other.nonNull) {
return nonNull == other.nonNull;
} else if (copyVar != null && other.copyVar != null) {
return copyVar == other.copyVar && component == other.component;
} else if (constantValue != null && other.constantValue != null) {
return constantValue.equalValue(other.constantValue);
Expand All @@ -132,7 +151,9 @@ public boolean equalValue(Value other) {

@Override
public String toString() {
if (copyVar != null) {
if (nonNull) {
return "non-null";
} else if (copyVar != null) {
return "copy of " + copyVar + (component < 0 ? "" : "." + component);
} else if (constantValue != null) {
return "constant " + constantValue;
Expand All @@ -152,13 +173,13 @@ public String toString() {
}
}

void optimizeFunc(ImFunction func) {
void optimizeFunc(ImFunction func, ImProg prog) {
ControlFlowGraph cfg = new ControlFlowGraph(func.getBody());
Map<Node, Knowledge> knowledge = calculateKnowledge(cfg);
rewriteCode(cfg, knowledge);
Map<Node, Knowledge> knowledge = calculateKnowledge(cfg, prog);
rewriteCode(cfg, knowledge, prog);
}

private void rewriteCode(ControlFlowGraph cfg, Map<Node, Knowledge> knowledge) {
private void rewriteCode(ControlFlowGraph cfg, Map<Node, Knowledge> knowledge, ImProg prog) {
for (Node node : cfg.getNodes()) {
ImStmt stmt = node.getStmt();
if (stmt == null) {
Expand All @@ -167,6 +188,23 @@ private void rewriteCode(ControlFlowGraph cfg, Map<Node, Knowledge> knowledge) {
Knowledge kn = knowledge.get(node);
stmt.accept(new ImStmt.DefaultVisitor() {

@Override
public void visit(ImOperatorCall call) {
if ((call.getOp() == WurstOperator.EQ || call.getOp() == WurstOperator.NOTEQ)
&& call.getArguments().size() == 2) {
ImExpr left = call.getArguments().get(0);
ImExpr right = call.getArguments().get(1);
Boolean nonNull = left instanceof ImNull ? nonNull(right, kn.varKnowledge, prog)
: right instanceof ImNull ? nonNull(left, kn.varKnowledge, prog) : null;
if (nonNull != null) {
call.replaceBy(JassIm.ImBoolVal(nonNull == (call.getOp() == WurstOperator.NOTEQ)));
totalPropagated++;
return;
}
}
super.visit(call);
}

@Override
public void visit(ImSet imSet) {
ImLExpr e = imSet.getLeft();
Expand Down Expand Up @@ -239,7 +277,7 @@ public void visit(ImVarAccess va) {
}
}

private Map<Node, Knowledge> calculateKnowledge(ControlFlowGraph cfg) {
private Map<Node, Knowledge> calculateKnowledge(ControlFlowGraph cfg, ImProg prog) {
Map<Node, Knowledge> knowledge = new java.util.HashMap<>();
List<Node> allNodes = cfg.getNodes();
if (allNodes.isEmpty()) {
Expand All @@ -265,7 +303,7 @@ protected Collection<Node> getIncidentNodes(Node t) {

// Analyze each SCC in topological order
for (List<Node> scc : sccs) {
analyzeComponent(scc, knowledge);
analyzeComponent(scc, knowledge, cfg, prog);
}

return knowledge;
Expand All @@ -274,7 +312,7 @@ protected Collection<Node> getIncidentNodes(Node t) {
/**
* Runs a local worklist algorithm on a single SCC until it reaches a fixed-point.
*/
private void analyzeComponent(List<Node> scc, Map<Node, Knowledge> knowledge) {
private void analyzeComponent(List<Node> scc, Map<Node, Knowledge> knowledge, ControlFlowGraph cfg, ImProg prog) {
NodeWorklist worklist = new NodeWorklist(scc);
java.util.HashSet<Node> sccNodeSet = new java.util.HashSet<>(scc);

Expand All @@ -286,22 +324,15 @@ private void analyzeComponent(List<Node> scc, Map<Node, Knowledge> knowledge) {
HashMap<ImVar, Value> newKnowledge = HashMap.empty();
if (!n.getPredecessors().isEmpty()) {
Node pred1 = n.getPredecessors().get(0);
newKnowledge = knowledge.get(pred1).varKnowledgeOut;
newKnowledge = edgeKnowledge(pred1, n, knowledge, cfg);

if (n.getPredecessors().size() > 1) {
for (int i = 1; i < n.getPredecessors().size(); i++) {
HashMap<ImVar, Value> other = edgeKnowledge(n.getPredecessors().get(i), n, knowledge, cfg);
for (Tuple2<ImVar, Value> e : newKnowledge) {
ImVar var = e._1();
Value val = e._2();
boolean allSame = true;
for (int i = 1; i < n.getPredecessors().size(); i++) {
Node predi = n.getPredecessors().get(i);
Value predi_val = knowledge.get(predi).varKnowledgeOut.get(var).getOrNull();
if (predi_val == null || !predi_val.equalValue(val)) {
allSame = false;
break;
}
}
if (!allSame) {
Value otherValue = other.get(var).getOrNull();
if (otherValue == null || !otherValue.equalValue(val)) {
newKnowledge = newKnowledge.remove(var);
}
}
Expand Down Expand Up @@ -339,7 +370,8 @@ private void analyzeComponent(List<Node> scc, Map<Node, Knowledge> knowledge) {
if(newOut.containsKey(varRight)) {
newValue = newOut.get(varRight).getOrNull();
} else {
newValue = Value.tryValue(right);
newValue = ImHelper.isNonNullHandleConstant(varRight, prog)
? Value.NON_NULL : Value.tryValue(right);
}
} else if(right instanceof ImTupleExpr) {
newValue = Value.tryValue(right);
Expand Down Expand Up @@ -440,4 +472,66 @@ private void analyzeComponent(List<Node> scc, Map<Node, Knowledge> knowledge) {
}
}
}

private HashMap<ImVar, Value> edgeKnowledge(Node from, Node to, Map<Node, Knowledge> knowledge,
ControlFlowGraph cfg) {
HashMap<ImVar, Value> values = knowledge.get(from).varKnowledgeOut;
Boolean branch = cfg.branchValue(from, to);
return branch == null ? values : assume((ImExpr) from.getStmt(), branch, values);
}

private HashMap<ImVar, Value> assume(ImExpr condition, boolean truth, HashMap<ImVar, Value> values) {
if (!(condition instanceof ImOperatorCall call)) {
return values;
}
ImExprs args = call.getArguments();
if (call.getOp() == WurstOperator.NOT) {
return assume(args.get(0), !truth, values);
}
if ((call.getOp() == WurstOperator.AND && truth) || (call.getOp() == WurstOperator.OR && !truth)) {
for (ImExpr arg : args) {
values = assume(arg, truth, values);
}
} else if (call.getOp() == WurstOperator.EQ || call.getOp() == WurstOperator.NOTEQ) {
ImExpr left = args.get(0);
ImExpr right = args.get(1);
ImExpr tested = left instanceof ImNull ? right : right instanceof ImNull ? left : null;
if (tested instanceof ImVarAccess access && !access.getVar().isGlobal()) {
boolean nonNull = truth == (call.getOp() == WurstOperator.NOTEQ);
Value value = nonNull ? Value.NON_NULL : new Value((ImConst) (left instanceof ImNull ? left : right));
values = values.put(access.getVar(), value);
}
}
return values;
}

private @Nullable Boolean nonNull(ImExpr expr, HashMap<ImVar, Value> values, ImProg prog) {
if (expr instanceof ImNull) {
return false;
}
if (!(expr instanceof ImVarAccess access)) {
return null;
}
ImVar var = access.getVar();
for (int i = 0; i <= values.size(); i++) {
if (ImHelper.isNonNullHandleConstant(var, prog)) {
return true;
}
Value value = values.get(var).getOrNull();
if (value == null) {
return null;
}
if (value.nonNull) {
return true;
}
if (value.constantValue instanceof ImNull) {
return false;
}
if (value.copyVar == null || value.component >= 0) {
return null;
}
var = value.copyVar;
}
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,20 @@ public ControlFlowGraph(ImStmts stmts) {
buildCfg(stmts);
}

/** The value of an if's condition on this edge, or unknown when both branches reach the same node. */
public @Nullable Boolean branchValue(Node from, Node to) {
ImStmt stmt = from.getStmt();
if (stmt == null || !(stmt.getParent() instanceof ImIf imIf) || stmt != imIf.getCondition()) {
return null;
}
Node thenNode = imIf.getThenBlock().isEmpty() ? getEndIfNode(imIf) : getNode(imIf.getThenBlock().get(0));
Node elseNode = imIf.getElseBlock().isEmpty() ? getEndIfNode(imIf) : getNode(imIf.getElseBlock().get(0));
if (thenNode == elseNode) {
return null;
}
return to == thenNode ? Boolean.TRUE : to == elseNode ? Boolean.FALSE : null;
}

/**
* The statements which no path from the first statement reaches, without the statements inside them: what follows
* a return, a loop which has no exitwhen of its own, or an if neither branch of which comes to its end.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ private void optimize() {
Preconditions.checkArgument(func.getReturnType() instanceof ImVoid, "func must return void");
// run some basic optimizations first:
func.flatten(tr);
new ConstantAndCopyPropagation().optimizeFunc(func);
new ConstantAndCopyPropagation().optimizeFunc(func, tr.getImProg());
new LocalMerger().optimizeFunc(func, tr);
Set<ImVar> usedVars = UsedVariables.calculate(func);
func.getLocals().removeIf(v -> !usedVars.contains(v));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package de.peeeq.wurstscript.translation.imtranslation;

import de.peeeq.wurstscript.ast.GlobalVarDef;
import de.peeeq.wurstscript.ast.WParameters;
import de.peeeq.wurstscript.attributes.CompileError;
import de.peeeq.wurstscript.jassIm.*;
Expand All @@ -12,6 +13,21 @@ public class ImHelper {
/** A Jass function takes at most this many parameters. */
public static final int JASS_MAX_PARAMETERS = 31;

/** An immutable common.j handle made by its enum converter exists before the script runs. */
public static boolean isNonNullHandleConstant(ImVar v, ImProg prog) {
if (!v.getIsBJ() || !(v.getTrace() instanceof GlobalVarDef def) || !def.attrIsConstant()) {
return false;
}
List<ImSet> inits = prog.getGlobalInits().get(v);
return inits != null && inits.size() == 1
&& inits.get(0).getRight() instanceof ImFunctionCall init
&& init.getFunc().isNative() && init.getFunc().isBj()
&& init.getFunc().getName().startsWith("Convert")
&& LuaNativeLowering.isHandleType(init.getFunc().getReturnType())
&& init.getArguments().size() == 1
&& init.getArguments().get(0) instanceof ImIntVal;
}

/**
* How many Jass parameters a value of this type occupies.
* <p>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package de.peeeq.wurstscript.translation.imtranslation;

import de.peeeq.wurstscript.WurstOperator;
import de.peeeq.wurstscript.ast.GlobalVarDef;
import de.peeeq.wurstscript.attributes.CompileError;
import de.peeeq.wurstscript.jassIm.*;
import de.peeeq.wurstscript.types.TypesHelper;
Expand Down Expand Up @@ -1031,21 +1030,7 @@ private static boolean isGuardedParam(ImVar param) {
* never nil, and an argument which reads it needs no nil test.
*/
private static boolean isNeverNil(ImExpr arg, ImProg prog) {
if (!(arg instanceof ImVarAccess access)) {
return false;
}
ImVar v = access.getVar();
if (!v.getIsBJ() || !(v.getTrace() instanceof GlobalVarDef def) || !def.attrIsConstant()) {
return false;
}
List<ImSet> inits = prog.getGlobalInits().get(v);
return inits != null && inits.size() == 1
&& inits.get(0).getRight() instanceof ImFunctionCall init
&& init.getFunc().isNative() && init.getFunc().isBj()
&& init.getFunc().getName().startsWith("Convert")
&& isHandleType(init.getFunc().getReturnType())
&& init.getArguments().size() == 1
&& init.getArguments().get(0) instanceof ImIntVal;
return arg instanceof ImVarAccess access && ImHelper.isNonNullHandleConstant(access.getVar(), prog);
}

/** Returns true for WC3 handle types (ImSimpleType that is not int/real/boolean/string). */
Expand Down
Loading
Loading