summaryrefslogtreecommitdiff
path: root/chapter28a/src/main/java/com
diff options
context:
space:
mode:
authorCliff Click <cliffc@acm.org>2026-11-16 14:25:14 -0800
committerCliff Click <cliffc@acm.org>2026-11-16 14:25:14 -0800
commit0dcd3513a633479ce228f24826db4f09e4c0fc8b (patch)
treed8fb6d0fb382df5799789e9dc1eb0fae2d381cce /chapter28a/src/main/java/com
parent51a029304d8105b201bdfb81a7692b8a1b16b028 (diff)
downloadSimple-0dcd3513a633479ce228f24826db4f09e4c0fc8b.tar.gz
Simple-0dcd3513a633479ce228f24826db4f09e4c0fc8b.zip
Phi fix
Fix Phi/Add refactoring peephole to canonicalize regardless of peephole order. Treat class fcns as having `self` be the class pointer
Diffstat (limited to 'chapter28a/src/main/java/com')
-rw-r--r--chapter28a/src/main/java/com/seaofnodes/simple/Parser.java101
-rw-r--r--chapter28a/src/main/java/com/seaofnodes/simple/node/CallNode.java11
-rw-r--r--chapter28a/src/main/java/com/seaofnodes/simple/node/PhiNode.java38
-rw-r--r--chapter28a/src/main/java/com/seaofnodes/simple/node/RegionNode.java2
4 files changed, 87 insertions, 65 deletions
diff --git a/chapter28a/src/main/java/com/seaofnodes/simple/Parser.java b/chapter28a/src/main/java/com/seaofnodes/simple/Parser.java
index 3b5a8ce7..fd9d9753 100644
--- a/chapter28a/src/main/java/com/seaofnodes/simple/Parser.java
+++ b/chapter28a/src/main/java/com/seaofnodes/simple/Parser.java
@@ -290,8 +290,16 @@ public class Parser {
// All args, "as-if" called externally
for( int i=0; i<ids.length; i++ ) {
Type t = sig.arg(i);
+ // 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
- _scope.define(ids[i], t, (i==0 && ids[0]=="self") || (finals!=null && finals.get(i)), new ParmNode(ids[i],i+2,t,fun,ConstantNode.seed(fun.defaultArg(i)).peephole()).peephole(), loc);
+ _scope.define(ids[i], t, (i==0 && ids[0]=="self") || (finals!=null && finals.get(i)), new ParmNode(ids[i],i+2,t,fun,ConstantNode.seed(i==0 && t instanceof TypeMemPtr ? t : fun.defaultArg(i)).peephole()).peephole(), loc);
}
if( isCtor && !isInit ) {
@@ -1075,6 +1083,10 @@ public class Parser {
throw error("Cannot reassign final '"+name+"'");
checkSharedFunction(def);
+ // All fields use the same receiver-based lvalue path.
+ if( fieldSelf(def)!=null )
+ { pos(old); return parseExpression(); }
+
// Parse assignment expression
Node expr = parseAsgn();
@@ -1084,27 +1096,6 @@ public class Parser {
// Update
_scope.update(name,lift);
- // Check for storing into an instance field instead of a local var
- int kx = _scope.kindx(def); // Declaration scope
- int fx = _scope.enclosingFunction(); // Enclosing function scope
- Kind kk = _scope._kinds.at(kx);
- Kind fk = _scope._kinds.at(fx);
- // Access instance field from 'self'
- if( kx+1 == fx && kk instanceof Kind.Func inst && FunNode.isInstance(inst._name) &&
- fk instanceof Kind.Func method && !inExplicitConstructor() ) {
- // Named field offset on an unknown struct type
- TypeMemPtr self = (TypeMemPtr)_scope.var(fk._lexSize).type();
- TypeStruct sobj = (TypeStruct)TYPES.get(self._obj._name);
- Field fld = sobj.field(name);
- int alias = fld._alias;
- Node ptr = _scope.in(method._lexSize);
- Node off = fldoff(ptr,name);
- Node prior = mem().keep();
- Node st = new StoreNode(loc(), name, alias, decl, ctrl(), prior, ptr, off, lift, inExplicitConstructor()).peephole().keep();
- storeMem(st,alias,prior);
- st.unkeep();
- prior.unkeep();
- }
lift.unkill();
@@ -2099,35 +2090,12 @@ public class Parser {
if( inExplicitConstructor() && var._uninit && missingInit(rvalue,new BitSet()) )
throw error("Field '"+id+"' might not be initialized",var._loc);
- // Check for an instance field load
- int kx = _scope.kindx(var); // Declaration scope
- int fx = _scope.enclosingFunction(); // Enclosing function scope
- Kind kk = _scope._kinds.at(kx);
- Kind fk = _scope._kinds.at(fx);
- // Access instance field from 'self'
- if( kx+1 == fx && kk instanceof Kind.Func inst && FunNode.isInstance(inst._name) && fk instanceof Kind.Func method && !inExplicitConstructor() )
- return parsePostfixName(_scope.in(method._lexSize),id,pre);
-
- // 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 && !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 error("Variable '"+var._name+"' is out of function scope and must be a final constant");
-
- // 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 = _scope.var( 2 );
- // Get the most recent sharpen global
- TypeStruct clz = (TypeStruct) TYPES.get( ((TypeMemPtr) clzptr.type())._obj._name );
- TypeMemPtr clztmp = TypeMemPtr.make( (byte) 2, clz, true );
- return parsePostfixName( con( clztmp ), id,pre );
- //return parsePostfixName(_scope.in(2),id);
- }
- }
+ Node self = fieldSelf(var);
+ if( self!=null ) return parsePostfixName(self,id,pre);
+ int kx = _scope.kindx(var), fx = _scope.enclosingFunction();
+ if( kx>0 && kx<fx && !inExplicitConstructor() &&
+ !(var._final && rvalue._type.isConstant()) )
+ throw error("Variable '"+var._name+"' is out of function scope and must be a final constant");
// Check for assign-update, x += e0;
char ch = pre==0 ? _lexer.matchOperAssign() : (char)pre;
@@ -2372,6 +2340,31 @@ public class Parser {
return parsePostfixMethod(value,defaultSelf());
}
+ // Find the receiver for a field lvalue. Initializers retain Scope values;
+ // class declarations retain their Scope values until initializer exit.
+ private Node fieldSelf(Var var) {
+ int kx = _scope.kindx(var);
+ ScopeNode.Kind kind = _scope._kinds.at(kx);
+ if( !(kind instanceof Kind.Func owner) || !FunNode.isInit(owner._name) || var._idx<owner._lexSize+2 ) return null;
+ // Instance constructors still accumulate their fields in Scope here.
+ if( FunNode.isInstance(owner._name) && (inExplicitConstructor() || _scope.enclosingFuncOrDecl()==kx) ) return null;
+ // Class declarations still accumulate their initial values in Scope.
+ // This also preserves declaration-time struct default expressions.
+ if( FunNode.isClz(owner._name) && _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();
+ Var receiver = _scope.var(owner._lexSize);
+ if( self._type instanceof TypeMemPtr ptr && receiver.type() instanceof TypeMemPtr declared &&
+ ptr._obj._name.equals(declared._obj._name) ) return self;
+ // 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 peep(new ConvertNode(receiver.type().upgradeType(TYPES),_scope.in(receiver)));
+ }
+
private void checkSharedFunction(Var v) {
if( _scope.canInit(v) && v._final && v.type() instanceof TypeFunPtr t && t.isConstant() )
throw error("Cannot reassign shared function '"+v._name+"'");
@@ -2563,7 +2556,7 @@ public class Parser {
java.util.BitSet finals = new java.util.BitSet();
Type self = implicitSelfType();
ts.push(self);
- ids.push(self == TypePtr.PTR ? "#self" : "self");
+ ids.push("self");
// Parse other arguments
_lexer.skipWhiteSpace();
@@ -2573,6 +2566,10 @@ public class Parser {
if( t==null ) break;
finals.set(ids.size(),bindingFinal(t));
String id = 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");
ts .push(t ); // Push type/arg pairs
ids.push(id);
match(",");
diff --git a/chapter28a/src/main/java/com/seaofnodes/simple/node/CallNode.java b/chapter28a/src/main/java/com/seaofnodes/simple/node/CallNode.java
index 1a8da215..e453387b 100644
--- a/chapter28a/src/main/java/com/seaofnodes/simple/node/CallNode.java
+++ b/chapter28a/src/main/java/com/seaofnodes/simple/node/CallNode.java
@@ -5,6 +5,7 @@ import com.seaofnodes.print.ExprPrinter;
import com.seaofnodes.simple.Parser;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypePtr;
import com.seaofnodes.simple.type.TypeFunPtr;
import com.seaofnodes.simple.type.TypeMem;
import com.seaofnodes.simple.type.TypeRPC;
@@ -73,13 +74,14 @@ 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( !external() ) return TypeMem.START;
Type input = dep.addDepForwards(mem())._type;
TypeMem escaped = input instanceof TypeMem m ? m : input.isHigh() ? TypeMem.TOP : TypeMem.BOT;
TypeMem outside = CodeGen.CODE._start.outside(dep);
- for( int i = 2; i<nIns()-1; i++ )
+ // A class receiver belongs to the callee; the caller does not expose its class.
+ for( int i = tfp.nargs()>0 && tfp.arg(0)==TypePtr.PTR ? 3 : 2; i<nIns()-1; i++ )
escaped = escaped.escapesFrom(dep.addDepForwards(arg(i))._type,outside);
return TypeMem.make(1,Type.BOTTOM,false,false,false,escaped._escFs,escaped._escAs);
}
@@ -156,7 +158,10 @@ 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);
+ // Match the callee's declared receiver view, including forward fields.
+ 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/chapter28a/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter28a/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 61e4b468..afab6082 100644
--- a/chapter28a/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter28a/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -105,7 +105,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
@@ -141,10 +142,28 @@ public class PhiNode extends Node {
return tested!=null && (early==null || early.dominates(r,this)) ? n : null;
}
+ // View x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ 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 in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof ShlNode &&
+ addDep(n.in(2))._type instanceof TypeInteger con && con.isConstant() && con.value()==1;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n 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.
@@ -162,7 +181,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
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;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode add && add._mode==1 && doubled(n))) ||
+ 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
@@ -180,21 +200,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.addDef(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/chapter28a/src/main/java/com/seaofnodes/simple/node/RegionNode.java b/chapter28a/src/main/java/com/seaofnodes/simple/node/RegionNode.java
index 923773c4..e0860233 100644
--- a/chapter28a/src/main/java/com/seaofnodes/simple/node/RegionNode.java
+++ b/chapter28a/src/main/java/com/seaofnodes/simple/node/RegionNode.java
@@ -65,7 +65,7 @@ public class RegionNode extends CFGNode {
if( use instanceof PhiNode phi ) {
PhiNode phi2 = phi.in(i) instanceof PhiNode phi2x && phi2x.region()==region ? phi2x : null;
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);
}
}