diff options
Diffstat (limited to 'chapter33/src')
37 files changed, 640 insertions, 60 deletions
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/README.md b/chapter33/src/main/java/com/seaofnodes/simple/README.md index 6b321e8e..021dad22 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/README.md +++ b/chapter33/src/main/java/com/seaofnodes/simple/README.md @@ -13,3 +13,10 @@ The root package retains `sys.java`, which loads the default Simple namespace. Java tests, the command-line driver, and the IR evaluator live under `src/test/java`; the Simple standard library lives under `src/main/smp`. + +Loop normalization runs after `FinalizeIR` and before `TypeCheck`. It builds the +loop tree and gives infinite loops structural exits through `NeverNode`, while +preserving their actual return state for diagnostics and serialized summaries. +Lowering assigns new control nodes to the containing loop of the operation it +expands. It does not rebuild the loop tree. Inlining after normalization queues +the affected caller for a local rebuild once its peepholes have settled. 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 4b0e7de4..b9e56823 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java @@ -27,10 +27,10 @@ public class CodeGen { Opto, // SCCP, numeric modes, seed the peephole worklist IterPostOpto, // Peepholes and inlining using SCCP results FinalizeIR, // Field layout, offset cleanup, function/CU roots + LoopTree, // Normalize loops and insert structural exits TypeCheck, // Last check for bad programs Serialize, // Save ideal IR, including opaque class initialization Lower, // Expand checked class initialization to ordinary IR - LoopTree, // Build a loop tree; break infinite loops Unlink, // Unlink call sites before machine code generation Select, // Convert to target hardware nodes Schedule, // Global schedule (code motion) nodes @@ -196,6 +196,7 @@ public class CodeGen { step(target, Phase.IterPostOpto, this::iterPostOpto, dump); // Field layouts; field symbols become constant offsets step(target, Phase.FinalizeIR, this::finalizeIR, dump); + step(target, Phase.LoopTree, this::loopTree, dump); // Final error check - bad programs fail here step(target, Phase.TypeCheck, this::typeCheck, dump); // Save reloadable ideal IR for a later seperate compilation @@ -203,9 +204,6 @@ public class CodeGen { // Eval2 executes ideal operations, including CLInit, directly. Only // machine compilation expands them before scheduling. step(target, Phase.Lower, () -> { if( cpu!=null ) lower(); }, dump); - // Compute the loop-tree, used for approximating exec frequencies for - // scheduling and register allocation - step(target, Phase.LoopTree, this::loopTree, dump); // Detach call-graph edges; ideal execution retains unloaded summaries // as dispatch targets and schedules their bodies on first use. step(target, Phase.Unlink, () -> unlink(cpu!=null), dump); @@ -362,17 +360,27 @@ public class CodeGen { return null; } - // An inline import can reveal a call to a private initializer whose + // An inline import can reveal a call to a private function whose // unused summary was deleted after SCCP. Recreate the wrapper from its // saved metadata; this is a direct call, not a function-pointer escape. public FunNode restoreClinit(CompUnit cu) { - if( cu==null || cu._obj==null ) return null; + return restoreSummary(cu,0); + } + public FunNode restoreFunction(int fidx) { + return restoreSummary(StaticData.owner(this,_fidxs.owner(fidx)),fidx); + } + private FunNode restoreSummary(CompUnit cu, int fidx) { + if( _phase.ordinal()<=Phase.Opto.ordinal() || cu==null || cu._src!=null || cu._obj==null ) return null; ElfReader elf = getElf(cu._obj); - if( elf._nodes!=null ) return null; + if( elf._nodes!=null || elf._functions==null ) return null; for( FunctionSummary summary : elf._functions ) - if( summary.name().equals(TypeStruct.addClzPrefix(cu._cname)+".<clinit>") ) { - if( _stop._inputs.find(cu._stop)==-1 ) _stop.addDef(cu._stop); - return summary.install(this,cu); + 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); + FunNode fun = summary.install(this,cu); + fun.summary().bindCallees(); + fun.summary().linkCallees(); + return fun; } return null; } @@ -533,7 +541,7 @@ public class CodeGen { // --------------------------- // Last check for bad programs - public CodeGen typeCheck() { return phase(Phase.TypeCheck, _phase==Phase.FinalizeIR, () -> TypeCheck.run(this)); } + public CodeGen typeCheck() { return phase(Phase.TypeCheck, _phase==Phase.LoopTree, () -> TypeCheck.run(this)); } // --------------------------- // TypeCheck queued surviving CLInits during its existing error walk. @@ -544,8 +552,28 @@ public class CodeGen { // --------------------------- // Build the loop tree; break never-exit loops public CodeGen loopTree() { - return phase(Phase.LoopTree, (_phase==Phase.Lower || _phase==Phase.TypeCheck || _phase==Phase.Serialize), - () -> _start.buildLoopTree(_linker,_stop)); + return phase(Phase.LoopTree, _phase==Phase.FinalizeIR, () -> { + _start.buildLoopTree(_linker,_stop); + Iter.repair(this); // Structural exits can change Return/Stop bounds. + _iter.iterate(this); + }); + } + + // Only inlining changes loop nesting after normalization. Lowered diamonds + // inherit their enclosing loop; rebuild only callers that receive code. + private WorkList<FunNode> _loopWork; + public void invalidateLoopTree(FunNode fun) { + if( _start._ltree==null ) return; + if( _loopWork==null ) _loopWork=new WorkList<>(); + _loopWork.push(fun); + } + boolean updateLoopTrees() { + if( _loopWork==null || _loopWork.isEmpty() ) return false; + FunNode fun; + while( (fun=_loopWork.pop())!=null ) + if( !fun.isDead() && !fun._type.isHigh() ) fun.rebuildLoopTree(_stop); + Iter.repair(this); + return true; } // --------------------------- @@ -586,7 +614,7 @@ public class CodeGen { unlink(true); } private void unlink(boolean removeImports) { - phase(Phase.Unlink, _phase==Phase.LoopTree, () -> { + phase(Phase.Unlink, (_phase==Phase.Lower || _phase==Phase.TypeCheck || _phase==Phase.Serialize), () -> { _start.setDef(2,null); // Releases the compiler-only escape analysis. if( removeImports ) Unlink.run(this,true); else Unlink.forEval(this,_start,_stop); diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionSummary.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionSummary.java index 37baf926..2e9be867 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionSummary.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionSummary.java @@ -22,7 +22,7 @@ record FunctionSummary(TypeFunPtr sig, TypeTuple state, String name, int size, i Node value = new ProjNode(body,2,"value").init(); ReturnNode ret = new ReturnNode(ctrl,memory,value,rpc,fun).init(); fun.setRet(ret); - cu._stop.addDef(ret); + code.add(cu._stop).addDef(ret); code.link(fun); return fun; } diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java index 54ccef09..8ce07a9c 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java @@ -88,7 +88,10 @@ public class IterPeeps { // Inlined, run peeps until clean again if( inlined ) { didInline = true; continue; } // No more candidates, check the defer list - if( !didInline ) break; // No more progress, so all the "maybe inline after cleanup" do not progress + if( !didInline ) { + if( code.updateLoopTrees() ) continue; + break; // No more progress, so deferred calls cannot inline. + } // Some inlining happened, retry all the "try again after cleanup" calls didInline = false; code.addAll(defer); 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 882a0f8a..18dd8015 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java @@ -1,6 +1,7 @@ package com.seaofnodes.simple.codegen; import com.seaofnodes.simple.parser.Parser; +import com.seaofnodes.simple.parser.Lexer; import com.seaofnodes.simple.node.*; import com.seaofnodes.simple.print.*; import com.seaofnodes.simple.type.*; @@ -28,6 +29,7 @@ public abstract class ParseAll { private static final Ary<CompUnit> WORK = new Ary<>(CompUnit.class); private static final Ary<CompUnit> NEEDS_LOAD = new Ary<>(CompUnit.class); + private static final HashMap<String,Lexer> REQUIRED_TYPES = new HashMap<>(); // Return a compilation unit (cached or new). If new, it does not necessarily // need to be compiled. @@ -88,6 +90,7 @@ public abstract class ParseAll { private static void parseAll(CodeGen code, CompUnit cunit) { WORK.clear(); // Cleanup from prior tests NEEDS_LOAD.clear(); + REQUIRED_TYPES.clear(); // Prime the pump with the first CompUnit enqueue(cunit); // Work through all unparsed compilation units and parse @@ -103,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. @@ -115,6 +121,9 @@ public abstract class ParseAll { TypeStruct[] tss = Type.closeOver(ary.asAry(),Parser.TYPES); for( TypeStruct ts : tss ) Parser.TYPES.put(ts._name,ts); + for( var required : REQUIRED_TYPES.entrySet() ) + if( !(Parser.TYPES.get(required.getKey()) instanceof TypeStruct ts) || ts._fref ) + throw Parser.error("Unknown type '"+required.getKey()+"'",required.getValue()); for( CompUnit cu : code._compunits.values() ) if( cu._ext==null ) cu._clz = (TypeStruct)Parser.TYPES.get(TypeStruct.addClzPrefix(cu._cname)); @@ -156,9 +165,11 @@ public abstract class ParseAll { if( Parser.TYPES.get(typeName) instanceof TypeStruct ts && !ts._fref ) continue; try { CompUnit xcunit = findRequiredType(code,cunit,typeName); - if( xcunit != null ) + if( xcunit != null ) { cunit.addDep(xcunit); - else + if( !typeName.equals(xcunit._cname) || (xcunit._obj!=null && xcunit._src==null) ) + REQUIRED_TYPES.putIfAbsent(typeName,required.getValue()); + } else throw Parser.error("Unknown type '"+typeName+"'",required.getValue()); } catch( IOException ioe ) { throw new RuntimeException(ioe); @@ -175,7 +186,16 @@ public abstract class ParseAll { if( xcunit != null ) return xcunit; } - return findCUnitExternalSimple(code,typeName); + // A nested struct is declared inside its owning object; it need not + // have its own compilation-unit symbol. Validate the complete name + // after the owner's declarations have been loaded and closed. + for( String name=typeName; ; ) { + CompUnit cu = findCUnitExternalSimple(code,name); + if( cu!=null ) return cu; + int dot = name.lastIndexOf('.'); + if( dot<0 ) return null; + name = name.substring(0,dot); + } } // Load the public symbols for this CompUnit, and add dependent CompUnits to the NEEDS_LOAD list. @@ -243,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 ) { @@ -257,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 ) { @@ -280,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 @@ -289,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/codegen/Serialize.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java index ec135149..2d52c9c3 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java @@ -52,6 +52,12 @@ public class Serialize { code._serials.put(cu,serial); if( cu._fname.equals(code._srcName==null ? "Test" : code._srcName) ) code._serial=serial; } + // Saved bodies can still call these functions even if lowering later + // inlines their last local caller. Keep native entries for that saved + // interface, using the already analyzed parameter bounds. + for( FunNode fun : code._linker ) + if( fun!=null && !fun.isDead() && fun.isFromSource() ) + Unlink.retainEntry(code,fun); } private BAOS serialize(CodeGen code, CompUnit top) { @@ -126,7 +132,7 @@ public class Serialize { if( n instanceof CallEndNode cend ) cend._rpc.gather(types); if( n instanceof FunNode fun ) { fun.sig().gather(types); - TypeTuple state = (TypeTuple)fun.ret()._type; + TypeTuple state = fun.returnState(); TypeMem mem = (TypeMem)state.mem(); // Retention can happen on a path that never returns. The // unit's escape summary includes those native-call effects. @@ -467,6 +473,12 @@ public class Serialize { Type[] types = tread.types(); String[] strs = tread.strs(); GlobalBits fileAliases = tread.fileAliases(); + // The saved CFG has structural exits. Keep its nonreturning summaries + // available for diagnostics when a body is loaded later for inlining. + HashMap<Integer,TypeTuple> nonreturning = new HashMap<>(); + for( FunctionSummary summary : elf._functions ) + if( summary.state().ctl()==Type.XCONTROL ) + nonreturning.put(summary.sig().fidx(),summary.state()); // D - Read the nodes @@ -492,6 +504,7 @@ public class Serialize { if( n instanceof FunNode fun ) { assert cu != null; fun._compunit = cu; + fun._semanticReturn=nonreturning.get(fun.sig().fidx()); if( fun._name==null || fun._name.isEmpty() ) fun._name=fidxs.symbol(fun.sig().fidx()); } if( n instanceof ExternNode ext && ext._con instanceof TypeFunPtr tfp && tfp.isConstant() ) { diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Unlink.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Unlink.java index bb9a6196..3b03e941 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Unlink.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Unlink.java @@ -1,11 +1,29 @@ package com.seaofnodes.simple.codegen; import com.seaofnodes.simple.node.*; +import com.seaofnodes.simple.type.*; import com.seaofnodes.simple.util.Ary; // Discard call-graph edges after LoopTree. Machine selection keeps only this // object's bodies; ideal evaluation keeps imports so their calls can execute. abstract class Unlink { + // A code-generation entry does not publish a function pointer or widen + // any parameter. It preserves an already checked callable implementation. + static void retainEntry(CodeGen code, FunNode fun) { + StartNode start = fun._compunit._start; + if( fun.nIns()>1 && fun.in(1)==start ) return; + code.add(fun).insertDef(1,start); + for( Node use : fun._outputs ) + if( use instanceof ParmNode parm ) { + // Preserve the range, not a recursive widening iteration. + Type seed = parm._type instanceof TypeInteger ti ? ti.makeWide((byte)0) : parm._type; + code.add(parm).insertDef(1,ConstantNode.seed(seed).init()); + code.addAll(parm._outputs); + parm.moveDepsToWorklist(); + } + code.keepInCompUnit(fun); + } + // Disconnect compiler-only interprocedural edges before scheduling. Keep // signatures in the linker; runtime calls resolve FIDXs, not graph edges. static Ary<FunNode> forEval(CodeGen code, StartNode start, StopNode stop) { diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/CFGNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/CFGNode.java index ba744dc3..c5d7130f 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/CFGNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/CFGNode.java @@ -4,6 +4,7 @@ import com.seaofnodes.simple.parser.Parser; import com.seaofnodes.simple.codegen.CodeGen; import com.seaofnodes.simple.type.*; import com.seaofnodes.simple.util.Ary; +import com.seaofnodes.simple.util.WorkList; import java.util.BitSet; import java.util.IdentityHashMap; @@ -16,7 +17,7 @@ import java.util.IdentityHashMap; * idepth is computed lazily upon first request, and is valid even in the * Parser, and is used by peepholes during parsing and afterward. * <p> - * loop_depth is computed after optimization as part of scheduling. + * loop_depth is computed before type checking and maintained through lowering. * * Start - Block head; has constants and trailing Funs * Region - Block head; has Phis. Includes Fun and Parms. @@ -225,6 +226,25 @@ public abstract class CFGNode extends Node { post.clear(); } + // Inlining has settled. Reconstruct just this caller's nesting, retaining + // the outer tree and every other function's loop descriptors. + public void rebuildLoopTree(StopNode stop) { + assert this instanceof FunNode; + WorkList<CFGNode> work = new WorkList<>(); + work.push(this); + CFGNode cfg; + while( (cfg=work.popOnce())!=null ) { + cfg._pre=0; + cfg._ltree=null; + if( cfg instanceof ReturnNode ) continue; + for( Node use : cfg._outputs ) + if( use instanceof CFGNode next && !cfg.skip(next) ) work.push(next); + } + BitSet post=CodeGen.CODE.visit(); + _bltWalk(2,(FunNode)this,stop,post,new Ary<>(FunNode.class)); + post.clear(); + } + int _bltWalk( int pre, FunNode fun, StopNode stop, BitSet post, Ary<FunNode> work ) { // Pre-walked? if( _pre!=0 ) return pre; diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/CLInitNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/CLInitNode.java index 4a122090..9b8c979d 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/CLInitNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/CLInitNode.java @@ -183,8 +183,8 @@ public class CLInitNode extends CFGNode implements MultiNode { // The callee establishes its parent before setting its own flag. IfNode iff = CodeGen.CODE.add(new IfNode(ctrl,ready()).init()); - Node done = CodeGen.CODE.add(new CProjNode(iff,0,"True").init()); - Node cold = CodeGen.CODE.add(new CProjNode(iff,1,"False").init()); + CProjNode done = CodeGen.CODE.add(new CProjNode(iff,0,"True").init()); + CProjNode cold = CodeGen.CODE.add(new CProjNode(iff,1,"False").init()); Node fptr = new FunPtrNode(target.sig(),CodeGen.CODE._start,target.ret()).peephole(); CallNode call = CodeGen.CODE.add(new CallNode(_loc,cold,memory,ptr(),arg,fptr).init()); @@ -198,9 +198,11 @@ public class CLInitNode extends CFGNode implements MultiNode { // the precise initializer effects already analyzed above. end.setType(end.compute()); unlink(); - Node called = CodeGen.CODE.add(new CProjNode(end,0,ScopeNode.CTRL).init()); + CProjNode called = CodeGen.CODE.add(new CProjNode(end,0,ScopeNode.CTRL).init()); Node after = CodeGen.CODE.add(new ProjNode(end,1,ScopeNode.MEM0).init()); RegionNode region = CodeGen.CODE.add(new RegionNode(_loc,null,done,called).init()); + // This diamond stays within the original operation's containing loop. + iff._ltree = done._ltree = cold._ltree = call._ltree = end._ltree = called._ltree = region._ltree = _ltree; Node merged = CodeGen.CODE.add(new BulkMemPhiNode(ScopeNode.MEM0,region,memory,after).init()); // Replace the individual outputs; no tuple-pack node or second diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/CProjNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/CProjNode.java index 073e4658..e6fba30d 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/CProjNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/CProjNode.java @@ -58,8 +58,13 @@ public class CProjNode extends CFGNode implements Proj { } // Flip a negating if-test, to remove the not - if( ctrl() instanceof IfNode iff && iff.pred() != null && addDep(iff.pred()) instanceof NotNode not ) - return new CProjNode(new IfNode(iff.ctrl(),not.in(1)).peephole(),1-_idx,_idx==0 ? "False" : "True"); + if( ctrl() instanceof IfNode iff && iff.pred() != null && addDep(iff.pred()) instanceof NotNode not ) { + IfNode flipped = new IfNode(iff.ctrl(),not.in(1)); + flipped._ltree = iff._ltree; + CProjNode proj = new CProjNode(flipped.peephole(),1-_idx,_idx==0 ? "False" : "True"); + proj._ltree = _ltree; + return proj; + } // Copy of some other input return ((MultiNode)ctrl()).pcopy(_idx,this); 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 abe7953b..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 @@ -257,6 +259,7 @@ public class CallEndNode extends CFGNode implements MultiNode { FunNode fun = ret.fun(); CallNode call = call(); assert fun.sig().isa(call.fptr()._type); + CodeGen.CODE.invalidateLoopTree(call.fun()); // Clone first if( _inline==2 ) { diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/CallNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/CallNode.java index a48f9115..c91d9a16 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/CallNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/CallNode.java @@ -161,9 +161,11 @@ public class CallNode extends CFGNode { // Walk the bits and link for( int fidx = fidxs.next(0); fidx > 0; fidx = fidxs.next(fidx) ) { FunNode fun = CodeGen.CODE.link(fidx); + boolean restored = fun==null; + if( fun==null && !CodeGen.CODE._midAssert ) fun = CodeGen.CODE.restoreFunction(fidx); if( fun==null ) addDepForwards(CodeGen.CODE._start); if( fun!=null && !addDep(fun)._folding && !linked(fun) ) - progress = link(fun); + progress = link(fun,restored); } } } @@ -180,7 +182,8 @@ public class CallNode extends CFGNode { } // Link so this calls fun - public Node link( FunNode fun ) { + public Node link( FunNode fun ) { return link(fun,false); } + private Node link( FunNode fun, boolean restored ) { assert !linked(fun); CodeGen.CODE.add(fun).addDef(this); for( Node use : fun._outputs ) @@ -207,7 +210,7 @@ public class CallNode extends CFGNode { CodeGen code = CodeGen.CODE; if( code._phase.ordinal()>CodeGen.Phase.Opto.ordinal() && code._phase.ordinal()<CodeGen.Phase.Lower.ordinal() ) { - boolean repair = !fun.compute().isa(fun._type) || !cend().compute().isa(cend()._type); + boolean repair = restored || !fun.compute().isa(fun._type) || !cend().compute().isa(cend()._type); for( Node use : fun._outputs ) if( use instanceof ParmNode && !use.compute().isa(use._type) ) repair = true; if( repair ) Iter.repair(code); diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/ConstantNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/ConstantNode.java index 0569f352..2bf2d62b 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/ConstantNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/ConstantNode.java @@ -72,7 +72,11 @@ public class ConstantNode extends TypeNode { } @Override public String label() { return "Con"; } - @Override public Node copy() { return raw(this); } + @Override public Node copy() { + // Inlining clones function-local constants (including Never's TOP) + // before bodyEdge installs their new inputs. Machine copies retain edges. + return CodeGen.CODE._phase.ordinal()<CodeGen.Phase.Select.ordinal() ? copyEmpty() : raw(this); + } @Override diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/FldOffNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/FldOffNode.java index e49162f4..93f2baf9 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/FldOffNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/FldOffNode.java @@ -31,7 +31,7 @@ public class FldOffNode extends TypeNode { } @Override public Type compute() { - return Type.BOTTOM; + return TypeInteger.BOT; } @Override public Node idealize() { 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 896dff05..b0293718 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java @@ -21,6 +21,10 @@ public class FunNode extends RegionNode { private TypeFunPtr _sig; // Initial signature private ReturnNode _ret; // Return pointer + // Never adds structural exits, not executions that return. Preserve the + // checked return state for diagnostics and separately compiled summaries. + public TypeTuple _semanticReturn; + public TypeTuple returnState() { return _semanticReturn==null ? (TypeTuple)ret()._type : _semanticReturn; } public String _name; // Debug name @@ -42,6 +46,7 @@ public class FunNode extends RegionNode { _name = fun._name; _compunit = fun._compunit; _extern = fun._extern; + _semanticReturn = fun._semanticReturn; } @Override public Tag serialTag() { return Tag.Fun; } @Override public void packed(BAOS baos, HashMap<String,Integer> strs, HashMap<Type,Integer> types, IdentityHashMap<Node,Integer> anodes ) { @@ -86,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; } @@ -197,12 +216,15 @@ 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. - if( !isRoot() && in(1) instanceof StartCUNode start ) { + // After serialization this can be a native entry for saved callers. + if( !isRoot() && in(1) instanceof StartCUNode start && + (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/LoopNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/LoopNode.java index 2ab76429..8869243e 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/LoopNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/LoopNode.java @@ -49,8 +49,9 @@ public class LoopNode extends RegionNode { NeverNode iff = new NeverNode(1.2f,back()).init(); // Ideal never-branch CProjNode t = new CProjNode(iff,0,"True" ).init(); CProjNode f = new CProjNode(iff,1,"False").init(); - setDef(2,t); // True continues loop, False (never) exits loop + CodeGen.CODE.add(this).setDef(2,t); // True continues loop, False (never) exits loop ReturnNode ret = fun.ret(); + if( fun._semanticReturn==null ) fun._semanticReturn=fun.returnState(); iff._ltree = t._ltree = _ltree; ret._ltree = f._ltree = fun._ltree; @@ -60,6 +61,7 @@ public class LoopNode extends RegionNode { // executing. Keep synthetic nodes local; do not GVN into that graph. Node top = ConstantNode.raw(Type.TOP); top.setDef(0,fun); + top.init(); MemMergeNode memout = new MemMergeNode(); memout.addDef(f); // placeholder for control memout.addDef(top); @@ -84,6 +86,9 @@ public class LoopNode extends RegionNode { ctrl.keep().addDef(f ); mem .keep().addDef(memout); expr.keep().addDef(top); + CodeGen.CODE.add(ctrl); + CodeGen.CODE.add(mem); + CodeGen.CODE.add(expr); } else { ctrl = f .keep(); mem = memout.keep(); 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/ParmNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/ParmNode.java index aea402f6..65807b12 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/ParmNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/ParmNode.java @@ -87,7 +87,7 @@ public class ParmNode extends PhiNode { Type arg = in(i)._type; // The unknown-caller callback input is Start's memory // projection, interpreted using this parameter's signature. - if( i==1 && r.in(i) instanceof StartNode && _idx>1 && arg instanceof TypeMem outside ) + if( i==1 && r.in(i) instanceof StartNode && _declaredType instanceof TypeFunPtr && arg instanceof TypeMem outside ) arg = outside.outside(_declaredType); t = t.meet(arg); } diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/ReturnNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/ReturnNode.java index f2972c91..1108f64f 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/ReturnNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/ReturnNode.java @@ -71,6 +71,7 @@ public class ReturnNode extends CFGNode { } @Override public Parser.ParseException err() { + if( _fun.returnState().ctl()==Type.XCONTROL ) return null; if( ctrl()._type == Type.CONTROL && expr()._type == Type.TOP ) return Parser.error("No defined return type",null); 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/main/java/com/seaofnodes/simple/type/TypeMem.java b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMem.java index a56aee69..011cbb37 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMem.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMem.java @@ -185,6 +185,19 @@ public class TypeMem extends Type { return make(_alias,_t._upgradeType(TYPES),_one,_clz,_final,_escFs,_escAs); } + @Override public TypeMem upgradeType(HashMap<String,Type> TYPES) { + TypeMem mem = (TypeMem)super.upgradeType(TYPES); + Type t = mem._t; + // A final singleton slot may have been seeded while its referent was + // still open. Recompute its escapes after closure, when recursive + // types are interned and their cached alias/FIDX summaries are valid. + // Aggregate memory and mutable slots can also hold earlier escapes. + if( mem._one && mem._clz && mem._final && mem._alias!=1 && t.isConstant() && !opaque(t) ) + return make(mem._alias,t,mem._one,mem._clz,mem._final, + escapeFIDX(TypeSet.EMPTY,t),escapeAlias(TypeSet.EMPTY,t)); + return mem; + } + @Override int hash() { return 9876543 + _alias + _t.hashCode() + (_one ? 8196 : 0) + (_clz ? 4098 : 0) + (_final ? 16392 : 0) + _escFs.hashCode() + _escAs.hashCode(); } @Override boolean eq(Type t) { diff --git a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeStruct.java b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeStruct.java index dc5d5f18..026a4018 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeStruct.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeStruct.java @@ -152,6 +152,8 @@ public class TypeStruct extends Type { Field[] fs = new Field[_fields.length]; for( int i=0; i<_fields.length; i++ ) { if( _fields[i]._extern ) { fs[i] = _fields[i]; continue; } + // BOT means unwritten, including during SCCP. TOP would disappear + // at a merge with a written path and hide missing initialization. fs[i] = _fields[i].makeFrom(TypeScalar.BOT); } return make(_name,_open,_fref,fs); diff --git a/chapter33/src/test/java/com/seaofnodes/simple/CallEndTest.java b/chapter33/src/test/java/com/seaofnodes/simple/CallEndTest.java index 7983141d..26e479b2 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/CallEndTest.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/CallEndTest.java @@ -78,7 +78,7 @@ public class CallEndTest { // with its data parameter, not share it with the old body. FldOffNode off = new FldOffNode(fun.parm(3),"<<",null).init(); fun.ret().setDef(2,off); - assertSame(Type.BOTTOM,off._type); + assertSame(TypeInteger.BOT,off._type); assertTrue("Unresolved field offset belongs to the function",fun.body().get(off._nid)); return; } diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter18Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter18Test.java index b1caae96..b6dc5138 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter18Test.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter18Test.java @@ -13,6 +13,52 @@ import static org.junit.Assert.*; import static org.junit.Assert.fail; public class Chapter18Test { + @Test public void testLateInlineNonreturningLoop() { + CodeGen code = new CodeGen("val spin_noInline={ -> while(1) {} }; if(arg) spin_noInline(); return 7;") + .driver(Phase.TypeCheck); + FunNode spin = code._stop.walk(n -> n instanceof FunNode f && f._name.endsWith("spin_noInline") ? f : null); + assertNotNull(spin); + CallEndNode end = code._stop.walk(n -> n instanceof CallEndNode c && c.nIns()==2 && c.in(1)==spin.ret() ? c : null); + assertNotNull(end); + spin._name="spin"; + code.add(end); + code._iter.iterate(code); + assertTrue(end.isDead()); + assertEquals("7",Eval2.eval(code,0)); + assertNull(Eval2.eval(code,1,10)); + } + + @Test public void testLateInlineLoopTree() { + CodeGen code = new CodeGen(""" + val work_noInline = { i64 n -> i64 j=0; while(j<n) j++; return j; }; + val keep_noInline = { i64 n -> i64 j=0; while(j<n) j+=2; return j; }; + i64 i=0; + while(i<arg) { i=work_noInline(i)+1; } + return i+keep_noInline(arg); + """).driver(Phase.TypeCheck); + FunNode work = code._stop.walk(n -> n instanceof FunNode f && f._name.endsWith("work_noInline") ? f : null); + FunNode keep = code._stop.walk(n -> n instanceof FunNode f && f._name.endsWith("keep_noInline") ? f : null); + assertNotNull(work); + assertNotNull(keep); + LoopNode untouched = code._stop.walk(n -> n instanceof LoopNode l && !(l instanceof StartNode) && l.fun()==keep ? l : null); + assertNotNull(untouched); + CFGNode.LoopTree untouchedTree = untouched._ltree; + CallEndNode end = code._stop.walk(n -> n instanceof CallEndNode c && c.nIns()==2 && c.in(1)==work.ret() ? c : null); + assertNotNull(end); + LoopNode outer = end.call().loop(); + CFGNode.LoopTree oldTree = outer._ltree; + // Permit this one call to inline after the initial normalization. + work._name="work"; + code.add(end); + code._iter.iterate(code); + assertTrue("The late call was inlined",end.isDead()); + assertNotSame("Rebuild the caller",oldTree,outer._ltree); + assertSame("Leave other functions alone",untouchedTree,untouched._ltree); + assertNotNull(code._stop.walk(n -> n instanceof LoopNode l && l!=outer && + l._ltree!=null && l._ltree._par==outer._ltree ? l : null)); + assertEquals("11",Eval2.eval(code,5)); + } + @Test public void testNeverExitLoopDepth() { String[] sources = { "if(arg) while(1) {} return 7;", @@ -21,7 +67,7 @@ public class Chapter18Test { "int x=0; while(arg) { if(arg==2) while(1) { x++; } x++; arg--; } return x;" }; for( String src : sources ) { - CodeGen code = new CodeGen(src).driver(CodeGen.Phase.LoopTree); + CodeGen code = new CodeGen(src).driver(CodeGen.Phase.TypeCheck); int[] nevers = {0}; code._stop.walk(n -> { if( n instanceof FunNode fun ) diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter20Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter20Test.java index 226425ca..008902c5 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter20Test.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter20Test.java @@ -29,15 +29,19 @@ public class Chapter20Test { }; for( String target : new String[]{"x86_64_v2","riscv","arm"} ) for( String src : sources ) { - CodeGen code = new CodeGen(src).driver(CodeGen.Phase.RegAlloc,target,"SystemV"); + CodeGen code = new CodeGen(src).driver(CodeGen.Phase.TypeCheck); + assertNotNull(code._stop.walk(n -> n instanceof com.seaofnodes.simple.node.NeverNode ? n : null)); + code.driver(CodeGen.Phase.RegAlloc,target,"SystemV"); com.seaofnodes.simple.codegen.RegAllocTestSupport.checkRegisters(code); - assertNotNull(code._stop.walk(n -> { + // Early normalization allows peepholes to fold Phi(value,TOP). + // Any TOP that survives must still need neither a register nor a split. + code._stop.walk(n -> { if( n._type!=com.seaofnodes.simple.type.Type.TOP ) return null; assertEquals(-1,code._regAlloc.regnum(n)); for( var use : n.outs() ) assertFalse(use instanceof com.seaofnodes.simple.node.SplitNode); - return n; - })); + return null; + }); code.encode(); } } diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter23Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter23Test.java index 8667c0bd..8fb781f9 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter23Test.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter23Test.java @@ -252,7 +252,7 @@ return (a && sq_noInline(0)) @Test - public void testFRefFields() { + public void testFRefFields() throws IOException { String src = """ // A hypothetical scanner class struct _Scan { @@ -279,7 +279,8 @@ return _s.peek('q'); CodeGen code = new CodeGen(src).driver(CodeGen.Phase.TypeCheck); assertEquals("return Phi(Region,0,1);", code.print()); assertEquals("1", Eval2.eval(code, 0)); - testCPU(src,"x86_64_v2", "win64",23,null); + testCPU(src,"x86_64_v2", "win64",31,null); + TestC.runSF(src.replace("return _s.peek('q');","return _s.peek('q') != 1;"),"frefFields","",-1); }; @Test 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 4cacd0e6..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,53 @@ 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;"); + CodeGen code=new CodeGen(root.toString(),root.resolve("obj").toString(),null,"Main", + "int i=0; while(i<arg) { i+=A.value+1; } return i;",123,true,TypeInteger.BOT) + .driver(CodeGen.Phase.TypeCheck); + var loops=new java.util.IdentityHashMap<LoopNode,CFGNode.LoopTree>(); + int[] touches={0}; + code._start.walk(n -> { + if( n instanceof LoopNode loop && !(loop instanceof StartNode) ) loops.put(loop,loop._ltree); + if( n instanceof CLInitNode init && init.loopDepth()>0 ) touches[0]++; + return null; + }); + assertFalse(loops.isEmpty()); + assertTrue("Exercise class initialization inside a loop",touches[0]>0); + CFGNode.LoopTree outer=code._start._ltree; + code.driver(CodeGen.Phase.Lower,"x86_64_v2","SystemV"); + assertSame(outer,code._start._ltree); + for( var entry : loops.entrySet() ) + if( !entry.getKey().isDead() ) assertSame(entry.getValue(),entry.getKey()._ltree); + code._start.walk(n -> { + if( n instanceof CFGNode cfg && !cfg.isDead() && !cfg._type.isHigh() && + !(cfg instanceof StartNode) && !(cfg instanceof StopNode) && + cfg.fun()!=null && cfg.fun().summary()==null ) + assertNotNull("Missing containing loop for "+cfg.label(),cfg._ltree); + return null; + }); + code.driver(CodeGen.Phase.Encoding,"x86_64_v2","SystemV"); + } + @Test public void testPrivateInitializerCallEdges() throws Exception { for( long seed : new long[]{1,123,987654321} ) { Path root = tempDir("private-roots-"); @@ -429,7 +476,11 @@ public class ClassInitDependenciesTest { if( n instanceof CLInitNode init && init.fun()==fun && init.cu()==b ) { touches[0]++; TypeTuple state=(TypeTuple)init._type; - assertSame(TypeMem.BOT,state._types[1]); + // Initialization merges whole memory; its escape sets + // can be sharper than the all-escaped MemBot bound. + TypeMem memory=(TypeMem)state._types[1]; + assertEquals(1,memory._alias); + assertSame(Type.BOTTOM,memory._t); TypeMem flag=(TypeMem)state._types[2]; assertEquals(b._clz.field("$init")._alias,flag._alias); assertSame(TypeInteger.TRUE,flag._t); @@ -547,6 +598,18 @@ public class ClassInitDependenciesTest { object(dir,dir,"Spin","val spin_noInline={ -> while(1) {} return 7; };"); CodeGen code=new CodeGen(null,dir.toString(),new Ary<>(new String[]{dir.toString()}), "Main","Spin.spin_noInline(); return 7;",123,true,TypeInteger.BOT).driver(CodeGen.Phase.TypeCheck); + FunNode spin=code._stop.walk(n -> n instanceof FunNode f && f._name.endsWith("spin_noInline") ? f : null); + assertNotNull(spin); + assertNotNull(spin.summary()); + assertSame(Type.XCONTROL,spin.returnState().ctl()); + assertNull(Eval2.eval(code,0,10)); + } + + @Test public void testInlineNonreturningObject() throws Exception { + Path dir=tempDir("nonreturning-inline-"); + object(dir,dir,"Spin","val spin={ -> while(1) {} return 7; };"); + CodeGen code=new CodeGen(null,dir.toString(),new Ary<>(new String[]{dir.toString()}), + "Main","Spin.spin(); return 7;",123,true,TypeInteger.BOT).driver(CodeGen.Phase.TypeCheck); assertNull(Eval2.eval(code,0,10)); } 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/PhaseTest.java b/chapter33/src/test/java/com/seaofnodes/simple/PhaseTest.java index 6505009d..36ac1477 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/PhaseTest.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/PhaseTest.java @@ -27,7 +27,7 @@ public class PhaseTest { code.driver(Phase.TypeCheck); // A repeated request does not rerun anything. assertEquals("45",Eval2.eval(code,10)); code.driver(Phase.LocalSched); - assertEquals("Parse Iter Opto IterPostOpto FinalizeIR TypeCheck LoopTree Unlink Schedule LocalSched", + assertEquals("Parse Iter Opto IterPostOpto FinalizeIR LoopTree TypeCheck Unlink Schedule LocalSched", String.join(" ",phases)); assertNull(code._serial); assertNull(code._mach); 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 72e26a2e..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,66 @@ 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", + "struct Box { i64 x=42; };",123,true,TypeInteger.BOT) + .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); + var paths=new Ary<>(new String[]{lib.toString()}); + // No expression mentions Library: only this parameter requests its type table. + CodeGen code=new CodeGen(null,lib.toString(),paths,"Client", + "val read_noInline={ Library.Box b -> b.x; }; return 0;",123,true,TypeInteger.BOT) + .driver(CodeGen.Phase.TypeCheck); + assertEquals("0",Eval2.eval(code,0)); + for( String name : new String[]{"Library.Missing"} ) { + try { + new CodeGen(null,lib.toString(),paths,"Client", + "val read_noInline={ "+name+" b -> b.x; }; return 0;",123,true,TypeInteger.BOT) + .driver(CodeGen.Phase.TypeCheck); + fail("Accepted nonexistent nested type "+name); + } catch( com.seaofnodes.simple.parser.Parser.ParseException expected ) { + assertTrue(expected.getMessage(),expected.getMessage().contains("Unknown type")); + } + } + } + + @Test public void testNestedTypeInAnotherSourceUnit() throws Exception { + Path root=Files.createTempDirectory(Files.createDirectories(Path.of("build/objs/separate")),"nested-source-"); + Files.createDirectories(root.resolve("Main")); + Files.writeString(root.resolve("Main/Library.smp"),"struct Box { i64 x=42; };"); + CodeGen code=new CodeGen(root.toString(),root.resolve("obj").toString(),null,"Main", + "val read_noInline={ Library.Box b -> b.x; }; return 0;",123,true,TypeInteger.BOT) + .driver(CodeGen.Phase.TypeCheck); + assertEquals("0",Eval2.eval(code,0)); + try { + new CodeGen(root.toString(),root.resolve("obj").toString(),null,"Main", + "val read_noInline={ Library.Missing b -> b.x; }; return 0;",123,true,TypeInteger.BOT) + .driver(CodeGen.Phase.TypeCheck); + fail("The owning file exists, but it does not define Missing"); + } catch( com.seaofnodes.simple.parser.Parser.ParseException expected ) { + assertTrue(expected.getMessage(),expected.getMessage().contains("Unknown type")); + } + } + @Test public void testSparseWideMemoryImport() throws Exception { Path build=Path.of("build/objs/separate"); Files.createDirectories(build); diff --git a/chapter33/src/test/java/com/seaofnodes/simple/StringFormatTest.java b/chapter33/src/test/java/com/seaofnodes/simple/StringFormatTest.java index d6783380..0163de05 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/StringFormatTest.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/StringFormatTest.java @@ -11,6 +11,10 @@ import org.junit.Test; import static org.junit.Assert.*; public class StringFormatTest extends TestC { + @Test public void testSingleIntegerInterpolation() throws Exception { + runSYS("val main={ -> sys.io.p(\"%(7)\"); return 0; };","singleIntegerInterpolation","7",-1); + } + // Share a few native programs, retaining a separately reported assertion // for each case. Blocks isolate locals; the delimiter preserves embedded // NULs and newlines in the expected output. diff --git a/chapter33/src/test/java/com/seaofnodes/simple/TypeTest.java b/chapter33/src/test/java/com/seaofnodes/simple/TypeTest.java index 28b6b0fb..fb1834fa 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/TypeTest.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/TypeTest.java @@ -1,12 +1,47 @@ package com.seaofnodes.simple; import com.seaofnodes.simple.type.*; +import java.util.HashMap; import org.junit.Assert; import org.junit.Test; import static org.junit.Assert.assertSame; public class TypeTest { + @Test public void testSingletonMemoryUpgradeEscapes() { + TypeStruct open = TypeStruct.open("class:UpgradeChild"); + TypeMemPtr ptr = TypeMemPtr.make((byte)2,open,true); + TypeFunPtr callback = TypeFunPtr.make1((byte)2,true,TypeFunPtr.TEMPTY,TypeInteger.BOT,11); + TypeStruct child = open.add(Field.make("self",ptr,7,true)) + .add(Field.make("callback",callback,8,true)) + .add(Field.make("value",TypeInteger.BOT,9,false)).close(); + HashMap<String,Type> types = new HashMap<>(); + types.put(child._name,child); + TypeMem initial = TypeMem.make(6,ptr,true,true,true,TypeSet.FULL,TypeSet.FULL); + TypeMem upgraded = (TypeMem)initial.upgradeType(types); + assertSame(child,((TypeMemPtr)upgraded._t)._obj); + assertSame(TypeSet.of(11),upgraded._escFs); + assertSame(TypeSet.of(7).with(8).with(9),upgraded._escAs); + assertSame(upgraded,upgraded.upgradeType(types)); + + // Only a final singleton class slot can replace its old escape bound. + // Aggregate memory and mutable/non-class slots retain prior escapes. + for( TypeMem other : new TypeMem[]{ + TypeMem.make(6,ptr,true,true,false,TypeSet.FULL,TypeSet.FULL), + TypeMem.make(6,ptr,true,false,true,TypeSet.FULL,TypeSet.FULL), + TypeMem.make(6,ptr,false,true,true,TypeSet.FULL,TypeSet.FULL), + TypeMem.make(1,ptr,true,true,true,TypeSet.FULL,TypeSet.FULL)} ) { + TypeMem kept = (TypeMem)other.upgradeType(types); + assertSame(TypeSet.FULL,kept._escFs); + assertSame(TypeSet.FULL,kept._escAs); + } + TypeStruct opaque = TypeStruct.forward("ExternalUpgradeChild"); + types.put(opaque._name,opaque); + TypeMem external = TypeMem.make(6,TypeMemPtr.make((byte)2,opaque,true), + true,true,true,TypeSet.FULL,TypeSet.FULL); + assertSame(external,external.upgradeType(types)); + } + @Test public void testFinalPointerCycles() { TypeStruct cycle = TypeStruct.open("FinalPointerCycle"); Assert.assertFalse(cycle.isFinal()); |
