From c37676fc0c04997f51f4659848570619f68ac10d Mon Sep 17 00:00:00 2001 From: Cliff Click Date: Sat, 28 Nov 2026 13:34:22 -0800 Subject: A redo of Allocation --- .../com/seaofnodes/simple/codegen/Allocation2.java | 460 +++++++++++++++++++++ 1 file changed, 460 insertions(+) create mode 100644 chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation2.java (limited to 'chapter33/src/main/java') diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation2.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation2.java new file mode 100644 index 00000000..42490961 --- /dev/null +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation2.java @@ -0,0 +1,460 @@ +package com.seaofnodes.simple.codegen; + +import com.seaofnodes.simple.node.*; +import com.seaofnodes.simple.type.*; +import com.seaofnodes.simple.util.*; + +import java.awt.*; +import java.util.*; + +/** Allocation-site points-to analysis of the optimized graph. One object per + * NewNode; calls share their callee's facts. Fields use weak updates and array + * indices share one field. This pass neither proves ownership nor changes IR. + *

+ * Facts only grow. Reading a fact registers a dependency; changing it + * schedules its readers. Loads/stores discover field dependencies as their + * bases grow. Unknown means arbitrary storage, not an empty points-to set. + */ +public final class Allocation2 { + private final CodeGen _code; + + // --------------------------------- + // Things that can be pointed-at; a NewNode allocation or a static pre- + // initialized Constant (basically a NewNode moved to program genysis). + public static final class Site { + public final Node _node; // NewNode or static ConstantNode + // Each field has its own set of things it points to. This array is + // indexed by Field index; it may be null if there are no reference + // fields; each element can be null if e.g. its a non-pointer, OR if no + // points-to info is discovered. + public final Points[] _byFld; + // Number of distinct incoming abstract FIELD edges. Even if its ONE + // incoming, might be a set of objects from the same allocation, + // meaning we may not have a single owner. + public int _incoming; + // The single incoming field edge, if exactly one + public String _src1; + + // A Site is an allocated TypeStruct, with all reference fields + // holding points-to info + private Site(Node n) { + _node = n; + TypeStruct ts = type(); + Points[] byFld = null; + if( ts._fields != null ) + for( int fx=0; fx1; + int fx = type().findAlias(alias); + if( fx<0 ) return null; // This possible base does not contain that field. + Points field = _byFld[fx]; + if( field==null ) + _byFld[fx] = field = new Points(); + return field; + } + + // Transitively escape + void escapes( HashSet escapes ) { + if( _byFld != null ) + for( Points fld : _byFld ) + if( fld != null ) + throw Utils.TODO(); + } + + @Override public String toString() { return str(new SB()).toString(); } + public SB str( SB sb ) { + TypeStruct ts = type(); + sb.p(name()).p(':').p(ts._name); + FunNode fun = function(_node); + if( fun!=null ) sb.p(" in ").p(fun._name); + if( _node instanceof NewNode alloc ) sb.p(" bytes=").p(alloc.size()._type.toString()); + sb.p(" incoming=").p(_incoming); + if( _src1!=null ) sb.p(" from ").p(_src1); + sb.p('\n'); + // Print field breakdown + if( _byFld !=null ) + for( int fx=0; fx<_byFld.length; fx++ ) { + Points fld = _byFld[fx]; + if( fld!=null ) { + sb.p(" .").p(ts._fields[fx]._fname).p(" -> "); + fld.strSite(sb).p('\n'); + } + } + return sb; + } + } + + // All allocation Sites by Node + public final IdentityHashMap _sites = new IdentityHashMap<>(); + private Site site(Node n) { Site site = new Site(n); _sites.put(n,site); return site; } + + // --------------------------------- + // Outgoing edge structure; all the things a Node might point to. This is + // treated as an extra field on Nodes, found by HashMap lookup instead of + // field name. + public static final class Points { + // All the Sites we point to. This changes during solving as we + // discover more points-to relations + public final HashSet _sites = new HashSet<>(); + + // Might point to Sites not in this compilation unit + public boolean _unknown; + + // HashSet of readers of this PointsTo; if this Points changes, these + // readers hit the worklist. Identity is required: Node.hashCode + // caches the GVN lock. + private IdentityHashMap _readers; + Points addDep( Node dep ) { + if( _readers==null ) _readers = new IdentityHashMap<>(); + _readers.put(dep,""); + return this; + } + + private Points() { } + + // A half-dozen variants of merge() + // + // Have a Point, merge the Point._unknown and all Point._sites. + // Have a HashSet instead. + // Have a Type, filer by Type. + // Have a WorkList, add changes if progress. + + // Merge Site into our existing Sites, return true if progress + boolean merge( Site site ) { return _sites.add(site); } + + void merge( Site site, WorkList work ) { + if( merge(site) ) + changed(work); + } + + boolean merge( Points p, Type t ) { + boolean progress = !_unknown && p._unknown && (_unknown = true); + for( Site site : p._sites ) + if( t==null || site.type().isa(t) ) + progress |= _sites.add(site); + return progress; + } + + boolean merge( Points p ) { return merge(p,(Type)null); } + + // Merge Points into self Points; queue readers if progress + void merge( Points p, WorkList work ) { + if( merge(p,(Type)null) ) + changed(work); + } + + boolean mergeTransitive( Points p ) { + boolean progress = false; + for( Site site : p._sites ) + if( _sites.add(site) ) { + progress = true; + if( site._byFld != null ) + throw Utils.TODO("transitive"); + } + return progress; + } + + void changed( WorkList work ) { + if( _readers != null ) + for( Node n : _readers.keySet() ) + work.push(n); + } + + public boolean contains(Site site) { + // Unknown sites are none of these, so it never contains one + //if( _unknown ) throw Utils.TODO(); + return _sites.contains(site); + } + + @Override public String toString() { return str(new SB(),null).toString(); } + public SB str( SB sb, Node n ) { + if( n != null ) { + sb.p("#").p(n._nid).p(' ').p(n.label()); + FunNode fun = function(n); + if( fun!=null ) sb.p(" in ").p(fun._name); + } + return strSite(sb.p(" => ")).p('\n'); + } + + SB strSite( SB sb ) { + sb.p('{'); + for( Site site : _sites ) + sb.p(site.name()).p(", "); + if( _unknown ) + sb.p("..."); + else if( !_sites.isEmpty() ) + sb.unchar(2); + return sb.p('}'); + } + } + + // Map from a Node to what it might point-to + public final IdentityHashMap _points = new IdentityHashMap<>(); + + // Set or add points-to from a Node + private Points points(Node n) { return _points.computeIfAbsent( n, k -> new Points() ); } + public Points getPts(Node n) { return _points.get(n); } + + + // All local allocations that escape + public final Points _escapes; + + + // --------------------------------- + // Worklist; iterate to a solution + private final WorkList _work = new WorkList<>(); + + // TypePtr is a mix of TypeMemPtr and TypeFunPtr; disallowed from following + // it to the pointed-at memory + private static boolean reference(Type type) { + if( type.isHigh() ) return false; + if( type instanceof TypeMemPtr ) return true; + if( type instanceof TypeTuple tt && tt._types.length==3 && tt.ret() instanceof TypeMemPtr ) return true; + return false; + } + + public Allocation2(CodeGen code) { + _code = code; + _escapes = new Points(); + _escapes._unknown = true; + + // Establish the finite object universe before solving any constraints. + code._start.walk(n -> { + if( n instanceof NewNode ) { + // Make new memory, without pointing to it + site(n); + + } else if( reference(n._type) ) { + // Node n points-to something + points(_work.push(n)); + // ConstantNodes imply some memory was pre-allocated at + // start time (unlike NewNodes, which make new every time) + if( n instanceof ConstantNode con && n._type.isConstant() ) + getPts(n).merge(site(n)); + + } else if( n instanceof StoreNode st && st.val()._type instanceof TypeMemPtr ) { + _work.push(n); + } + + return null; + }); + + // Solve the points-to + solve(); + + // Use the points-to to gather some quick facts + incoming(); + + assert verify() : "Did not hit fixedpoint"; + } + + // Solve the points-to + private void solve() { + int steps=0; // Steps to solve; nice binary search for solver crashes + // Pass work to be done in backdoor _reader, to avoid having to pass it + // everywhere + // Current worklist element being worked on + Node n; + while( (n = _work.pop()) != null ) { + steps++; + transfer( n ); + } + } + + private Points read(Node node, Node dep) { + return points(node).addDep(dep); + } + + // Transfer function in our MAF + private void transfer(Node n) { + switch( n ) { + case StoreNode store when store.val()._type instanceof TypeMemPtr -> { + Points bases = read(store.ptr(),n), src = read(store.val(),n); + for( Site site : bases._sites ) { + Points field = site.field(store._alias); + if( field!=null ) + field.merge(src,_work); + } + // Storing local values into unknown sites + if( bases._unknown && _escapes.mergeTransitive(src) ) + _escapes.changed(_work); + } + + //case CLInitNode init when !init.bypass() -> { + // FunNode fun = _code.link(init.cu()); + // if( fun==null || fun.summary()!=null ) effects(n,fun); + //} + case CallEndNode cend -> cend(cend); + case ReturnNode ret -> { + if( reference(ret.expr()._type) ) points(n).merge(read(ret.expr(),n), _work); + } + //case PtrToIntNode raw -> { + // int[] writes=XInt.EMPTY; + // if( raw.in(1)._type instanceof TypeMemPtr ptr && ptr._obj._fields!=null ) { + // if( ptr._obj.isAry() ) writes=XInt.make(ptr._obj.field("[]")._alias); + // else for( Field field : ptr._obj._fields ) writes=XInt.make(writes,field._alias); + // } else writes=XInt.FULL; + // opaque(n,writes,"raw-address access"); + //} + //case NewNode alloc -> {} // Seeded before solving. + case ConstantNode con -> { // Constant static memory already handled + assert n._type instanceof TypeMemPtr; + } + + case PhiNode phi -> { + boolean progress = false; + Points dst = points(n); + for( int i = 1; i { + boolean progress = false; + Points dst = points(n); + Points bases = read(load.ptr(),n); + for( Site site : bases._sites ) { + Points field = site.field(load._alias); + if( field!=null ) progress |= dst.merge(field.addDep(n)); + } + if( bases._unknown ) + // Loading from an unknown; dst includes all escapees of the correct type + progress |= dst.merge(_escapes.addDep(load), ((TypeMemPtr)load._type)._obj ); + if( progress ) dst.changed(_work); + } + + case ProjNode proj -> { + switch( proj.in(0) ) { + case NewNode nnn -> { assert proj._idx==0; points(n).merge( _sites.get(nnn), _work ); } + case CallEndNode cend -> { assert proj._idx==2; points(n).merge(read(cend,n), _work ); } + case SummaryNode sum -> { assert proj._idx==2; points(n).merge(read(sum,n),_work); } + default -> throw Utils.TODO(); + }; + } + + case ReadOnlyNode ro -> forward(ro); + case GuardNode guard -> forward(guard); + case ConstructNode con -> forward(con); + case InitViewNode view -> forward(view); + //case ConvertNode conv -> forward(conv ,nonNull); + case ArrayInitNode init -> points(n).merge(read(init.in(2),n),_work); + default -> + throw Utils.TODO("transfer: "+n.getClass().getSimpleName()); + } + } + + private void forward(Node n) { + assert reference(n.in(1)._type); + points(n).merge(read(n.in(1),n), _work); + } + + private void cend(CallEndNode cend) { + assert reference(cend._type); // Only here for calls returning pointers + CallNode call = cend.call(); + if( Intrinsic.arrayDelete(call) || Intrinsic.pure(call) ) + throw Utils.TODO("untested");//return; + if( !(call.fptr()._type instanceof TypeFunPtr fp) ) + throw Utils.TODO("why weak tfp"); + assert !XInt.isHigh(fp.fidxs()); // Again, why any dead calls here? + + if( !(cend._type instanceof TypeTuple state) ) + throw Utils.TODO("why weak return"); + Type result = state.ret(); + + Points p = points(cend); + boolean progress = false; + // Walk target functions + for( int fidx = XInt.next(fp.fidxs(),0); fidx>=0; fidx = XInt.next(fp.fidxs(),fidx) ) { + FunNode fun = _code.link(fidx); + if( fun==null || fun._extern || fun.summary()!=null ) { + // Might return some unknown allocation + progress |= p.merge(_escapes.addDep(cend), ((TypeMemPtr)result)._obj); + // All arguments escape as well + for( int i=3; i { + if( reference(n._type) || + (n instanceof StoreNode st && st.val()._type instanceof TypeMemPtr) ) + _work.push(n); + return null; + }); + solve(); + + return before.equals(toString()); + } + + // Diagnostic only: unpinned points and global constants have no local CFG. + public static FunNode function(Node node) { + CFGNode cfg = node instanceof CFGNode c ? c : node.cfg0(); + return cfg==null ? null : cfg.fun(); + } + + @Override public String toString() { + SB out = new SB("Allocation2 points-to\n"); + // All allocation sites + for( Site site : _sites.values() ) + site.str(out); + _escapes.str(out.p("Escapes: "),null); + // All Nodes' points-to + for( Node n : _points.keySet() ) + getPts(n).str(out,n); + + return out.toString(); + } +} -- cgit v1.2.3