From b1cf31c5fcc15ba0d8a5af7834f3f67d647f4a84 Mon Sep 17 00:00:00 2001 From: Cliff Click Date: Fri, 4 Dec 2026 20:18:12 -0800 Subject: Retain summarized callers until imported bodies are connected Late body loading can reveal calls after single-caller inlining has consumed their target. Bind serialized callee dependencies to FunPtrNode inputs on SummaryNode, and retain the target's single default caller while a live summary references it. These references do not publish function pointers. Connect loaded calls before releasing the replaced summaries, and restore callee references when recreating a summary. SCCP also activates calls from nonreturning summaries. Enable the all-caller class-initialization flag proof. Merge replaced default memory projections and make unknown private-memory shapes conservatively bound their stored references, fixing issues exposed by retained defaults and cloning. Add regressions for summary/default handoff, unreachable summary cycles, nonreturning callers, private-memory monotonicity, and class flag proofs. Validation: make -j8 tests passed, including TicTacToe native integration; the final SelectiveLoadingTest run passed all 13 tests. --- chapter33/README.md | 6 ++ .../com/seaofnodes/simple/codegen/CodeGen.java | 5 +- .../java/com/seaofnodes/simple/codegen/Opto.java | 8 ++- .../com/seaofnodes/simple/codegen/ParseAll.java | 20 +++++++ .../com/seaofnodes/simple/node/CallEndNode.java | 12 ++-- .../java/com/seaofnodes/simple/node/FunNode.java | 17 +++++- .../java/com/seaofnodes/simple/node/LoadNode.java | 41 +++++++++++++ .../com/seaofnodes/simple/node/MemMergeNode.java | 4 +- .../com/seaofnodes/simple/node/SummaryNode.java | 41 ++++++++++++- .../simple/ClassInitDependenciesTest.java | 17 ++++++ .../java/com/seaofnodes/simple/MemMergeTest.java | 19 +++++- .../seaofnodes/simple/SelectiveLoadingTest.java | 68 ++++++++++++++++++++++ 12 files changed, 244 insertions(+), 14 deletions(-) diff --git a/chapter33/README.md b/chapter33/README.md index 5f231240..2c995ca5 100644 --- a/chapter33/README.md +++ b/chapter33/README.md @@ -8,6 +8,12 @@ This chapter starts with the completed chapter 32 compiler. Automatic memory management will be introduced in small steps, keeping the full test suite passing. No new allocation analysis or reclamation is implemented yet. +Unloaded function summaries retain their possible callees through function-pointer +edges. These references keep a single default caller on each target without +publishing its function pointer. Loading a body connects its concrete calls before +releasing the summary references. Single-caller inlining therefore waits until +both escaped callers and live summarized callers have been accounted for. + From this directory, run `make -j8 tests` for the full suite, including the type lattice, compiler regressions, library tests, and native integration tests. Run `make -j8 release` to build the compiler and runtime. diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java index cbc8ec23..b9e56823 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java @@ -377,7 +377,10 @@ public class CodeGen { if( fidx==0 ? summary.name().equals(TypeStruct.addClzPrefix(cu._cname)+".") : summary.sig().fidx()==fidx ) { if( _stop._inputs.find(cu._stop)==-1 ) add(_stop).addDef(cu._stop); - return summary.install(this,cu); + FunNode fun = summary.install(this,cu); + fun.summary().bindCallees(); + fun.summary().linkCallees(); + return fun; } return null; } diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Opto.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Opto.java index 63a39292..95eb46a6 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Opto.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Opto.java @@ -200,10 +200,10 @@ abstract public class Opto { } } - // Function is now reachable by unknown callers through Start. The + // Function is reachable by escaped or still-summarized callers through Start. The // Memory and callback defaults read Start's changing outside state. // Scalar defaults remain constants; hidden self uses the owning class. - static void linkStart( CodeGen code, FunNode fun ) { + public static void linkStart( CodeGen code, FunNode fun ) { assert !fun.isDead(); StartCUNode start = fun._compunit._start; if( !fun.unknownCallers() ) { @@ -235,6 +235,10 @@ abstract public class Opto { count++; Type oval = n._type, nval = n.compute(); if( n instanceof CLInitNode init ) init.link(); + // A nonreturning summary can still call other functions. Use entry + // reachability, not its returned control, even if nval is unchanged. + if( n instanceof SummaryNode summary && !summary.in(0)._type.isHigh() ) + summary.linkCallees(); // Remember possible peephole work without walking the graph again. // SCCP can still fall back to the old type, so filter at the end. if( nval!=oldTypes.atX(n._nid) || n.isUnlocked() ) changes.push(n); diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java index 79655b40..18dd8015 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java @@ -106,6 +106,9 @@ public abstract class ParseAll { // Load all pre-compiled CompUnits for( CompUnit cu : NEEDS_LOAD ) loadSummaries(code,cu); + for( CompUnit cu : NEEDS_LOAD ) + for( Node ret : cu._stop._inputs ) + ((ReturnNode)ret).fun().summary().bindCallees(); // Many types will have been declared cyclically either internally or // across multiple compilation units. @@ -260,6 +263,7 @@ public abstract class ParseAll { cunit._clz = (TypeStruct)Parser.TYPES.get(TypeStruct.addClzPrefix(cunit._cname)); StartNode lstart = (StartNode)elf._nodes.at(0); StopNode lstop = ( StopNode)elf._nodes.last(); + Ary replaced = new Ary<>(SummaryNode.class); // Add all new loaded functions to the linker table for( Node n : lstop._inputs ) { @@ -274,6 +278,8 @@ public abstract class ParseAll { FunNode old = code._link(fun.sig().fidx()); code.link(fun); if( old!=null && old.summary()!=null && !old.isDead() ) { + // Keep outgoing references until the loaded calls are linked. + replaced.add(old.summary().keep()); old.ret().keep(); for( int i = 1; i0 ) return intrinsic; byte inline = inlineCandidate(false); if( CodeGen.CODE._midAssert ) @@ -154,11 +154,13 @@ public class CallEndNode extends CFGNode implements MultiNode { public boolean loadForInline() { CodeGen code = CodeGen.CODE; if( code._phase!=CodeGen.Phase.IterPostOpto || nIns()!=2 || - !(in(1) instanceof ReturnNode ret) || ret.fun().summary()==null ) return false; + !(in(1) instanceof ReturnNode ret) || ret.fun().summary()==null ) + return false; // Fetch bodies only for calls in functions compiled from source here. // Calls inside imported functions become eligible when inlined into one. if( !(in(0) instanceof CallNode call) || !call.fun().isFromSource() || - inlineCandidate(true)<=0 ) return false; + inlineCandidate(true)<=0 ) + return false; code.loadForInline(ret.fun()._compunit); return true; } @@ -167,7 +169,7 @@ public class CallEndNode extends CFGNode implements MultiNode { // policy, but can only estimate the size of a summarized body. private byte inlineCandidate(boolean loading) { if( _inline < -2 ) return -2; // Never - if( _folding ) return -2; // No, and will collapse anyways + if( _folding ) return -2; // No, and will collapse anyway if( !(in(0) instanceof CallNode call) ) return -2; // malformed because mid-death if( nIns()!=2 ) return -1; // Not exactly 1 link, but can change diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java index 122de0ce..b0293718 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java @@ -91,6 +91,20 @@ public class FunNode extends RegionNode { // An unloaded body's Summary is constructed before every other user. public SummaryNode summary() { return nOuts()>0 && out(0) instanceof SummaryNode summary ? summary : null; } + // Different sharpened FunPtrs can denote this same FIDX. Inspect their + // graph uses, not pointer use counts, to find still-unmaterialized calls. + public boolean hasSummaryCallers() { + if( _ret==null ) return false; + for( Node use : _ret._outputs ) + if( use instanceof FunPtrNode ptr ) { + addDep(ptr); // Removing a summary use can release the default. + for( Node user : ptr._outputs ) + if( user instanceof SummaryNode summary && summary.references(ptr) && + !addDep(summary.in(0))._type.isHigh() ) return true; + } + return false; + } + // This invocation compiles the defining CompUnit from source. Imported // functions still belong to a CompUnit, but its _src is null. public boolean isFromSource() { return _compunit!=null && _compunit._src!=null; } @@ -202,6 +216,7 @@ public class FunNode extends RegionNode { // - Must be past pessimistic Iter, which discovers and links calls // through class-field loads and other initially imprecise values. // - FIDX is not in the escape set + // - No live unloaded summary still holds a call dependency // Concrete callers keep the body alive; FinalizeIR retains surviving // functions for emission without giving them unknown callers. // After serialization this can be a native entry for saved callers. @@ -209,7 +224,7 @@ public class FunNode extends RegionNode { (CODE._phase==null || CODE._phase.ordinal()=CodeGen.Phase.IterPostOpto.ordinal() && + classInitialized(mem,new BitSet()) ) + return CodeGen.CODE.con(TypeInteger.TRUE); + Node slice = CLInitNode.slice(mem,_alias,this); if( slice!=mem ) { setDef(1,slice); return this; } @@ -230,6 +239,38 @@ public class LoadNode extends MemOpNode { return null; } + // A class flag has one global slot per alias. Unknown memory and cycles + // fail the proof; a cycle must not establish its own initialization. + private boolean classInitialized(Node mem, BitSet active) { + addDep(mem); + if( mem._type.isHigh() ) return true; + if( mem._type instanceof TypeMem tm && tm._alias==_alias && tm._t==TypeInteger.TRUE ) return true; + if( active.get(mem._nid) ) return false; + active.set(mem._nid); + boolean ready=false; + if( mem instanceof MemMergeNode merge ) + ready=classInitialized(merge.alias(_alias),active); + else if( mem instanceof ProjNode proj && proj._idx==1 && proj.in(0) instanceof CLInitNode init ) { + addDep(init.ptr()); + Field flag=init.flag(); + ready=flag!=null && flag._alias==_alias; + } + else if( mem instanceof StoreNode st ) { + if( st._alias==_alias ) ready=addDep(st.val())._type==TypeInteger.TRUE; + else if( st._alias>1 ) ready=classInitialized(st.mem(),active); + } else if( mem instanceof PhiNode phi ) { + addDep(phi.region()); + if( !phi.inProgress() ) { + ready=true; + for( int i=1; iCodeGen.Phase.Opto.ordinal() ) + fun = CodeGen.CODE.restoreFunction(fidx); + if( fun!=null && !fun.isDead() ) + addDef(new FunPtrNode(fun.sig(),CodeGen.CODE._start,fun.ret()).init()); + } + } + + public boolean references(FunPtrNode ptr) { + for( int i=_args; i B.value; }; + int value=0; + if(arg) { state=1; value=B.value; value+=_read_noInline(); } + else { state=2; BEFORE value+=_read_noInline(); } + """.replace("BEFORE",both ? "value=B.value;" : "").replace("_read_noInline",name),"B","int value=arg;"),123); + CLInitNode touch=code._stop.walk(n -> n instanceof CLInitNode init && + init.fun()._name.endsWith(name) ? init : null); + if( both && name.startsWith("_") ) assertNull("Every caller has already initialized B",touch); + else assertNotNull("An uninitialized or unknown caller still needs the check",touch); + } + } + @Test public void testLoweringPreservesLoopTree() throws Exception { Path root=tempDir("lower-loops-"); Files.writeString(root.resolve("A.smp"),"int value=arg;"); diff --git a/chapter33/src/test/java/com/seaofnodes/simple/MemMergeTest.java b/chapter33/src/test/java/com/seaofnodes/simple/MemMergeTest.java index 253bce0b..6ab3ee67 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/MemMergeTest.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/MemMergeTest.java @@ -2,11 +2,28 @@ package com.seaofnodes.simple; import com.seaofnodes.simple.codegen.CodeGen; import com.seaofnodes.simple.node.*; -import com.seaofnodes.simple.type.TypeMem; +import com.seaofnodes.simple.type.*; import org.junit.Test; import static org.junit.Assert.*; public class MemMergeTest { + @Test public void testUnknownPrivateShapeBoundsStoredReferences() { + CodeGen code=new CodeGen("return 0;").parse(); + TypeFunPtr callback=TypeFunPtr.make1((byte)2,true,TypeFunPtr.TEMPTY,TypeInteger.BOT,7); + TypeStruct shape=TypeStruct.make("PrivateCallback",false,Field.make("callback",callback,21,true)); + Node base=ConstantNode.raw(TypeMem.makePrivate(Type.BOTTOM).makeFrom(TypeSet.EMPTY,TypeSet.EMPTY)); + StoreNode store=new StoreNode(null,"callback",21,callback,code._start,base, + code.con(TypeMemPtr.make(shape)),code.con(TypeInteger.ZERO),code.con(callback),true).init(); + MemMergeNode mem=new MemMergeNode(null,base); + mem.alias(21,store); + Type bound=mem.compute(); + base._type=TypeMem.makePrivate(shape); + store._type=store.compute(); + TypeMem precise=(TypeMem)mem.compute(); + assertTrue(precise._escFs.contains(7)); + assertTrue("Learning the private shape must refine the old result",precise.isa(bound)); + } + @Test public void testDenseAliasesAndDefaults() { CodeGen code = new CodeGen(""); Node defaults = code.con(TypeMem.START), value = code.con(TypeMem.BOT).keep(); diff --git a/chapter33/src/test/java/com/seaofnodes/simple/SelectiveLoadingTest.java b/chapter33/src/test/java/com/seaofnodes/simple/SelectiveLoadingTest.java index 447025f6..8ea351d0 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/SelectiveLoadingTest.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/SelectiveLoadingTest.java @@ -4,6 +4,8 @@ import com.seaofnodes.simple.parser.Parser; import com.seaofnodes.simple.codegen.*; import com.seaofnodes.simple.node.*; import com.seaofnodes.simple.type.TypeInteger; +import com.seaofnodes.simple.type.TypeTuple; +import com.seaofnodes.simple.type.Type; import com.seaofnodes.simple.util.Ary; import java.io.IOException; import java.nio.file.*; @@ -11,6 +13,72 @@ import org.junit.Test; import static org.junit.Assert.*; public class SelectiveLoadingTest { + @Test public void testNonreturningSummaryRetainsCallees() throws Exception { + Path root=library("summary-nonreturning-"); + Ary paths=new Ary<>(new String[]{root.toString()}); + object(root,paths,"Library",""" + var _state=0; + val _helper_noInline={ -> _state=1; }; + val spin_noInline={ -> _helper_noInline(); while(1) {} return 7; }; + """); + CodeGen code=new CodeGen(null,root.toString(),paths,"Main", + "Library.spin_noInline(); return 7;",123,true,TypeInteger.BOT) + .driver(CodeGen.Phase.IterPostOpto); + assertSame(Type.XCONTROL,function(code,"spin_noInline").summary()._state.ctl()); + FunNode helper=function(code,"_helper_noInline"); + assertTrue(helper.hasSummaryCallers()); + assertTrue("Calls before a nonreturning exit still execute",helper.unknownCallers()); + } + + @Test public void testUnreachableSummaryCycleIsNotARoot() throws Exception { + Path root=library("summary-cycle-"); + Ary paths=new Ary<>(new String[]{root.toString()}); + object(root,paths,"Library",""" + val _left_noInline={ i64 x -> x ? _right_noInline(x-1) : 0; }; + val _right_noInline={ i64 x -> x ? _left_noInline(x-1) : 1; }; + val entry_noInline={ i64 x -> _left_noInline(x); }; + """); + for( long seed : new long[]{1,123,987654321} ) { + CodeGen code=new CodeGen(null,root.toString(),paths,"Main",""" + val _false_noInline={ -> false; }; + if(_false_noInline()) return Library.entry_noInline(((arg<<32)>>32)); + return 7; + """,seed,true,TypeInteger.BOT).driver(CodeGen.Phase.TypeCheck); + CompUnit library=code._compunits.get("Library"); + for( FunNode fun : code._linker ) + assertTrue("A cycle of summary references must not root its functions", + fun==null || fun.isDead() || fun._compunit!=library); + assertEquals("7",Eval2.eval(code,0)); + } + } + + @Test public void testSummaryCalleeDefaultAndRelease() throws Exception { + Path root=library("summary-callees-"); + Ary paths=new Ary<>(new String[]{root.toString()}); + object(root,paths,"Library",""" + val _helper_noInline={ int x -> x+1; }; + val entry_noInline={ int x -> _helper_noInline(x); }; + """); + CodeGen code=new CodeGen(null,root.toString(),paths,"Main", + "return Library.entry_noInline(((arg<<32)>>32));",123,true,TypeInteger.BOT) + .driver(CodeGen.Phase.IterPostOpto); + FunNode helper=function(code,"_helper_noInline"); + assertTrue("An unloaded caller retains the default",helper.unknownCallers()); + assertTrue(helper.hasSummaryCallers()); + assertFalse("A summary call does not publish its target", + ((TypeTuple)code._start._type).mem()._escFs.contains(helper.sig().fidx())); + + code.loadForInline(code._compunits.get("Library")); + code._iter.iterate(code); + helper=function(code,"_helper_noInline"); + assertFalse("Concrete calls replace the summary references",helper.hasSummaryCallers()); + assertEquals("Only escapes can retain the default after loading", + ((TypeTuple)helper._compunit._start._type).mem()._escFs.contains(helper.sig().fidx()),helper.unknownCallers()); + assertTrue(helper.nIns()>1); + code.driver(CodeGen.Phase.TypeCheck); + assertEquals("42",Eval2.eval(code,41)); + } + @Test public void testSharedConstantsInSeparateObjects() throws Exception { Path root = library("shared-constants-"); Path src = Files.createDirectory(root.resolve("src")); -- cgit v1.2.3