From 3d0f3f38d9d8345b6508b3289dc94b0500c53d9e Mon Sep 17 00:00:00 2001 From: Cliff Click Date: Sat, 14 Nov 2026 12:41:16 -0800 Subject: Breakout, Clock demos Math lib with simple constants raw bit converters TypeConAry unified Big Formatting change Debug symbols for constant data IterPeeps was endlessly running asserts with much inlining RegAlloc rounds raised --- .../java/com/seaofnodes/simple/ArithNodeTest.java | 2 +- .../java/com/seaofnodes/simple/ArrayInitTest.java | 36 ++++ .../com/seaofnodes/simple/AssemblyDumpTest.java | 61 +++++++ .../java/com/seaofnodes/simple/BreakoutTest.java | 163 ++++++++++++++++++ .../java/com/seaofnodes/simple/BulkMemPhiTest.java | 25 +++ .../java/com/seaofnodes/simple/Chapter25Test.java | 2 +- .../com/seaofnodes/simple/ConstantArrayTest.java | 123 ++++++++++++++ .../com/seaofnodes/simple/ConvertNodeTest.java | 2 +- .../src/test/java/com/seaofnodes/simple/Eval2.java | 7 + .../seaofnodes/simple/FloatNegationNativeTest.java | 21 +++ .../java/com/seaofnodes/simple/GraphicsTest.java | 69 +++++++- .../java/com/seaofnodes/simple/IntrinsicTest.java | 188 +++++++++++++++++++++ .../test/java/com/seaofnodes/simple/TypeTest.java | 20 +++ .../simple/codegen/PrintRegTestSupport.java | 24 +++ 14 files changed, 739 insertions(+), 4 deletions(-) create mode 100644 chapter31/src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java create mode 100644 chapter31/src/test/java/com/seaofnodes/simple/BreakoutTest.java create mode 100644 chapter31/src/test/java/com/seaofnodes/simple/ConstantArrayTest.java create mode 100644 chapter31/src/test/java/com/seaofnodes/simple/FloatNegationNativeTest.java create mode 100644 chapter31/src/test/java/com/seaofnodes/simple/IntrinsicTest.java (limited to 'chapter31/src/test/java') diff --git a/chapter31/src/test/java/com/seaofnodes/simple/ArithNodeTest.java b/chapter31/src/test/java/com/seaofnodes/simple/ArithNodeTest.java index 1e6c6fc0..b29c9706 100644 --- a/chapter31/src/test/java/com/seaofnodes/simple/ArithNodeTest.java +++ b/chapter31/src/test/java/com/seaofnodes/simple/ArithNodeTest.java @@ -65,7 +65,7 @@ public class ArithNodeTest { TypePtr.gather(inputs); TypeMemPtr.gather(inputs); TypeFunPtr.gather(inputs); - inputs.add(TypeConAryB.make(new byte[]{1,2,3})); + inputs.add(TypeConAry.make(new byte[]{1,2,3})); for( long value : new long[]{Long.MIN_VALUE,Long.MIN_VALUE+1,-1,1,Long.MAX_VALUE} ) inputs.add(TypeInteger.constant(value)); for( double value : new double[]{-0.0,0.0,-1.0,1.0,16777216.0,16777217.0,Double.NaN,Double.NEGATIVE_INFINITY,Double.POSITIVE_INFINITY} ) diff --git a/chapter31/src/test/java/com/seaofnodes/simple/ArrayInitTest.java b/chapter31/src/test/java/com/seaofnodes/simple/ArrayInitTest.java index 6cba5ee3..d298828e 100644 --- a/chapter31/src/test/java/com/seaofnodes/simple/ArrayInitTest.java +++ b/chapter31/src/test/java/com/seaofnodes/simple/ArrayInitTest.java @@ -1,10 +1,46 @@ package com.seaofnodes.simple; import com.seaofnodes.simple.codegen.CodeGen; +import com.seaofnodes.simple.node.ArrayInitNode; +import com.seaofnodes.simple.node.ConstantNode; +import com.seaofnodes.simple.node.Node; +import com.seaofnodes.simple.type.*; +import com.seaofnodes.simple.util.Ary; +import java.util.ArrayList; import org.junit.Test; import static org.junit.Assert.*; public class ArrayInitTest { + @Test public void constantListComputeIsMonotone() { + CodeGen code = new CodeGen("return 0;").parse(); + TypeStruct layout = TypeStruct.makeAry("[]i32",TypeInteger.U32,2,TypeInteger.I32,3,true); + Type array = TypeMemPtr.make(layout); + Node ctrl = ConstantNode.seed(Type.CONTROL); + Node ptr = ConstantNode.seed(Type.TOP); + Node len = ConstantNode.seed(Type.TOP); + Node x = ConstantNode.seed(Type.TOP), y = ConstantNode.seed(Type.TOP); + ArrayInitNode init = new ArrayInitNode(ctrl,code.ZERO,ptr,len,2,null,new Ary<>(new Node[]{x,y})); + Type[][] inputs = { + {Type.TOP,TypeMemPtr.TOP,array}, + {Type.TOP,TypeInteger.TOP,TypeInteger.TWO,TypeInteger.U32}, + {Type.TOP,TypeInteger.TOP,TypeInteger.constant(5),TypeInteger.BOT}, + {Type.TOP,TypeInteger.TOP,TypeInteger.constant(6),TypeInteger.BOT} + }; + var states = new ArrayList(); + for( Type p : inputs[0] ) + for( Type l : inputs[1] ) + for( Type a : inputs[2] ) + for( Type b : inputs[3] ) { + ptr._type = p; len._type = l; x._type = a; y._type = b; + states.add(new Type[]{p,l,a,b,init.compute()}); + } + for( Type[] before : states ) + for( Type[] after : states ) + if( before[0].isa(after[0]) && before[1].isa(after[1]) && + before[2].isa(after[2]) && before[3].isa(after[3]) ) + assertTrue("Array initializer rose from "+before[4]+" to "+after[4],before[4].isa(after[4])); + } + private static void value(String src, long expected) { CodeGen code=new CodeGen(src).driver(CodeGen.Phase.TypeCheck); assertEquals(Long.toString(expected),Eval2.eval(code,0,100000)); diff --git a/chapter31/src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java b/chapter31/src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java new file mode 100644 index 00000000..0e4c230a --- /dev/null +++ b/chapter31/src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java @@ -0,0 +1,61 @@ +package com.seaofnodes.simple; + +import com.seaofnodes.simple.codegen.CodeGen; +import com.seaofnodes.simple.type.*; +import com.seaofnodes.simple.util.BAOS; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HexFormat; +import org.junit.Test; +import static org.junit.Assert.*; + +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) + .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); + 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 ==="); + 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; + TypeConAry glyphs=(TypeConAry)ptr._obj.field("[]")._t; + assertEquals(96,glyphs.len()); + BAOS bytes=new BAOS(); + glyphs.write(bytes); + assertTrue("The complete font follows its u32 length header", + 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"); + 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); + } + + @Test public void combinedEncodingAndEarlierPhase() { + for( String cpu : new String[]{"x86_64_v2","arm","riscv"} ) { + CodeGen code=new CodeGen("val a=new u16[~]{5,6,7}; return a[arg&1];") + .driver(CodeGen.Phase.RegAlloc,cpu,"SystemV"); + assertFalse(code.asm().contains("Constant Pool")); + code.driver(cpu,"SystemV",true,false); + String dump=code.asm(); + assertFalse(dump.contains("=== Compilation unit:")); + assertTrue(dump.contains("Constant Pool")); + assertTrue(dump.contains("03000000050006000700")); + } + } +} diff --git a/chapter31/src/test/java/com/seaofnodes/simple/BreakoutTest.java b/chapter31/src/test/java/com/seaofnodes/simple/BreakoutTest.java new file mode 100644 index 00000000..efdb1dd7 --- /dev/null +++ b/chapter31/src/test/java/com/seaofnodes/simple/BreakoutTest.java @@ -0,0 +1,163 @@ +package com.seaofnodes.simple; + +import java.awt.image.BufferedImage; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.file.Files; +import java.nio.file.Path; +import javax.imageio.ImageIO; +import org.junit.Test; +import static org.junit.Assert.*; + +// Exercise the actual Simple game and rasterizer in native code, without a window. +public class BreakoutTest { + private static String game() throws Exception { + String source = Files.readString(Path.of("docs/examples/Breakout.smp")); + // Physics/rendering tests supply their own entry point. Input and + // sound are exercised by GraphicsTest with the complete program. + int end = source.indexOf("// Short, fading triangle waves"); + assertTrue("Breakout physics/rendering section",end >= 0); + String physics = source.substring(0,end); + // The shared square-root helper now follows the input code. + int sqrt = source.indexOf("val _sqrt ="); + if( sqrt >= end ) { + int close = source.indexOf("\n};",sqrt); + assertTrue("Square-root helper end",close >= 0); + physics += source.substring(sqrt,close+4); + } + return physics; + } + + @Test public void paddleLivesAndPause() throws Exception { + TestC.runSYS(game()+""" + val main={ -> + val g=new Game; + if( g.remaining!=192 || g.score!=0 || g.lives!=3 || g.phase!=READY ) return 1; + _tick(g,1); + if( g.paddle<510.39 || g.paddle>510.41 || g.x!=g.paddle ) return 2; + g._paddle(-100.0); if( g.paddle != 80.0 ) return 3; + g._paddle(2000.0); if( g.paddle != 928.0 ) return 4; + _reset(g); + g.x=g.paddle-50.0; _rebound(g); + if( g.dx > -0.78 || g.dy>=0.0 ) return 5; + g.x=g.paddle+50.0; _rebound(g); + if( g.dx < 0.78 || g.dy>=0.0 ) return 6; + g.x=g.paddle; _rebound(g); + if( g.dy > -0.99 || g.dx*g.dx+g.dy*g.dy<0.999999 ) return 7; + _serve(g); g.paused=true; + f64 x=g.x, y=g.y, paddle=g.paddle; + _tick(g,1); + if( g.x!=x || g.y!=y || g.paddle!=paddle ) return 8; + g.paused=false; + for( int i=0; i<3; i++ ) { + _serve(g); g.x=40.0; g.y=723.0; g.dx=0.0; g.dy=1.0; + _tick(g,0); + if( g.lives!=2-i || g.backWall || g.sound!=5 ) return 9; + } + if( g.phase!=LOST ) return 10; + _serve(g); if( g.phase!=LOST ) return 11; + _reset(g); + if( g.phase!=READY || g.lives!=3 || g.boosted || g.paused || g.speed!=320.0 ) return 12; + return 0; + }; + ""","breakoutControls","",-1); + } + + @Test public void collisionsAndBoost() throws Exception { + TestC.runSYS(game()+""" + val main={ -> + val g=new Game; + _serve(g); + g.x=29.1; g.y=400.0; g.dx=-1.0; g.dy=0.0; + _tick(g,0); + if( g.dx<=0.0 || g.x<29.0 || g.sound!=1 ) return 1; + g.x=978.9; g.dx=1.0; _tick(g,0); + if( g.dx>=0.0 || g.x>979.0 ) return 2; + // Front of the bottom row: one point, no acceleration or boost. + g.x=44.0; g.y=330.0; g.dx=0.0; g.dy=-1.0; + _tick(g,0); + if( g.bricks[168]!=0 || g.score!=1 || g.dy<=0.0 || g.boosted || g.soundDepth!=1 ) return 3; + // Top of a brick alone does not arm the back-wall bonus. + g.x=44.0; g.y=146.0; g.dy=1.0; + _tick(g,0); + if( g.bricks[0]!=0 || g.score!=9 || g.speed!=565.0 || g.boosted || g.soundDepth!=8 ) return 4; + // Back wall arms it; hitting a side still must not trigger it. + g.x=84.0; g.y=89.1; g.dy=-1.0; + _tick(g,0); + if( !g.backWall || g.dy<=0.0 || g.boosted ) return 5; + g.x=60.0; g.y=160.0; g.dx=1.0; g.dy=0.0; + _tick(g,0); + if( g.bricks[1]!=0 || g.dx>=0.0 || g.boosted ) return 6; + g.x=124.0; g.y=146.0; g.dx=0.0; g.dy=1.0; + _tick(g,0); + if( !g.boosted || g.speed<932.24 || g.speed>932.26 || g.dy>=0.0 || g.sound!=4 ) return 7; + // Another back hit cannot multiply the speed a second time. + g.x=164.0; g.y=146.0; g.dy=1.0; + _tick(g,0); + if( g.speed>932.26 || g.bricks[3]!=0 ) return 8; + // A boosted front hit cannot tunnel through the brick either. + g.x=84.0; g.y=331.0; g.dy=-1.0; + _tick(g,0); + if( g.bricks[169]!=0 || g.dy<=0.0 || g.speed<932.24 ) return 9; + // Actual paddle contact disarms the trip and chooses its angle. + g.x=g.paddle+50.0; g.y=668.0; g.dy=1.0; g.dx=0.0; + _tick(g,0); + if( g.dy>=0.0 || g.dx<0.78 || g.backWall || !g.boosted ) return 10; + // A lost ball clears both kinds of acceleration, preserving the wall/score. + int score=g.score, remaining=g.remaining; + g.x=40.0; g.y=723.0; g.dx=0.0; g.dy=1.0; + _tick(g,0); + if( g.phase!=READY || g.lives!=2 || g.speed!=320.0 || g.depth!=1 || g.boosted ) return 11; + if( g.score!=score || g.remaining!=remaining ) return 12; + _serve(g); + if( g.speed!=320.0 ) return 13; + // The new ball can earn its own boost. + g.sound=0; g.backWall=true; + g.x=204.0; g.y=146.0; g.dx=0.0; g.dy=1.0; + _tick(g,0); + if( !g.boosted || g.speed<932.24 || g.sound!=4 ) return 14; + return 0; + }; + ""","breakoutCollisions","",-1); + } + + @Test public void clearEveryBrickAndRender() throws Exception { + TestC.runSYS(game()+""" + val main={ -> + val g=new Game; + val c=new sys.draw.Canvas(WIDTH,HEIGHT); + _draw(c,g); + for( int row=0; row=0; i-- ) { + g.x=LEFT+20.0+(i-i/COLS*COLS)*BRICK_DX; + g.y=BRICK_TOP+1.0+(i/COLS)*BRICK_DY+BRICK_H+RADIUS; + g.dx=0.0; g.dy=-1.0; + _tick(g,0); + if( g.bricks[i]!=0 ) return 4; + } + if( g.phase!=WON || g.remaining!=0 || g.score!=864 || g.sound!=6 ) return 5; + f64 y=g.y; _tick(g,0); + if( g.y!=y ) return 6; + _reset(g); + for( int i=0; i + o.type instanceof TypeStruct ts && ts.isConAry() && + ts.field("[]")._t instanceof TypeConAry c && c.storageType()==storage && c.len()==len).toList(); + assertEquals(1,arrays.size()); + assertTrue(arrays.getFirst().readOnly); + return arrays.getFirst(); + } + + @Test public void typedDataAndSharing() throws Exception { + String source=""" + val a=new u16[~]{025755,65535,65538}; + val b=new u16[~]{025755,65535,65538}; + val fresh={ -> new u16[~]{025755,65535,65538}; }; + val main={ -> + if(a!=b || a!=fresh() || a#!=3 || a[0]!=025755 || a[1]!=65535 || a[2]!=2) return 1; + val bytes=new u8[~]{65,66,67}; + if(bytes!="ABC") return 2; + val signed=new i16[~]{-32768,-1,32767}; + if(signed[0]!=-32768 || signed[1]!=-1 || signed[2]!=32767) return 3; + val ints=new i32[~]{-2147483648,2147483647}; + if(ints[0]!=-2147483648 || ints[1]!=2147483647) return 4; + val uints=new u32[~]{0,4294967295}; + if(uints[1]!=4294967295) return 5; + val longs=new i64[~]{1<<63,0x7fffffffffffffff}; + if(longs[0]!=(1<<63) || longs[1]!=0x7fffffffffffffff) return 6; + val empty=new u16[~]{}; + if(empty#!=0) return 7; + return 0; + }; + """; + TestC.runSF(source,"constantArrayWidths","",-1); + CodeGen code=new CodeGen(source).driver(CodeGen.Phase.Encoding,TestC.CPU_PORT,TestC.CALL_CONVENTION); + StaticData.ObjectData obj=array(code,TypeInteger.U16,3); + assertEquals("Test.a, Test.b",obj.label()); + assertEquals(12,obj.size); // Four-byte length, six data bytes, alignment padding. + byte[] bytes=code._encoding._cpool.buf(); + assertEquals(3,bytes[obj.offset]); + assertEquals(025755&255,bytes[obj.offset+4]&255); + assertEquals(025755>>>8,bytes[obj.offset+5]&255); + assertEquals(255,bytes[obj.offset+6]&255); + assertEquals(255,bytes[obj.offset+7]&255); + assertNull(code._stop.walk(n -> n instanceof NewNode ? n : null)); + com.seaofnodes.simple.codegen.PrintRegTestSupport.checkDataAliases( + Path.of("build/objs/constantArrayWidths.o"),12,"constantArrayWidths.a","constantArrayWidths.b"); + } + + @Test public void arbitraryProducerUsesStaticData() { + for(String cpu:new String[]{"x86_64_v2","arm","riscv"}) { + CodeGen code=new CodeGen("u16[~]? unused=null; return 0;").parse(); + TypeStruct layout=(TypeStruct)Parser.TYPES.get("[]u16"); + TypeConAry contents=TypeConAry.make(TypeInteger.U16,new long[]{1,65535}); + TypeStruct array=TypeStruct.makeAry(layout._name,layout.field("#")._alias,layout.field("[]")._alias,contents); + Type ptr=TypeMemPtr.make((byte)2,array,true).makeRO(); + // No initializer or allocation node: only compute() supplies the type. + Node producer=new ReadOnlyNode(code.ZERO) { + @Override public String label() { return "constant-array producer"; } + @Override public Type compute() { return ptr; } + }; + ReturnNode ret=code._stop.walk(n -> n instanceof ReturnNode r && r.fun().isClz() ? r : null); + assertNotNull(ret); + ret.setDef(2,producer.peephole()); + code.add(ret); + code.driver(CodeGen.Phase.Encoding,cpu,"SystemV"); + StaticData.ObjectData obj=array(code,TypeInteger.U16,2); + assertEquals(8,obj.size); + } + } + + @Test public void sideEffectsAndMutableArrays() throws Exception { + CodeGen eval=new CodeGen(""" + val same_noInline={u16[~] a -> a==new u16[~]{1,2};}; + return same_noInline(new u16[~]{1,2}); + """).driver(CodeGen.Phase.TypeCheck); + assertEquals("1",Eval2.eval(eval,0)); + TestC.runSF(""" + val next={int[] counter -> counter[0]++; return 7;}; + val main={ -> + val count=new int[1]; + val a=new int[~]{next(count),next(count)}; + if(count[0]!=2 || a[0]!=7 || a[1]!=7) return 1; + val b=new int[]{7,7}, c=new int[]{7,7}; + if(b==c) return 2; + int[~] view=b; + b[0]=9; + if(view[0]!=9 || c[0]!=7) return 3; + return 0; + }; + ""","constantArrayEffects","",-1); + } + + @Test public void importedTypedConstants() throws Exception { + Path root=Path.of("build/objs/separate"); + Files.createDirectories(root); + Path lib=Files.createTempDirectory(root,"constant-arrays-"); + new CodeGen(null,lib.toString(),null,"Table",""" + val small=new u16[~]{1,65535}; + val wide=new i64[~]{1<<63,0x7fffffffffffffff}; + val uints=new u32[~]{4294967295}; + val signed=new i32[~]{-2147483648}; + """,126,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,"build/objs",paths,"TableClient",""" + return Table.small[1]==65535 && Table.wide[0]==(1<<63) && + Table.wide[1]==0x7fffffffffffffff && Table.uints[0]==4294967295 && Table.signed[0]==-2147483648; + """,126,true,TypeInteger.BOT).driver(CodeGen.Phase.TypeCheck); + assertEquals("1",Eval2.eval(code,0)); + } +} diff --git a/chapter31/src/test/java/com/seaofnodes/simple/ConvertNodeTest.java b/chapter31/src/test/java/com/seaofnodes/simple/ConvertNodeTest.java index 96d73f26..bdda3171 100644 --- a/chapter31/src/test/java/com/seaofnodes/simple/ConvertNodeTest.java +++ b/chapter31/src/test/java/com/seaofnodes/simple/ConvertNodeTest.java @@ -28,7 +28,7 @@ public class ConvertNodeTest { for( boolean arrayRO : new boolean[]{false,true} ) inputs.add(TypeMemPtr.make(TypeStruct.makeAry("[]test",len,-1, TypeMemPtr.TEST.withAccess(elementRO),-2,false)).withAccess(arrayRO)); - inputs.add(TypeConAryB.make(new byte[]{1,2,3})); + inputs.add(TypeConAry.make(new byte[]{1,2,3})); for( long value : new long[]{Long.MIN_VALUE,-129,-128,-1,0,1,127,128,255,256,Long.MAX_VALUE} ) inputs.add(TypeInteger.constant(value)); for( double value : new double[]{-0.0,0.0,1.0,16777217.0,Double.NaN,Double.NEGATIVE_INFINITY,Double.POSITIVE_INFINITY} ) diff --git a/chapter31/src/test/java/com/seaofnodes/simple/Eval2.java b/chapter31/src/test/java/com/seaofnodes/simple/Eval2.java index b6228666..eef05f93 100644 --- a/chapter31/src/test/java/com/seaofnodes/simple/Eval2.java +++ b/chapter31/src/test/java/com/seaofnodes/simple/Eval2.java @@ -110,6 +110,7 @@ public abstract class Eval2 { // Class pointers and initializer self parameters share one object per run. private static final HashMap CLASSES = new HashMap<>(); + private static final IdentityHashMap ARRAYS = new IdentityHashMap<>(); public static String eval( CodeGen code, long arg ) { return eval(code,arg,1000); } public static String eval( CodeGen code, long arg, int timeout ) { @@ -122,6 +123,7 @@ public abstract class Eval2 { // selection. Objects loaded later are scheduled independently. code.driver(CodeGen.Phase.LocalSched); CLASSES.clear(); + ARRAYS.clear(); // Timer for when we run too long. Ticks once per backedge or function call int loopCnt = 0; @@ -334,6 +336,8 @@ public abstract class Eval2 { case RoundF32Node rnd -> (double)(float)d(rnd.in(1)); case ToIntegerNode cvt -> (long)d(cvt.in(1)); case ToFloatNode toflt-> (double)x(toflt.in(1)); + case Intrinsic.F64BitsNode cast -> Double.doubleToRawLongBits(d(cast.in(1))); + case Intrinsic.F64FromBitsNode cast -> Double.longBitsToDouble(x(cast.in(1))); case XorNode xor -> x(xor.in(1)) ^ x(xor.in(2)); default -> throw Utils.TODO(); }; @@ -361,9 +365,12 @@ public abstract class Eval2 { if( tmp._obj.isAry() ) { // Constant array ptr Type elem = tmp._obj.field("[]")._t; if( elem instanceof TypeConAry con ) { + Object[] old=ARRAYS.get(tmp._obj); + if( old!=null ) yield old; Object[] xs = new Object[con.len()]; for( int i=0; i -x;}; + val main={ -> + if( neg_noInline(2.5)!=-2.5 || neg_noInline(-3.75)!=3.75 ) return 1; + if( 1.0/neg_noInline(0.0)!=-1e300*1e300 ) return 2; + if( 1.0/neg_noInline(-0.0)!=1e300*1e300 ) return 3; + if( neg_noInline(1e300*1e300)!=-1e300*1e300 ) return 4; + f64 nan=neg_noInline(1e300*1e300-1e300*1e300); + if( nan==nan ) return 5; + return 0; + }; + ""","floatNegation","",-1); + } +} diff --git a/chapter31/src/test/java/com/seaofnodes/simple/GraphicsTest.java b/chapter31/src/test/java/com/seaofnodes/simple/GraphicsTest.java index 66ced278..110a6a38 100644 --- a/chapter31/src/test/java/com/seaofnodes/simple/GraphicsTest.java +++ b/chapter31/src/test/java/com/seaofnodes/simple/GraphicsTest.java @@ -10,7 +10,7 @@ import static org.junit.Assert.*; // These tests never open a window and do not need MiniFB installed. public class GraphicsTest { - private static String graphics, text, game, clock; + private static String graphics, text, game, clock, breakout; @BeforeClass public static void compilePrograms() throws Exception { var paths = new Ary<>(new String[]{TestC.RELEASE_SYS_DIR}); @@ -22,6 +22,8 @@ public class GraphicsTest { "graphics_game",paths,TestC.CALL_CONVENTION,null,null,-1); clock = TestC.compile(Files.readString(Path.of("docs/examples/Clock.smp")), "graphics_clock",paths,TestC.CALL_CONVENTION,null,null,-1); + breakout = TestC.compile(Files.readString(Path.of("docs/examples/Breakout.smp")), + "graphics_breakout",paths,TestC.CALL_CONVENTION,null,null,-1); } private static String run(String exe, String backend, int exit) throws Exception { @@ -101,6 +103,71 @@ public class GraphicsTest { assertTrue(run(clock,"off",1).contains("disabled")); } + @Test public void breakoutWithoutBackend() throws Exception { + assertTrue(run(breakout,"off",1).contains("disabled")); + } + + @Test public void breakoutInputAndFrames() throws Exception { + Path source=Path.of("build/objs/breakout_input.c"); + Path library=Path.of("build/objs/breakout_input"+(TestC.OS.startsWith("Windows") ? ".dll" : ".so")); + Files.writeString(source,""" + #include "simple_graphics.h" + #include + #include + static int frames, previous_ball, previous_paddle; + static int32_t open_window(const char *s,uint32_t w,uint32_t h) { + return w==1008 && h==760 ? 0 : -1; + } + static int32_t present(const uint32_t *p,uint32_t n) { + if(n!=1008*760) return -1; + int paddle=-1,ball=-1; + for(int x=24;x<984;x++) if(p[675*1008+x]==0x4ce0ef) { paddle=x; break; } + for(int y=560;y<674 && ball<0;y++) + for(int x=24;x<984;x++) if(p[y*1008+x]==0xeef7ff) { ball=y; break; } + int ok=paddle>=0 && ball>=0; + if(frames==0) ok=ok && paddle==448 && ball==658; + if(frames==1 || frames==6 || frames==9) ok=ok && ballprevious_paddle; + if(frames==4 || frames==5) ok=ok && paddle==previous_paddle && ball==previous_ball; + if(frames==7) ok=ok && paddle==584; + if(frames==8) ok=ok && paddle==448 && ball==658; + if(!ok) { + printf("bad frame %d: paddle %d (was %d), ball %d (was %d)\\n", + frames,paddle,previous_paddle,ball,previous_ball); + return -1; + } + previous_ball=ball; previous_paddle=paddle; + if(++frames==10) puts("breakout input smoke passed"); + return 0; + } + static int32_t poll_events(int32_t n) { return 0; } + static int32_t mouse_x(void) { return frames>=7 ? 640 : 504; } + static int32_t mouse_y(void) { return 680; } + static int32_t key(int32_t k) { + return (k==' ' && (frames==1 || frames==9)) || + (k==262 && (frames==2 || frames==3)) || + (k=='P' && (frames==4 || frames==6)) || + (k=='R' && (frames==8 || frames==9)); + } + static int32_t wait_events(int64_t ms) { usleep(ms*1000); return 0; } + static void close_window(void) {} + static const struct simple_graphics_api api={SIMPLE_GRAPHICS_VERSION, + open_window,present,poll_events,mouse_x,mouse_y,poll_events,key,close_window,wait_events}; + const struct simple_graphics_api *simple_minifb_api(void) { return &api; } + """); + TestC.exec(30,"gcc","-shared","-fPIC","-Isrc/main/c",source.toString(),"-o",library.toString()); + var pb=new ProcessBuilder(Path.of(breakout).toAbsolutePath().toString(),"smoke").redirectErrorStream(true); + pb.environment().put("SIMPLE_MINIFB",library.toAbsolutePath().toString()); + pb.environment().put("SIMPLE_MINIAUDIO","off"); + Process child=pb.start(); + try { + assertTrue("Breakout timed out",child.waitFor(10,TimeUnit.SECONDS)); + String output=new String(child.getInputStream().readAllBytes(),java.nio.charset.StandardCharsets.UTF_8); + assertEquals(output,0,child.exitValue()); + assertEquals("breakout input smoke passed\n",output); + } finally { if(child.isAlive()) child.destroyForcibly(); } + } + @Test public void missingLibrary() throws Exception { String missing = Path.of("build","no-such-minifb-backend").toAbsolutePath().toString(); String output = run(graphics,missing,1); diff --git a/chapter31/src/test/java/com/seaofnodes/simple/IntrinsicTest.java b/chapter31/src/test/java/com/seaofnodes/simple/IntrinsicTest.java new file mode 100644 index 00000000..e3b30efb --- /dev/null +++ b/chapter31/src/test/java/com/seaofnodes/simple/IntrinsicTest.java @@ -0,0 +1,188 @@ +package com.seaofnodes.simple; + +import com.seaofnodes.simple.codegen.CodeGen; +import com.seaofnodes.simple.node.*; +import com.seaofnodes.simple.type.*; +import com.seaofnodes.simple.util.Ary; +import com.seaofnodes.simple.codegen.RegAllocTestSupport.CheckedCodeGen; +import java.nio.file.Files; +import java.nio.file.Path; +import org.junit.Test; +import static org.junit.Assert.*; + +public class IntrinsicTest { + private static final String DECL=""" + { f64 -> i64 } simple_f64_bits="C"; + { i64 -> f64 } simple_f64_from_bits="C"; + """; + + @Test public void constantsAndRawNaNs() { + long[] patterns={0,Long.MIN_VALUE,1,0x0010000000000000L,0x3ff0000000000000L, + 0x7fefffffffffffffL,0x7ff0000000000000L,0xfff0000000000000L, + 0x7ff8000000000001L,0x7ff8000000000002L,0xfff800000000002aL,0x7ff0000000000001L}; + for(long bits:patterns) { + String literal=bits==Long.MIN_VALUE ? "(-9223372036854775807-1)" : Long.toString(bits); + CodeGen code=new CodeGen(DECL+"return simple_f64_bits(simple_f64_from_bits("+literal+"));") + .driver(CodeGen.Phase.TypeCheck); + assertNull(code._stop.walk(n -> n instanceof CallNode ? n : null)); + assertEquals(Long.toString(bits),Eval2.eval(code,0)); + } + assertNotSame(TypeFloat.constant(Double.longBitsToDouble(patterns[8])), + TypeFloat.constant(Double.longBitsToDouble(patterns[9]))); + } + + @Test public void runtimeNodesAndMemory() { + CodeGen code=new CodeGen(DECL+""" + val bits=simple_f64_bits; + val a=new f64[1]; + a[0]=simple_f64_from_bits(arg); + if( arg==0 ) a[0]=-0.0; + return bits(a[0]); + """).driver(CodeGen.Phase.TypeCheck); + assertNotNull(code._stop.walk(n -> n instanceof Intrinsic.BitCastNode ? n : null)); + assertNull(code._stop.walk(n -> n instanceof CallNode ? n : null)); + assertEquals(Long.toString(Long.MIN_VALUE),Eval2.eval(code,0)); + assertEquals("9221120237041090602",Eval2.eval(code,0x7ff800000000002aL)); + } + + @Test public void ordinaryFunctionWithSameName() { + CodeGen code=new CodeGen(""" + val simple_f64_bits={ f64 x -> 42; }; + return simple_f64_bits(1.0); + """); + assertEquals("42",Eval2.eval(code,0)); + } + + @Test public void wrongSignature() { + try { + new CodeGen("{ i64 -> i64 } simple_f64_bits=\"C\"; return simple_f64_bits(arg);") + .driver(CodeGen.Phase.TypeCheck); + fail("The reserved C symbol has fixed semantics and a fixed signature"); + } catch(RuntimeException e) { + assertTrue(e.getMessage(),e.getMessage().contains("Intrinsic 'simple_f64_bits' requires")); + } + } + + @Test public void nativeRepresentations() throws Exception { + TestC.runSYS(""" + val bits_noInline={ f64 x -> sys.math.f64Bits(x); }; + val float_noInline={ i64 x -> sys.math.f64FromBits(x); }; + val main={ -> + val patterns=new i64[~]{0,sys.integer.MIN_I64,1,0x0010000000000000, + 0x3ff0000000000000,0x7fefffffffffffff,0x7ff0000000000000, + 0x7ff8000000000001,0x7ff8000000000002,-2251799813685206,0x7ff0000000000001}; + for( int i=0; i i64 } llround="C"; + val apply_noInline={ { f64 -> i64 } f, f64 x -> f(x); }; + val main={ -> + if( apply_noInline(simple_f64_bits,-0.0)!=(-9223372036854775807-1) ) return 1; + if( apply_noInline(llround,3.75)!=4 ) return 2; + if( apply_noInline(simple_f64_bits,1.0)!=0x3ff0000000000000 ) return 3; + if( apply_noInline(simple_f64_bits,simple_f64_from_bits(0x7ff800000000002a))!=0x7ff800000000002a ) return 4; + return 0; + }; + """; + CodeGen code=new CodeGen(source).driver(CodeGen.Phase.TypeCheck); + assertNotNull("The indirect C call must survive",code._stop.walk(n -> + n instanceof CallNode c && c.external() && !c.tfp().isConstant() ? n : null)); + TestC.runSYS(source,"intrinsicFallback","",-1); + } + + @Test public void importedNodesAndNaNConstants() throws Exception { + Path dir=Files.createTempDirectory(Path.of("build/objs"),"intrinsic-import-"); + String library=DECL+""" + val bits_noInline={ f64 x -> simple_f64_bits(x); }; + val float_noInline={ i64 x -> simple_f64_from_bits(x); }; + val nan=simple_f64_from_bits(0x7ff8000000000001); + val otherNaN=simple_f64_from_bits(0x7ff8000000000002); + """; + new CodeGen(null,dir.toString(),null,"Bits",library,126,true,TypeInteger.BOT) + .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); + var paths=new Ary<>(new String[]{dir.toString()}); + String[] clients={ + "return Bits.bits_noInline(Bits.float_noInline(arg));", + "return Bits.bits_noInline(Bits.nan);", + "return Bits.bits_noInline(Bits.otherNaN);" + }; + long[] expected={0x7ff800000000002aL,0x7ff8000000000001L,0x7ff8000000000002L}; + for(int i=0;i n instanceof MachConcreteNode m && m.op().equals("f64bits") ? n : null)); + assertNotNull(code._stop.walk(n -> n instanceof MachConcreteNode m && m.op().equals("f64frombits") ? n : null)); + } + } + + @Test public void invalidArgumentIsNotInlinedAway() { + try { + new CodeGen(DECL+"return simple_f64_bits(1);").driver(CodeGen.Phase.TypeCheck); + fail("Intrinsic inlining must not hide the call's type error"); + } catch(RuntimeException e) { + assertTrue(e.getMessage(),e.getMessage().contains("Argument #1 isa")); + } + } + + @Test public void discardedValueKeepsArgumentEffects() throws Exception { + TestC.runSYS(DECL+""" + val next={ i64[] a -> a[0]++; return 1.0; }; + val main={ -> + val a=new i64[1]; + simple_f64_bits(next(a)); + return a[0]!=1; + }; + ""","intrinsicEffects","",-1); + } + + @Test public void emulatedRepresentationMoves() throws Exception { + long[] patterns={0,Long.MIN_VALUE,1,0x3ff0000000000000L,0x7ff0000000000000L, + 0xfff0000000000000L,0x7ff800000000002aL,0x7ff0000000000001L}; + for(boolean toBits:new boolean[]{true,false}) { + String source=toBits + ? "val cast={ f64 x -> { f64 -> i64 } simple_f64_bits=\"C\"; return simple_f64_bits(x); };" + : "val cast={ i64 x -> { i64 -> f64 } simple_f64_from_bits=\"C\"; return simple_f64_from_bits(x); };"; + var arm=TestArm64.build("cast",source,0,-1,false); + var risc=TestRisc5.build(source,"cast",0,-1,false); + int armStart=arm._pc, riscStart=risc._pc; + for(long bits:patterns) { + arm._pc=armStart; risc._pc=riscStart; + if(toBits) { + arm.fregs[0]=Double.longBitsToDouble(bits); + risc.fregs[10]=Double.longBitsToDouble(bits); + } else { + arm.regs[0]=bits; + risc.regs[10]=bits; + } + assertEquals(0,arm.step(1000)); + assertEquals(0,risc.step(1000)); + assertEquals(bits,toBits ? arm.regs[0] : Double.doubleToRawLongBits(arm.fregs[0])); + assertEquals(bits,toBits ? risc.regs[10] : Double.doubleToRawLongBits(risc.fregs[10])); + } + } + } +} diff --git a/chapter31/src/test/java/com/seaofnodes/simple/TypeTest.java b/chapter31/src/test/java/com/seaofnodes/simple/TypeTest.java index 16b75fdc..52e857e9 100644 --- a/chapter31/src/test/java/com/seaofnodes/simple/TypeTest.java +++ b/chapter31/src/test/java/com/seaofnodes/simple/TypeTest.java @@ -7,6 +7,26 @@ import static org.junit.Assert.assertSame; public class TypeTest { + @Test public void testConstantArrayElements() { + TypeConAry range=TypeConAry.make(TypeInteger.U16,new long[]{5,6,7}); + Assert.assertEquals("[5-7]",range.toString()); + Assert.assertEquals("[5-7]",TypeConAry.make(TypeInteger.U8,new long[]{5,6,7}).toString()); + Assert.assertEquals("[\"abc\"]",TypeConAry.make("abc").toString()); + for( TypeInteger storage : new TypeInteger[]{TypeInteger.BOOL,TypeInteger.I8,TypeInteger.U8, + TypeInteger.I16,TypeInteger.U16,TypeInteger.I32,TypeInteger.U32,TypeInteger.BOT} ) { + TypeConAry empty=TypeConAry.make(storage,new long[0]); + assertSame(storage.dual(),empty.elem()); + assertSame(storage,((TypeConAry)empty.dual()).elem()); + for( long[] values : new long[][]{{0},{1},{0,1},{storage._min,storage._max}} ) { + TypeConAry array=TypeConAry.make(storage,values); + Assert.assertTrue(empty.isa(array)); + assertSame(array,empty.meet(array)); + assertSame(empty,array.join(empty)); + check_symmetric(empty,array); + } + } + } + @Test public void testOpaqueExternalEscapes() { TypeMem defaults = TypeMem.START.makeFrom(XInt.make(2),XInt.make(3)); TypeMem prior = TypeMem.START.makeFrom(XInt.make(5),XInt.make(7)); diff --git a/chapter31/src/test/java/com/seaofnodes/simple/codegen/PrintRegTestSupport.java b/chapter31/src/test/java/com/seaofnodes/simple/codegen/PrintRegTestSupport.java index b0f0f225..190cf17c 100644 --- a/chapter31/src/test/java/com/seaofnodes/simple/codegen/PrintRegTestSupport.java +++ b/chapter31/src/test/java/com/seaofnodes/simple/codegen/PrintRegTestSupport.java @@ -3,6 +3,30 @@ import com.seaofnodes.simple.node.*; import com.seaofnodes.simple.type.TypeInteger; import static org.junit.Assert.*; public class PrintRegTestSupport { + public static void checkDataAliases(java.nio.file.Path file, int size, String... names) { + ElfReader elf=ElfReader.load(file.toFile(),null); + assertNotNull(elf); + ElfReader.Section symbols=java.util.Arrays.stream(elf._sections) + .filter(s -> ".symtab".equals(s._name)).findFirst().orElseThrow(); + ElfReader.Section strings=elf._sections[symbols._link]; + var bytes=java.nio.ByteBuffer.wrap(elf._buf).order(java.nio.ByteOrder.LITTLE_ENDIAN); + var wanted=new java.util.HashSet<>(java.util.Arrays.asList(names)); + Long address=null; + for( int i=0; i