diff options
16 files changed, 373 insertions, 59 deletions
diff --git a/chapter33/docs/memory-management.md b/chapter33/docs/memory-management.md index 29461b99..6ed805b9 100644 --- a/chapter33/docs/memory-management.md +++ b/chapter33/docs/memory-management.md @@ -117,14 +117,31 @@ outside writes, raw addresses, and intrinsic calls need explicit treatment. The current implementation and regression tests expose these gaps. Neither an unknown result nor a low incoming-edge count permits a lifetime decision. -Cofinite imported escape sets also need a defined receiving universe. Renaming -only their finite exclusions admits caller-private FIDXs into the infinite tail. -Preserve membership of known remote identities while excluding local identities -from the anonymous remote remainder. Actual local escapes enter through the -caller's escape flow. Today type-table loading occurs during parsing, before all -local identities exist, although SummaryNodes are installed after parsing. -Import ordering and universe rebasing are pending work; ordinary universal type -bounds must retain their meaning. +Parsing discovers external names and dependencies without reading their type +tables. All queued source units finish parsing before imported types and summaries +are installed. This establishes the local FIDX, alias and RPC identities before +renaming any imported sets. Function bodies still load on demand. + +For an imported cofinite set, map its finite exclusions by global identity, then +also exclude receiving identities absent from the file's identity table. Shared +identities keep their original membership; reserved bits keep their meaning; +the unknown tail stays infinite. Finite sets only map their members. Mapping the +whole identity table first prevents a shared identity from being mistaken for a +new local one. Explicit caller escape flow can subsequently admit local IDs. + +Declaration bounds and saved analysis facts need distinct imported views. A +callback parameter's `ALL` accepts future caller callbacks; a saved escape set's +`ALL` must exclude caller-private functions. The reader interns both views, +sharing unchanged types. Function signatures and declared node metadata use +bounds, while node types and summary states use rebased facts. Unknown callback +results additionally admit functions exposed by the current caller, so returning +a supplied callback remains possible. This is conservative; it is not a relational +argument-to-result summary. + +Deferring declarations also requires unresolved field accesses to use bulk +memory until the real alias is known. An inferred field whose declaration stays +broad uses the declaration's full-width slot. Implicit conditional zero waits +for its result family when parsing cannot yet distinguish numeric zero from null. ### Normalized exits diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/ElfReader.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/ElfReader.java index 1dced3a8..0064d12b 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/ElfReader.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/ElfReader.java @@ -107,9 +107,9 @@ public class ElfReader { return _clz; } - // Loads strings, mappings, and types, but not Nodes. Used after the - // public-string scan finds a matching Simple ELF, so parsing can resolve - // imported field/array aliases before the full graph is linked in later. + // Loads mappings, types and summaries, but not Nodes. ParseAll calls this + // after every local source unit has been parsed; names alone are discovered + // earlier through the public-string table. public TypeStruct loadPublicTypes(CodeGen code) { Serialize.readTypes(code, this, code._aliases, code._fidxs, code._rpcs); return _clz; diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/GlobalBits.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/GlobalBits.java index acd2eee5..b9fa3733 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/GlobalBits.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/GlobalBits.java @@ -126,6 +126,20 @@ public class GlobalBits { return findOrNext(fileBits._local2Clz.at(fileLocal), fileBits._local2Order.at(fileLocal)); } + // Install the file's identity universe and return destination-only bits. + // A remote infinite tail denotes unknown identities, not local identities + // absent from the file. Shared global identities keep their remote membership. + public int[] importExclusions(GlobalBits fileBits) { + int limit = _local; + int[] missing = XInt.alloc((limit>>>5)+2); + for( int i=RESERVED; i<limit; i++ ) missing[(i>>>5)+1] |= 1<<i; + for( int i=RESERVED; i<fileBits._local; i++ ) { + int mapped = map(fileBits,i); + if( mapped<limit ) missing[(mapped>>>5)+1] &= ~(1<<mapped); + } + return XInt.intern(missing); + } + // Map a global {clz,order} to a local one; keep any existing mapping or // make a new one as needed. private int findOrNext(String clz, int order ) { 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 8026a5de..719bda3f 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 @@ -100,7 +103,9 @@ public abstract class ParseAll { parseOne( code, cu ); // Parse } - // Load all pre-compiled CompUnits + // All source units have now allocated their aliases, FIDXs and RPCs. + // Only now import type tables and summaries, so a remote cofinite set + // can exclude identities which belong solely to this compilation. for( CompUnit cu : NEEDS_LOAD ) loadSummaries(code,cu); @@ -115,6 +120,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 +164,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 +185,16 @@ public abstract class ParseAll { if( xcunit != null ) return xcunit; } - return findCUnitExternalSimple(code,typeName); + // Nested structs are declarations inside their owning object, not + // necessarily separately published compilation-unit names. Validate + // the full type only after that object's type table has been read. + 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. @@ -420,8 +439,8 @@ public abstract class ParseAll { } catch( IOException ioe ) { throw new RuntimeException(ioe); } - ElfReader typedElf = code.getElf(cunit._obj); - if( typedElf != null ) typedElf.loadPublicTypes(code); + // Discover names during parsing; leave types and summaries on NEEDS_LOAD. + // Reading them here would precede later local declarations. TypeStruct clz = (TypeStruct)Parser.TYPES.get(clzName); if( clz == null ) Parser.TYPES.put(clzName,clz = TypeStruct.make(clzName,true)); 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 49c11e8c..74ed7d9f 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java @@ -349,7 +349,7 @@ public class Serialize { } // -------------------------------------------------- - record TypeRead(Type[] types, String[] strs, GlobalBits fileAliases, GlobalBits fileFidxs, GlobalBits fileRpcs) {} + record TypeRead(Type[] types, Type[] bounds, String[] strs, GlobalBits fileAliases, GlobalBits fileFidxs, GlobalBits fileRpcs) {} static TypeRead readTypes( CodeGen code, ElfReader elf, GlobalBits aliases, GlobalBits fidxs, GlobalBits rpcs ) { if( elf._types!=null ) return elf._types; @@ -404,10 +404,12 @@ public class Serialize { int[] pubTypeIds = new int[npubTypes]; for( int i=0; i<npubTypes; i++ ) pubTypeIds[i] = bais.packed4(); - Type[] types = Type.packed(bais,strs,ntypes, Parser.TYPES, + Type.ImportedTypes imported = Type.packed(bais,strs,ntypes, fileAliases,aliases, fileFidxs ,fidxs, fileRpcs ,rpcs); + Type[] types = imported.values(); + Type[] bounds = imported.bounds(); // aliases.set(0,0); // Check and collect first published symbols map to TypeStructs @@ -431,7 +433,7 @@ public class Serialize { } elf._functions = new FunctionSummary[bais.packed4()]; for( int i = 0; i<elf._functions.length; i++ ) { - TypeFunPtr sig = (TypeFunPtr)types[bais.packed2()]; + TypeFunPtr sig = (TypeFunPtr)bounds[bais.packed2()]; TypeTuple state = (TypeTuple)types[bais.packed2()]; String name = strs[bais.packed2()]; int size = bais.packed4(); @@ -439,7 +441,7 @@ public class Serialize { for( int j = 0; j<edges.length; j++ ) edges[j]=fidxs.map(fileFidxs,bais.packed4()); elf._functions[i]=new FunctionSummary(sig,state,name.isEmpty() ? fidxs.symbol(sig.fidx()) : name,size,edges); } - return elf._types = new TypeRead(types,strs,fileAliases,fileFidxs,fileRpcs); + return elf._types = new TypeRead(types,bounds,strs,fileAliases,fileFidxs,fileRpcs); } private static void installType(TypeStruct ts) { @@ -471,7 +473,10 @@ public class Serialize { for( int i = 0; i<num; i++ ) { Node.Tag tag = Node.Tag.VALS[bais.packed1()]; Type t = types[bais.packed2()]; - Node n = tag.make(bais,strs,types,fileAliases,aliases); + // Node metadata is a declaration, except constant values and the + // saved CallEnd result/RPC. Node._type is always an analysis fact. + Type[] metadata = tag==Node.Tag.Con || tag==Node.Tag.CallEnd ? types : tread.bounds(); + Node n = tag.make(bais,strs,metadata,fileAliases,aliases); n._type = t; nodes.push(n); // A little extra for FunNodes diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/ScopeNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/ScopeNode.java index 2fa551fb..1a6928ca 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/ScopeNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/ScopeNode.java @@ -70,7 +70,7 @@ public class ScopeNode extends MemMergeNode { // Extra guards; tested predicates and cast results private final Ary<Node> _guards; private Pending _keeps; // Materialized only when a scope has a real address use - private final Ary<Node> _emptyKeeps = new Ary<>(Node.class); // Zeroes and lazy loop sentinels + private final Ary<Node> _emptyKeeps = new Ary<>(Node.class); // Zeroes only // A new ScopeNode public ScopeNode() { @@ -133,7 +133,9 @@ public class ScopeNode extends MemMergeNode { public int keepDepth() { return _keeps==null ? _emptyKeeps.size() : _keeps.nIns(); } private Node keepAt(int i) { return _keeps==null ? _emptyKeeps.at(i) : _keeps.in(i); } private void materializeKeeps(Node value) { - if( _keeps!=null || value==CodeGen.CODE.ZERO || value instanceof ScopeNode ) return; + // Lazy loop sentinels need real edges too: an early Return can retain + // one after the loop closes, and must keep its pending values alive. + if( _keeps!=null || value==CodeGen.CODE.ZERO ) return; _keeps=new Pending().keep(); for( Node n : _emptyKeeps ) _keeps.addDef(n); _emptyKeeps.clear(); 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..66c974a2 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,9 @@ 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 + // An inferred field can remain broad when its initializer referred to + // an unloaded library. Use the declaration's full-width slot, matching + // TypeStruct's layout; a later value does not change its storage width. 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 4ebdd156..b2ce3e25 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java @@ -33,7 +33,13 @@ public class SummaryNode extends CFGNode implements MultiNode { TypeMem outside = TypeMem.opaque(arg) ? CodeGen.CODE._start.outside(this) : TypeMem.BOT; mem = mem.escapesFrom(arg,outside); } - return TypeTuple.make(_state.ctl(),mem,_state.ret()); + Type result = _state.ret(); + // A remote unknown callback can also be one this caller supplied. + // Import rebasing excludes local IDs initially; ordinary escape flow + // adds the accessible ones back, without admitting private locals. + if( result instanceof TypeFunPtr fp && XInt.isHigh(fp._fidxs) ) + result = fp.makeFrom(XInt.meet(fp._fidxs,mem._escFs)); + return TypeTuple.make(_state.ctl(),mem,result); } @Override public Node idealize() { return null; } public TypeMem exposed(Node dep) { diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/ZeroNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/ZeroNode.java new file mode 100644 index 00000000..4fa30624 --- /dev/null +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/ZeroNode.java @@ -0,0 +1,61 @@ +package com.seaofnodes.simple.node; + +import com.seaofnodes.simple.type.*; +import com.seaofnodes.simple.codegen.CodeGen; +import com.seaofnodes.simple.util.WorkList; + +// Implicit zero for a missing conditional arm. Its family may be unknown +// until imported declarations are available. Folds before serialization. +public class ZeroNode extends Node { + public ZeroNode(Node value) { super(null,value); } + public static Node make(Node value) { + Type t=value._type; + return unknown(t) && !t.isHigh() ? new ZeroNode(value).peephole() : CodeGen.CODE.con(t.makeZero()); + } + private static boolean unknown(Type t) { + return t==Type.TOP || t==Type.BOTTOM || t==TypeScalar.TOP || t==TypeScalar.BOT; + } + @Override public String label() { return "Zero"; } + // The input supplies a type, not a runtime value or scheduling constraint. + @Override public boolean isConst() { return true; } + @Override public Type compute() { + return zero(in(1)); + } + private Type zero(Node value) { + Type t = addDepForwards(value)._type; + // A dead arm can have TOP flow while its declared result family is + // known. The false arm still needs a real zero of that family. + if( unknown(t) ) { + if( value instanceof BoolNode || value instanceof NotNode ) t=TypeInteger.BOOL; + else if( value instanceof ConvertNode convert && !unknown(convert.dst()) ) t=convert.dst(); + else if( value instanceof TypeNode typed && !unknown(typed._con) ) t=typed._con; + else if( value instanceof PhiNode ) { + // A short-circuit RHS may be unreachable on the first loop + // iteration. Its Phis still describe the zero's type family; + // waiting for that RHS to execute can stall SCCP's backedge. + WorkList<Node> work=new WorkList<>(); + work.push(value); + Type result=Type.TOP; + Node n; + while( (n=work.popOnce())!=null ) { + addDepForwards(n); + if( n instanceof PhiNode ) { + for( int i=1; i<n.nIns(); i++ ) work.push(n.in(i)); + } else result=result.meet(zero(n)); + } + return result; + } + else if( value instanceof ProjNode proj && proj._idx==2 && proj.in(0) instanceof CallEndNode end ) { + Node fptr=addDepForwards(end.call().fptr()); + Type sig=fptr instanceof TypeNode typed ? typed._con : fptr._type; + if( sig instanceof TypeFunPtr fp ) t=fp.ret(); + } + } + if( t==Type.TOP || t==TypeScalar.TOP ) return Type.TOP; + if( t==Type.BOTTOM || t==TypeScalar.BOT ) return TypeScalar.BOT; + return t.makeZero(); + } + @Override public Node idealize() { + return _type.isConstant() ? CodeGen.CODE.con(_type) : null; + } +} diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/ControlFlow.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/ControlFlow.java index 95ae3168..102cd478 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/parser/ControlFlow.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/ControlFlow.java @@ -61,9 +61,9 @@ final class ControlFlow { boolean doRHS = false; // RHS is optional for if/else and trinary if( fside.equals("else") ) P._scope.pushKeep(); Node rhs = switch( fside ) { - case "else" -> (doRHS = P.match(fside)) ? P.statements.parseStatement() : P.con(lhs._type.makeZero()); - case ":" -> (doRHS = P.match(fside)) ? P.expressions.parseAssignment() : P.con(lhs._type.makeZero()); - case "&&" -> P.con(lhs._type.makeZero()); // pred && expr_is_ignored + case "else" -> (doRHS = P.match(fside)) ? P.statements.parseStatement() : ZeroNode.make(lhs); + case ":" -> (doRHS = P.match(fside)) ? P.expressions.parseAssignment() : ZeroNode.make(lhs); + case "&&" -> ZeroNode.make(lhs); // pred && expr_is_ignored case "||" -> P.expressions.parseLogical(); // pred || expr default -> throw TODO(); }; diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java index 1f896f03..bcadce05 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java @@ -199,7 +199,9 @@ final class References { P.classInit(site,expr); // With no field, we will update the bulk memory - int alias = fld==null ? 1 : fld._alias; + // A forward type's invented field is only a structural constraint. + // Its eventual imported declaration can have a different alias. + int alias = fld==null || ts._fref ? 1 : fld._alias; Type decl = fld==null ? Type.BOTTOM : fld._t; // Field offset; fixed for structs, computed for arrays diff --git a/chapter33/src/main/java/com/seaofnodes/simple/type/Type.java b/chapter33/src/main/java/com/seaofnodes/simple/type/Type.java index 41fe039f..ef7b605a 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/type/Type.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/type/Type.java @@ -583,56 +583,81 @@ public class Type /*implements Cloneable*/ { }; } - // Read a packed Type array - public static Type[] packed( BAOS bais, String[] strs, int ntypes, HashMap<String,Type> existingTypes, + // Declarations accept values supplied by future callers. Saved analysis + // facts describe the file's universe and exclude destination-only identities. + public record ImportedTypes(Type[] values, Type[] bounds) {} + public static ImportedTypes packed( BAOS bais, String[] strs, int ntypes, GlobalBits fileAliases, GlobalBits aliases, GlobalBits fileFidxs , GlobalBits fidxs , GlobalBits fileRpcs , GlobalBits rpcs ) { + int[] aliasExclusions = aliases.importExclusions(fileAliases); + int[] fidxExclusions = fidxs .importExclusions(fileFidxs); + int[] rpcExclusions = rpcs .importExclusions(fileRpcs); Type[] types = new Type[ntypes]; + Type[] bounds = new Type[ntypes]; + BAOS declarations = new BAOS(bais.buf(),bais.size()); // Read Types in ID# order, no children - for( int i=0; i<ntypes; i++ ) + for( int i=0; i<ntypes; i++ ) { types[i] = Type.packed(bais,strs); + bounds[i] = Type.packed(declarations,strs); + } // Start possibly recursive type collection BOTTOM.recurOpen(); // Read Types in ID# order, only children for( int i=0; i<ntypes; i++ ) { VISIT.put(types[i]._uid,types[i]); + VISIT.put(bounds[i]._uid,bounds[i]); int nkids = types[i].nkids(); - for( int j=0; j<nkids; j++ ) - types[i].set(j,types[bais.packed4()]); + for( int j=0; j<nkids; j++ ) { + int kid = bais.packed4(); + // A function value's signature is a bound on future calls, + // including callbacks they may supply or receive. + types[i].set(j,types[i] instanceof TypeFunPtr ? bounds[kid] : types[kid]); + bounds[i].set(j,bounds[kid]); + } } // Remap file-local aliases/fidxs/rpcs into this compilation unit's // local dense indexes via their global identities. for( int i=0; i<ntypes; i++ ) { - if( types[i] instanceof Field fld ) { - if( fld._alias >= GlobalBits.RESERVED ) - fld._alias = aliases.map(fileAliases,fld._alias); - } - if( types[i] instanceof TypeFunPtr tfp ) - tfp._fidxs = remapBits(fileFidxs,fidxs,tfp._fidxs,GlobalBits.RESERVED); - if( types[i] instanceof TypeRPC rpc ) - rpc._rpcs = remapBits(fileRpcs,rpcs,rpc._rpcs,GlobalBits.RESERVED); - if( types[i] instanceof TypeMem mem ) { - if( mem._alias >= GlobalBits.RESERVED ) - mem._alias = aliases.map(fileAliases,mem._alias); - mem._escFs = remapBits(fileFidxs ,fidxs ,mem._escFs,GlobalBits.RESERVED); - mem._escAs = remapBits(fileAliases,aliases,mem._escAs,GlobalBits.RESERVED); - } + remap(types[i],fileAliases,aliases,fileFidxs,fidxs,fileRpcs,rpcs,aliasExclusions,fidxExclusions,rpcExclusions); + remap(bounds[i],fileAliases,aliases,fileFidxs,fidxs,fileRpcs,rpcs,XInt.EMPTY,XInt.EMPTY,XInt.EMPTY); } - // Intern them all at once - BOTTOM.recurClose(types); - return types; + // Intern both views together; unchanged types still share one instance. + Type[] both = new Type[2*ntypes]; + System.arraycopy(types,0,both,0,ntypes); + System.arraycopy(bounds,0,both,ntypes,ntypes); + BOTTOM.recurClose(both); + System.arraycopy(both,0,types,0,ntypes); + System.arraycopy(both,ntypes,bounds,0,ntypes); + return new ImportedTypes(types,bounds); + } + + private static void remap(Type t, GlobalBits fileAliases, GlobalBits aliases, + GlobalBits fileFidxs, GlobalBits fidxs, GlobalBits fileRpcs, GlobalBits rpcs, + int[] aliasExclusions, int[] fidxExclusions, int[] rpcExclusions) { + if( t instanceof Field fld && fld._alias >= GlobalBits.RESERVED ) + fld._alias = aliases.map(fileAliases,fld._alias); + if( t instanceof TypeFunPtr tfp ) + tfp._fidxs = remapBits(fileFidxs,fidxs,tfp._fidxs,fidxExclusions); + if( t instanceof TypeRPC rpc ) + rpc._rpcs = remapBits(fileRpcs,rpcs,rpc._rpcs,rpcExclusions); + if( t instanceof TypeMem mem ) { + if( mem._alias >= GlobalBits.RESERVED ) + mem._alias = aliases.map(fileAliases,mem._alias); + mem._escFs = remapBits(fileFidxs ,fidxs ,mem._escFs,fidxExclusions); + mem._escAs = remapBits(fileAliases,aliases,mem._escAs,aliasExclusions); + } } - private static int[] remapBits(GlobalBits fileBits, GlobalBits bits, int[] fileLocals, int firstMapped ) { - if( fileLocals == XInt.EMPTY || fileLocals == XInt.FULL ) + private static int[] remapBits(GlobalBits fileBits, GlobalBits bits, int[] fileLocals, int[] exclusions ) { + if( fileLocals == XInt.EMPTY ) return fileLocals; boolean complement = XInt.isHigh(fileLocals); if( complement ) fileLocals = XInt.dual(fileLocals); - int[] locals = XInt.EMPTY; + int[] locals = complement ? exclusions : XInt.EMPTY; for( int fileLocal = XInt.next(fileLocals,-1); fileLocal >=0; fileLocal = XInt.next(fileLocals,fileLocal) ) - locals = XInt.make(locals,fileLocal < firstMapped ? fileLocal : bits.map(fileBits,fileLocal)); + locals = XInt.make(locals,fileLocal < GlobalBits.RESERVED ? fileLocal : bits.map(fileBits,fileLocal)); return complement ? XInt.dual(locals) : locals; } diff --git a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java index c6f53022..d6bf3a72 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java @@ -79,6 +79,7 @@ public class TypeFunPtr extends TypeNil { @Override TypeFunPtr makeFrom( byte nil ) { return nil ==_nil ? this : make( nil,_open,_sig,_ret, _fidxs); } public TypeFunPtr makeFrom( Type ret ) { return ret ==_ret ? this : make( _nil,_open,_sig, ret, _fidxs); } public TypeFunPtr makeFrom( int fidx ) { return make1(_nil,_open,_sig,_ret,fidx); } + public TypeFunPtr makeFrom( int[] fidxs ) { return fidxs==_fidxs ? this : make(_nil,_open,_sig,_ret,fidxs); } public TypeFunPtr restrictFIDXs(int[] fidxs) { int[] ids = XInt.dual(XInt.meet(XInt.dual(_fidxs),XInt.dual(fidxs))); return ids==_fidxs ? this : make(_nil,_open,_sig,_ret,ids); diff --git a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeRPC.java b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeRPC.java index 8a12f50a..b7e8b064 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeRPC.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeRPC.java @@ -84,13 +84,12 @@ public class TypeRPC extends Type { baos.write(TAGOFFS[_type] + 1); baos.packed2(rpc()); } else { // Generic - assert !XInt.isHigh(_rpcs); // Not serializing above-center RPC baos.write(TAGOFFS[_type] + 2); XInt.packed(baos,_rpcs); } } static TypeRPC packed( int tag, BAOS bais ) { - if( tag==0 ) return BOT; + if( tag==0 ) return malloc(XInt.FULL); // Remapping must not mutate BOT. if( tag==1 ) return malloc(XInt.make(bais.packed2())); return malloc(XInt.packed(bais)); } diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java index f28eed00..99470aa3 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java @@ -456,4 +456,92 @@ public class Chapter33Test { 123,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation2); assertTrue(code._allocation2.verify()); } + @Test public void testLateImportUniverses() { + ImportTestSupport.checkUniverses(); + } + + @Test public void testLateImportReturnedCallback() throws Exception { + Path lib=Files.createTempDirectory(Files.createDirectories(Path.of("build/objs")),"late-callback-"); + new CodeGen(null,lib.toString(),null,"Relay","val relay_noInline={{i64->i64} f -> f;}; return 0;", + 123,true,TypeInteger.BOT).driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); + CodeGen code=new CodeGen(null,null,new Ary<>(new String[]{lib.toString()}),"Client",""" + val _sent={i64 x -> x+1;}; + val _private={i64 x -> x-1;}; + val main={->Relay.relay_noInline(_sent);}; + return 0; + """,123,true,TypeInteger.BOT).driver(CodeGen.Phase.Opto); + FunNode sent=null, hidden=null, relay=null; + for( FunNode fun : code._linker ) if( fun!=null ) { + if( "_sent".equals(fun._name) ) sent=fun; + if( "_private".equals(fun._name) ) hidden=fun; + if( "relay_noInline".equals(fun._name) ) relay=fun; + } + assertNotNull(sent); assertNotNull(hidden); assertNotNull(relay); + TypeFunPtr result=(TypeFunPtr)((TypeTuple)relay.summary()._type).ret(); + assertTrue(XInt.bit(result._fidxs,sent.sig().fidx())); + assertFalse(XInt.bit(result._fidxs,hidden.sig().fidx())); + assertFalse(hidden.unknownCallers()); + } + + @Test public void testDeferredConditionalZero() { + for( String source : new String[]{ + "val test={->arg;}; return arg && (test()==1);", + "val test={->arg;}; return arg && (test()==1 && test()==1);", + "val test={->arg;}; return 0 && (test()==1);" + } ) { + CodeGen code; + try { code=compile(source); } + catch( Exception e ) { throw new AssertionError(source,e); } + assertEquals("0",Eval2.eval(code,0)); + assertNull(code._start.walk(n -> n instanceof ZeroNode ? n : null)); + } + } + + @Test public void testLateImportPrivateFunctions() throws Exception { + Path root=Files.createTempDirectory(Files.createDirectories(Path.of("build/objs")),"late-import-"); + Path src=Files.createDirectory(root.resolve("src")); + Path obj=Files.createDirectory(root.resolve("obj")); + new CodeGen(null,obj.toString(),null,"Library", + "val id_noInline={i64 x -> x;}; return 0;",123,true,TypeInteger.BOT) + .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); + Files.writeString(src.resolve("Helper.smp"),"val _hidden={i64 x -> x;}; val value_noInline={->2;}; return 0;"); + var paths=new Ary<>(new String[]{obj.toString()}); + String draw="val _draw={i64 x -> x+1;};"; + String main="val main={->Library.id_noInline(1)+Helper.value_noInline();};"; + for( boolean early : new boolean[]{true,false} ) { + CodeGen code=new CodeGen(src.toString(),obj.toString(),paths,"Client", + (early ? draw+main : main+draw)+"return 0;",123,true,TypeInteger.BOT).parse(); + FunNode privateFun=null, library=null; + for( FunNode fun : code._linker ) if( fun!=null ) { + if( "_draw".equals(fun._name) ) privateFun=fun; + if( "class:Library.<clinit>".equals(fun._name) ) library=fun; + } + assertNotNull(privateFun); + assertNotNull(library); + assertNotNull("The later discovered source unit was parsed",code._compunits.get("Helper")._src); + TypeMem saved=(TypeMem)library.summary()._state.mem(); + for( FunNode fun : code._linker ) + if( fun!=null && fun._compunit._src!=null ) + assertFalse(fun._name,XInt.bit(saved._escFs,fun.sig().fidx())); + int fidx=privateFun.sig().fidx(); + code.driver(CodeGen.Phase.Opto); + assertFalse(privateFun.unknownCallers()); + assertFalse(XInt.bit(((TypeTuple)code._start._type).mem()._escFs,fidx)); + } + } + + @Test public void testDeferredConditionalZeroLoop() { + CodeGen code=compile(""" + int count=0; + for( int i=0; i<4; i++ ) { + var inside = i>=2; + var border = inside && (i==2 || i==3); + if( border ) count++; + } + return count; + """); + assertEquals("2",Eval2.eval(code,0)); + assertNull(code._start.walk(n -> n instanceof ZeroNode ? n : null)); + } + } diff --git a/chapter33/src/test/java/com/seaofnodes/simple/codegen/ImportTestSupport.java b/chapter33/src/test/java/com/seaofnodes/simple/codegen/ImportTestSupport.java new file mode 100644 index 00000000..fe61580a --- /dev/null +++ b/chapter33/src/test/java/com/seaofnodes/simple/codegen/ImportTestSupport.java @@ -0,0 +1,74 @@ +package com.seaofnodes.simple.codegen; + +import com.seaofnodes.simple.type.*; +import com.seaofnodes.simple.util.BAOS; +import java.util.HashMap; +import static org.junit.Assert.*; + +public class ImportTestSupport { + public static void checkUniverses() { + new CodeGen("return 0;"); + GlobalBits file = new GlobalBits(), local = new GlobalBits(); + int excluded = file.next("Library"), included = file.next("Library"); + int shared = file.next("Shared"); + // Cross word boundaries, including bit 31 and bit 63. + for( int i=0; i<65; i++ ) local.next("Client"); + int localShared = local.next("Shared"); + int[] cofinite = XInt.dual(XInt.make(excluded)); + TypeFunPtr callback = TypeFunPtr.make(false,TypeFunPtr.TEMPTY,TypeInteger.BOT); + TypeFunPtr value = TypeFunPtr.make((byte)2,true,new Type[]{callback},TypeInteger.BOT,cofinite); + TypeTuple root = TypeTuple.make(TypeMem.START.makeFrom(cofinite,cofinite),TypeMem.BOT, + value,TypeRPC.BOT,TypeRPC.constant(included)); + Type.ImportedTypes decoded = unpack(root,file,local); + TypeTuple copy = (TypeTuple)decoded.values()[0]; + TypeTuple bounds = (TypeTuple)decoded.bounds()[0]; + TypeMem mem = (TypeMem)copy._types[0]; + TypeMem all = (TypeMem)copy._types[1]; + TypeFunPtr fun = (TypeFunPtr)copy._types[2]; + TypeRPC rpc = (TypeRPC)copy._types[3]; + int mappedExcluded=local.map(file,excluded), mappedIncluded=local.map(file,included); + assertEquals(localShared,local.map(file,shared)); + for( int[] bits : new int[][]{mem._escFs,mem._escAs,all._escFs,all._escAs,fun._fidxs,rpc._rpcs} ) { + for( int i=2; i<localShared; i++ ) assertFalse("Local bit "+i,XInt.bit(bits,i)); + assertTrue(XInt.bit(bits,mappedIncluded)); + assertTrue(XInt.bit(bits,localShared)); + assertTrue("Unknown remote tail remains infinite",XInt.bit(bits,10000)); + } + assertFalse(XInt.bit(mem._escFs,mappedExcluded)); + assertFalse(XInt.bit(mem._escAs,mappedExcluded)); + assertFalse(XInt.bit(fun._fidxs,mappedExcluded)); + assertEquals(mappedIncluded,((TypeRPC)copy._types[4]).rpc()); + assertSame("Declarations remain universal",TypeMem.BOT,bounds._types[1]); + assertSame(TypeRPC.BOT,bounds._types[3]); + assertSame(XInt.FULL,((TypeFunPtr)fun.arg(0))._fidxs); + assertSame("Decoding ALL never mutates the canonical RPC",XInt.FULL,TypeRPC.BOT._rpcs); + for( int i=0; i<GlobalBits.RESERVED; i++ ) + assertEquals(XInt.bit(cofinite,i),XInt.bit(mem._escFs,i)); + + // A re-export must preserve previous exclusions and narrow its new + // receiving universe too, including generic cofinite RPC encoding. + GlobalBits next = new GlobalBits(); + int newer = next.next("NextClient"); + TypeTuple again = (TypeTuple)unpack(copy,local,next).values()[0]; + TypeRPC againRPC = (TypeRPC)again._types[3]; + assertFalse(XInt.bit(againRPC._rpcs,newer)); + assertFalse(XInt.bit(againRPC._rpcs,next.map(local,2))); + assertTrue(XInt.bit(againRPC._rpcs,next.map(local,mappedIncluded))); + assertSame(XInt.FULL,TypeRPC.BOT._rpcs); + } + + private static Type.ImportedTypes unpack(Type root, GlobalBits file, GlobalBits local) { + Type.TAGOFFS(); + HashMap<Type,Integer> ids = new HashMap<>(); + root.gather(ids); + Type[] types = new Type[ids.size()]; + for( var entry : ids.entrySet() ) types[entry.getValue()] = entry.getKey(); + BAOS out = new BAOS(); + HashMap<String,Integer> strings = new HashMap<>(); + for( Type t : types ) t.packed(out,strings); + for( Type t : types ) + for( int i=0; i<t.nkids(); i++ ) out.packed4(ids.get(t.at(i))); + return Type.packed(new BAOS(out.toByteArray()),new String[]{""},types.length, + file,local,file,local,file,local); + } +} |
