diff options
15 files changed, 280 insertions, 17 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)+".<clinit>") : 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<SummaryNode> 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; i<old.nIns(); i++ ) if( old.in(i) instanceof CallNode call ) { @@ -297,6 +303,10 @@ public abstract class ParseAll { code.releaseReplacedNode(oldStart); int idx = code._stop._inputs.find(oldStop); if( idx!=-1 ) code._stop.delDef(idx); + // Retained summary defaults can still use the old memory input. + // Merge it before protecting the new projection from DCE below. + ProjNode newMem = cunit._start.proj(1); + if( oldMem!=null && !oldMem.isDead() && newMem!=null && oldMem!=newMem ) oldMem.subsume(newMem); oldStart.subsume(cunit._start); } // Saved types describe the library's original compilation. Repair @@ -306,6 +316,16 @@ public abstract class ParseAll { if( startMem!=null ) code.keepUntilFinalize(startMem); Iter.imports(code,elf._nodes); + // Deserialization may omit an entry's default. Other unloaded bodies + // can still reference it, via FunPtrs moved from the old Return above. + for( Node n : elf._nodes ) + if( n instanceof FunNode fun && !fun.isDead() && fun.hasSummaryCallers() ) + Opto.linkStart(code,fun); + Iter.repair(code); + for( Node n : elf._nodes ) + if( n instanceof CallNode call && !call.isDead() ) call.idealize(); + for( SummaryNode summary : replaced ) code.add(summary.unkeep()); + // Add the new top-level loaded class Parser.TYPES.put(cunit._clz._name,cunit._clz); // Layout belongs to the allocator's object result. An initializer's diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java index 9e5fc7ef..cb56c9b6 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java @@ -123,7 +123,7 @@ public class CallEndNode extends CFGNode implements MultiNode { for( int i=1; i<nIns(); i++ ) state = (TypeTuple)state.meet(in(i)._type); // Keep a live continuation even before any callee exit is reachable. - // Otherwise a transient no-return result can tear down the caller + // Otherwise, a transient no-return result can tear down the caller // and lose class-init dependencies before SCCP finds those exits. if( state.ctl()==Type.XCONTROL ) return TypeTuple.make(Type.CONTROL,TypeMem.TOP,Type.TOP); @@ -137,7 +137,7 @@ public class CallEndNode extends CFGNode implements MultiNode { } public byte maybeInline() { - byte intrinsic=Intrinsic.tryInline(this); + byte intrinsic = Intrinsic.tryInline(this); if( intrinsic>0 ) 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.Serialize.ordinal()) ) { boolean preOpto = CodeGen.CODE._phase == null || CodeGen.CODE._phase.ordinal() < CodeGen.Phase.Opto.ordinal(); - if( !preOpto && !start.escapedFIDX(_sig.fidx()) && _ret!=null ) { + if( !preOpto && !start.escapedFIDX(_sig.fidx()) && !hasSummaryCallers() && _ret!=null ) { // CLInit has a call edge but no Return edge. Keep a called // body's Return rooted even after dropping unknown callers. if( !isClz() || nIns()<=2 ) { diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java index 14efa315..7c6d6b56 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java @@ -163,6 +163,15 @@ public class LoadNode extends MemOpNode { if( _alias == 1 ) return null; + // Whole-memory parameters lose individual alias types. Recover the + // class flag from every caller without moving a load across a call. + // SCCP must have finished discovering callers before we remove it. + if( "$init".equals(_name) && ptr._type instanceof TypeMemPtr clz && + TypeStruct.startsClzPrefix(clz._obj._name) && + CodeGen.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; i<phi.nIns(); i++ ) + if( !addDep(phi.region().in(i))._type.isHigh() && + !classInitialized(phi.in(i),active) ) { ready=false; break; } + } + } + active.clear(mem._nid); + return ready; + } + // Load a flavored zero from a New private Node zero(NewNode nnn) { // Object fields acquire values from their initializer's Stores. diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java index 03cf4d36..d97e6052 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java @@ -110,7 +110,9 @@ public class MemMergeNode extends Node { // Is this a single private instance memory? if( defmem._one ) { if( !(defmem._t instanceof TypeStruct ts) ) - return defmem; + // Stores can introduce references even when the default has + // none. An unknown shape must bound the shaped result below. + return defmem.escapes(defmem._t); // Perfect singleton memory, so all updates are parallel and // independent and stack. for( int i=2; i<nIns(); i++ ) { diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/StoreNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/StoreNode.java index 204e0c4b..511afa4e 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/StoreNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/StoreNode.java @@ -251,8 +251,8 @@ public class StoreNode extends MemOpNode { Field fld = obj.field(_name); if( fld == null || fld._t == null ) return 0; - if( fld._t == Type.BOTTOM ) - return 0; // Store into a final field + // Broad inferred declarations still reserve full-width slots. Match + // TypeStruct's layout rather than leaving these Stores unsized. assert fld._t != Type.TOP; // Freshly parsed field stores retain the declaring structure on their // symbolic offset even after the pointer's flow type sharpens. diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java index 5b945457..5cf2d50a 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java @@ -9,16 +9,51 @@ import java.util.HashMap; public class SummaryNode extends CFGNode implements MultiNode { public TypeTuple _state; - // Callees and touched class initializers, by FIDX, for class-init cycle checks. + // Callees and touched class initializers, by FIDX. Used for class-init + // cycle checks and to retain callees until their call sites are loaded. public final int[] _classDependencyFIDXs; + // Inputs [2,_args) are actual arguments; the remaining inputs retain + // callees whose call sites are still inside this unloaded body. + private final int _args; public SummaryNode(TypeTuple state, int[] classDependencyFIDXs, Node... inputs) { super(inputs); _state = state; _classDependencyFIDXs = classDependencyFIDXs; + _args = inputs[0] instanceof FunNode fun ? 2+fun.sig().nargs() : inputs.length; CodeGen.CODE.add(CodeGen.CODE._globalEscapes); } + // Bind after all summaries have been installed, so forward references + // can use ordinary graph edges rather than another linker-side table. + public void bindCallees() { + assert nIns()==_args; + if( _classDependencyFIDXs==null ) return; + for( int fidx : _classDependencyFIDXs ) { + if( fidx==0 ) continue; // Unknown callbacks are covered by escapes. + FunNode fun = CodeGen.CODE._link(fidx); + if( (fun==null || fun.isDead()) && CodeGen.CODE._phase!=null && + CodeGen.CODE._phase.ordinal()>CodeGen.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<nIns(); i++ ) if( in(i)==ptr ) return true; + return false; + } + + // SCCP activates these defaults only when this summary becomes reachable. + // A dependency does not publish the callee's function pointer. + public void linkCallees() { + for( int i=_args; i<nIns(); i++ ) { + FunPtrNode ptr = (FunPtrNode)in(i); + if( ptr.ret()!=null ) Opto.linkStart(CodeGen.CODE,ptr.fun()); + } + } + @Override public String label() { return "Summary"; } @Override public boolean blockHead() { return true; } @Override public Type compute() { @@ -26,7 +61,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 = firstArgument(); i<nIns(); i++ ) { + for( int i = firstArgument(); i<_args; 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,7 +74,7 @@ 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 = firstArgument(); i<nIns(); i++ ) { + for( int i = firstArgument(); i<_args; 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); diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java index b243beb2..87f9564d 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java @@ -3,7 +3,8 @@ package com.seaofnodes.simple; import com.seaofnodes.simple.codegen.CodeGen; import com.seaofnodes.simple.node.*; import com.seaofnodes.simple.util.WorkList; -import com.seaofnodes.simple.type.TypeInteger; +import com.seaofnodes.simple.type.*; +import com.seaofnodes.simple.parser.Parser; import java.nio.file.Files; import java.nio.file.Path; import org.junit.Test; @@ -11,6 +12,19 @@ import static org.junit.Assert.*; /** Regressions for the independent compiler fixes introduced in this chapter. */ public class Chapter33Test { + @Test public void testBroadFieldStoreMatchesLayout() { + CodeGen code=new CodeGen("return 0;").driver(CodeGen.Phase.FinalizeIR); + int alias=code.alias("Test"); + TypeStruct ts=TypeStruct.make("Test.Broad",false,Field.make("value",Type.BOTTOM,alias,false)); + Parser.TYPES.put(ts._name,ts); + Node ptr=code.con(TypeMemPtr.make(ts)); + StoreNode store=new StoreNode(null,"value",alias,Type.BOTTOM,null, + code.con(TypeMem.make(alias,Type.BOTTOM)),ptr,code.con(ts.offset(0)),code.con(4294967297L),false).init(); + store.idealize(); + assertEquals("A broad declaration still reserves a complete storage slot", + ts.offset(1)-ts.offset(0),store.storeSize()); + } + @Test public void testWorkListRequeueAndTraversal() { CodeGen code = new CodeGen("return arg;").parse(); Node arg = code.expr(); diff --git a/chapter33/src/test/java/com/seaofnodes/simple/ClassInitDependenciesTest.java b/chapter33/src/test/java/com/seaofnodes/simple/ClassInitDependenciesTest.java index 71b90f7f..3b52a5d2 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/ClassInitDependenciesTest.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/ClassInitDependenciesTest.java @@ -27,6 +27,23 @@ import org.junit.runners.model.Statement; import static org.junit.Assert.*; public class ClassInitDependenciesTest { + @Test public void testInitializedFlagAcrossCallers() throws Exception { + for( String name : new String[]{"_read_noInline","read_noInline"} ) + for( boolean both : new boolean[]{true,false} ) { + CodeGen code=compile("A",Map.of("A",""" + int state=0; + val _read_noInline={ -> 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<String> 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<String> 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<String> 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")); diff --git a/chapter33/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java b/chapter33/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java index db8e696c..be20b41d 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java @@ -10,6 +10,25 @@ import org.junit.Test; import static org.junit.Assert.*; public class SeparateCompilationTest { + @Test public void testInferredImportedFieldStoreWidth() throws Exception { + Path lib=Files.createTempDirectory(Files.createDirectories(Path.of("build/objs/separate")),"inferred-store-"); + new CodeGen(null,lib.toString(),null,"Library", + "val number_noInline={ -> 7; };",123,true,TypeInteger.BOT) + .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); + var paths=new Ary<>(new String[]{lib.toString()}); + String src=""" + struct Box { var value=Library.number_noInline(); }; + val b=new Box; + b.value=4294967297; + return b.value; + """; + CodeGen code=new CodeGen(null,lib.toString(),paths,"Client",src,123,true,TypeInteger.BOT) + .driver(CodeGen.Phase.TypeCheck); + assertEquals("4294967297",Eval2.eval(code,0)); + TestC.run(src.replace("return b.value;","return b.value!=4294967297;"), + "inferred_import_store",paths,TestC.CALL_CONVENTION,null,null,"",-1); + } + @Test public void testImportedNestedTypeOnlyReference() throws Exception { Path lib=Files.createTempDirectory(Files.createDirectories(Path.of("build/objs/separate")),"nested-type-"); new CodeGen(null,lib.toString(),null,"Library", |
