From 0b263f550d5e54d050f58f6b315b092944c9eff9 Mon Sep 17 00:00:00 2001 From: Cliff Click Date: Mon, 10 Aug 2026 11:11:18 -0700 Subject: Chapter 32: Compiler Internal Speedups Co-authored-by: Hsiang-Ying Fu <66062782+fuhsnn@users.noreply.github.com> Co-authored-by: fuhsnn <66062782+fuhsnn@users.noreply.github.com> Co-authored-by: Symious <14933944+symious@users.noreply.github.com> Co-authored-by: Jun Kawasaki Co-authored-by: Claude Opus 5 --- src/main/c/simple_graphics.c | 2 +- src/main/java/com/seaofnodes/simple/README.md | 2 +- .../com/seaofnodes/simple/codegen/CodeGen.java | 2 +- .../java/com/seaofnodes/simple/codegen/IFG.java | 96 +++++++------- .../com/seaofnodes/simple/codegen/IterPeeps.java | 17 ++- .../com/seaofnodes/simple/codegen/RegAlloc.java | 7 +- .../com/seaofnodes/simple/codegen/Serialize.java | 33 ++--- .../com/seaofnodes/simple/node/BulkMemPhiNode.java | 12 +- .../java/com/seaofnodes/simple/node/CallNode.java | 20 ++- .../java/com/seaofnodes/simple/node/IfNode.java | 4 +- .../java/com/seaofnodes/simple/node/LoopNode.java | 4 +- .../com/seaofnodes/simple/node/MemMergeNode.java | 117 +++++++++++++---- .../java/com/seaofnodes/simple/node/PhiNode.java | 20 +-- .../com/seaofnodes/simple/node/RegionNode.java | 7 +- .../com/seaofnodes/simple/node/SummaryNode.java | 15 ++- .../simple/node/cpus/x86_64_v2/x86_64_v2.java | 7 +- .../java/com/seaofnodes/simple/parser/README.md | 2 +- .../com/seaofnodes/simple/parser/package-info.java | 2 +- src/main/java/com/seaofnodes/simple/type/Type.java | 12 +- .../com/seaofnodes/simple/type/TypeFunPtr.java | 5 +- .../com/seaofnodes/simple/type/TypeStruct.java | 8 +- src/main/java/com/seaofnodes/simple/util/BAOS.java | 45 ++++--- src/main/smp/sys/audio.md | 6 +- src/main/smp/sys/draw/README.md | 4 +- src/main/smp/sys/gfx.md | 12 +- src/main/smp/sys/time/README.md | 6 +- .../com/seaofnodes/simple/AssemblyDumpTest.java | 28 +++-- src/test/java/com/seaofnodes/simple/BAOSTest.java | 58 +++++++++ .../java/com/seaofnodes/simple/CallEndTest.java | 24 ++++ .../java/com/seaofnodes/simple/Chapter05Test.java | 31 +++-- .../java/com/seaofnodes/simple/Chapter10Test.java | 8 +- .../java/com/seaofnodes/simple/Chapter13Test.java | 4 +- .../java/com/seaofnodes/simple/Chapter21Test.java | 4 +- .../java/com/seaofnodes/simple/Chapter23Test.java | 2 +- .../java/com/seaofnodes/simple/EscapeFlowTest.java | 31 +++++ .../java/com/seaofnodes/simple/MemMergeTest.java | 83 ++++++++++++ src/test/java/com/seaofnodes/simple/ModTest.java | 27 ++-- .../java/com/seaofnodes/simple/SchedulingTest.java | 39 ++++++ .../seaofnodes/simple/SeparateCompilationTest.java | 36 ++++++ .../com/seaofnodes/simple/StringFormatTest.java | 113 ++++++++++++----- .../java/com/seaofnodes/simple/TestWorkspace.java | 54 ++++++++ src/test/java/com/seaofnodes/simple/TypeTest.java | 140 +++++++++++++++------ .../java/com/seaofnodes/simple/WorklistTest.java | 49 ++++++++ .../simple/codegen/RegAllocTestSupport.java | 6 +- .../simple/type/PackedTypeTestSupport.java | 20 +++ 45 files changed, 949 insertions(+), 275 deletions(-) create mode 100644 src/test/java/com/seaofnodes/simple/BAOSTest.java create mode 100644 src/test/java/com/seaofnodes/simple/MemMergeTest.java create mode 100644 src/test/java/com/seaofnodes/simple/TestWorkspace.java create mode 100644 src/test/java/com/seaofnodes/simple/WorklistTest.java create mode 100644 src/test/java/com/seaofnodes/simple/type/PackedTypeTestSupport.java (limited to 'src') diff --git a/src/main/c/simple_graphics.c b/src/main/c/simple_graphics.c index a35c28a6..a1c0e952 100644 --- a/src/main/c/simple_graphics.c +++ b/src/main/c/simple_graphics.c @@ -36,7 +36,7 @@ static void *find_backend(void) { } const char *relative[]={"./" BACKEND_NAME, "./build/release/" BACKEND_ABI "/" BACKEND_NAME, - "./chapter31/build/release/" BACKEND_ABI "/" BACKEND_NAME}; + "./chapter32/build/release/" BACKEND_ABI "/" BACKEND_NAME}; for (unsigned i=0;i 0; } public static boolean expensiveAssert( int trip ) { if( EXPENSIVE_ASSERT_LOG <= 0 ) return false; diff --git a/src/main/java/com/seaofnodes/simple/codegen/IFG.java b/src/main/java/com/seaofnodes/simple/codegen/IFG.java index 6ad7c0ad..a027263f 100644 --- a/src/main/java/com/seaofnodes/simple/codegen/IFG.java +++ b/src/main/java/com/seaofnodes/simple/codegen/IFG.java @@ -8,18 +8,20 @@ import java.util.BitSet; import java.util.IdentityHashMap; // Interference Graph -abstract public class IFG { +public class IFG { // Interference Graph Support + // Scratch for one function, reused across its spill retries. // Map from a Basic Block to Live-Out: {a map from a Live Range to a Def} - private static final IdentityHashMap> BBOUTS = new IdentityHashMap<>(); - static void resetBBLiveOut() { - for( IdentityHashMap bbout : BBOUTS.values() ) + private final IdentityHashMap> _bbouts = new IdentityHashMap<>(); + private void resetBBLiveOut() { + for( IdentityHashMap bbout : _bbouts.values() ) bbout.clear(); } - static final IdentityHashMap TMP = new IdentityHashMap<>(); + private final IdentityHashMap _tmp = new IdentityHashMap<>(); - // Inteference Graph: Array of Bitsets + // Interference Graph: Array of Bitsets. Reuse capacity across functions; + // these contain only live-range numbers, not references to the graph. static final Ary IFG = new Ary<>(BitSet.class); static void resetIFG() { for( BitSet bs : IFG ) @@ -42,10 +44,10 @@ abstract public class IFG { } - private static final Ary WORK = new Ary<>(CFGNode.class); - static void pushWork(CFGNode bb) { - if( WORK.find(bb) == -1 ) - WORK.push(bb); + private final Ary _work = new Ary<>(CFGNode.class); + private void pushWork(CFGNode bb) { + if( _work.find(bb) == -1 ) + _work.push(bb); } // ------------------------------------------------------------------------ @@ -65,20 +67,20 @@ abstract public class IFG { // - At block head, "push" the new live-out to prior blocks. // - - If they pick up new live-outs, put them on the worklist. - public static boolean build( int round, RegAlloc alloc ) { + public boolean build( int round, RegAlloc alloc ) { // Reset all to empty resetBBLiveOut(); resetIFG(); - WORK.clear(); + _work.clear(); // Last block has nothing live out for( CFGNode bb : alloc._cfg ) if( bb.blockHead()) - WORK.push( bb ); + _work.push( bb ); // Process blocks until no more changes - while( !WORK.isEmpty() ) - do_block(round,alloc,WORK.pop()); + while( !_work.isEmpty() ) + do_block(round,alloc,_work.pop()); if( alloc.success() ) convert2DAdjacency(alloc); @@ -86,12 +88,12 @@ abstract public class IFG { } // Walk one block backwards, compute live-in from live-out, and build IFG - static void do_block( int round, RegAlloc alloc, CFGNode bb ) { + private void do_block( int round, RegAlloc alloc, CFGNode bb ) { assert bb.blockHead(); - IdentityHashMap live_out = BBOUTS.get(bb); - TMP.clear(); + IdentityHashMap live_out = _bbouts.get(bb); + _tmp.clear(); if( live_out != null ) - TMP.putAll(live_out); // Copy bits to temp + _tmp.putAll(live_out); // Copy bits to temp // A backwards walk over instructions in the basic block for( int inum = bb.nOuts()-1; inum >= 0; inum-- ) { @@ -118,14 +120,14 @@ abstract public class IFG { mergeLiveOut(alloc,bb,0); } - private static void do_node(RegAlloc alloc, Node n) { + private void do_node(RegAlloc alloc, Node n) { // Defining means killing live LRG LRG lrg = alloc.lrg(n); if( lrg != null ) { // Check for def-side self-conflict live ranges. These must split, // and only happens during the first round a particular LRG splits. selfConflict(alloc,n,lrg); - TMP.remove(lrg); // Kill def + _tmp.remove(lrg); // Kill def } // Phis use and define the same live range, i.e. these LRGs already @@ -141,7 +143,7 @@ abstract public class IFG { // Interfere n with all live if( lrg!=null ) { // Interfere n with all live - for( LRG tlrg : TMP.keySet() ) { + for( LRG tlrg : _tmp.keySet() ) { assert tlrg.leader(); // Skip self if( lrg != tlrg && @@ -177,7 +179,7 @@ abstract public class IFG { selfConflict(alloc,def,lrg1); // All operands are live together, regardless of their input order. - TMP.put(lrg1,def); + _tmp.put(lrg1,def); } // Check fixed-register uses after gathering every operand. An indirect @@ -191,9 +193,9 @@ abstract public class IFG { RegMask ni_mask = m.regmap(i); if( ni_mask!=null && ni_mask.size1() ) { // Must-use single register // Search all current live - for( LRG tlrg : TMP.keySet() ) { + for( LRG tlrg : _tmp.keySet() ) { assert tlrg.leader(); - Node live = TMP.get(tlrg); + Node live = _tmp.get(tlrg); if( live != def && live instanceof MachNode lmach && lmach.outregmap().overlap(ni_mask) ) { // Deny the register, since it absolutely must be used here if( !tlrg.clr(ni_mask.firstReg()) ) @@ -210,15 +212,15 @@ abstract public class IFG { // Single-register defines *must* have their register; other live ranges // *must* avoid this register, so instead of interfering we remove the // single register from the other rmask. - private static void kills( RegAlloc alloc, MachNode m ) { + private void kills( RegAlloc alloc, MachNode m ) { RegMask killMask = m.killmap(); if( killMask==null ) return; // Kill registers with all live - for( LRG tlrg : TMP.keySet() ) { + for( LRG tlrg : _tmp.keySet() ) { assert tlrg.leader(); // Always, tlrg cannot use kills if( tlrg._mask.overlap(killMask) ) { - Node live = TMP.get(tlrg); + Node live = _tmp.get(tlrg); // Disallow clone-ables from living across killed registers. // Fail them and let splitting re-clone closer to the target use. if( live instanceof MachNode mach && mach.isClone() ) @@ -231,8 +233,8 @@ abstract public class IFG { // Check for self-conflict live ranges. These must split, and only happens // during the first round a particular LRG splits. - private static void selfConflict(RegAlloc alloc, Node n, LRG lrg) { - selfConflict(alloc,n,lrg,TMP.get(lrg)); + private void selfConflict(RegAlloc alloc, Node n, LRG lrg) { + selfConflict(alloc,n,lrg,_tmp.get(lrg)); } private static void selfConflict(RegAlloc alloc, Node n, LRG lrg, Node prior) { if( prior!=null && prior != n ) { @@ -242,17 +244,17 @@ abstract public class IFG { } } - // Merge TMP into bb's live-out set; if changes put bb on WORK - private static void mergeLiveOut( RegAlloc alloc, CFGNode priorbb, int i ) { + // Merge _tmp into bb's live-out set; if changes put bb on _work + private void mergeLiveOut( RegAlloc alloc, CFGNode priorbb, int i ) { CFGNode bb = priorbb.cfg(i); if( bb == null ) return; // Start has no prior while( !bb.blockHead() ) bb = bb.cfg0(); // Lazy get live-out set for bb - IdentityHashMap lrgs = BBOUTS.computeIfAbsent( bb, k -> new IdentityHashMap<>() ); + IdentityHashMap lrgs = _bbouts.computeIfAbsent( bb, k -> new IdentityHashMap<>() ); - for( LRG lrg : TMP.keySet() ) { - Node def = TMP.get(lrg); + for( LRG lrg : _tmp.keySet() ) { + Node def = _tmp.get(lrg); // Effective def comes from phi input from prior block if( def instanceof PhiNode phi && phi.cfg0()==priorbb ) { assert i!=0; @@ -306,6 +308,9 @@ abstract public class IFG { // If there's no spare color we'll have to spill this at-risk live range. public static boolean color(int round, RegAlloc alloc) { + // Coalescing is finished; splitting may change this area next round. + FunNode fun = alloc._cfg.at(0).fun(); + int functionArea = functionArea(fun,alloc); int maxlrg = alloc._LRGS.length, nlrgs=0; for( int i=1; i bestScore ) { best = i; bestScore = iScore; } } @@ -446,16 +452,16 @@ abstract public class IFG { // // Picking a live range that is very close to coloring might allow it to // color despite being risky. - private static int pickRiskyScore( LRG lrg, RegAlloc alloc ) { + private static int pickRiskyScore( LRG lrg, int functionArea ) { // Callee-save live ranges cover the whole function and are cheap to // split. Rank scheduled area recovered against the loop-scaled cost // of the def- and use-side moves. if( lrg._machDef instanceof CalleeSaveNode ) - return areaScore(functionArea(lrg._fun,alloc), + return areaScore(functionArea, splitCost((Node)lrg._machDef,(Node)lrg._machUse)); if( lrg._splitDef != null && lrg._splitDef. in(1) instanceof CalleeSaveNode && lrg._splitUse != null && lrg._splitUse.out(0) instanceof ReturnNode ) - return areaScore(functionArea(lrg._fun,alloc), + return areaScore(functionArea, splitCost(lrg._splitDef,lrg._splitUse)); // Pick single-def clonables that are not right next to their single-use. @@ -465,7 +471,7 @@ abstract public class IFG { Node use = ((Node)lrg._machUse); CFGNode cfg = def.cfg0(); int area = cfg != use.cfg0() - ? functionArea(lrg._fun,alloc) + ? functionArea : cfg._outputs.find(use)-cfg._outputs.find(def)-1; // A single-use function address can move next to its use without // adding an instruction. Prefer that to saving a callee-save diff --git a/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java b/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java index f4acb729..fe935a69 100644 --- a/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java +++ b/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java @@ -95,6 +95,9 @@ public class IterPeeps { code.addAll(defer); defer.clear(); } + // Check the completed fixed point, not every intermediate inline batch. + // Periodic progress checks still verify scheduling during the run. + assert !CodeGen.expensiveAssert(0) || schedulableUses(code); } // Run all the code-reduction and type-lifting peeps as possible @@ -122,7 +125,13 @@ public class IterPeeps { // A self-returning peephole can have rewritten its input // edges. The new defs gained a user and may have // backwards, user-sensitive peepholes of their own. - for( Node z : x._inputs ) _work.push(z); + boolean edited = x!=n || x.isUnlocked(); + for( Node z : x._inputs ) + // A type-only update adds no users. A stable memory + // Phi has no backwards rewrite based on user types. + // Keep first-use and edited/unprocessed Phis queued. + if( edited || !(z instanceof MemPhiNode) || z.nOuts()<=1 || z.isUnlocked() ) + _work.push(z); // If the result is not self, revisit all inputs (because // there's a new user), and replace in the graph. if( x != n ) { @@ -143,8 +152,6 @@ public class IterPeeps { } if( obs != null ) obs.after(n, x!=null ? x : unused ? n : null, true); } - assert !CodeGen.expensiveAssert(0) || schedulableUses(code); - } // Visit ALL nodes and confirm the invariant: @@ -236,7 +243,9 @@ public class IterPeeps { } return found; } - return CFGNode.safeCFG(use); + // A memory op can execute after its control (e.g. a range check). + // Like schedEarly, include its data inputs before constraining its defs. + return use instanceof MemOpNode ? CFGNode.earlyCFG(use,earlyCache,VISIT) : CFGNode.safeCFG(use); } private static String badSchedule(Node n, CFGNode early, CFGNode lca) { diff --git a/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java b/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java index 303fd355..c3be4b71 100644 --- a/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java +++ b/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java @@ -213,8 +213,9 @@ public class RegAlloc { } private void allocateFunction() { + IFG ifg = new IFG(); _deferredLoopSelf.clear(); - for( byte round=0; !graphColor(round); round++ ) { + for( byte round=0; !graphColor(round,ifg); round++ ) { split(round); if( round >= 10 ) { FunNode fun = _cfg.at(0).fun(); @@ -281,7 +282,7 @@ public class RegAlloc { return cfg==null ? null : cfg.fun(); } - private boolean graphColor(byte round) { + private boolean graphColor(byte round, IFG ifg) { _failed.clear(); _lrgs.clear(); _lrg_num = 1; @@ -291,7 +292,7 @@ public class RegAlloc { // Build Live Ranges BuildLRG.run(round,this) && // if no hard register conflicts // Build Interference Graph - IFG.build(round,this) && // If no self conflicts or uncolorable + ifg.build(round,this) && // If no self conflicts or uncolorable // Conservative coalesce copies Coalesce.coalesce(round,this) && // Color attempt diff --git a/src/main/java/com/seaofnodes/simple/codegen/Serialize.java b/src/main/java/com/seaofnodes/simple/codegen/Serialize.java index b168c4af..9c43e029 100644 --- a/src/main/java/com/seaofnodes/simple/codegen/Serialize.java +++ b/src/main/java/com/seaofnodes/simple/codegen/Serialize.java @@ -103,8 +103,10 @@ public class Serialize { Type startType = TypeTuple.make(Type.CONTROL,stopType.mem(),((StartNode)nodes.at(0)).arg()); BAOS baos = new BAOS(); - // A - Print the C0DE header. The format is not versioned yet. - baos.write('C').write('0').write('D').write('E'); + // A - Print the C0DE header; last byte is the version number. + // Format 2: gradual packed ints, UTF-8 strings, sparse MemMerge edges, + // and wider singleton function IDs. Reject old cached objects clearly. + baos.write('C').write('0').write('D').write('2'); // Count unique Types var types = new HashMap(); @@ -265,8 +267,11 @@ public class Serialize { } // Write out the input indices packed. for( Node n : nodes ) { - for( int j=0; j=2 ) + baos.packed2(mem.aliasAt(j)); Node def = n.in(j); Integer idx = def==null ? Integer.valueOf(0) : anodes.get(def); // Imported function constants retain their symbol, not a body. @@ -330,7 +335,7 @@ public class Serialize { Type.TAGOFFS(); // A - Read a header - if( bais.read()!='C' || bais.read()!='0' || bais.read()!='D' || bais.read()!='E' ) + if( bais.read()!='C' || bais.read()!='0' || bais.read()!='D' || bais.read()!='2' ) throw new IllegalArgumentException("Unsupported serialized IR format; rebuild the object file"); // B - Packed read of #strings, then strings @@ -363,7 +368,7 @@ public class Serialize { String[] strs = elf._strs; if( strs == null ) { // A - Read a header - if( bais.read() != 'C' || bais.read() != '0' || bais.read() != 'D' || bais.read() != 'E' ) + if( bais.read() != 'C' || bais.read() != '0' || bais.read() != 'D' || bais.read() != '2' ) throw new IllegalArgumentException( "Unsupported serialized IR format; rebuild the object file" ); // B - Packed read of #strings, then strings @@ -500,19 +505,17 @@ public class Serialize { // Node edges for( Node n : nodes ) { - int len = n.nIns(); + int len = n instanceof MemMergeNode mem ? mem.readSize() : n.nIns(); for( int i = 0; i=2 ? bais.packed2() : 0; int idx = bais.packed2(); Node def = idx==0 ? null : nodes.at(idx-1); - // MemMerge precise aliases are encoded by their input slot. - // Remap populated file-local slots into this compilation's - // local alias numbering; null holes carry no identity. - int local = i; - if( n instanceof MemMergeNode && i >= GlobalBits.RESERVED ) { - if( def == null ) continue; - local = aliases.map(fileAliases,i); - } - n.setDefX(local,def); + // Remap only explicit slices; omitted aliases use the default. + if( n instanceof MemMergeNode mem && i>=2 ) { + if( def==null ) continue; + int alias = aliases.map(fileAliases,fileAlias); + mem.alias(alias,def); + } else n.setDefX(i,def); // Call's output[0] is always the CallEnd if( n instanceof CallEndNode cend && i==0 ) { var outs = cend.call()._outputs; diff --git a/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java b/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java index b49163e7..f4d1e195 100644 --- a/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java +++ b/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java @@ -118,7 +118,7 @@ public class BulkMemPhiNode extends PhiNode { } else if( m instanceof MemMergeNode mmm && mmm.in(1) instanceof BulkMemPhiNode bulk && bulk._aliases.get(alias) && - (alias >= mmm.nIns() || mmm.in(alias)==null) ) + mmm.explicitAlias(alias)==null ) return false; return true; } @@ -187,11 +187,9 @@ public class BulkMemPhiNode extends PhiNode { // First explicit MemMerge slice still covered by this Phi. A user's slice // may point to this Phi after a precise Phi folds; splitting is still valid. private int missingAlias( MemMergeNode mmm ) { - for( int alias=2; alias= 0; alias = bulk._aliases.nextSetBit(alias+1) ) - if( alias >= mmm.nIns() || mmm.in(alias)==null ) + if( mmm.explicitAlias(alias)==null ) return false; return true; } diff --git a/src/main/java/com/seaofnodes/simple/node/CallNode.java b/src/main/java/com/seaofnodes/simple/node/CallNode.java index 9030d43d..5506621b 100644 --- a/src/main/java/com/seaofnodes/simple/node/CallNode.java +++ b/src/main/java/com/seaofnodes/simple/node/CallNode.java @@ -102,10 +102,13 @@ public class CallNode extends CFGNode { if( !external() ) return TypeMem.START; Type input = dep.addDepForwards(mem())._type; TypeMem escaped = input instanceof TypeMem m ? m : input.isHigh() ? TypeMem.TOP : TypeMem.BOT; - TypeMem outside = CodeGen.CODE._start.outside(dep); - // A class receiver belongs to the callee; the caller does not expose its class. - for( int i = tfp.nargs()>0 && tfp.arg(0)==TypePtr.PTR ? 3 : 2; i0 && tfp.arg(0)==TypePtr.PTR ? 3 : 2; i strs, HashMap types, IdentityHashMap anodes ) { - // A memory merge always has inputs. Zero escapes a wide alias table, - // preserving every existing nonzero single-byte count. - assert nIns()>0; - baos.packed1(nIns()<=255 ? nIns() : 0); - if( nIns()>255 ) baos.packed4(nIns()); + // Keep the extent even if its last precise slice was removed. Edges + // are dense: control/default followed by explicit (alias,input) pairs. + baos.packed4(_aliasLimit); + baos.packed2(nIns()); } static Node make( BAOS bais ) { - int count=bais.packed1(); - if( count==0 ) count=bais.packed4(); - Node mem=new MemMergeNode(); - mem.setDefX(count-1,null); + int limit=bais.packed4(), count=bais.packed2(); + assert 2<=count && count<=limit; + MemMergeNode mem=new MemMergeNode(null,null); + mem._readSize=count; + mem._aliasLimit=limit; return mem; } @@ -42,7 +87,7 @@ public class MemMergeNode extends Node { protected ExprPrinter _print1(ExprPrinter p) { p.p("MEM[ "); for( int j=2; j=nIns() || in(i)==null ) - setDefX(i,mem.in(i)); + int alias = mem.aliasAt(i); + if( explicitAlias(alias)==null ) + alias(alias,mem.in(i)); } } CodeGen.CODE.add(mem.in(1)); @@ -140,12 +188,33 @@ public class MemMergeNode extends Node { public Node in( Var v ) { return in(v._idx); } public Node alias( int alias ) { - assert !(in(1) instanceof BulkMemPhiNode bulk && bulk.isSplit(alias) && - (alias >= nIns() || in(alias)==null)); - return alias < nIns() && in(alias)!=null ? in(alias) : in(1); + Node precise = explicitAlias(alias); + assert !(in(1) instanceof BulkMemPhiNode bulk && bulk.isSplit(alias) && precise==null); + return precise==null ? in(1) : precise; } - public Node alias( int alias, Node st ) { return setDefX(alias,st); } + public Node alias( int alias, Node st ) { + if( alias==1 ) return setDef(1,st); + assert alias>1; + _aliasLimit=Math.max(_aliasLimit,alias+1); + int input = _aliasToInput==null ? 0 : _aliasToInput.get(alias); + if( st==null ) { + if( input!=0 ) removeAlias(input); + return st; + } + if( input!=0 ) return setDef(input,st); + if( _aliases==null ) { + _aliases = new AryInt(); + _aliasToInput = new IntHashMap(0); + } + int pos = Arrays.binarySearch(_aliases._es,0,_aliases.len(),alias); + assert pos<0; + pos = -pos-1; + _aliases.insert(pos,alias); + for( int i=pos; i<_aliases.len(); i++ ) _aliasToInput.put(_aliases.at(i),i+2); + insertDef(pos+2,st); + return st; + } // Now one-time do a useless-phi removal void _useless( ) { diff --git a/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/src/main/java/com/seaofnodes/simple/node/PhiNode.java index af24a94b..94376086 100644 --- a/src/main/java/com/seaofnodes/simple/node/PhiNode.java +++ b/src/main/java/com/seaofnodes/simple/node/PhiNode.java @@ -148,6 +148,9 @@ public class PhiNode extends Node { return null; if( !(r.in(3-nzIdx) instanceof CProjNode z && z._idx==1 && z.ctrl()==iff) ) return null; + // A rewritten predicate can make this guard match without changing the Phi inputs. + addDep(iff); + addDep(iff.pred()); // subsume wakes the replaced predicate's dependents. // Predicate was guarded? Node n = cast.in(1), tested = null; while( true ) { @@ -159,23 +162,23 @@ public class PhiNode extends Node { return tested!=null && (early==null || early.dominates(r,this)) ? n : null; } - // View x<<1 as x+x only while matching mixed Phi arms. Do not - // expand the graph into Adds that would immediately strength-reduce again. + // View x<<1 as x+x when factoring mixed Add/Shl arms. Do not expand the + // graph: Add would immediately strength-reduce it again. If all arms are + // shifts, keep the ordinary shift factoring (including arbitrary counts). private Node factoringOp() { Node op = in(1); if( doubled(op) ) for( int i=2; i writers=load.antiDeps(new Ary<>(Node.class)); if( writers.isEmpty() ) return true; - var seen=new IdentityHashMap(); + var seen=new BitSet(); Ary work=new Ary<>(Node.class); work.push(value); while( !work.isEmpty() ) { Node n=work.pop(); - if( seen.put(n,Boolean.TRUE)!=null ) continue; + if( seen.get(n._nid) ) continue; + seen.set(n._nid); if( writers.find(n)!=-1 ) return false; for( Node def : n._inputs ) if( def!=null ) work.push(def); } diff --git a/src/main/java/com/seaofnodes/simple/parser/README.md b/src/main/java/com/seaofnodes/simple/parser/README.md index 48cf13c8..a474eb17 100644 --- a/src/main/java/com/seaofnodes/simple/parser/README.md +++ b/src/main/java/com/seaofnodes/simple/parser/README.md @@ -2,7 +2,7 @@ The parser builds Sea-of-Nodes IR directly. Each component shares the cursor, active scope, and compilation state through its `Parser P` reference; there is no intermediate -AST. The [grammar map](../../../../../../../docs/chapter31/31-grammar.md) connects language +AST. The [grammar map](../../../../../../../docs/chapter32/32-grammar.md) connects language productions to their entry points. | File | Responsibility | diff --git a/src/main/java/com/seaofnodes/simple/parser/package-info.java b/src/main/java/com/seaofnodes/simple/parser/package-info.java index 73ebec2e..828ac6d9 100644 --- a/src/main/java/com/seaofnodes/simple/parser/package-info.java +++ b/src/main/java/com/seaofnodes/simple/parser/package-info.java @@ -7,7 +7,7 @@ * use-side name/field resolution; Allocations, ControlFlow, and Conversions * contain their shared IR construction. Lexer also supplies location snapshots. * - *

See {@code chapter31/docs/31-grammar.md} for the production-to-method map. + *

See {@code chapter32/docs/32-grammar.md} for the production-to-method map. * Evaluation order and scope lifetimes are explicit: loop updates and declared * constructor bodies are the two deferred source fragments. There is no AST. */ diff --git a/src/main/java/com/seaofnodes/simple/type/Type.java b/src/main/java/com/seaofnodes/simple/type/Type.java index 2e228494..221de04c 100644 --- a/src/main/java/com/seaofnodes/simple/type/Type.java +++ b/src/main/java/com/seaofnodes/simple/type/Type.java @@ -401,10 +401,6 @@ public class Type /*implements Cloneable*/ { return rez; } - // Read-only recursive visits do not *make* cyclic types and so the cleanup - // is much easier. - static boolean recurClose(boolean rez) { VISIT.clear(); return rez; } - final Type tern() { if( _terned ) return this; if( !BITS.get(_uid) ) { @@ -464,8 +460,9 @@ public class Type /*implements Cloneable*/ { } // Strict constant values, things on the lattice centerline. - // Excludes both high and low values - public final boolean isConstant() { return recurClose(recurOpen()._isConstant()); } + // Excludes both high and low values. Pointers check their own identity, + // not their referents, so aggregate checks do not follow type cycles. + public final boolean isConstant() { return _isConstant(); } boolean _isConstant() { return _type==TNIL; } // Are all reachable struct Fields are final? @@ -473,7 +470,8 @@ public class Type /*implements Cloneable*/ { // Otherwise an alias could insert a readonly pointer into a writable slot. public boolean accessISA(Type dst) { return true; } - public final boolean isFinal() { return recurClose(recurOpen()._isFinal()); } + // Pointer finality comes from its access qualifier, not its referent. + public final boolean isFinal() { return _isFinal(); } boolean _isFinal() { assert is_nokids(); return true; } public final Type makeRO() { diff --git a/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java b/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java index 19ec5019..c6f53022 100644 --- a/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java +++ b/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java @@ -248,7 +248,7 @@ public class TypeFunPtr extends TypeNil { @Override int TAGOFF() { return 8; } @Override public void packed( BAOS baos, HashMap strs ) { assert _open; // Open: Passing extra args is fine, and extras ignored. - if( _nil==2 && nargs()<6 && nfcns() == 1 && fidx() < 64 ) { + if( _nil==2 && nargs()<6 && nfcns() == 1 && fidx()<=65535 ) { baos.write(TAGOFFS[_type] + nargs()); baos.packed2(fidx()); } else { @@ -259,8 +259,7 @@ public class TypeFunPtr extends TypeNil { } static TypeFunPtr packed( int tag, BAOS bais ) { if( tag < 6 ) { - int fidx = bais.read(); - assert fidx < 64; // Need a larger fidx space + int fidx = bais.packed2(); return malloc((byte)2,true,new Type[tag],null, XInt.make(fidx)); } byte nil = (byte)(tag==6 ? 2 : 3); diff --git a/src/main/java/com/seaofnodes/simple/type/TypeStruct.java b/src/main/java/com/seaofnodes/simple/type/TypeStruct.java index 11ba3cc4..d1586547 100644 --- a/src/main/java/com/seaofnodes/simple/type/TypeStruct.java +++ b/src/main/java/com/seaofnodes/simple/type/TypeStruct.java @@ -399,9 +399,7 @@ public class TypeStruct extends Type { @Override boolean _isConstant() { assert !_open; // who is asking about constant open structs? if( _open ) return false; // Infinite BOT fields - assert !VISIT.containsKey(_uid); //expect constants to not include self-cycles. if( VISIT.containsKey(_uid) ) return true; // Cycles assume constant - VISIT.put(_uid,this); - // Check all fields for being constant + // Check field values; pointers do not recurse into their referents. for( Field field : _fields ) if( !field._isConstant() ) return false; @@ -411,9 +409,7 @@ public class TypeStruct extends Type { // All fields are final @Override boolean _isFinal() { if( _open ) return false; // May have more non-final fields - if( VISIT.containsKey(_uid) ) // Test: been here before? - return true; // Cycles assume final - VISIT.put(_uid,this); // Set: don't do this again + // Pointer fields check their access qualifier without following cycles. for( Field fld : _fields ) if( !fld._isFinal() ) return false; diff --git a/src/main/java/com/seaofnodes/simple/util/BAOS.java b/src/main/java/com/seaofnodes/simple/util/BAOS.java index 61ce7387..c47d386c 100644 --- a/src/main/java/com/seaofnodes/simple/util/BAOS.java +++ b/src/main/java/com/seaofnodes/simple/util/BAOS.java @@ -1,7 +1,8 @@ package com.seaofnodes.simple.util; -import java.util.HashMap; +//import java.util.HashMap; import java.util.Arrays; +import java.nio.charset.StandardCharsets; // "ByteArrayOutputStream", and Input Stream and not synchronized and has // matching pack/unpack strategies. @@ -96,12 +97,12 @@ public class BAOS { } // ----------------------------------------------------------------------- - // Write a packed integer to the BAOS. Track a histogram to make more - // intelligent choices in the future. - private static final HashMap PACKED_HISTOGRAM = new HashMap<>(); + // Optional profiling for choosing smaller packed representations. Leave + // disabled during normal compilation; re-enable when studying .simple size. + //private static final HashMap PACKED_HISTOGRAM = new HashMap<>(); private BAOS histo(long x) { - Integer cnt = PACKED_HISTOGRAM.get(x); - PACKED_HISTOGRAM.put(x,cnt==null ? 1 : cnt+1); + //Integer cnt = PACKED_HISTOGRAM.get(x); + //PACKED_HISTOGRAM.put(x,cnt==null ? 1 : cnt+1); return this; } @@ -125,15 +126,29 @@ public class BAOS { return x==0xFF ? read2() : x; } - // Write a packed i32 + // Signed zigzag varint: -64..63 use one byte, -8192..8191 two, + // and the full int range needs at most five. Seven payload bits per byte. public void packed4(int x) { - ((-127 <= x && x <= 127 ) ? write(x) : write(-128).write4(x)).histo(x); + histo(x); + int bits = (x<<1) ^ (x>>31); + while( (bits & ~127)!=0 ) { + write((bits & 127) | 128); + bits >>>= 7; + } + write(bits); } // Read a packed i32 public int packed4() { - int x = _buf[_len++]; // Signed byte read - return x== -128 ? read4() : x; + int bits=0; + for( int shift=0; shift<32; shift+=7 ) { + int b = read(); + if( shift==28 && (b & 0xF0)!=0 ) + throw new IllegalArgumentException("Packed int overflow"); + bits |= (b & 127)<>>1) ^ -(bits & 1); + } + throw new IllegalArgumentException("Unterminated packed int"); } // Write a packed i64 @@ -148,14 +163,16 @@ public class BAOS { } public void packedS(String s) { - packed4(s.length()); - for( int i=0; i` and `../release/` directories. These cover the examples and test build layouts regardless of the current directory. It also checks the current directory, `build/release/`, and -`chapter31/build/release/` relative to the current directory. Thus built +`chapter32/build/release/` relative to the current directory. Thus built examples such as `Clock.exe` can be launched directly without configuration. `SIMPLE_MINIFB` overrides discovery; an invalid explicit path reports an error diff --git a/src/main/smp/sys/time/README.md b/src/main/smp/sys/time/README.md index baa920cb..602015e9 100644 --- a/src/main/smp/sys/time/README.md +++ b/src/main/smp/sys/time/README.md @@ -1,6 +1,6 @@ # Time and single-threaded animation -[Chapter 31](../../../../../README.md#time-library) introduces the library. +[Chapter 31](../../../../../../chapter31/README.md#time-library) introduces the library. The implementation is in [time.smp](../time.smp), [DateTime.smp](DateTime.smp), and [Timers.smp](Timers.smp). @@ -122,8 +122,8 @@ The [digital and analog clock example](../../../../../docs/examples/Clock.smp) c the repository root, with graphics dependencies already cached: ```sh -make -C chapter31 clock-example # Build without opening a window. -make -C chapter31 run-clock # Build the backend and run. +make -C chapter32 clock-example # Build without opening a window. +make -C chapter32 run-clock # Build the backend and run. ``` Click the button or press Space to switch between green seven-segment digits diff --git a/src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java b/src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java index 0e4c230a..5399aecf 100644 --- a/src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java +++ b/src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java @@ -13,25 +13,39 @@ public class AssemblyDumpTest { @Test public void libraryUnitsAndGlyphs() throws Exception { Path root=Path.of("build/objs/assembly-dump"); Files.createDirectories(root); - Path build=Files.createTempDirectory(root,"sys-"); - CodeGen code=new CodeGen("src/main/smp",build.toString(),null,"sys",null,123,true,TypeInteger.BOT) + Path fixture=Files.createTempDirectory(root,"font-"); + Path source=Files.createDirectories(fixture.resolve("src")); + Path build=Files.createDirectories(fixture.resolve("obj")); + Files.createDirectories(source.resolve("Atlas")); + // Use the real font, but only two tiny modules: drawing integration is + // covered by DrawTest. This test needs multiple units and constant data. + String canvasSource=Files.readString(Path.of("src/main/smp/sys/draw/Canvas.smp")); + int fontStart=canvasSource.indexOf("val _glyphs ="); + assertTrue("Font declaration",fontStart>=0); + int fontEnd=canvasSource.indexOf("};",fontStart); + assertTrue("Font initializer",fontEnd>=0); + Files.writeString(source.resolve("Atlas/Font.smp"),canvasSource.substring(fontStart,fontEnd+2)+ + "\nval glyph={int i -> _glyphs[i];};\n"); + Files.writeString(source.resolve("Atlas.smp"),"val glyph={int i -> Font.glyph(i);};\n"); + CodeGen code=new CodeGen(source.toString(),build.toString(),null,"Atlas",null,123,true,TypeInteger.BOT) .driver(CodeGen.Phase.Serialize,TestC.CPU_PORT,TestC.CALL_CONVENTION) .driver(CodeGen.Phase.Encoding,TestC.CPU_PORT,TestC.CALL_CONVENTION); var entry=code._encoding; String before=code.asm(); assertSame("Dumping another unit must not change the active encoding",entry,code._encoding); + assertEquals(2,code._compunits.size()); for( var unit : code._compunits.values() ) if( unit._src!=null ) { String heading="=== Compilation unit: "+unit._cname+" ==="; assertEquals("Exactly one heading for "+unit._cname,2,before.split(heading,-1).length); } - int start=before.indexOf("=== Compilation unit: sys.draw.Canvas ==="); + int start=before.indexOf("=== Compilation unit: Atlas.Font ==="); assertTrue(start>=0); int end=before.indexOf("=== Compilation unit:",start+1); String canvas=before.substring(start,end<0 ? before.length() : end); assertTrue(canvas.contains("Constant Pool")); - assertTrue(canvas.contains("sys.draw.Canvas._glyphs: []u16")); - TypeMemPtr ptr=(TypeMemPtr)code._compunits.get("sys/draw/Canvas")._clz.field("_glyphs")._t; + assertTrue(canvas.contains("Atlas.Font._glyphs: []u16")); + TypeMemPtr ptr=(TypeMemPtr)code._compunits.get("Atlas/Font")._clz.field("_glyphs")._t; TypeConAry glyphs=(TypeConAry)ptr._obj.field("[]")._t; assertEquals(96,glyphs.len()); BAOS bytes=new BAOS(); @@ -40,10 +54,10 @@ public class AssemblyDumpTest { canvas.contains("60000000"+HexFormat.of().formatHex(bytes.toByteArray()))); code.exportELF(false,false); com.seaofnodes.simple.codegen.PrintRegTestSupport.checkDataAliases( - build.resolve("sys/draw/Canvas.o"),196,"sys.draw.Canvas._glyphs"); + build.resolve("Atlas/Font.o"),196,"Atlas.Font._glyphs"); assertSame(entry,code._encoding); assertEquals("Export must not truncate the dump to its entry unit",before,code.asm()); - Files.writeString(build.resolve("sys.asm"),before); + Files.writeString(build.resolve("Atlas.asm"),before); } @Test public void combinedEncodingAndEarlierPhase() { diff --git a/src/test/java/com/seaofnodes/simple/BAOSTest.java b/src/test/java/com/seaofnodes/simple/BAOSTest.java new file mode 100644 index 00000000..03e53b6d --- /dev/null +++ b/src/test/java/com/seaofnodes/simple/BAOSTest.java @@ -0,0 +1,58 @@ +package com.seaofnodes.simple; + +import com.seaofnodes.simple.codegen.CodeGen; +import com.seaofnodes.simple.type.PackedTypeTestSupport; +import com.seaofnodes.simple.util.BAOS; +import java.util.Random; +import org.junit.Test; +import static org.junit.Assert.*; + +public class BAOSTest { + @Test public void packedIntBoundaries() { + int[] values={Integer.MIN_VALUE,-134217729,-134217728,-1048577,-1048576, + -8193,-8192,-65,-64,-1,0,1,63,64,8191,8192,1048575,1048576, + 134217727,134217728,Integer.MAX_VALUE}; + int[] widths={5,5,4,4,3,3,2,2,1,1,1,1,1,2,2,3,3,4,4,5,5}; + BAOS out=new BAOS(); + for( int i=0; i x+1; }; return f(arg);").parse(); + FunNode fun = null; + for( FunNode f : code._linker ) + if( f!=null && "f".equals(f._name) ) fun=f; + assertNotNull(fun); + CallNode call = null; + for( Node in : fun._inputs ) + if( in instanceof CallNode c ) call=c; + assertNotNull(call); + Node[] uses = fun._outputs.asAry(); + code._iter._work.clear(); + call.unlink(fun,fun._inputs.find(call)); + int parms = 0; + for( Node use : uses ) + if( use instanceof ParmNode && !use.isDead() ) { + assertTrue(code._iter._work.on(use)); + parms++; + } + assertTrue(parms>0); + } + // An unknown value can become a private object or callback. Both escape // sinks must reserve those possibilities before the value is known. @Test public void testUnknownEscapesRefineToPrivateValues() { diff --git a/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/src/test/java/com/seaofnodes/simple/Chapter05Test.java index ed4a54bd..9f733da5 100644 --- a/src/test/java/com/seaofnodes/simple/Chapter05Test.java +++ b/src/test/java/com/seaofnodes/simple/Chapter05Test.java @@ -202,19 +202,17 @@ return a; catch( RuntimeException e ) { assertEquals("Undefined name 'ififif'",e.getMessage()); } } - private static N init(N n) { n._type=n.compute(); return n; } - @Test public void testDoublingBeforeAndAfterStrengthReduction() { - for( boolean reduced : new boolean[]{false,true} ) + for( boolean shift : new boolean[]{false,true} ) for( boolean reverse : new boolean[]{false,true} ) { CodeGen code = new CodeGen(""); - Node ctrl = init(new CProjNode(code._start,0,"Ctrl")); - RegionNode region = init(new RegionNode(null,null,ctrl,ctrl)); - Node p = code.con(TypeInteger.BOT); - Node i = init(new MinusNode(p)); - Node twice = reduced ? init(new ShlNode(null,p,code.con(1))) : init(new AddNode(p,p,(byte)1)); - Node sum = init(new AddNode(i,p,(byte)1)); - PhiNode phi = init(new PhiNode("sum",region,reverse ? sum : twice,reverse ? twice : sum)); + Node ctrl = new CProjNode(code._start,0,"Ctrl").init(); + RegionNode region = new RegionNode(null,null,ctrl,ctrl).init(); + Node p = code.con(TypeInteger.BOT), i = code.con(TypeInteger.I32); + Node twice = shift ? new ShlNode(null,p,code.con(1)).init() + : new AddNode(p,p,(byte)1).init(); + Node sum = new AddNode(i,p,(byte)1).init(); + PhiNode phi = new PhiNode("sum",region,reverse ? sum : twice,reverse ? twice : sum).init(); phi.keep(); Node factored = phi.idealize(); assertTrue(factored instanceof AddNode); @@ -225,4 +223,17 @@ return a; phi.unkeep(); } } + + @Test public void testOtherShiftIsNotDoubling() { + CodeGen code = new CodeGen(""); + Node ctrl = new CProjNode(code._start,0,"Ctrl").init(); + RegionNode region = new RegionNode(null,null,ctrl,ctrl).init(); + Node p = code.con(TypeInteger.BOT), i = code.con(TypeInteger.I32); + Node shift = new ShlNode(null,p,code.con(2)).init(); + Node sum = new AddNode(i,p,(byte)1).init(); + PhiNode phi = new PhiNode("sum",region,shift,sum).init(); + phi.keep(); + assertNull(phi.idealize()); + phi.unkeep(); + } } diff --git a/src/test/java/com/seaofnodes/simple/Chapter10Test.java b/src/test/java/com/seaofnodes/simple/Chapter10Test.java index 559def2f..13950789 100644 --- a/src/test/java/com/seaofnodes/simple/Chapter10Test.java +++ b/src/test/java/com/seaofnodes/simple/Chapter10Test.java @@ -197,7 +197,9 @@ while (arg) { return bar.a; """); code.driver(CodeGen.Phase.FinalizeIR); - assertEquals("Stop[ return ((Phi(Loop,0,(Sar+2))<<32)>>32); return Test.Bar; ]", code.print()); + assertEquals("Stop[ return Phi(Loop,0,(((Phi_a+2)<<32)>>32)); return Test.Bar; ]", code.print()); + assertEquals("0",Eval2.eval(code,0)); + assertEquals("6",Eval2.eval(code,-3)); } @Test @@ -319,7 +321,9 @@ while( i.x < i.len ) { return sum; """); code.driver(CodeGen.Phase.FinalizeIR); - assertEquals("Stop[ return Phi(Loop,0,(((Phi_sum+((Phi(Loop,0,(((Sar+1)<<32)>>32))<<32)>>32))<<32)>>32)); return Test.Iter; ]", code.print()); + assertEquals("Stop[ return Phi(Loop,0,(((Phi_sum+((Phi(Loop,0,(Sar+1))<<32)>>32))<<32)>>32)); return Test.Iter; ]", code.print()); + assertEquals("0",Eval2.eval(code,0)); + assertEquals("45",Eval2.eval(code,10)); } diff --git a/src/test/java/com/seaofnodes/simple/Chapter13Test.java b/src/test/java/com/seaofnodes/simple/Chapter13Test.java index 70cfe25e..738a4d15 100644 --- a/src/test/java/com/seaofnodes/simple/Chapter13Test.java +++ b/src/test/java/com/seaofnodes/simple/Chapter13Test.java @@ -116,7 +116,9 @@ if (v1) { return v0.f; """); code.driver(CodeGen.Phase.FinalizeIR); - assertEquals("return ((Phi(Region,((.f<<32)>>32),2)<<32)>>32);", code.print()); + assertEquals("return Phi(Region,((.f<<32)>>32),2);", code.print()); + assertEquals("2",Eval2.eval(code,0)); + assertEquals("0",Eval2.eval(code,1)); } diff --git a/src/test/java/com/seaofnodes/simple/Chapter21Test.java b/src/test/java/com/seaofnodes/simple/Chapter21Test.java index bd2a453a..7a59adb0 100644 --- a/src/test/java/com/seaofnodes/simple/Chapter21Test.java +++ b/src/test/java/com/seaofnodes/simple/Chapter21Test.java @@ -533,8 +533,8 @@ val sieve = { int N -> String sprimes = sb.p("]").toString(); // Compile, link against native C; expect the above string of primes to be printed out by C - // Load/Phi hoisting now requires the pointer before the loop entry. - TestC.runC(src, "sieve", sprimes,216); + // Phi factoring also recognizes p<<1 after p+p strength reduction. + TestC.runC(src, "sieve", sprimes,215); // Evaluate on RISC5 emulator; expect return of an array of primes in // the simulated heap. diff --git a/src/test/java/com/seaofnodes/simple/Chapter23Test.java b/src/test/java/com/seaofnodes/simple/Chapter23Test.java index f1ad4898..8667c0bd 100644 --- a/src/test/java/com/seaofnodes/simple/Chapter23Test.java +++ b/src/test/java/com/seaofnodes/simple/Chapter23Test.java @@ -279,7 +279,7 @@ 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",31,null); + testCPU(src,"x86_64_v2", "win64",23,null); }; @Test diff --git a/src/test/java/com/seaofnodes/simple/EscapeFlowTest.java b/src/test/java/com/seaofnodes/simple/EscapeFlowTest.java index 12634f24..ee7406c6 100644 --- a/src/test/java/com/seaofnodes/simple/EscapeFlowTest.java +++ b/src/test/java/com/seaofnodes/simple/EscapeFlowTest.java @@ -113,6 +113,37 @@ public class EscapeFlowTest { assertTrue(XInt.bit(((TypeFunPtr)after.ret()).fidxs(),7)); } + // Ordinary arguments do not read Start, but a later opaque argument must + // subscribe both the summary and consumers of its exposed escapes. + @Test public void testSummaryOutsideDependency() { + CodeGen code = new CodeGen("return 0;").parse(); + code._phase = CodeGen.Phase.Opto; + TypeTuple state = TypeTuple.make(Type.CONTROL,TypeMem.START,TypeInteger.BOT); + code._start._type = TypeTuple.make(Type.CONTROL,TypeMem.BOT,TypeInteger.BOT); + Node ctrl = ConstantNode.raw(Type.CONTROL), mem = ConstantNode.raw(TypeMem.START); + Node arg = ConstantNode.raw(Type.BOTTOM); + SummaryNode summary = new SummaryNode(state,new int[0],ctrl,mem,arg).init(); + SummaryNode observer = new SummaryNode(state,new int[0],ctrl,mem).init(); + summary.exposed(observer); + code._iter._work.clear(); + code._start.setType(TypeTuple.make(Type.CONTROL,TypeMem.START.makeFrom(XInt.make(XInt.make(7),8),XInt.EMPTY),TypeInteger.BOT)); + assertFalse(code._iter._work.on(summary)); + assertFalse(code._iter._work.on(observer)); + + arg.setType(TypeMemPtr.makeNullable(TypeStruct.forward("OpaqueSummary"))); + assertTrue(code._iter._work.on(summary)); + assertTrue(code._iter._work.on(observer)); + assertTrue(XInt.bit(((TypeTuple)summary.compute()).mem()._escFs,7)); + assertTrue(XInt.bit(summary.exposed(observer)._escFs,7)); + code._iter._work.clear(); + code._start.setType(TypeTuple.make(Type.CONTROL,TypeMem.START.makeFrom(XInt.make(8),XInt.EMPTY),TypeInteger.BOT)); + assertTrue(code._iter._work.on(summary)); + assertTrue(code._iter._work.on(observer)); + assertTrue(XInt.bit(((TypeTuple)summary.compute()).mem()._escFs,8)); + assertTrue(XInt.bit(summary.exposed(observer)._escFs,8)); + assertFalse(XInt.bit(summary.exposed(observer)._escFs,7)); + } + // Public construction exposes the allocator; private-memory helpers // remain internal and can inline into it. @Test public void testPublicAllocator() { diff --git a/src/test/java/com/seaofnodes/simple/MemMergeTest.java b/src/test/java/com/seaofnodes/simple/MemMergeTest.java new file mode 100644 index 00000000..253bce0b --- /dev/null +++ b/src/test/java/com/seaofnodes/simple/MemMergeTest.java @@ -0,0 +1,83 @@ +package com.seaofnodes.simple; + +import com.seaofnodes.simple.codegen.CodeGen; +import com.seaofnodes.simple.node.*; +import com.seaofnodes.simple.type.TypeMem; +import org.junit.Test; +import static org.junit.Assert.*; + +public class MemMergeTest { + @Test public void testDenseAliasesAndDefaults() { + CodeGen code = new CodeGen(""); + Node defaults = code.con(TypeMem.START), value = code.con(TypeMem.BOT).keep(); + MemMergeNode mem = new MemMergeNode(null,defaults); + mem.alias(10000,value); + mem.alias(2,value); + mem.alias(513,value); + assertEquals(5,mem.nIns()); + assertEquals(2,mem.aliasAt(2)); + assertEquals(513,mem.aliasAt(3)); + assertEquals(10000,mem.aliasAt(4)); + assertSame(value,mem.alias(10000)); + assertSame(defaults,mem.alias(512)); + assertNull(mem.explicitAlias(9999)); + assertSame(value,mem.explicitAlias(10000)); + mem.alias(513,null); + assertEquals(4,mem.nIns()); + assertEquals(10000,mem.aliasAt(3)); + assertSame(value,mem.alias(10000)); + mem.alias(2,defaults); + assertSame(mem,mem.idealize()); + assertEquals(3,mem.nIns()); + assertSame(defaults,mem.alias(2)); + // Removing/reinserting colliding keys must not leave tombstones or stale slots. + for( int i=0; i<100; i++ ) { + mem.alias(100+i*8,value); + mem.alias(100+i*8,null); + } + assertEquals(3,mem.nIns()); + mem.alias(10000,defaults); + assertSame(mem,mem.idealize()); + assertEquals(2,mem.nIns()); + // Retain the sparse implementation's fold eligibility for this experiment. + assertNull(mem.idealize()); + assertSame(defaults,new MemMergeNode(null,defaults).idealize()); + value.unkeep(); + } + + @Test public void testIndependentCopyMaps() { + CodeGen code = new CodeGen(""); + Node defaults = code.con(TypeMem.START), value = code.con(TypeMem.BOT); + MemMergeNode mem = new MemMergeNode(null,defaults); + mem.alias(200,value); + MemMergeNode copy = (MemMergeNode)mem.copyEmpty(); + for( Node in : mem._inputs ) copy.addDef(in); + copy.alias(7,value); + assertEquals(3,mem.nIns()); + assertEquals(4,copy.nIns()); + assertSame(defaults,mem.alias(7)); + assertSame(value,mem.alias(200)); + copy.alias(200,null); + assertSame(value,mem.alias(200)); + assertSame(defaults,copy.alias(200)); + code._phase = CodeGen.Phase.Select; + MemMergeNode selected = new MemMergeNode(mem); + assertEquals(200,selected.aliasAt(2)); + assertSame(value,selected.alias(200)); + } + + @Test public void testStackedMergesKeepOverrides() { + CodeGen code = new CodeGen(""); + Node defaults = code.con(TypeMem.START), value = code.con(TypeMem.BOT), override = code.con(TypeMem.TOP); + MemMergeNode inner = new MemMergeNode(null,defaults); + inner.alias(8,value); + inner.alias(10000,value); + MemMergeNode outer = new MemMergeNode(null,inner); + outer.alias(10000,override); + assertSame(outer,outer.idealize()); + assertEquals(4,outer.nIns()); + assertSame(defaults,outer.in(1)); + assertSame(value,outer.alias(8)); + assertSame(override,outer.alias(10000)); + } +} diff --git a/src/test/java/com/seaofnodes/simple/ModTest.java b/src/test/java/com/seaofnodes/simple/ModTest.java index 7f79599d..c06e99f1 100644 --- a/src/test/java/com/seaofnodes/simple/ModTest.java +++ b/src/test/java/com/seaofnodes/simple/ModTest.java @@ -166,20 +166,31 @@ public class ModTest { return integerEdges(new long[]{Long.MIN_VALUE,Long.MIN_VALUE+1,-17,-5,-1,0,1,5,17,Long.MAX_VALUE}); } private static String integerEdges(long[] values) { + // Keep the full value matrix in data, rather than compiling a long + // chain of constant calls and conditional returns for every pair. StringBuilder source=new StringBuilder(""" val rem_noInline={ i64 x,i64 y -> x%y; }; val div_noInline={ i64 x,i64 y -> x/y; }; val main={ -> + val values=new i64[~]{ """); - int failure=1; - for( long x : values ) - for( long y : values ) { - source.append("if(rem_noInline(").append(literal(x)).append(',').append(literal(y)) - .append(")!=").append(literal(y==0 ? 0 : x%y)).append(") return ").append(failure++).append(';'); - source.append("if(div_noInline(").append(literal(x)).append(',').append(literal(y)) - .append(")!=").append(literal(y==0 ? 0 : x/y)).append(") return ").append(failure++).append(';'); + for(int i=0;i n instanceof ReturnNode ? n : null); + LoadNode load = (LoadNode)ret.expr(); + // The load may move below its check, but cannot serve a use above its memory. + ret.setDef(0,load.in(0)); + try { + IterPeeps.schedulableUses(code); + fail("A load cannot execute before its memory is available"); + } catch( AssertionError error ) { + assertTrue(error.getMessage(),error.getMessage().contains("Unschedulable data node LoadNode")); + } + } + + private static CodeGen loadAfterMemoryMerge() { + CodeGen code = new CodeGen("return arg;").parse(); + ReturnNode ret = (ReturnNode)code._stop.walk(n -> n instanceof ReturnNode ? n : null); + Node ctrl = ret.ctrl(); + IfNode iff = new IfNode(ctrl,ret.expr()).init(); + Node yes = new CProjNode(iff,0,"True").init(); + Node no = new CProjNode(iff,1,"False").init(); + RegionNode region = new RegionNode(null,null,yes,no).init(); + Node phi = new BulkMemPhiNode("mem",region,ret.mem(),ret.mem()).init(); + Node mem = new MemMergeNode(null,phi).init(); + Node load = new LoadNode(null,"[]",2,ctrl,mem,code.con(TypeMemPtr.BOT),code.con(TypeInteger.ZERO)).init(); + ret.setDef(0,region); + ret.setDef(2,load); + return code; + } @Test public void nativeFoldedLoadsWithLaterOperands() throws Exception { TestC.runSYS(""" val compare_noInline={ i64[] a, int flag -> diff --git a/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java b/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java index 1c278791..cc4e552f 100644 --- a/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java +++ b/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java @@ -10,6 +10,42 @@ import org.junit.Test; import static org.junit.Assert.*; public class SeparateCompilationTest { + @Test public void testSparseWideMemoryImport() throws Exception { + Path build=Path.of("build/objs/separate"); + Files.createDirectories(build); + Path lib=Files.createTempDirectory(build,"wide-memory-"); + StringBuilder source=new StringBuilder("int f0=7;\n"); + for( int i=1; i<300; i++ ) source.append("int f").append(i).append("=0;\n"); + source.append("val touch={int n -> f299=n; return f0+f299;};"); + new CodeGen(null,lib.toString(),null,"Wide",source.toString(),123,true,TypeInteger.BOT) + .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); + var paths=new Ary<>(new String[]{lib.toString()}); + CodeGen code=new CodeGen(null,null,paths,"WideEval","return Wide.touch((arg<<32)>>32);",123,true,TypeInteger.BOT) + .driver(CodeGen.Phase.TypeCheck); + assertEquals("12",Eval2.eval(code,5)); + TestC.run("return Wide.touch(5)==12 ? 0 : 1;","wide_memory_client",paths, + TestC.CALL_CONVENTION,null,null,"",-1); + } + + @Test public void testOldObjectFormatRequestsRebuild() throws Exception { + Path build=Path.of("build/objs/separate"); + Files.createDirectories(build); + Path lib=Files.createTempDirectory(build,"old-format-"); + new CodeGen(null,lib.toString(),null,"Old","val value=7;",123,true,TypeInteger.BOT) + .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); + Path file=lib.resolve("Old.o"); + ElfReader elf=ElfReader.load(file.toFile(),null); + byte[] bytes=Files.readAllBytes(file); + bytes[elf._bais.size()+3]='E'; // Previous C0DE header, before format 2. + Files.write(file,bytes); + try { + ElfReader.load(file.toFile(),null).loadPublicTypes(new CodeGen("")); + fail("old format accepted"); + } catch( IllegalArgumentException expected ) { + assertTrue(expected.getMessage().contains("rebuild the object file")); + } + } + @Test public void testImportedReadOnlyPrimitiveArray() throws Exception { Path build=Path.of("build/objs/separate"); Files.createDirectories(build); diff --git a/src/test/java/com/seaofnodes/simple/StringFormatTest.java b/src/test/java/com/seaofnodes/simple/StringFormatTest.java index 59b62709..d6783380 100644 --- a/src/test/java/com/seaofnodes/simple/StringFormatTest.java +++ b/src/test/java/com/seaofnodes/simple/StringFormatTest.java @@ -11,28 +11,88 @@ import org.junit.Test; import static org.junit.Assert.*; public class StringFormatTest extends TestC { - private static void prints(String body, String expected) throws Exception { - runSYS("val main={ -> "+body+" return 0; };", "stringFormat",expected,-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. + private enum Format { + DefaultsAndNestedStrings("sys.io.p(\"CPU plays %(2+3). %(\"nested %(7)\") %(true) %(1.5)\\n\");", + "CPU plays 5. nested 7 1 1.5\n"), + Formats("sys.io.p(\"%+06d(17)|%#08x(42)|%-5.3s(\"abcdef\")|%.2f(1.25)|%c(65)|%b(false)\\n\");", + "+00017|0x00002a|abc |1.25|A|false\n"), + RemainderInInterpolation("int mod=17; sys.io.p(\"%(mod%5)|%02d(mod%5)|%%|\\%|%(mod %= 5)|%(mod)\");", + "2|02|%|%|2|2"), + IntegerLimits("i64 lo=-9223372036854775807-1; sys.io.p(\"%(lo)|%(9223372036854775807)|%u(-1)|%X(-1)\");", + "-9223372036854775808|9223372036854775807|18446744073709551615|FFFFFFFFFFFFFFFF"), + IntegerPaddingRules("sys.io.p(\"%#.0o(0)|%#.3o(1)|%#x(0)|%-08d(17)|%08.4d(-17)|%+d(0)|% d(0)\");", + "0|001|0|17 | -0017|+0| 0"), + BuilderNumberUsesFormatter("val b=new sys.aryu8(); b.num(-9223372036854775807-1).add('|').num(9223372036854775807); sys.io.p(sys.text.end(b));", + "-9223372036854775808|9223372036854775807"), + EvaluationOrder("int x=0; val s=\"%(x++)%(x++)%(x++)\"; sys.io.p(\"%(s):%(s#):%(x)|%%|\\%\");", + "012:3:3|%|%"), + EvaluationMutatesBytes("val a=new u8[1]; a[0]='A'; sys.io.p(\"%(a)%(a[0]='B')%(a)\");", "A66B"), + Converters("sys.io.p(sys.text.int(17)); sys.io.p(sys.text.char(65)); sys.io.p(sys.text.bool(true)); sys.io.p(sys.text.flt(1.5));", + "17Atrue1.5"), + FieldNamedInt("struct S { int int=7; }; sys.io.p(\"%((new S).int)\");", "7"), + FloatAndAlternateFormats("f32 x=1.25f; sys.io.p(\"%(x)|%f(x)|%.2e(x)|%.2G(x)|%#o(9)|% d(7)|%.0d(0)|%a(1.5)\");", + "1.25|1.250000|1.25e+00|1.2|011| 7||0x1.8p+0"), + BufferGrowth("sys.io.p(\"%0100d(17)|%.100f(1.0)\");", "0".repeat(98)+"17|1."+"0".repeat(100)), + BytesAndEmptyStrings("val empty=\"%(\"\")\"; val bytes=\"a\\0b\"; sys.io.p(\"%(empty#):%s(bytes):%.2s(bytes):%c(0)\");", + "0:a\0b:a\0:\0"), + Utf8String("val s=\"π\"; sys.io.p(\"%(s):%(s#):%(s[0]):π\");", "π:2:207:π"), + DeferredParsing(""" + struct S { u8[~] s; new S={ -> s="%("}) %(3)")"; }; }; + val s=new S; + sys.io.p(s.s); + for(int i=0; i<2; sys.io.p("%(i++) %("(")")) { } + """, "}) 30 (1 ("); + + final String body, expected; + Format(String body, String expected) { this.body=body; this.expected=expected; } + } + private static final String END="\n--end-format-case--\n"; + private static final int BATCH_SIZE=5; + private static final String[] OUTPUTS=new String[Format.values().length]; + + @org.junit.BeforeClass public static void resetNativeBatches() { + java.util.Arrays.fill(OUTPUTS,null); + } + + private static void prints(Format test) throws Exception { + int index=test.ordinal(); + if( OUTPUTS[index]==null ) { + Format[] cases=Format.values(); + int first=index/BATCH_SIZE*BATCH_SIZE, limit=Math.min(first+BATCH_SIZE,cases.length); + StringBuilder source=new StringBuilder("val main={ -> "); + for( int i=first; i(new String[]{RELEASE_SYS_DIR}),CALL_CONVENTION,null,null,-1); + String[] outputs=exec(TEST_TIMEOUT_SECONDS,exe).split(java.util.regex.Pattern.quote(END),-1); + assertEquals("Each format case must complete",limit-first+1,outputs.length); + assertEquals("No output after final case", "",outputs[outputs.length-1]); + for( int i=first; i \"%(x)|%f(x)\"; }; val main={ -> sys.io.p(format_noInline(1.25f)); return 0; };", "stringFormatFloat","1.25|1.250000",-1); } @Test public void testBufferGrowth() throws Exception { - prints("sys.io.p(\"%0100d(17)|%.100f(1.0)\");", "0".repeat(98)+"17|1."+"0".repeat(100)); + prints(Format.BufferGrowth); } @Test public void testLiteralRemainsConstant() { @@ -107,18 +162,12 @@ public class StringFormatTest extends TestC { } @Test public void testBytesAndEmptyStrings() throws Exception { - prints("val empty=\"%(\"\")\"; val bytes=\"a\\0b\"; sys.io.p(\"%(empty#):%s(bytes):%.2s(bytes):%c(0)\");", - "0:a\0b:a\0:\0"); - prints("val s=\"π\"; sys.io.p(\"%(s):%(s#):%(s[0]):π\");", "π:2:207:π"); + prints(Format.BytesAndEmptyStrings); + prints(Format.Utf8String); } @Test public void testDeferredParsing() throws Exception { - prints(""" - struct S { u8[~] s; new S={ -> s="%("}) %(3)")"; }; }; - val s=new S; - sys.io.p(s.s); - for(int i=0; i<2; sys.io.p("%(i++) %("(")")) { } - """, "}) 30 (1 ("); + prints(Format.DeferredParsing); } @Test public void testImportedFormatter() throws Exception { diff --git a/src/test/java/com/seaofnodes/simple/TestWorkspace.java b/src/test/java/com/seaofnodes/simple/TestWorkspace.java new file mode 100644 index 00000000..d875c47a --- /dev/null +++ b/src/test/java/com/seaofnodes/simple/TestWorkspace.java @@ -0,0 +1,54 @@ +package com.seaofnodes.simple; + +import java.io.IOException; +import java.nio.file.*; +import java.nio.file.attribute.BasicFileAttributes; + +/** Prepare a Make test group's working directory without sharing native outputs. */ +public class TestWorkspace { + public static void main(String[] args) throws IOException { + if( args.length!=2 || !args[0].matches("tests_group[0-7]|sanity_group[0-2]") || !args[1].matches("[A-Za-z0-9_]+") ) + throw new IllegalArgumentException("Expected test group and CPU_ABI"); + Path root = Path.of("").toAbsolutePath().normalize(); + Path work = root.resolve("build/tests").resolve(args[0]).normalize(); + if( !work.startsWith(root.resolve("build/tests")) ) + throw new IllegalArgumentException("Test workspace outside build/tests"); + // Classes and JARs use the parent's absolute classpath. Copy source + // fixtures and native libraries; tests may write their own build tree. + for( String tree : new String[]{"src","docs","build/release/"+args[1],"build/objs/lib_"+args[1]} ) + sync(root.resolve(tree),work.resolve(tree)); + Files.createDirectories(work.resolve("build/objs")); + } + + private static void sync(Path source, Path target) throws IOException { + if( !Files.isDirectory(source) ) throw new IOException("Missing test input: "+source); + // Remove deleted/renamed inputs as well as refreshing changed files; + // stale modules could otherwise make a test pass incorrectly. Only + // copied input trees are cleaned, preserving generated test artifacts. + if( Files.exists(target) ) Files.walkFileTree(target,new SimpleFileVisitor<>() { + @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Path original = source.resolve(target.relativize(file)); + if( attrs.isSymbolicLink() || !Files.isRegularFile(original) ) Files.delete(file); + return FileVisitResult.CONTINUE; + } + @Override public FileVisitResult postVisitDirectory(Path dir, IOException error) throws IOException { + if( error!=null ) throw error; + if( !Files.isDirectory(source.resolve(target.relativize(dir))) ) Files.delete(dir); + return FileVisitResult.CONTINUE; + } + }); + Files.walkFileTree(source,new SimpleFileVisitor<>() { + @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { + Files.createDirectories(target.resolve(source.relativize(dir))); + return FileVisitResult.CONTINUE; + } + @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Path copy = target.resolve(source.relativize(file)); + if( !Files.exists(copy) || Files.size(copy)!=attrs.size() || + !Files.getLastModifiedTime(copy).equals(attrs.lastModifiedTime()) ) + Files.copy(file,copy,StandardCopyOption.REPLACE_EXISTING,StandardCopyOption.COPY_ATTRIBUTES); + return FileVisitResult.CONTINUE; + } + }); + } +} diff --git a/src/test/java/com/seaofnodes/simple/TypeTest.java b/src/test/java/com/seaofnodes/simple/TypeTest.java index 52e857e9..adcc1b3a 100644 --- a/src/test/java/com/seaofnodes/simple/TypeTest.java +++ b/src/test/java/com/seaofnodes/simple/TypeTest.java @@ -7,6 +7,58 @@ import static org.junit.Assert.assertSame; public class TypeTest { + @Test public void testFinalPointerCycles() { + TypeStruct cycle = TypeStruct.open("FinalPointerCycle"); + Assert.assertFalse(cycle.isFinal()); + TypeMemPtr self = TypeMemPtr.make(cycle).withAccess(true); + cycle = cycle.add(Field.make("self",self,2,true)) + .add(Field.make("value",TypeInteger.BOT,3,true)).close(); + self = (TypeMemPtr)cycle.field("self")._t; + assertSame(cycle,self._obj); + Assert.assertTrue(self.isFinal()); + Assert.assertTrue(cycle.isFinal()); + assertSame(cycle,cycle.makeRO()); + + // Slot finality and pointer access are independent: a final slot can + // still hold a writable pointer, and a readonly pointer can refer to + // an object whose declared fields are mutable. + Assert.assertFalse(TypeMemPtr.make(cycle).isFinal()); + Assert.assertFalse(Field.make("slot",self,4,false).isFinal()); + TypeStruct mutable = cycle.addOrUpdate(Field.make("value",TypeInteger.BOT,3,false)); + Assert.assertFalse(mutable.isFinal()); + Assert.assertTrue(TypeMemPtr.make(mutable).withAccess(true).isFinal()); + Assert.assertTrue(cycle.isFinal()); + } + + @Test public void testConstantPointerCycles() { + TypeStruct cycle = TypeStruct.open("ConstantPointerCycle"); + TypeMemPtr self = TypeMemPtr.make((byte)2,cycle,true); + cycle = cycle.add(Field.make("self",self,2,true)) + .add(Field.make("value",TypeInteger.constant(7),3,true)).close(); + self = (TypeMemPtr)cycle.field("self")._t; + assertSame(cycle,self._obj); + Assert.assertTrue(self.isConstant()); + Assert.assertTrue(cycle.isConstant()); + // A constant shape does not make an arbitrary pointer a singleton. + Assert.assertFalse(TypeMemPtr.make(cycle).isConstant()); + + TypeStruct varying = TypeStruct.make("VaryingConstantReferent",false, + Field.make("value",TypeInteger.BOT,4,false)); + Assert.assertFalse(varying.isConstant()); + // Conversely, a singleton pointer can refer to mutable contents. + Assert.assertTrue(TypeMemPtr.make((byte)2,varying,true).isConstant()); + + TypeMem memory = TypeMem.make(2,cycle,true,true,true,XInt.EMPTY,XInt.EMPTY); + Assert.assertTrue(memory.isConstant()); + Assert.assertFalse(TypeMem.make(2,cycle,true,false,true,XInt.EMPTY,XInt.EMPTY).isConstant()); + // Repeated aggregate types are sharing, not recursion. Neither query + // should require or leave behind a cyclic-traversal visit marker. + TypeTuple tuple = TypeTuple.make(cycle,memory,cycle); + Assert.assertTrue(tuple.isConstant()); + Assert.assertTrue(tuple.isConstant()); + Assert.assertFalse(TypeTuple.make(cycle,TypeInteger.BOT).isConstant()); + } + @Test public void testConstantArrayElements() { TypeConAry range=TypeConAry.make(TypeInteger.U16,new long[]{5,6,7}); Assert.assertEquals("[5-7]",range.toString()); @@ -223,64 +275,78 @@ public class TypeTest { @Test public void testLatticeTheory() { Type[] ts = Type.gather(); + // Make partitions the outer loop between independent JVMs. A direct + // JUnit/IDE invocation retains the full coverage. + int parts = Integer.parseInt(System.getProperty("simple.lattice.parts","1")); + int part = Integer.parseInt(System.getProperty("simple.lattice.part" ,"0")); + Assert.assertTrue("Invalid lattice partition",parts > 0 && parts <= ts.length && part >= 0 && part < parts); + + // Every triple reuses these pairs. Compute both operand orders rather + // than assuming commutativity in the table we are about to check. + Type[][] meets = new Type[ts.length][ts.length]; + Type[][] joins = new Type[ts.length][ts.length]; + for( int i=0; i()); + assertEquals(id<=254 ? 2 : 4,out.size()); + BAOS in=new BAOS(out.toByteArray()); + TypeFunPtr copy=(TypeFunPtr)Type.packed(in,new String[]{""}); + assertEquals(id,copy.fidx()); + assertEquals(0,copy.nargs()); + assertEquals(out.size(),in.size()); + } +} -- cgit v1.2.3