summaryrefslogtreecommitdiff
path: root/chapter32
diff options
context:
space:
mode:
Diffstat (limited to 'chapter32')
-rw-r--r--chapter32/README.md103
-rw-r--r--chapter32/docs/32-grammar.md10
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/node/CallNode.java15
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/node/PhiNode.java39
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/node/RegionNode.java3
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/node/SummaryNode.java11
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/parser/Expressions.java3
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/parser/Functions.java14
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/parser/References.java55
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/Chapter05Test.java35
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/Chapter20Test.java4
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/Chapter21Test.java8
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/Chapter22Test.java6
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java71
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/ReceiverTest.java93
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java2
16 files changed, 405 insertions, 67 deletions
diff --git a/chapter32/README.md b/chapter32/README.md
index f06b404f..7a814966 100644
--- a/chapter32/README.md
+++ b/chapter32/README.md
@@ -460,6 +460,109 @@ must be rebuilt; an old header produces an explicit rebuild error. For an
existing chapter32 build, `make clean` followed by `make -j 8 release` rebuilds
the generated artifacts. Rebuild any separately maintained Simple libraries too.
+## Receiver backport and spill investigation
+
+The shared class receiver is taught in
+[chapter 28a](../chapter28a/README.md#globals-use-the-same-receiver-as-fields),
+with imported summaries in [chapter 28b](../chapter28b/README.md).
+Those fixes are carried through the later snapshots. Phi factoring after
+strength reduction starts in
+[chapter 5](../chapter05/README.md#factoring-after-strength-reduction), using
+multiply-by-two there and shift-by-one where that representation is introduced.
+
+The receiver investigation also exposed a missed notification in
+[RegionNode](src/main/java/com/seaofnodes/simple/node/RegionNode.java): flattening
+regions adds Phi inputs, so their definitions must be queued too. A newly added
+precise memory user can require its bulk-memory input to split immediately.
+That prerequisite accompanies the receiver backport.
+
+The following measurements describe the chapter32 investigation before backporting.
+
+Validation: all 817 test executions pass on Windows with log8 verification and
+Linux with the default log10. A focused 62-test run passes with log1, checking
+every progress step. Native callbacks, imported receivers, FileIO, and ARM/RISC-V
+execution remain covered.
+
+There is a compilation/code-size cost to review. The following Windows comparison
+uses the preceding uncommitted assignment fix as its baseline, assertions enabled,
+two JVM processors, seed 456, and each compiler's freshly built libraries. Times
+are medians of four warm rounds after discarding the first round; this is a small
+local sample, not a timing guarantee. Sys sizes sum its 22 object files.
+
+| Compile | Time, ms (before → after) | Peepholes (before → after) | `.text` bytes (before → after) |
+| --- | ---: | ---: | ---: |
+| sys | 961 → 977 | 185,960 → 208,552 | 37,725 → 40,355 |
+| Clock | 256 → 381 | 86,873 → 106,615 | 6,717 → 7,053 |
+| Breakout | 553 → 593 | 158,712 → 174,500 | 14,868 → 15,031 |
+| TicTacToe | 161 → 177 | 56,222 → 63,774 | 4,251 → 4,411 |
+
+The small String and HelloWorld examples also retain additional initialization
+checks, and their spill expectations have been updated. The receiver-only change
+exposed an existing ordering sensitivity in Sieve: across seeds 120–127, both
+compilers produced seven 28-split/343-weight results and one 26-split/215-weight
+result, with the smaller result moving from seed 126 to 121.
+
+The spill investigation separates compile time from generated moves: Clock's
+weighted split score improves from 785 to 762. These scores count all retained
+SplitNodes, including register copies, with weight `8^loopDepth`; they are not
+counts of stack spills. Sieve's 215-to-343 change is two extra register copies
+inside its depth-two loop. Early `p+p` strength reduction in
+[AddNode](src/main/java/com/seaofnodes/simple/node/AddNode.java) turns the entry
+value into `p<<1` before [PhiNode](src/main/java/com/seaofnodes/simple/node/PhiNode.java)
+can factor `Phi(p+p,i+p)` into `Phi(p,i)+p`.
+
+Phi factoring now views `x<<1` as `x+x` when matching mixed Add/Shl arms. It uses
+the existing factoring checks and trial graph, without expanding a shift into
+an Add that would immediately strength-reduce again. Pure shift arms retain
+ordinary shift factoring. Multiply-by-two already reduces to this shift, so it
+is covered too. This is a local canonicalization: peeling one `x` from `k*x` for
+arbitrary k would require a new `(k-1)*x` expression, with less clear cost and
+rewrite-order benefits. The implementation stops at doubling.
+
+All eight Sieve seeds now produce 26 splits and score 215, with every-step
+verification; the spill expectation is 215. Direct graph tests check factoring
+before and after strength reduction, either arm order, and rejection of a
+different shift count. The 819-test Windows sweep passes with log8 verification
+(the Sieve group rerun after updating its expectation), and 64 focused tests
+pass with log1. Native and emulator Sieve results are checked too.
+
+The largest individual sys increase in the receiver-only comparison was
+`Canvas._circle`, from 455 to 517.
+Allocation keeps the loop-invariant boolean in a general register and the pixel
+pointer in an XMM register; recovering the pointer adds a transfer at each pixel
+store. The baseline makes the opposite choice. Both ranges receive the default
+score 1000 in [IFG.pickRiskyScore](src/main/java/com/seaofnodes/simple/codegen/IFG.java),
+leaving their selection sensitive to ordering. An isolated trial giving SetX86
+candidates one extra priority point brings `_circle` to 454 and total sys to
+8869, versus baseline 8719 and current 8932. Other sys functions' weighted scores
+are unchanged by that trial. This identifies an allocator sensitivity; the
+opcode-specific preference is diagnostic, not an adopted heuristic.
+
+With Phi factoring fixed, sys's weighted score is 8850 and `_circle` returns to
+455 through another ordering change. Clock stays at 762, Breakout changes from
+3387 to 3393, and TicTacToe stays at 1468. A bounded allocator follow-up tried
+three cheap refinements of the default score: breaking ties toward fewer excess
+neighbors (degree minus available colors), toward more excess neighbors, and a
+bonus for cheap single-def/single-use splits based on loop depth. Sys scored
+9039, 8844, and 8850 respectively; the three games were unchanged. The tiny
+six-point gain does not justify adopting the degree tie-break on this evidence.
+The production allocator remains unchanged; no additional graph walks or
+searches were added.
+
+Backporting retains each chapter's allocator. Code-quality expectations are
+therefore checked locally: chapter21's RISC-V Sieve score changes from 92 to
+164, despite the chapter32 improvement above, and chapter31's forward-field
+scanner test changes from 23 to 31 on x86-64/Win64. Execution checks remain in
+place; these earlier snapshots do not inherit the later allocator experiments.
+Chapter31 also groups `TimeTest` with its sys tests: its wide-library compile
+passes in a fresh JVM, but following the large catch-all suite exhausted that
+snapshot's existing 16-bit type IDs. This keeps the checks and the older type
+implementation intact; it does not remove the compiler's type-ID limit.
+
+The saved baseline, comparison drivers, measurements, and verification logs are
+under `build/receiver-profile/`. Proving initialization checks redundant is the
+main follow-up suggested by these measurements.
+
## Build and test
From `chapter32`, using the existing offline dependency caches:
diff --git a/chapter32/docs/32-grammar.md b/chapter32/docs/32-grammar.md
index 2628f566..4a794341 100644
--- a/chapter32/docs/32-grammar.md
+++ b/chapter32/docs/32-grammar.md
@@ -69,6 +69,7 @@ constructorParameter : type '^'? bindingModifier? IDENTIFIER ;
// A method is an ordinary fixed function binding in a struct definition.
// The compiler supplies self; it is not written in parameterList.
// Function types and expressions both receive their implicit receiver here.
+// Global functions use their owning class singleton as self.
methodDeclaration : 'val' bindingModifier? memberName '=' functionExpression ';' ;
memberName : IDENTIFIER | primitiveType ;
@@ -254,10 +255,11 @@ one-pass IR builder:
- A statement beginning with `{` might be a block or a function-type binding.
`Declarations` and `Types` use speculative parsing and cursor restore;
qualified type lookup also stops before a suffix that belongs to an expression.
-- Bare assignment, field assignment, and compound updates share the grammar's
- precedence but use different IR paths. `References` decides between an SSA
- local, a constructor field's local value, and an actual memory access. A
- function-valued field may also supply an implicit receiver to a call.
+- `References` resolves bare fields through their receiver, so assignments,
+ reads, and updates share the field-access path. Locals use SSA; class
+ initializer declarations retain their Scope values until initializer exit.
+ Global functions receive their owning class singleton as `self`, including
+ when invoked through a callback. Instance methods receive their object.
- `for` updates are scanned first and parsed after the body, where their effects
belong. Explicit constructor bodies are scanned first and parsed after field
discovery, so later fields have local slots. Both use `Lexer.skipTo`, which
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/node/CallNode.java b/chapter32/src/main/java/com/seaofnodes/simple/node/CallNode.java
index 3b2dc75b..5506621b 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/node/CallNode.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/node/CallNode.java
@@ -7,6 +7,7 @@ import com.seaofnodes.simple.parser.Parser;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.codegen.Iter;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypePtr;
import com.seaofnodes.simple.type.TypeMemPtr;
import com.seaofnodes.simple.type.TypeFunPtr;
import com.seaofnodes.simple.type.TypeMem;
@@ -95,13 +96,15 @@ public class CallNode extends CFGNode {
// A broad scalar target can refine to a function pointer during Iter.
// It cannot yet promise that the call exposes nothing.
if( _type!=Type.CONTROL ) return TypeMem.BOT;
- if( !(fptr()._type instanceof TypeFunPtr) )
+ if( !(fptr()._type instanceof TypeFunPtr tfp) )
return fptr()._type.isHigh() ? TypeMem.START : TypeMem.BOT;
if( Intrinsic.pure(this) ) return TypeMem.START;
if( !external() ) return TypeMem.START;
Type input = dep.addDepForwards(mem())._type;
TypeMem escaped = input instanceof TypeMem m ? m : input.isHigh() ? TypeMem.TOP : TypeMem.BOT;
- for( int i = 2; i<nIns()-1; i++ ) {
+ // The class-receiver slot is absent from the ABI. The callee supplies
+ // its own singleton, so passing a callback does not expose our class.
+ for( int i = tfp.nargs()>0 && tfp.arg(0)==TypePtr.PTR ? 3 : 2; i<nIns()-1; i++ ) {
Type arg = dep.addDepForwards(arg(i))._type;
TypeMem outside = TypeMem.opaque(arg) ? CodeGen.CODE._start.outside(dep) : TypeMem.BOT;
escaped = escaped.escapesFrom(arg,outside);
@@ -182,7 +185,13 @@ public class CallNode extends CFGNode {
CodeGen.CODE.add(fun).addDef(this);
for( Node use : fun._outputs )
if( use instanceof ParmNode parm ) {
- Node def = parm._idx==0 ? ConstantNode.seed(cend()._rpc).peephole() : arg(parm._idx);
+ // A class function's receiver belongs to the callee, even
+ // when a different class or an instance forwards its callback.
+ // Match its declared view: before SCCP, forward fields can
+ // still differ from the completed class layout.
+ Node def = parm._idx==0 ? ConstantNode.seed(cend()._rpc).peephole()
+ : parm._idx==2 && fun.sig().arg(0)==TypePtr.PTR
+ ? ConstantNode.seed(parm._declaredType).peephole() : arg(parm._idx);
CodeGen.CODE.add(parm).addDef(def);
// Linking can happen during post-SCCP inlining. Keep an RPC
// Parm's cached finite set synchronized with its newly added
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter32/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 7544962f..94376086 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -122,7 +122,8 @@ public class PhiNode extends Node {
// Generic "pull down op"
Node progress;
- if( same_op() && (progress = drop_same_op()) != null )
+ Node op = factoringOp();
+ if( same_op(op) && (progress = drop_same_op(op)) != null )
return progress;
// If merging Phi(ZERO, guardNZ(N)) at the matching `if(N)` join, the
@@ -161,10 +162,28 @@ public class PhiNode extends Node {
return tested!=null && (early==null || early.dominates(r,this)) ? n : null;
}
+ // View x<<1 as x+x when factoring mixed Add/Shl arms. Do not expand the
+ // graph: Add would immediately strength-reduce it again. If all arms are
+ // shifts, keep the ordinary shift factoring (including arbitrary counts).
+ private Node factoringOp() {
+ Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode add && add._mode==1 ) return add;
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof ShlNode && addDep(n.in(2))._type==TypeInteger.TRUE;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return n instanceof ShlNode && op instanceof AddNode ? n.in(1) : n.in(j);
+ }
+
// Same op on all Phi paths; all ops have only the Phi as a use.
// None have a control input.
- private boolean same_op() {
- Node op = in(1);
+ private boolean same_op(Node op) {
if( op instanceof EscapeNode || op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -181,8 +200,10 @@ public class PhiNode extends Node {
Node busy = null;
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
+ boolean same = op.getClass()==n.getClass() && op.eq(n);
+ if( !same && op instanceof AddNode add && add._mode==1 ) same = doubled(n);
if( addDep(region().in(i))._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !same || n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -200,21 +221,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp._inputs.add(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
// Do not introduce an operand Phi mixing incompatible type families.
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/node/RegionNode.java b/chapter32/src/main/java/com/seaofnodes/simple/node/RegionNode.java
index ca358b5a..17126f27 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/node/RegionNode.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/node/RegionNode.java
@@ -68,8 +68,9 @@ public class RegionNode extends CFGNode {
for( Node use : _outputs ) {
if( use instanceof PhiNode phi ) {
PhiNode phi2 = phi.in(i) instanceof PhiNode phi2x && phi2x.region()==region ? phi2x : null;
+ // New users can require a bulk-memory input to split.
for( int j=1; j<region.nIns(); j++ )
- phi.addDef(phi2==null ? phi.in(i) : phi2.in(j));
+ phi.addDef(CodeGen.CODE.add(phi2==null ? phi.in(i) : phi2.in(j)));
CodeGen.CODE.add(phi);
}
}
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/node/SummaryNode.java b/chapter32/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
index f73ba611..5b945457 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
@@ -26,7 +26,7 @@ public class SummaryNode extends CFGNode implements MultiNode {
// A library summary does not forget escapes already present in the caller.
TypeMem mem = in(1)._type instanceof TypeMem m ? m : in(1)._type.isHigh() ? TypeMem.TOP : TypeMem.BOT;
mem = (TypeMem)mem.meet(_state.mem());
- for( int i = 2; i<nIns(); i++ ) {
+ for( int i = firstArgument(); i<nIns(); i++ ) {
Type arg = in(i)._type;
// Only opaque arguments can hide identities supplied by outside code.
TypeMem outside = TypeMem.opaque(arg) ? CodeGen.CODE._start.outside(this) : TypeMem.BOT;
@@ -39,13 +39,20 @@ public class SummaryNode extends CFGNode implements MultiNode {
dep.addDepForwards(this);
if( dep.addDepForwards(in(0))._type.isHigh() ) return TypeMem.START;
TypeMem mem = (TypeMem)_state.mem();
- for( int i = 2; i<nIns(); i++ ) {
+ for( int i = firstArgument(); i<nIns(); i++ ) {
Type arg = dep.addDepForwards(in(i))._type;
TypeMem outside = TypeMem.opaque(arg) ? CodeGen.CODE._start.outside(dep) : TypeMem.BOT;
mem = mem.escapesFrom(arg,outside);
}
return TypeMem.make(1,Type.BOTTOM,false,false,false,mem._escFs,mem._escAs);
}
+ // A class receiver is supplied by the callee, not exposed by its caller.
+ // Actual uses which publish self are already represented in _state.
+ private int firstArgument() {
+ if( !(in(0) instanceof FunNode fun) ) return 2;
+ TypeFunPtr sig = fun.sig();
+ return sig.nargs()>0 && sig.arg(0)==TypePtr.PTR ? 3 : 2;
+ }
@Override boolean _upgradeType(HashMap<String,Type> types) {
TypeTuple state = (TypeTuple)_state.upgradeType(types);
if( state==_state ) return false;
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/parser/Expressions.java b/chapter32/src/main/java/com/seaofnodes/simple/parser/Expressions.java
index ffc96f57..f791a34c 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/parser/Expressions.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/parser/Expressions.java
@@ -36,6 +36,9 @@ final class Expressions {
{ P.pos(old); return parseExpression(); }
P.references.checkAssignment(def,site);
+ // All fields use the same receiver-based lvalue path.
+ if( P.references.fieldSelf(def)!=null )
+ { P.pos(old); return parseExpression(); }
return P.references.assign(def,parseAssignment());
}
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/parser/Functions.java b/chapter32/src/main/java/com/seaofnodes/simple/parser/Functions.java
index 84bd509e..a7726521 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/parser/Functions.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/parser/Functions.java
@@ -36,7 +36,7 @@ final class Functions {
Type self = P.types.implicitSelfType();
if( P.structs.inStructDeclaration() ) self = self.makeRO();
ts.push(self);
- ids.push(self == TypePtr.PTR ? "#self" : "self");
+ ids.push("self");
// Parse other arguments
P._lexer.skipWhiteSpace();
@@ -130,6 +130,10 @@ final class Functions {
P._lexer.skipWhiteSpace();
Lexer nameLoc=P.loc();
String id = P.requireId();
+ // Older free functions may explicitly name a source argument
+ // "self". It shadows the implicit class receiver, not its ABI slot.
+ if( id=="self" && ts.at(0)==TypePtr.PTR && ids.at(0)=="self" )
+ ids.set(0,"#self");
if( ids.find(id)!=-1 ) throw Parser.error("Duplicate parameter '"+id+"'",nameLoc);
ts .push(t ); // Push type/arg pairs
ids.push(id);
@@ -359,6 +363,14 @@ final class Functions {
if( i == 0 && ids[0].equals("self") && !FunNode.isInit(funName) &&
!(sig.ret() instanceof TypeMem) && t instanceof TypeMemPtr ptr )
t = ptr.withAccess(false);
+ // The body sees its owning class receiver. PTR remains in the
+ // signature as the ABI marker for a receiver with no machine slot.
+ if( i==0 && t==TypePtr.PTR ) {
+ TypeStruct clz = ((TypeMemPtr)fun.defaultArg(i))._obj;
+ // A file can add globals after its struct declaration closes.
+ // Keep this view open until SCCP installs the completed class.
+ t = TypeMemPtr.make((byte)2,TypeStruct.make(clz._name,true,clz._fields),true);
+ }
// Args take a default input if called from Start/external-world
Type seed = i == 0 && t instanceof TypeMemPtr ? t : fun.defaultArg(i);
Node parm = new ParmNode(ids[i],i+2,t,fun,ConstantNode.seed(seed).peephole()).peephole();
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/parser/References.java b/chapter32/src/main/java/com/seaofnodes/simple/parser/References.java
index 7724103e..91cf6859 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/parser/References.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/parser/References.java
@@ -93,23 +93,9 @@ final class References {
// Check for a function-escaping variable; these require true
// closures. Final constants are OK; final vars require a hidden var
// argument; not-final fields can just use an explicit struct arg.
- if( kx < fx && !P.structs.inExplicitConstructor() && // Out of scope
- !(var._final && rvalue._type.isConstant()) ) { // Not a final constant
- if( kx > 0 ) // Global scope is OK, only ever one of these (not one per function invoke)
- throw Parser.error("Variable '"+var._name+"' is out of function scope and must be a final constant",site);
-
- // var.idx==2 is self argument, 3 is args, 4 or more are now static globals
- if( var._idx >= 4 ) {
- // Read from global scope.
- // Surely a nicer way to get the top-level scope compile name?
- Var clzptr = P._scope.var( 2 );
- // Get the most recent sharpen global
- TypeStruct clz = (TypeStruct) Parser.TYPES.get( ((TypeMemPtr) clzptr.type())._obj._name );
- TypeMemPtr clztmp = TypeMemPtr.make( (byte) 2, clz, true );
- return parseField( P.con( clztmp ), id,pre );
- //return parseField(_scope.in(2),id);
- }
- }
+ if( kx>0 && kx<fx && !P.structs.inExplicitConstructor() &&
+ !(var._final && rvalue._type.isConstant()) )
+ throw Parser.error("Variable '"+var._name+"' is out of function scope and must be a final constant",site);
// Check for assign-update, x += e0;
char ch = pre==0 ? P._lexer.matchOperAssign() : (char)pre;
@@ -144,19 +130,6 @@ final class References {
}
Node assign(Var def, Node expr) {
- Node self = fieldSelf(def);
- if( self!=null ) {
- TypeStruct ts = P.types.latestStruct(((TypeMemPtr)self._type)._obj);
- Field fld = ts.field(def._name);
- Node val = expr.keep();
- Node lift = P.conversions.convertExpr(val,def.type());
- Node mem = P.construction.storeMemory(self).keep();
- Node st = new StoreNode(P.loc(),fld._fname,fld._alias,fld._t,P.ctrl(),mem,self,
- ConFldOffNode.make(ts,fld._fname),lift,P.construction.own(self)).peephole();
- P.construction.store(self,fld._alias,st,mem);
- mem.unkeep();
- return val.unkeep();
- }
String name = def._name;
// Lift expression, based on type
Type decl = def.type(); // Declared type
@@ -305,19 +278,27 @@ final class References {
return P._scope.in(P._scope.update(P._scope.var(selfx),null));
}
- // Fields are lvalues in memory, including inside their initializer and
- // explicit constructor. Scope slots retain declaration metadata only.
- private Node fieldSelf(Var var) {
+ // Find the receiver for a field lvalue. Instance initializers use memory;
+ // class declarations retain their Scope values until initializer exit.
+ Node fieldSelf(Var var) {
int kx = P._scope.kindx(var);
ScopeNode.Kind kind = P._scope._kinds.at(kx);
- if( !(kind instanceof Kind.Func inst) || !FunNode.isInstance(inst._name) || var._idx<inst._lexSize+2 ) return null;
+ if( !(kind instanceof Kind.Func owner) || !FunNode.isInit(owner._name) || var._idx<owner._lexSize+2 ) return null;
+ // Class declarations still accumulate their initial values in Scope.
+ // This also preserves declaration-time struct default expressions.
+ if( FunNode.isClz(owner._name) && P._scope.enclosingFunction()==kx ) return null;
// Nested functions have their own receiver parameter. Resolve fields
// through it even across intervening function and block scopes.
Node self = defaultSelf();
- Type owner = P._scope.var(inst._lexSize).type();
- if( self._type instanceof TypeMemPtr ptr && owner instanceof TypeMemPtr declared &&
+ Var receiver = P._scope.var(owner._lexSize);
+ if( self._type instanceof TypeMemPtr ptr && receiver.type() instanceof TypeMemPtr declared &&
ptr._obj._name.equals(declared._obj._name) ) return self;
- return null;
+ // An instance method can also name fields of its enclosing class.
+ // Use that declaration's receiver; normal folding handles its identity.
+ if( !FunNode.isClz(owner._name) ) return null;
+ // The enclosing declaration may have discovered more fields since
+ // creating its receiver. View that same receiver with its current type.
+ return P.peep(new ConvertNode(receiver.type().upgradeType(Parser.TYPES),P._scope.in(receiver)));
}
private void checkSharedFunction(Var v) {
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter32/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index 43057c00..9f733da5 100644
--- a/chapter32/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter32/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -2,6 +2,7 @@ package com.seaofnodes.simple;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeInteger;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -201,4 +202,38 @@ return a;
catch( RuntimeException e ) { assertEquals("Undefined name 'ififif'",e.getMessage()); }
}
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean shift : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ CodeGen code = new CodeGen("");
+ Node ctrl = new CProjNode(code._start,0,"Ctrl").init();
+ RegionNode region = new RegionNode(null,null,ctrl,ctrl).init();
+ Node p = code.con(TypeInteger.BOT), i = code.con(TypeInteger.I32);
+ Node twice = shift ? new ShlNode(null,p,code.con(1)).init()
+ : new AddNode(p,p,(byte)1).init();
+ Node sum = new AddNode(i,p,(byte)1).init();
+ PhiNode phi = new PhiNode("sum",region,reverse ? sum : twice,reverse ? twice : sum).init();
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
+
+ @Test public void testOtherShiftIsNotDoubling() {
+ CodeGen code = new CodeGen("");
+ Node ctrl = new CProjNode(code._start,0,"Ctrl").init();
+ RegionNode region = new RegionNode(null,null,ctrl,ctrl).init();
+ Node p = code.con(TypeInteger.BOT), i = code.con(TypeInteger.I32);
+ Node shift = new ShlNode(null,p,code.con(2)).init();
+ Node sum = new AddNode(i,p,(byte)1).init();
+ PhiNode phi = new PhiNode("sum",region,shift,sum).init();
+ phi.keep();
+ assertNull(phi.idealize());
+ phi.unkeep();
+ }
}
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/Chapter20Test.java b/chapter32/src/test/java/com/seaofnodes/simple/Chapter20Test.java
index 273d76ba..226425ca 100644
--- a/chapter32/src/test/java/com/seaofnodes/simple/Chapter20Test.java
+++ b/chapter32/src/test/java/com/seaofnodes/simple/Chapter20Test.java
@@ -262,8 +262,8 @@ val hashCode = { !String self ->
""";
// Return the public hashCode wrapper; keep its helper private.
testCPU(src,"x86_64_v2", "SystemV",28,null);
- testCPU(src,"riscv" , "SystemV",8,null);
- testCPU(src,"arm" , "SystemV",6,null);
+ testCPU(src,"riscv" , "SystemV",11,null);
+ testCPU(src,"arm" , "SystemV",11,null);
}
@Test
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/Chapter21Test.java b/chapter32/src/test/java/com/seaofnodes/simple/Chapter21Test.java
index 347f2ce4..7a59adb0 100644
--- a/chapter32/src/test/java/com/seaofnodes/simple/Chapter21Test.java
+++ b/chapter32/src/test/java/com/seaofnodes/simple/Chapter21Test.java
@@ -386,8 +386,8 @@ val hashCode = { !String self ->
""";
// Return the public hashCode wrapper; keep its helper private.
testCPU(src,"x86_64_v2", "SystemV",28,null);
- testCPU(src,"riscv" , "SystemV",8,null);
- testCPU(src,"arm" , "SystemV",6,null);
+ testCPU(src,"riscv" , "SystemV",11,null);
+ testCPU(src,"arm" , "SystemV",11,null);
}
@Test public void testStringExport() throws IOException {
@@ -533,8 +533,8 @@ val sieve = { int N ->
String sprimes = sb.p("]").toString();
// Compile, link against native C; expect the above string of primes to be printed out by C
- // Load/Phi hoisting now requires the pointer before the loop entry.
- TestC.runC(src, "sieve", sprimes,216);
+ // Phi factoring also recognizes p<<1 after p+p strength reduction.
+ TestC.runC(src, "sieve", sprimes,215);
// Evaluate on RISC5 emulator; expect return of an array of primes in
// the simulated heap.
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/Chapter22Test.java b/chapter32/src/test/java/com/seaofnodes/simple/Chapter22Test.java
index c9791de4..f9146ae6 100644
--- a/chapter32/src/test/java/com/seaofnodes/simple/Chapter22Test.java
+++ b/chapter32/src/test/java/com/seaofnodes/simple/Chapter22Test.java
@@ -302,17 +302,17 @@ val p = { u8[~] str ->
p("Hello, World!");
return 0;
""";
- TestC.runSF(src,"helloWorld", "Hello, World!",2);
+ TestC.runSF(src,"helloWorld", "Hello, World!",4);
// Evaluate on RISC5 emulator
- EvalRisc5 R5 = TestRisc5.build( src, "helloWorld", 0, 5, false);
+ EvalRisc5 R5 = TestRisc5.build( src, "helloWorld", 0, 8, false);
int trap = R5.step(100);
assertEquals(0,trap);
assertEquals(0,R5.regs[riscv.A0]);
assertEquals("Hello, World!",R5._stdout.toString());
// Evaluate on ARM emulator
- EvalArm64 arm = TestArm64.build("helloWorld", src,0, 5, false);
+ EvalArm64 arm = TestArm64.build("helloWorld", src,0, 8, false);
trap = arm.step(100);
assertEquals(0,trap);
assertEquals(0,arm.regs[0]);
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java b/chapter32/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java
new file mode 100644
index 00000000..51ed10c6
--- /dev/null
+++ b/chapter32/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java
@@ -0,0 +1,71 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.CodeGen;
+import com.seaofnodes.simple.parser.Parser;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class GlobalAssignmentTest {
+ private static final String SOURCE = """
+ int value=1;
+ int writes=0;
+ u8 small=0;
+ val set={int n -> value=n; return value;};
+ val set_noInline={int n ->
+ if( n<0 ) value=3;
+ else value=n;
+ return value;
+ };
+ val rhs_noInline={ -> writes=writes+1; return value+1;};
+ val shadow={int value -> value=42; return value;};
+ struct Writer {
+ int seen;
+ new Writer={int n -> value=n; seen=value;};
+ };
+ struct InitWriter { int seen=(value=17); };
+ val main={ ->
+ if( set(5)!=5 || value!=5 ) return 1;
+ if( set_noInline(-1)!=3 || value!=3 ) return 2;
+ if( set_noInline(8)!=8 || value!=8 ) return 3;
+ int result=(value=rhs_noInline());
+ if( result!=9 || value!=9 || writes!=1 ) return 4;
+ value=writes=11;
+ if( value!=11 || writes!=11 ) return 5;
+ if( shadow(0)!=42 || value!=11 ) return 6;
+ int wide=(small=257);
+ if( wide!=257 || small!=1 ) return 7;
+ val constructed=new Writer(13);
+ if( value!=13 || constructed.seen!=13 ) return 8;
+ val initialized=new InitWriter;
+ // Default expressions run at declaration time, not per instance.
+ if( value!=13 || initialized.seen!=17 ) return 9;
+ return 0;
+ };
+ return main();
+ """;
+
+ @Test public void storesGlobalMemory() throws Exception {
+ assertEquals("0",Eval2.eval(new CodeGen(SOURCE).driver(CodeGen.Phase.TypeCheck),0));
+ TestC.runSF(SOURCE,"global_assignment","",-1);
+ }
+
+ @Test public void rejectsFinalGlobal() {
+ try {
+ new CodeGen("val value=1; val set={ -> value=2; }; return set();")
+ .driver(CodeGen.Phase.TypeCheck);
+ fail("Assigned a final global");
+ } catch( Parser.ParseException e ) {
+ assertEquals("Cannot reassign final 'value'",e.getMessage());
+ }
+ }
+
+ @Test public void rejectsIncompatibleGlobalValue() {
+ try {
+ new CodeGen("struct S { int x; }; int value=1; val set={ -> value=new S; }; set(); return value;")
+ .driver(CodeGen.Phase.TypeCheck);
+ fail("Stored an object in an integer global");
+ } catch( Parser.ParseException expected ) {
+ assertTrue(expected.getMessage(),expected.getMessage().contains("not of declared type"));
+ }
+ }
+}
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/ReceiverTest.java b/chapter32/src/test/java/com/seaofnodes/simple/ReceiverTest.java
new file mode 100644
index 00000000..83bf6768
--- /dev/null
+++ b/chapter32/src/test/java/com/seaofnodes/simple/ReceiverTest.java
@@ -0,0 +1,93 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.*;
+import com.seaofnodes.simple.type.TypeInteger;
+import com.seaofnodes.simple.util.Ary;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class ReceiverTest {
+ @Test public void classAndInstanceFields() throws Exception {
+ String source="""
+ int total=1;
+ val forward={ -> late(); };
+ val early={ -> total; };
+ val late={ -> early(); };
+ val add_noInline={int n -> self.total=self.total+n; return total;};
+ val read_noInline={ -> self.total; };
+ val nested={ ->
+ val inc={ -> self.total++; };
+ inc();
+ return total;
+ };
+ struct Counter {
+ int total=100;
+ val read=read_noInline;
+ };
+ struct Writer {
+ int count=2;
+ val step={ -> self.count++; total=count; return total; };
+ };
+ val table=new u16[~2]{7,9};
+ val lookup={u8 c -> c<2 ? table[c] : 0;};
+ val main={ ->
+ total=1;
+ if( forward()!=1 ) return 4;
+ if( lookup(1)!=9 || lookup(2)!=0 ) return 5;
+ if( add_noInline(5)!=6 || nested()!=7 ) return 1;
+ val counter=new Counter;
+ if( counter.read()!=7 || counter.total!=100 ) return 2;
+ val a=new Writer, b=new Writer;
+ if( a.step()!=3 || total!=3 || a.count!=3 || b.count!=2 ) return 3;
+ return 0;
+ };
+ return main();
+ """;
+ assertEquals("0",Eval2.eval(new CodeGen(source).driver(CodeGen.Phase.TypeCheck),0));
+ TestC.runSF(source,"class_instance_receivers","",-1);
+ }
+
+ @Test public void importedCallbackKeepsItsClass() throws Exception {
+ Path build=Path.of("build/objs/receivers");
+ Files.createDirectories(build);
+ Path lib=Files.createTempDirectory(build,"classes-");
+ new CodeGen(null,lib.toString(),null,"Owner",
+ "int value=7; val get_noInline={ -> self.value; };",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ new CodeGen(null,lib.toString(),null,"Forwarder",
+ "int value=99; val apply_noInline={ {int} action -> action()+self.value; };",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ var paths=new Ary<>(new String[]{lib.toString()});
+ String source="return Forwarder.apply_noInline(Owner.get_noInline)==106 ? 0 : 1;";
+ CodeGen code=new CodeGen(null,null,paths,"ReceiverClient",source,123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ assertEquals("0",Eval2.eval(code,0));
+ TestC.run(source,"imported_receivers",paths,TestC.CALL_CONVENTION,null,null,"",-1);
+ }
+
+ @Test public void classReceiverHasNoNativeArgument() throws Exception {
+ String source="""
+ int base=10;
+ val calc={int a,int b,int c,int d,int e,int f,int g ->
+ self.base+a+2*b+3*c+4*d+5*e+6*f+7*g;
+ };
+ val callback_noInline={int n -> self.base+n;};
+ { {int -> i64} int -> i64 } invoke="C";
+ val viaC={int n -> invoke(callback_noInline,n);};
+ """;
+ Path build=Path.of("build/objs/receivers");
+ Files.createDirectories(build);
+ Path driver=build.resolve("native_receiver.c");
+ Files.writeString(driver,"""
+ typedef long long (__attribute__((CALL_CONV)) *action_t)(int);
+ __attribute__((CALL_CONV)) long long invoke(action_t action, int n) { return action(n); }
+ __attribute__((CALL_CONV)) extern long long calc(int,int,int,int,int,int,int);
+ __attribute__((CALL_CONV)) extern long long viaC(int);
+ int main(void) { return calc(1,2,3,4,5,6,7)!=150 || viaC(5)!=15; }
+ """);
+ TestC.run(source,"native_receiver",null,TestC.CALL_CONVENTION,
+ TestC.CALL_CONVENTION.equals("win64") ? "ms_abi" : "sysv_abi",driver.toString(),"",-1);
+ }
+}
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java b/chapter32/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java
index 404201e3..cc4e552f 100644
--- a/chapter32/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java
+++ b/chapter32/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java
@@ -16,7 +16,7 @@ public class SeparateCompilationTest {
Path lib=Files.createTempDirectory(build,"wide-memory-");
StringBuilder source=new StringBuilder("int f0=7;\n");
for( int i=1; i<300; i++ ) source.append("int f").append(i).append("=0;\n");
- source.append("val touch={int n -> f299+=n; return f0+f299;};");
+ source.append("val touch={int n -> f299=n; return f0+f299;};");
new CodeGen(null,lib.toString(),null,"Wide",source.toString(),123,true,TypeInteger.BOT)
.driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
var paths=new Ary<>(new String[]{lib.toString()});