summaryrefslogtreecommitdiff
path: root/chapter18/src/main/java
diff options
context:
space:
mode:
authorCliff Click <cliffc@acm.org>2024-12-25 22:24:58 -0800
committerCliff Click <cliffc@acm.org>2025-01-15 15:07:30 -0800
commit9814de0f115704c58c1ccbc0ebfa1fa98338f656 (patch)
treea31c2ea288bb4f8f618a67b1caa45c3a436acd42 /chapter18/src/main/java
parentfcd6dcf5265b4b23fd69af761316c064b8f9f7ce (diff)
downloadSimple-9814de0f115704c58c1ccbc0ebfa1fa98338f656.tar.gz
Simple-9814de0f115704c58c1ccbc0ebfa1fa98338f656.zip
Cleanup compile driver
Top level makes a "main" function and calls it. Opto() pass inlines main into top-level and removes the function call. If peeps are off, the function call remains; this breaks many tests. Add a FunNode function header; Return is its end. Return no long used at the top level; only a single return per-function, merging all returns (breaks many tests). Add a Call & CallEnd nodes. Fix many tests to pass again. Fix a bunch of minor bugs.
Diffstat (limited to 'chapter18/src/main/java')
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/CodeGen.java92
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/GlobalCodeMotion.java15
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/GraphVisualizer.java2
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/IRPrinter.java49
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/IterPeeps.java3
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/JSViewer.java36
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/Parser.java168
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/AndNode.java2
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/CFGNode.java8
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/CProjNode.java3
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/CallEndNode.java79
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/CallNode.java96
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/FunNode.java47
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/LoopNode.java23
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/MemOpNode.java2
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/MultiNode.java11
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/MultiUse.java4
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/Node.java14
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/OrNode.java2
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/OutNode.java7
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/ParmNode.java47
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/PhiNode.java2
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/ProjNode.java6
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/RegionNode.java2
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/ReturnNode.java47
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/SarNode.java2
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/ScopeMinNode.java25
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/ScopeNode.java5
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/ShlNode.java2
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/StopNode.java49
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/StoreNode.java2
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/XorNode.java2
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java74
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/type/TypeTuple.java50
34 files changed, 754 insertions, 224 deletions
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/CodeGen.java b/chapter18/src/main/java/com/seaofnodes/simple/CodeGen.java
new file mode 100644
index 00000000..184b6f9c
--- /dev/null
+++ b/chapter18/src/main/java/com/seaofnodes/simple/CodeGen.java
@@ -0,0 +1,92 @@
+ package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.Parser;
+import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.*;
+import java.util.*;
+
+public class CodeGen {
+
+ public enum Phase {
+ Parse, Opto, TypeCheck, Schedule, RegAlloc;
+ }
+ public Phase _phase;
+
+ public final String _src;
+ // Compile-time known initial argument type
+ public final TypeInteger _arg;
+
+ public Parser P;
+ public StartNode _start;
+ public StopNode _stop ;
+
+ // Last created CodeGen as a global, for easier debugging prints
+ public static CodeGen CODE;
+
+ CodeGen( String src, TypeInteger arg ) { _phase = null; _src = src; _arg=arg; CODE=this; }
+ public CodeGen( String src ) { this(src,TypeInteger.BOT); }
+
+ public CodeGen parse() { return parse(false); }
+ public CodeGen parse(boolean disable) {
+ assert _phase == null;
+ _phase = Phase.Parse;
+ P = new Parser(_src,_arg);
+ Node._disablePeephole = disable;
+ _stop = P.parse();
+ _start = Parser.START; // Capture global start
+ P = null; // No longer parsing
+ return this;
+ }
+
+ public CodeGen opto() {
+ assert _phase == Phase.Parse;
+ _phase = Phase.Opto;
+
+ // Optimization
+ IterPeeps.iterate(_stop);
+
+ // TODO:
+ // Optimistic
+ return this;
+ }
+
+ public CodeGen typeCheck() {
+ assert _phase == Phase.Opto;
+ _phase = Phase.TypeCheck;
+
+ // Type check
+ String err = _stop.walk( Node::err );
+ if( err != null )
+ throw new RuntimeException(err);
+ return this;
+ }
+
+
+ public CodeGen codegen() { return codegen(false); }
+ public CodeGen codegen(boolean show) {
+ assert _phase == Phase.TypeCheck;
+ _phase = Phase.Schedule;
+
+ // Build the loop tree, fix never-exit loops
+ _start.buildLoopTree(_stop);
+ if( show )
+ System.out.println(new GraphVisualizer().generateDotOutput(_stop,null,null));
+
+ // TODO:
+ // loop unroll, peel, RCE, etc
+
+ GlobalCodeMotion.buildCFG(_start,_stop);
+
+ _phase = Phase.RegAlloc;
+
+ return this;
+ }
+
+ // Debugging helper
+ @Override public String toString() {
+ return _stop.p(9999);
+ }
+
+ // Debugging helper
+ public Node f(int idx) { return _stop.find(idx); }
+}
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/GlobalCodeMotion.java b/chapter18/src/main/java/com/seaofnodes/simple/GlobalCodeMotion.java
index 9698abd9..7ce12091 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/GlobalCodeMotion.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/GlobalCodeMotion.java
@@ -10,10 +10,9 @@ public abstract class GlobalCodeMotion {
// Arrange that the existing isCFG() Nodes form a valid CFG. The
// Node.use(0) is always a block tail (either IfNode or head of the
// following block). There are no unreachable infinite loops.
- public static void buildCFG( StopNode stop ) {
- schedEarly();
- Parser.SCHEDULED = true;
- schedLate( stop);
+ public static void buildCFG( StartNode start, StopNode stop ) {
+ schedEarly(start);
+ schedLate(stop);
}
@@ -22,10 +21,10 @@ public abstract class GlobalCodeMotion {
// (except at loops). Since defs are visited first - and hoisted as early
// as possible, when we come to a use we place it just after its deepest
// input.
- private static void schedEarly() {
+ private static void schedEarly(StartNode start) {
ArrayList<CFGNode> rpo = new ArrayList<>();
BitSet visit = new BitSet();
- _rpo_cfg(Parser.START, visit, rpo);
+ _rpo_cfg(start, visit, rpo);
// Reverse Post-Order on CFG
for( int j=rpo.size()-1; j>=0; j-- ) {
CFGNode cfg = rpo.get(j);
@@ -164,8 +163,8 @@ public abstract class GlobalCodeMotion {
CFGNode found=null;
for( int i=1; i<phi.nIns(); i++ )
if( phi.in(i)==n )
- if( found==null ) found = phi.region().cfg(i);
- else Utils.TODO(); // Can be more than once
+ found = phi.region().cfg(i)._idom(found,null);
+
assert found!=null;
return found;
}
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/GraphVisualizer.java b/chapter18/src/main/java/com/seaofnodes/simple/GraphVisualizer.java
index ea6862d2..bd778696 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/GraphVisualizer.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/GraphVisualizer.java
@@ -137,7 +137,7 @@ public class GraphVisualizer {
for (Node n : all) {
if (n instanceof RegionNode region) {
sb.append("\t\t{ rank=same; ");
- sb.append(region).append(";");
+ sb.append(region.uniqueName()).append(";");
for (Node phi : region._outputs)
if (phi instanceof PhiNode) sb.append(phi.uniqueName()).append(";");
sb.append("}\n");
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/IRPrinter.java b/chapter18/src/main/java/com/seaofnodes/simple/IRPrinter.java
index bd071870..4f422a25 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/IRPrinter.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/IRPrinter.java
@@ -18,7 +18,9 @@ public class IRPrinter {
return;
}
for( Node def : n._inputs )
- sb.append(def==null ? "____ " : "%4d ".formatted(def._nid));
+ sb.append(def==null ? "____" : "%4d".formatted(def._nid))
+ // Lazy Phi indicator
+ .append(n instanceof ScopeMinNode && def instanceof ScopeMinNode ? "^" : " ");
for( int i = n._inputs.size(); i<4; i++ )
sb.append(" ");
sb.append(" [[ ");
@@ -41,7 +43,7 @@ public class IRPrinter {
}
public static String prettyPrint(Node node, int depth) {
- return Parser.SCHEDULED
+ return CodeGen.CODE._phase.ordinal() > CodeGen.Phase.Schedule.ordinal()
? _prettyPrintScheduled( node, depth )
: _prettyPrint( node, depth );
}
@@ -54,7 +56,7 @@ public class IRPrinter {
ArrayList<Node> rpos = new ArrayList<>();
BitSet visit = new BitSet();
for( int i=bfs._lim; i< bfs._bfs.size(); i++ )
- postOrd( bfs._bfs.get(i), rpos, visit, bfs._bs);
+ postOrd( bfs._bfs.get(i), null, rpos, visit, bfs._bs);
// Reverse the post-order walk
StringBuilder sb = new StringBuilder();
boolean gap=false;
@@ -78,23 +80,26 @@ public class IRPrinter {
return sb.toString();
}
- private static void postOrd(Node n, ArrayList<Node> rpos, BitSet visit, BitSet bfs) {
+ private static void postOrd(Node n, Node prior, ArrayList<Node> rpos, BitSet visit, BitSet bfs) {
if( !bfs.get(n._nid) )
return; // Not in the BFS visit
+ if( n instanceof FunNode && !(prior instanceof StartNode) )
+ return; // Only visit Fun from Start
if( visit.get(n._nid) ) return; // Already post-order walked
visit.set(n._nid);
// First walk the CFG, then everything
if( n instanceof CFGNode ) {
for( Node use : n._outputs )
- if( use instanceof CFGNode && use.nOuts() >= 1 && !(use._outputs.get( 0 ) instanceof LoopNode) )
- postOrd(use, rpos,visit,bfs);
+ if( use instanceof CFGNode && use.nOuts() >= 1 &&
+ !(use._outputs.get( 0 ) instanceof LoopNode) )
+ postOrd(use, n, rpos,visit,bfs);
for( Node use : n._outputs )
if( use instanceof CFGNode )
- postOrd(use,rpos,visit,bfs);
+ postOrd(use,n,rpos,visit,bfs);
}
for( Node use : n._outputs )
if( use != null )
- postOrd(use, rpos,visit,bfs);
+ postOrd(use, n, rpos,visit,bfs);
// Post-order
rpos.add(n);
}
@@ -176,15 +181,15 @@ public class IRPrinter {
}
// Print by block with least idepth
StringBuilder sb = new StringBuilder();
- ArrayList<Node> bns = new ArrayList<>();
+ Ary<Node> bns = new Ary<>(Node.class);
while( !ds.isEmpty() ) {
CFGNode blk = null;
for( Node n : ns ) {
CFGNode cfg = n instanceof CFGNode cfg0 && cfg0.blockHead() ? cfg0 : n.cfg0();
- if( blk==null || cfg.idepth() < blk.idepth() )
+ if( blk==null || cfg.idepth() < blk.idepth() || (blk instanceof FunNode && !(cfg instanceof FunNode)))
blk = cfg;
}
- ds.remove(blk._nid);
+ Integer d = ds.remove(blk._nid);
ns.remove(blk);
// Print block header
@@ -192,11 +197,13 @@ public class IRPrinter {
sb.append( " ".repeat(4) ).append(" [[ ");
if( blk instanceof StartNode ) ;
else if( blk instanceof RegionNode || blk instanceof StopNode )
- for( int i=(blk instanceof StopNode ? 0 : 1); i<blk.nIns(); i++ )
+ for( int i=(blk instanceof StopNode ? 3 : 1); i<blk.nIns(); i++ )
label(sb,blk.cfg(i));
else
label(sb,blk.cfg(0));
sb.append(" ]] \n");
+ sb.append(d);
+ printLine(blk,sb);
// Collect block contents that are in the depth limit
bns.clear();
@@ -204,7 +211,8 @@ public class IRPrinter {
for( Node use : blk._outputs ) {
Integer i = ds.get(use._nid);
if( i!=null && !(use instanceof CFGNode cfg && cfg.blockHead()) ) {
- bns.add(use);
+ if( bns.find(use)==-1 )
+ bns.add(use);
xd = Math.min(xd,i);
}
}
@@ -233,12 +241,16 @@ public class IRPrinter {
private static void _walk( HashMap<Integer,Integer> ds, ArrayList<Node> ns, Node node, int d ) {
Integer nd = ds.get(node._nid);
- if( nd!=null && d <= nd ) return; // Been there, done that
- if( ds.put(node._nid,d) == null )
+ if( nd!=null && d >= nd ) return; // Been there, done that
+ Integer old = ds.put(node._nid,d) ;
+ if( old == null )
ns.add(node);
if( d == 0 ) return; // Depth cutoff
for( Node def : node._inputs )
- if( def != null )
+ if( def != null &&
+ // Don't walk into or out of functions
+ !(node instanceof CallEndNode && def instanceof ReturnNode) &&
+ !(node instanceof FunNode && def instanceof CallNode) )
_walk(ds,ns,def,d-1);
}
@@ -250,9 +262,10 @@ public class IRPrinter {
if( !blk.blockHead() ) blk = blk.cfg(0);
sb.append( "%-9.9s ".formatted( label( blk ) ) );
}
- static void printLine( Node n, StringBuilder sb, ArrayList<Node> bns, int i, HashMap<Integer,Integer> ds, ArrayList<Node> ns ) {
+ static void printLine( Node n, StringBuilder sb, Ary<Node> bns, int i, HashMap<Integer,Integer> ds, ArrayList<Node> ns ) {
+ sb.append(ds.get(n._nid));
printLine( n, sb );
- if( i != -1 ) Utils.del(bns,i);
+ if( i != -1 ) bns.del(i);
ds.remove(n._nid);
ns.remove(n);
}
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/IterPeeps.java b/chapter18/src/main/java/com/seaofnodes/simple/IterPeeps.java
index aad9bf31..a321b13e 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/IterPeeps.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/IterPeeps.java
@@ -57,7 +57,7 @@ public abstract class IterPeeps {
/**
* Iterate peepholes to a fixed point
*/
- public static StopNode iterate(StopNode stop) {
+ public static void iterate( StopNode stop) {
assert progressOnList(stop);
int cnt=0;
@@ -93,7 +93,6 @@ public abstract class IterPeeps {
n.kill(); // Just plain dead
}
- return stop;
}
// Visit ALL nodes and confirm the invariant:
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/JSViewer.java b/chapter18/src/main/java/com/seaofnodes/simple/JSViewer.java
index 7b8f2631..869448fa 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/JSViewer.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/JSViewer.java
@@ -1,10 +1,11 @@
package com.seaofnodes.simple;
+import com.seaofnodes.simple.CodeGen;
import com.seaofnodes.simple.node.*;
import com.seaofnodes.simple.type.*;
-
-import java.nio.file.Paths;
import java.io.IOException;
+import java.util.Stack;
+import java.nio.file.Paths;
import java.util.Collection;
public class JSViewer implements AutoCloseable {
@@ -21,8 +22,7 @@ public class JSViewer implements AutoCloseable {
static SimpleWebSocket SERVER;
static int N; // Dot frames
- static Parser P; //
- static StopNode STOP; //
+ static CodeGen CODE; //
JSViewer() throws Exception {
// Launch server; hand shake
@@ -42,16 +42,13 @@ public class JSViewer implements AutoCloseable {
try {
N=0;
// Use parser scope, xscope when building views
- P = new Parser(src);
- STOP = P.STOP;
+ CODE = new CodeGen(src);
SHOW = true;
show();
// Parse program, generating views at every parse point
- P.parse();
+ CODE.parse();
// No longer user parse internal state when building views
- P = null;
- STOP.iterate();
-
+ CODE.opto();
// Catch and ignore Parser errors
} catch(RuntimeException re) {
@@ -72,11 +69,14 @@ public class JSViewer implements AutoCloseable {
public static void show() { if( SERVER!=null && SHOW ) _show(); }
private static void _show() {
- Collection<Node> all = GraphVisualizer.findAll(P==null ? null : P._xScopes, STOP, P==null ? null : P._scope);
+ boolean midParse = CODE.P!=null;
+ Stack<ScopeNode> xScopes = midParse ? CODE.P._xScopes : null;
+
+ Collection<Node> all = GraphVisualizer.findAll(xScopes, CODE._stop, midParse ? CODE.P._scope: null);
SB sb = new SB();
sb.p("digraph view_").p(N++).p(" {\n").ii();
- if( P!=null )
- sb.i().p("// POS: ").p(P.pos()).nl();
+ if( midParse )
+ sb.i().p("// POS: ").p(CODE.P.pos()).nl();
// To keep the Scopes below the graph and pointing up into the graph we
// need to group the Nodes in a subgraph cluster, and the scopes into a
@@ -101,17 +101,17 @@ public class JSViewer implements AutoCloseable {
nodes(sb, all);
// Now the scopes, in a cluster no edges
- if( P!=null )
- for( ScopeNode xscope : P._xScopes )
+ if( midParse )
+ for( ScopeNode xscope : xScopes )
if( !xscope.isDead() )
scope( sb, xscope );
// Walk the Node edges
- nodeEdges(sb, P!=null && !P._xScopes.empty() ? P._xScopes.peek() : null, all);
+ nodeEdges(sb, midParse && !xScopes.empty() ? xScopes.peek() : null, all);
// Walk the active Scope edges
- if( P!=null )
- for( ScopeNode xscope : P._xScopes )
+ if( midParse )
+ for( ScopeNode xscope : xScopes )
if( !xscope.isDead() )
scopeEdges( sb, xscope );
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/Parser.java b/chapter18/src/main/java/com/seaofnodes/simple/Parser.java
index 7301f63b..f6bf71a9 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/Parser.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/Parser.java
@@ -32,9 +32,6 @@ public class Parser {
public StopNode STOP;
- // Debugger Printing.
- public static boolean SCHEDULED; // True if debug printer can use schedule info
-
// The Lexer. Thin wrapper over a byte[] buffer with a cursor.
private final Lexer _lexer;
@@ -91,6 +88,7 @@ public class Parser {
ScopeNode _continueScope;
ScopeNode _breakScope; // Merge all the while-breaks here
+ FunNode _fun; // Current function being parsed
// Mapping from a type name to a Type. The string name matches
// `type.str()` call. No TypeMemPtrs are in here, because Simple does not
@@ -100,12 +98,16 @@ public class Parser {
// Mapping from a type name to the constructor for a Type.
public final HashMap<String, StructNode> INITS;
+ // "Linker" mapping from constant TypeFunPtrs to heads of function
+ public static final HashMap<TypeFunPtr,FunNode> LINKER = new HashMap<>();
+
+
public Parser(String source) { this(source, TypeInteger.BOT); }
public Parser(String source, TypeInteger arg) {
Node.reset();
IterPeeps.reset();
- SCHEDULED = false;
+ LINKER.clear();
_lexer = new Lexer(source);
_scope = new ScopeNode();
_continueScope = _breakScope = null;
@@ -154,25 +156,39 @@ public class Parser {
_xScopes.push(_scope);
// Enter a new scope for the initial control and arguments
_scope.push();
+ Node ctrl = new CProjNode(START, 0, ScopeNode.CTRL).peephole();
+ Node pmem = new ProjNode(START, 1, ScopeNode.MEM0).peephole();
+ Node arg = new ProjNode(START, 2, ScopeNode.ARG0).peephole();
ScopeMinNode mem = new ScopeMinNode();
mem.addDef(null);
- _scope.define(ScopeNode.CTRL, Type.CONTROL , false, new CProjNode(START, 0, ScopeNode.CTRL).peephole());
- mem.addDef( new ProjNode(START, 1, ScopeNode.MEM0).peephole());
- _scope.define(ScopeNode.MEM0, TypeMem.BOT , false, mem .peephole());
- _scope.define(ScopeNode.ARG0, TypeInteger.BOT, false, new ProjNode(START, 2, ScopeNode.ARG0).peephole());
- JSViewer.show();
+ mem.addDef(pmem);
+ _scope.define(ScopeNode.CTRL, Type.CONTROL , false, ctrl);
+ _scope.define(ScopeNode.MEM0, TypeMem.BOT , false, mem );
+ _scope.define(ScopeNode.ARG0, TypeInteger.BOT, false, arg );
+
+ // Call main
+ CallNode main = (CallNode)new CallNode(ctrl,pmem,arg,con(TypeFunPtr.MAIN)).peephole();
+ // Call End
+ CallEndNode cend = (CallEndNode)new CallEndNode(main).peephole();
+ STOP.addDef(new CProjNode(cend,0,ScopeNode.CTRL).peephole());
+ STOP.addDef(new ProjNode(cend,1,ScopeNode.MEM0).peephole());
+ STOP.addDef(new ProjNode(cend,2,ScopeNode.ARG0).peephole());
+
+ // Parse whole program, as-if function header "{ int arg -> body }"
+ ReturnNode ret = parseFunctionBody("main",TypeFunPtr.MAIN,"arg");
+ LINKER.put(TypeFunPtr.MAIN,ret.fun());
+ main.peephole();
+ if( cend.peephole() != null )
+ IterPeeps.addAll(cend._outputs);
- // Parse whole program
- parseBlock(false);
+ if( !_lexer.isEOF() ) throw _errorSyntax("unexpected");
- if( ctrl()._type==Type.CONTROL )
- STOP.addReturn(new ReturnNode(ctrl(), ZERO, _scope).peephole());
+ // Clean up and reset
_scope.kill();
_xScopes.pop();
for( StructNode init : INITS.values() )
init.unkeep().kill();
INITS.clear();
- if( !_lexer.isEOF() ) throw _errorSyntax("unexpected");
STOP.peephole();
JSViewer.show();
if( show ) showGraph();
@@ -180,6 +196,67 @@ public class Parser {
}
/**
+ * Parses a function body, assuming the header is parsed.
+ */
+ private ReturnNode parseFunctionBody(String name, TypeFunPtr sig, String... ids) {
+ sig.setName(name);
+ FunNode fun = _fun = (FunNode)peep(new FunNode(START,sig,name));
+
+ // Build a multi-exit return point for all function returns
+ RegionNode r = new RegionNode(null,null);
+ assert r.inProgress();
+ PhiNode rmem = new PhiNode(ScopeNode.MEM0,TypeMem.BOT,r,null);
+ PhiNode rrez = new PhiNode(ScopeNode.ARG0,Type.BOTTOM,r,null);
+ ReturnNode ret = new ReturnNode(r, rmem, rrez, fun);
+ assert ret.inProgress();
+ STOP.addDef(ret);
+
+ // Pre-call the function from Start, with worse-case arguments. This
+ // represents all the future, yet-to-be-parsed functions calls and
+ // external calls.
+ _scope.push();
+ ctrl(fun); // Scope control from function
+ // Private mem alias tracking per function
+ ScopeMinNode startMem = _scope.mem();
+ ScopeMinNode mem = new ScopeMinNode();
+ mem.addDef(null); // Alias#0
+ mem.addDef(new ParmNode(ScopeNode.MEM0,1,TypeMem.BOT,fun,startMem).peephole()); // All aliases
+ _scope.mem(mem);
+ // All args, "as-if" called externally
+ for( int i=0; i<ids.length; i++ ) {
+ Type t = sig.arg(i);
+ assert t==t.glb(); // Expect args declared type not be lifted
+ _scope.define(ids[i], t, false, new ParmNode(ids[i],i+2,t,fun,con(t)).peephole());
+ }
+
+ // Parse the body
+ Node last=null;
+ while (!peek('}') && !_lexer.isEOF())
+ last = parseStatement();
+
+ // Last expression is the return
+ if( ctrl()._type==Type.CONTROL )
+ STOP.addReturn(ctrl(), _scope.mem(), last, fun);
+
+ // Function scope ends
+ _scope.pop();
+ _fun = null;
+
+ // Pop off the inProgress node on the multi-exit Region merge
+ assert r.inProgress();
+ r ._inputs.pop();
+ rmem._inputs.pop();
+ rrez._inputs.pop();
+ assert !r.inProgress();
+
+ // Force peeps, which have been avoided due to inProgress
+ ret.setDef(1,rmem.peephole());
+ ret.setDef(2,rrez.peephole());
+ ret.setDef(0,r.peephole());
+ return (ReturnNode)ret.peephole();
+ }
+
+ /**
* Parses a block
*
* <pre>
@@ -191,11 +268,13 @@ public class Parser {
private Node parseBlock(boolean inCon) {
// Enter a new scope
_scope.push(inCon);
+ Node last = ZERO;
while (!peek('}') && !_lexer.isEOF())
- parseStatement();
+ last = parseStatement();
// Exit scope
+ last.keep();
_scope.pop();
- return null;
+ return last.unkeep();
}
/**
@@ -323,7 +402,7 @@ public class Parser {
// Our current scope is the body Scope
ctrl(ifT.unkeep()); // set ctrl token to ifTrue projection
_scope.addGuards(ifT,pred.unkeep(),false); // Up-cast predicate
- parseStatement(); // Parse loop body
+ Node expr = parseStatement().keep(); // Parse loop body
_scope.removeGuards(ifT);
// Merge the loop bottom into other continue statements
@@ -363,7 +442,7 @@ public class Parser {
_xScopes.pop();
_xScopes.push(exit);
_scope = exit;
- return _scope;
+ return peep(expr.unkeep());
}
private ScopeNode jumpTo(ScopeNode toScope) {
@@ -386,7 +465,7 @@ public class Parser {
private void checkLoopActive() { if (_breakScope == null) throw error("No active loop for a break or continue"); }
- private Node parseContinue() { checkLoopActive(); return (_continueScope = require(jumpTo( _continueScope ),";")); }
+ private Node parseContinue() { checkLoopActive(); _continueScope = require(jumpTo( _continueScope ),";"); return ZERO; }
private Node parseBreak () {
checkLoopActive();
// At the time of the break, and loop-exit conditions are only valid if
@@ -395,11 +474,11 @@ public class Parser {
_breakScope.removeGuards(_breakScope.ctrl());
_breakScope = require(jumpTo(_breakScope ),";");
_breakScope.addGuards(_breakScope.ctrl(), null, false);
- return _breakScope;
+ return ZERO;
}
// Look for an unbalanced `)`, skipping balanced
- private Type skipAsgn() {
+ private void skipAsgn() {
int paren=0;
while( true )
// Next X char handles skipping complex comments
@@ -407,8 +486,10 @@ public class Parser {
case Character.MAX_VALUE:
throw Utils.TODO();
case ')':
- if( --paren<0 )
- return posT(pos()-1); // Leave the `)` behind
+ if( --paren<0 ) {
+ posT( pos() - 1 );
+ return; // Leave the `)` behind
+ }
break;
case '(': paren ++; break;
default: break;
@@ -449,7 +530,7 @@ public class Parser {
// Parse the true side
ctrl(ifT.unkeep()); // set ctrl token to ifTrue projection
_scope.addGuards(ifT,pred,false); // Up-cast predicate
- Node lhs = stmt ? parseStatement() : parseAsgn().keep(); // Parse true-side
+ Node lhs = (stmt ? parseStatement() : parseAsgn()).keep(); // Parse true-side
_scope.removeGuards(ifT);
ScopeNode tScope = _scope;
@@ -461,9 +542,9 @@ public class Parser {
// remain true if the true clause exits: `if( !ptr ) return 0; return ptr.fld;`
_scope.addGuards(ifF,pred,true);
boolean doRHS = match(fside);
- Node rhs = doRHS
+ Node rhs = (doRHS
? (stmt ? parseStatement() : parseAsgn())
- : (stmt ? null : con(lhs._type.makeZero()));
+ : con(lhs._type.makeZero())).keep();
_scope.removeGuards(ifF);
if( doRHS )
fScope = _scope;
@@ -475,9 +556,8 @@ public class Parser {
// Check the trinary widening int/flt
if( !stmt ) {
- rhs = widenInt( rhs, lhs._type ).keep();
+ rhs = widenInt( rhs.unkeep(), lhs._type ).keep();
lhs = widenInt( lhs.unkeep(), rhs._type ).keep();
- rhs.unkeep();
}
// Merge results
@@ -485,7 +565,7 @@ public class Parser {
_xScopes.pop(); // Discard pushed from graph display
RegionNode r = ctrl(tScope.mergeScopes(fScope));
- Node ret = stmt ? r : peep(new PhiNode("",lhs._type.meet(rhs._type),r,lhs.unkeep(),rhs));
+ Node ret = peep(new PhiNode("",lhs._type.meet(rhs._type),r,lhs.unkeep(),rhs.unkeep()));
r.peephole();
return ret;
}
@@ -501,9 +581,9 @@ public class Parser {
*/
private Node parseReturn() {
var expr = require(parseAsgn(), ";");
- Node ret = STOP.addReturn(new ReturnNode(ctrl(), expr, _scope).peephole());
+ STOP.addReturn(ctrl(), _scope.mem(), expr, _fun);
ctrl(XCTRL); // Kill control
- return ret;
+ return expr;
}
/**
@@ -540,11 +620,11 @@ public class Parser {
throw error("Cannot reassign final '"+name+"'");
// Lift expression, based on type
- Node lift = liftExpr(expr, def.type(), def._final);
+ Node lift = liftExpr(expr.keep(), def.type(), def._final);
// Update
_scope.update(name,lift);
// Return un-lifted expr
- return expr;
+ return expr.unkeep();
}
// Make finals deep; widen ints to floats; narrow wide int types.
@@ -636,7 +716,7 @@ public class Parser {
// Define a new name,
if( !_scope.define(name,t,xfinal,lift) )
throw error("Redefining name '" + name + "'");
- return null;
+ return lift;
}
@@ -678,7 +758,7 @@ public class Parser {
require("}");
require(";");
_scope.pop();
- return null;
+ return ZERO;
}
@@ -756,21 +836,18 @@ public class Parser {
if( match("}") ) // No-arg function { -> type }
throw Utils.TODO();
Ary<Type> ts = new Ary<>(Type.class);
- ts.push(null); // Return filled in later
ts.push(t0); // First argument
while( true ) {
if( match("->") ) { // End of arguments, parse return
Type ret = type();
- if( ret==null ) return posT(old);
- ts.set(0,ret);
- if( !match("}") ) return posT(old); // Not a function
- return TypeFunPtr.make(match("?"),TypeTuple.make(ts.asAry()));
+ if( ret==null || !match("}") )
+ return posT(old); // Not a function
+ return TypeFunPtr.make(match("?"),TypeTuple.make(ts.asAry()),ret);
}
Type t1 = type();
if( t1==null ) return posT(old); // Not a function
ts.push(t1);
}
-
}
// True if a TypeFunPtr, without advancing parser
@@ -1215,8 +1292,6 @@ public class Parser {
int old = pos(); // Record lexer position
Ary<Type> ts = new Ary<>(Type.class);
Ary<String> ids = new Ary<>(String.class);
- ts .push(Type.BOTTOM); // Return type, unknown yet
- ids.push(null); // Not an argument
while( true ) {
Type t = type(); // Arg type
if( t==null ) break;
@@ -1227,13 +1302,10 @@ public class Parser {
}
require("->");
// Make a concrete function type, with a fidx
- TypeFunPtr tfp = TypeFunPtr.makeFun(TypeTuple.make(ts.asAry()));
- //FunNode fun = (FunNode)peep(new FunNode());
-
- throw Utils.TODO();
+ TypeFunPtr tfp = TypeFunPtr.makeFun(TypeTuple.make(ts.asAry()),Type.BOTTOM);
+ return parseFunctionBody(null,tfp,ids.asAry());
}
-
/**
* Parse integer literal
*
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/AndNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/AndNode.java
index 17a4e0ca..68a8079d 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/AndNode.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/AndNode.java
@@ -60,7 +60,7 @@ public class AndNode extends Node {
return null;
}
@Override Node copy(Node lhs, Node rhs) { return new AndNode(lhs,rhs); }
- @Override String err() {
+ @Override public String err() {
if( !(in(1)._type instanceof TypeInteger) ) return "Cannot '&' " + in(1)._type;
if( !(in(2)._type instanceof TypeInteger) ) return "Cannot '&' " + in(2)._type;
return null;
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/CFGNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/CFGNode.java
index 052ad8fc..bed4eb17 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/CFGNode.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/CFGNode.java
@@ -82,16 +82,16 @@ public abstract class CFGNode extends Node {
// Start is a LoopNode which contains all at depth 1.
public void buildLoopTree(StopNode stop) {
_ltree = stop._ltree = Parser.XCTRL._ltree = new LoopTree((StartNode)this);
- _bltWalk(2,stop, new BitSet());
+ _bltWalk(2,null,stop, new BitSet());
}
- private int _bltWalk(int pre, StopNode stop, BitSet post) {
+ private int _bltWalk(int pre, FunNode fun, StopNode stop, BitSet post) {
// Pre-walked?
if( _pre!=0 ) return pre;
_pre = pre++;
// Pre-walk
for( Node use : _outputs )
if( use instanceof CFGNode usecfg )
- pre = usecfg._bltWalk(pre,stop,post);
+ pre = usecfg._bltWalk(pre,use instanceof FunNode fuse ? fuse : fun,stop,post);
// Post-order work: find innermost loop
LoopTree inner = null, ltree;
@@ -109,7 +109,7 @@ public abstract class CFGNode extends Node {
if( ltree._par == null )
// This loop never had an If test choose to take its
// exit, i.e. it is a no-exit infinite loop.
- ltree._par = ltree._head.forceExit(stop)._ltree;
+ ltree._par = ltree._head.forceExit(fun,stop)._ltree;
ltree = ltree._par;
}
}
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/CProjNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/CProjNode.java
index 0b9d89d2..01119310 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/CProjNode.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/CProjNode.java
@@ -49,7 +49,8 @@ public class CProjNode extends CFGNode implements MultiUse {
if( ctrl() instanceof IfNode iff && iff.pred().addDep(this) instanceof NotNode not )
return new CProjNode(new IfNode(iff.ctrl(),not.in(1)).peephole(),1-_idx,_idx==0 ? "False" : "True");
- return null;
+ // Copy of some other input
+ return ((MultiNode)ctrl()).pcopy(_idx);
}
@Override
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/CallEndNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/CallEndNode.java
new file mode 100644
index 00000000..31c245f9
--- /dev/null
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/CallEndNode.java
@@ -0,0 +1,79 @@
+package com.seaofnodes.simple.node;
+
+import com.seaofnodes.simple.IterPeeps;
+import com.seaofnodes.simple.Parser;
+import com.seaofnodes.simple.Utils;
+import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypeFunPtr;
+import java.util.BitSet;
+
+/**
+ * CallEnd
+ */
+public class CallEndNode extends CFGNode implements MultiNode {
+
+ // When set true, this Call/CallEnd/Fun/Return is being trivially inlined
+ private boolean _folding;
+
+ public CallEndNode(CallNode call) { super(call); }
+
+ @Override
+ public String label() { return "CallEnd"; }
+ @Override public boolean blockHead() { return true; }
+
+ CallNode call() { return (CallNode)in(0); }
+
+ @Override
+ StringBuilder _print1(StringBuilder sb, BitSet visited) {
+ sb.append("cend( ");
+ if( call()==null ) sb.append("---, ");
+ else sb.append("Call, ");
+ for( int i=1; i<nIns()-1; i++ )
+ in(i)._print0(sb,visited).append(",");
+ sb.setLength(sb.length()-1);
+ return sb.append(")");
+ }
+
+ @Override
+ public Type compute() {
+ for( Node n : _inputs )
+ if( n!=null && n._type==Type.CONTROL )
+ return Type.CONTROL;
+ return Type.XCONTROL;
+ }
+
+ @Override
+ public Node idealize() {
+
+ // Trivial inlining: call site calls a single function; single function
+ // is only called by this call site.
+ if( !_folding && nIns()==2 ) {
+ CallNode call = call();
+ Node fptr = call.fptr();
+ if( fptr.nOuts() == 1 ) { // Only user is this call
+ ReturnNode ret = (ReturnNode)in(1);
+ FunNode fun = ret.fun();
+ assert fun.nIns()==3; // Expecting Start, and the Call
+ assert fun.in(1) instanceof StartNode && fun.in(2)==call;
+
+ // Trivial inline: rewrite
+ _folding = true;
+ // Rewrite Fun so the normal RegionNode ideal collapses
+ fun._folding = true;
+ fun.setDef(1,Parser.XCTRL); // No default/unknown StartNode caller
+ fun.setDef(2,call.ctrl()); // Bypass the Call;
+ fun.ret().setDef(3,null); // Return is folding also
+ IterPeeps.addAll(fun._outputs);
+ return this;
+ } else { // Function ptr has multiple users (so maybe multiple call sites)
+ fptr.addDep(this);
+ }
+ }
+
+ return null;
+ }
+
+ @Override public Node pcopy(int idx) {
+ return _folding ? in(1).in(idx) : null;
+ }
+}
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/CallNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/CallNode.java
new file mode 100644
index 00000000..0839ad2c
--- /dev/null
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/CallNode.java
@@ -0,0 +1,96 @@
+package com.seaofnodes.simple.node;
+
+import com.seaofnodes.simple.Parser;
+import com.seaofnodes.simple.Utils;
+import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypeFunPtr;
+import java.util.BitSet;
+
+/**
+ * Call
+ */
+public class CallNode extends CFGNode {
+
+ public CallNode(Node... nodes) { super(nodes); }
+
+ @Override
+ public String label() { return "Call"; }
+
+ @Override
+ StringBuilder _print1(StringBuilder sb, BitSet visited) {
+ String fname = null;
+ Node fptr = fptr();
+ if( fptr._type instanceof TypeFunPtr tfp && tfp.isConstant() )
+ fname = Parser.LINKER.get(tfp)._name;
+ if( fname==null ) fptr._print0(sb,visited);
+ else sb.append(fname);
+ sb.append("( ");
+ for( int i=2; i<nIns()-1; i++ )
+ in(i)._print0(sb,visited).append(",");
+ sb.setLength(sb.length()-1);
+ return sb.append(")");
+ }
+
+ Node ctrl() { return in(0); }
+ Node mem () { return in(1); }
+ // Args mapped 1-to-1 on inputs
+ Node arg(int idx) { return in(idx); }
+ // args from input 2 to last
+ Node fptr() { return _inputs.last(); }
+
+ // Find the Call End from the Call
+ CallEndNode cend() {
+ // Always in use slot 0
+ return (CallEndNode)out(0);
+ }
+
+ @Override
+ public Type compute() {
+ return ctrl()._type;
+ }
+
+ @Override
+ public Node idealize() {
+ // Link: call calls target function. Linking makes the target FunNode
+ // point to this Call, and all his Parms point to the call arguments;
+ // also the CallEnd points to the Return.
+ if( fptr()._type instanceof TypeFunPtr tfp ) {
+ // If fidxs is negative, then infinite unknown functions
+ long fidxs = tfp.fidxs();
+ if( fidxs > 0 ) {
+ // Walk the (63 max) bits and link
+ for( ; fidxs!=0; fidxs = TypeFunPtr.nextFIDX(fidxs) ) {
+ int fidx = Long.numberOfTrailingZeros(fidxs);
+ TypeFunPtr tfp0 = tfp.makeFrom(fidx);
+ FunNode fun = Parser.LINKER.get(tfp0);
+ if( fun!=null && !fun._folding && !linked(fun) )
+ link(fun);
+ }
+ }
+ }
+
+ return null;
+ }
+
+ // True if Fun is linked to this Call
+ boolean linked( FunNode fun ) {
+ for( Node n : fun._inputs )
+ if( n == this )
+ return true;
+ return false;
+ }
+
+
+ // Link so this calls fun
+ private void link( FunNode fun ) {
+ assert !linked(fun);
+ fun.addDef(this);
+ for( Node use : fun._outputs )
+ if( use instanceof ParmNode parm )
+ parm.addDef(arg(parm._idx));
+ // Call end points to function return
+ cend().addDef(fun.ret());
+ assert linked(fun);
+ }
+
+}
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/FunNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/FunNode.java
new file mode 100644
index 00000000..9087926e
--- /dev/null
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/FunNode.java
@@ -0,0 +1,47 @@
+package com.seaofnodes.simple.node;
+
+import com.seaofnodes.simple.Utils;
+import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypeFunPtr;
+
+public class FunNode extends RegionNode {
+
+ // When set true, this Call/CallEnd/Fun/Return is being trivially inlined
+ boolean _folding;
+
+ TypeFunPtr _sig; // Initial signature may be missing return
+ String _name; // Debug label, optional
+
+ public FunNode( StartNode start, TypeFunPtr sig, String name ) { super(null,start); _sig=sig; _name=name; }
+
+ @Override
+ public String label() { return _name; }
+
+ ReturnNode ret() {
+ ReturnNode ret=null;
+ for( Node n : _outputs )
+ if( n instanceof ReturnNode ret0 ) {
+ assert ret==null || ret==ret0; // Found more than one return
+ ret=ret0;
+ }
+ return ret;
+ }
+
+
+ @Override
+ public Type compute() {
+ // Only dead if no callers after SCCP
+ return Type.CONTROL;
+ }
+
+ @Override
+ public Node idealize() {
+ // If no default/unknown caller, use the normal RegionNode ideal rules
+ // to collapse
+ if( inProgress() ) return null;
+ return super.idealize();
+ }
+
+ // Always in-progress until we run out of unknown callers
+ @Override public boolean inProgress() { return in(1) instanceof StartNode; }
+}
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/LoopNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/LoopNode.java
index ecda9c63..33420eb9 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/LoopNode.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/LoopNode.java
@@ -3,6 +3,7 @@ package com.seaofnodes.simple.node;
import com.seaofnodes.simple.Parser;
import com.seaofnodes.simple.Utils;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypeMem;
import com.seaofnodes.simple.type.TypeInteger;
import java.util.BitSet;
import java.util.HashSet;
@@ -34,7 +35,7 @@ public class LoopNode extends RegionNode {
// If this is an unreachable loop, it may not have an exit. If it does not
// (i.e., infinite loop), force an exit to make it reachable.
- public StopNode forceExit( StopNode stop ) {
+ public StopNode forceExit( FunNode fun, StopNode stop ) {
// Walk the backedge, then immediate dominator tree util we hit this
// Loop again. If we ever hit a CProj from an If (as opposed to
// directly on the If) we found our exit.
@@ -50,12 +51,28 @@ public class LoopNode extends RegionNode {
// Found a no-exit loop. Insert an exit
NeverNode iff = new NeverNode(back());
for( Node use : _outputs )
- if( use instanceof PhiNode phi )
+ if( use instanceof PhiNode )
iff.addDef(use);
CProjNode t = new CProjNode(iff,0,"True" );
CProjNode f = new CProjNode(iff,1,"False");
setDef(2,f);
- stop.addDef(new ReturnNode(t,Parser.ZERO,null));
+
+ // Now fold control into the exit
+ if( fun!=null )
+ throw Utils.TODO();
+
+ // If not in a function, look for a last-level merge point;
+ // make if not there.
+ RegionNode ctrl = stop.ctrl() instanceof RegionNode r ? r : new RegionNode(null,stop.ctrl());
+ PhiNode mem = stop.mem () instanceof PhiNode phi && phi.in(0)==ctrl ? phi : new PhiNode("",stop.mem ()._type,ctrl,stop.mem ());
+ PhiNode expr = stop.expr() instanceof PhiNode phi && phi.in(0)==ctrl ? phi : new PhiNode("",stop.expr()._type,ctrl,stop.expr());
+ if( stop.ctrl()!=ctrl ) stop.setDef(0,ctrl);
+ if( stop.mem ()!=mem ) stop.setDef(1,mem );
+ if( stop.expr()!=expr ) stop.setDef(2,expr);
+ Node top = new ConstantNode(Type.TOP).peephole();
+ ctrl.addDef(t );
+ mem .addDef(top);
+ expr.addDef(top);
return stop;
}
}
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/MemOpNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/MemOpNode.java
index 62323031..96274789 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/MemOpNode.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/MemOpNode.java
@@ -44,7 +44,7 @@ public abstract class MemOpNode extends Node {
int hash() { return _alias; }
@Override
- String err() {
+ public String err() {
Type ptr = ptr()._type;
// Already an error, but better error messages come from elsewhere
if( ptr == Type.BOTTOM ) return null;
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/MultiNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/MultiNode.java
index ac9c0045..17d00881 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/MultiNode.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/MultiNode.java
@@ -1,6 +1,11 @@
package com.seaofnodes.simple.node;
-public interface MultiNode extends OutNode {
+import com.seaofnodes.simple.Ary;
+
+
+public interface MultiNode {
+
+ abstract Ary<Node> outs();
// Find a projection by index
default ProjNode proj( int idx ) {
@@ -17,4 +22,8 @@ public interface MultiNode extends OutNode {
return prj;
return null;
}
+
+ // Return not-null if this projection index is a ideal copy.
+ // Called by ProjNode ideal and used to collapse Multis.
+ default Node pcopy(int idx) { return null; }
}
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/MultiUse.java b/chapter18/src/main/java/com/seaofnodes/simple/node/MultiUse.java
index e4548dfd..436d3432 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/MultiUse.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/MultiUse.java
@@ -1,3 +1,5 @@
package com.seaofnodes.simple.node;
-public interface MultiUse { abstract int idx(); }
+public interface MultiUse {
+ abstract int idx();
+}
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/Node.java b/chapter18/src/main/java/com/seaofnodes/simple/node/Node.java
index 1a595f49..6369fb01 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/Node.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/Node.java
@@ -11,7 +11,7 @@ import java.util.function.Function;
* The Node class provides common functionality used by all subtypes.
* Subtypes of Node specialize by overriding methods.
*/
-public abstract class Node implements OutNode {
+public abstract class Node {
/**
* Each node has a unique dense Node ID within a compilation context
@@ -125,7 +125,7 @@ public abstract class Node implements OutNode {
*/
public Node in(int i) { return _inputs.get(i); }
public Node out(int i) { return _outputs.get(i); }
- @Override public Ary<Node> outs() { return _outputs; }
+ public final Ary<Node> outs() { return _outputs; }
public int nIns() { return _inputs.size(); }
@@ -162,9 +162,11 @@ public abstract class Node implements OutNode {
new_def.addUse(this);
// Set the new_def over the old (killed) edge
_inputs.set(idx,new_def);
- if( old_def != null && // If the old def exists, remove a def->use edge
- old_def.delUse(this) ) // If we removed the last use, the old def is now dead
- old_def.kill(); // Kill old def
+ if( old_def != null ) { // If the old def exists, remove a def->use edge
+ if( old_def.delUse(this) ) // If we removed the last use, the old def is now dead
+ old_def.kill(); // Kill old def
+ else IterPeeps.add(old_def);// Else old lost a use, so onto worklist
+ }
moveDepsToWorklist();
// Return new_def for easy flow-coding
return new_def;
@@ -609,7 +611,7 @@ public abstract class Node implements OutNode {
Node copy(Node lhs, Node rhs) { throw Utils.TODO("Binary ops need to implement copy"); }
// Report any post-optimize errors
- String err() { return null; }
+ public String err() { return null; }
/**
* Used to allow repeating tests in the same JVM. This just resets the
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/OrNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/OrNode.java
index b572346f..bd771198 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/OrNode.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/OrNode.java
@@ -57,7 +57,7 @@ public class OrNode extends Node {
return null;
}
@Override Node copy(Node lhs, Node rhs) { return new OrNode(lhs,rhs); }
- @Override String err() {
+ @Override public String err() {
if( !(in(1)._type instanceof TypeInteger) ) return "Cannot '|' " + in(1)._type;
if( !(in(2)._type instanceof TypeInteger) ) return "Cannot '|' " + in(2)._type;
return null;
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/OutNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/OutNode.java
deleted file mode 100644
index dbac136b..00000000
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/OutNode.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package com.seaofnodes.simple.node;
-
-import com.seaofnodes.simple.Ary;
-
-public interface OutNode {
- Ary<Node> outs();
-}
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/ParmNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/ParmNode.java
new file mode 100644
index 00000000..136494b5
--- /dev/null
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/ParmNode.java
@@ -0,0 +1,47 @@
+package com.seaofnodes.simple.node;
+
+import com.seaofnodes.simple.Utils;
+import com.seaofnodes.simple.type.Type;
+import java.util.BitSet;
+
+public class ParmNode extends PhiNode {
+
+ // Argument indices are mapped one-to-one on CallNode inputs
+ final int _idx; // Argument index
+
+ public ParmNode(String label, int idx, Type declaredType, Node... inputs) {
+ super(label,declaredType,inputs);
+ _idx = idx;
+ }
+
+ @Override public String label() { return MemOpNode.mlabel(_label); }
+
+ @Override public String glabel() { return _label; }
+
+ FunNode fun() { return (FunNode)in(0); }
+
+ @Override
+ StringBuilder _print1(StringBuilder sb, BitSet visited) {
+ if( fun()._name.equals("main") && _label.equals("arg") )
+ return sb.append("arg");
+ sb.append(_label).append("(");
+ for( Node in : _inputs ) {
+ if (in == null) sb.append("____");
+ else in._print0(sb, visited);
+ sb.append(",");
+ }
+ sb.setLength(sb.length()-1);
+ sb.append(")");
+ return sb;
+ }
+
+
+ @Override
+ public Node idealize() {
+ if( inProgress() ) return null;
+ return super.idealize();
+ }
+
+ // Always in-progress until we run out of unknown callers
+ @Override public boolean inProgress() { return fun().inProgress(); }
+}
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index c0557639..6dd4f57d 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -155,7 +155,7 @@ public class PhiNode extends Node {
}
// True if last input is null
- public final boolean inProgress() {
+ public boolean inProgress() {
return in(nIns()-1) == null;
}
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/ProjNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/ProjNode.java
index 525b5df0..9519f5ec 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/ProjNode.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/ProjNode.java
@@ -26,7 +26,9 @@ public class ProjNode extends Node implements MultiUse {
@Override
StringBuilder _print1(StringBuilder sb, BitSet visited) { return sb.append(_label); }
- @Override public CFGNode cfg0() { return in(0).cfg0(); }
+ @Override public CFGNode cfg0() {
+ return in(0) instanceof CFGNode cfg ? cfg : in(0).cfg0();
+ }
@Override public boolean isMultiTail() { return in(0).isMultiHead(); }
@Override public boolean isMem() { return _type instanceof TypeMem; }
@@ -38,7 +40,7 @@ public class ProjNode extends Node implements MultiUse {
return t instanceof TypeTuple tt ? tt._types[_idx] : Type.BOTTOM;
}
- @Override public Node idealize() { return null; }
+ @Override public Node idealize() { return ((MultiNode)in(0)).pcopy(_idx); }
@Override
boolean eq( Node n ) { return _idx == ((ProjNode)n)._idx; }
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/RegionNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/RegionNode.java
index fb39af17..0f9fce7a 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/RegionNode.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/RegionNode.java
@@ -109,7 +109,7 @@ public class RegionNode extends CFGNode {
}
// True if last input is null
- public final boolean inProgress() {
+ public boolean inProgress() {
return nIns()>1 && in(nIns()-1) == null;
}
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/ReturnNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/ReturnNode.java
index b586a44f..b305a96e 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/ReturnNode.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/ReturnNode.java
@@ -1,5 +1,6 @@
package com.seaofnodes.simple.node;
+import com.seaofnodes.simple.Parser;
import com.seaofnodes.simple.type.*;
import java.util.BitSet;
@@ -15,16 +16,14 @@ import java.util.BitSet;
*/
public class ReturnNode extends CFGNode {
- public ReturnNode(Node ctrl, Node data, ScopeNode scope) {
- // Add memory slices to Return, so all memory updates are live-on-exit.
- super(ctrl, data);
- if( scope!=null )
- for( int i=2; i<scope.mem().nIns(); i++ )
- addDef(scope.mem().in(i));
+ public ReturnNode(Node ctrl, Node mem, Node data, FunNode fun) {
+ super(ctrl, mem, data, fun);
}
public Node ctrl() { return in(0); }
- public Node expr() { return in(1); }
+ public Node mem () { return in(1); }
+ public Node expr() { return in(2); }
+ public FunNode fun() { return (FunNode)in(3); }
@Override
public String label() { return "Return"; }
@@ -32,19 +31,41 @@ public class ReturnNode extends CFGNode {
@Override
StringBuilder _print1(StringBuilder sb, BitSet visited) {
sb.append("return ");
+ if( expr()==null ) return sb.append("INPROGRESS");
expr()._print0(sb, visited);
return sb.append(";");
}
@Override
public Type compute() {
- return TypeTuple.make(ctrl()._type,expr()._type);
+ if( inProgress() ) return TypeTuple.RET; // In progress
+ return TypeTuple.make(ctrl()._type,mem()._type,expr()._type);
}
- @Override
- public Node idealize() {
- if( ctrl()._type==Type.XCONTROL )
- return ctrl();
- return null;
+ @Override public Node idealize() { return null; }
+
+ public boolean inProgress() {
+ return ctrl() instanceof RegionNode r && r.inProgress();
+ }
+
+ // Add a return exit to the current parsing function
+ void addReturn(Node ctrl, Node rmem, Node expr) {
+ assert inProgress();
+ RegionNode r = (RegionNode)ctrl();
+ // Assert that the Phis are in particular outputs; not reordered or shuffled
+ PhiNode mem = (PhiNode)r.out(0); assert mem._declaredType == TypeMem.BOT;
+ PhiNode rez = (PhiNode)r.out(1); assert rez._declaredType == Type.BOTTOM;
+ // Pop "inProgress" null off
+ r ._inputs.pop();
+ mem._inputs.pop();
+ rez._inputs.pop();
+ // Add new return point
+ r .addDef(ctrl);
+ mem.addDef(rmem);
+ rez.addDef(expr);
+ // Back to being inProgress
+ r .addDef(null);
+ mem.addDef(null);
+ rez.addDef(null);
}
}
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/SarNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/SarNode.java
index 4270ef88..a3d1045f 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/SarNode.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/SarNode.java
@@ -52,7 +52,7 @@ public class SarNode extends Node {
return null;
}
@Override Node copy(Node lhs, Node rhs) { return new SarNode(lhs,rhs); }
- @Override String err() {
+ @Override public String err() {
if( !(in(1)._type instanceof TypeInteger) ) return "Cannot '>>' " + in(1)._type;
if( !(in(2)._type instanceof TypeInteger) ) return "Cannot '>>' " + in(2)._type;
return null;
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/ScopeMinNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/ScopeMinNode.java
index e9a4eb82..f5a33890 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/ScopeMinNode.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/ScopeMinNode.java
@@ -42,7 +42,7 @@ public class ScopeMinNode extends Node {
public ScopeMinNode() { _type = TypeMem.BOT; }
- @Override public String label() { return "$mem"; }
+ @Override public String label() { return "ALLMEM"; }
@Override public boolean isMem() { return true; }
@Override
@@ -66,7 +66,15 @@ public class ScopeMinNode extends Node {
@Override public Type compute() { return TypeMem.BOT; }
- @Override public Node idealize() { return null; }
+ @Override public Node idealize() {
+ if( inProgress() ) return null;
+
+ // If not merging any memory (all memory is just the default)
+ if( nIns()==2 )
+ return in(1); // Become default memory
+
+ return null;
+ }
public Node in( Var v ) { return in(v._idx); }
@@ -79,7 +87,6 @@ public class ScopeMinNode extends Node {
return setDef(alias,st);
}
-
// Read or update from memory.
// A shared implementation allows us to create lazy phis both during
// lookups and updates; the lazy phi creation is part of chapter 8.
@@ -148,4 +155,16 @@ public class ScopeMinNode extends Node {
}
}
+ // If being used by a Scope, this is "in progress" from the Parser.
+ // Once no more scope users, this is just a memory-merge.
+ boolean inProgress() {
+ for( Node n : _outputs )
+ if( n instanceof ScopeNode scope )
+ return true;
+ return false;
+ }
+
+ @Override boolean eq( Node n ) {
+ return this==n || !inProgress();
+ }
}
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/ScopeNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/ScopeNode.java
index e720a58f..8685e66b 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/ScopeNode.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/ScopeNode.java
@@ -81,6 +81,7 @@ public class ScopeNode extends ScopeMinNode {
* @return Node that was bound
*/
public <N extends Node> N ctrl(N n) { return setDef(0,n); }
+ public Node mem(Node n) { return setDef(1,n); }
public void push() { push(false); }
public void push(boolean inCon) {
@@ -350,7 +351,9 @@ public class ScopeNode extends ScopeMinNode {
if( !(n instanceof CFGNode) )
n.unkill();
_guards.clear();
- super.kill();
+ // Can have lazy uses remaining
+ if( isUnused() )
+ super.kill();
}
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/ShlNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/ShlNode.java
index d3639ed7..e454362a 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/ShlNode.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/ShlNode.java
@@ -56,7 +56,7 @@ public class ShlNode extends Node {
return null;
}
@Override Node copy(Node lhs, Node rhs) { return new ShlNode(lhs,rhs); }
- @Override String err() {
+ @Override public String err() {
if( !(in(1)._type instanceof TypeInteger) ) return "Cannot '<<' " + in(1)._type;
if( !(in(2)._type instanceof TypeInteger) ) return "Cannot '<<' " + in(2)._type;
return null;
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/StopNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/StopNode.java
index 269c2f6c..4b91f1eb 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/StopNode.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/StopNode.java
@@ -1,11 +1,7 @@
package com.seaofnodes.simple.node;
+import com.seaofnodes.simple.Utils;
import com.seaofnodes.simple.type.Type;
-import com.seaofnodes.simple.Parser;
-import com.seaofnodes.simple.IterPeeps;
-import com.seaofnodes.simple.GlobalCodeMotion;
-import com.seaofnodes.simple.GraphVisualizer;
-
import java.util.BitSet;
public class StopNode extends CFGNode {
@@ -25,7 +21,9 @@ public class StopNode extends CFGNode {
@Override
StringBuilder _print1(StringBuilder sb, BitSet visited) {
- if( ret()!=null ) return ret()._print0(sb, visited);
+ // For the sake of many old tests, and single value prints as "return val"
+ if( nIns() == 3 ) return expr()._print0(sb.append("return "),visited).append(";");
+ if( ret()!=null ) return ret()._print0(sb,visited);
sb.append("Stop[ ");
for( Node ret : _inputs )
ret._print0(sb, visited).append(" ");
@@ -34,10 +32,15 @@ public class StopNode extends CFGNode {
@Override public boolean blockHead() { return true; }
+
+ public CFGNode ctrl() { return (CFGNode)in(0); }
+ public Node mem () { return in(1); }
+ public Node expr() { return in(2); }
+
// If a single Return, return it.
// Otherwise, null because ambiguous.
public ReturnNode ret() {
- return nIns()==1 ? (ReturnNode)in(0) : null;
+ return nIns()==4 && in(3) instanceof ReturnNode ret ? ret : null;
}
@Override
@@ -48,8 +51,8 @@ public class StopNode extends CFGNode {
@Override
public Node idealize() {
int len = nIns();
- for( int i=0; i<nIns(); i++ )
- if( in(i)._type==Type.XCONTROL )
+ for( int i=3; i<nIns(); i++ )
+ if( ((ReturnNode)in(i)).fun()==null )
delDef(i--);
if( len != nIns() ) return this;
return null;
@@ -59,28 +62,16 @@ public class StopNode extends CFGNode {
if( _idepth!=0 ) return _idepth;
int d=0;
for( Node n : _inputs )
- if( n!=null )
- d = Math.max(d,((CFGNode)n).idepth()+1);
+ if( n instanceof CFGNode cfg )
+ d = Math.max(d,cfg.idepth()+1);
return _idepth=d;
}
- @Override public CFGNode idom(Node dep) { return null; }
- public Node addReturn(Node node) {
- return addDef(node);
- }
-
- public StopNode iterate( ) { return IterPeeps.iterate(this).typeCheck().GCM(false); }
- public StopNode iterate(boolean show) { return IterPeeps.iterate(this).typeCheck().GCM(show ); }
- StopNode typeCheck() {
- String err = walk( Node::err );
- if( err != null ) throw new RuntimeException(err);
- return this;
- }
- StopNode GCM(boolean show) {
- Parser.START.buildLoopTree(this);
- if( show )
- System.out.println(new GraphVisualizer().generateDotOutput(this,null,null));
- GlobalCodeMotion.buildCFG(this);
- return this;
+ // Add a new function exit point. Validates Parsers function borders, then
+ // hands off to the guaranteed return.
+ public void addReturn(Node ctrl, Node mem, Node rez, FunNode fun) {
+ ReturnNode ret = (ReturnNode)_inputs.last();
+ assert ret.fun()==fun && ret.inProgress();
+ ret.addReturn(ctrl,mem,rez);
}
}
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/StoreNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/StoreNode.java
index 5bc88aa5..39a2dc2c 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/StoreNode.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/StoreNode.java
@@ -111,7 +111,7 @@ public class StoreNode extends MemOpNode {
}
@Override
- String err() {
+ public String err() {
String err = super.err();
if( err != null ) return err;
TypeMemPtr tmp = (TypeMemPtr)ptr()._type;
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/XorNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/XorNode.java
index 191933f9..c140ba83 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/XorNode.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/XorNode.java
@@ -57,7 +57,7 @@ public class XorNode extends Node {
return null;
}
@Override Node copy(Node lhs, Node rhs) { return new XorNode(lhs,rhs); }
- @Override String err() {
+ @Override public String err() {
if( !(in(1)._type instanceof TypeInteger) ) return "Cannot '^' " + in(1)._type;
if( !(in(2)._type instanceof TypeInteger) ) return "Cannot '^' " + in(2)._type;
return null;
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java b/chapter18/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java
index f1a16de4..6acd6798 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java
@@ -20,21 +20,25 @@ import java.util.HashMap;
public class TypeFunPtr extends TypeNil {
// A TypeFunPtr is Signature and a set of functions.
public final TypeTuple _sig;
+ public final Type _ret;
// Cheesy easy implementation for a small set; 1 bit per unique function
// within the TypeTuple. Can be upgraded to a BitSet for larger classes of
- // functions.
- private final long _fidxs; // 64 unique functions per signature
+ // functions. Negative means "these 63 concrete bits plus infinite unknown more"
+ private final long _fidxs; // 63 unique functions per signature
+ public String _name; // Optional debug function name; only for named single function
- private TypeFunPtr(byte nil, TypeTuple sig, long fidxs) {
+ private TypeFunPtr(byte nil, TypeTuple sig, Type ret, long fidxs) {
super(TFUNPTR,nil);
assert sig != null;
_sig = sig;
+ _ret = ret;
_fidxs = fidxs;
}
- static TypeFunPtr make( byte nil, TypeTuple sig, long fidxs ) { return new TypeFunPtr(nil,sig,fidxs).intern(); }
- public static TypeFunPtr make( boolean nil, TypeTuple sig ) { return make((byte)(nil ? 3 : 2),sig,-1); }
- @Override TypeFunPtr makeFrom( byte nil ) { return nil==_nil ? this : make(nil,_sig,_fidxs); }
+ static TypeFunPtr make( byte nil, TypeTuple sig, Type ret, long fidxs ) { return new TypeFunPtr(nil,sig,ret,fidxs).intern(); }
+ public static TypeFunPtr make( boolean nil, TypeTuple sig, Type ret ) { return make((byte)(nil ? 3 : 2),sig,ret,-1); }
+ @Override TypeFunPtr makeFrom( byte nil ) { return nil==_nil ? this : make(nil,_sig,_ret,_fidxs); }
+ public TypeFunPtr makeFrom( int fidx ) { return make(_nil,_sig,_ret,1L<<fidx); }
// Compute "function indices": FIDX
private static final HashMap<TypeTuple,Integer> FIDXS = new HashMap<>();
@@ -45,42 +49,51 @@ public class TypeFunPtr extends TypeNil {
assert fidx<64; // TODO: need a larger FIDX space
return fidx; // Return
}
- public static TypeFunPtr makeFun( TypeTuple sig ) {
- return make((byte)2,sig,1L<<nextFIDX(sig));
+ public static TypeFunPtr makeFun( TypeTuple sig, Type ret ) {
+ return make((byte)2,sig,ret,1L<<nextFIDX(sig));
}
- public static TypeFunPtr BOT = make((byte)3,TypeTuple.SIGBOT,-1);
- public static TypeFunPtr TEST = make((byte)2,TypeTuple.SIGTEST,1);
- public static TypeFunPtr TEST0 = make((byte)3,TypeTuple.SIGTEST,3);
- public static void gather(ArrayList<Type> ts) { ts.add(TEST); ts.add(TEST0); ts.add(BOT); }
+ public static TypeFunPtr BOT = make((byte)3,TypeTuple.BOT,Type.BOTTOM,-1);
+ public static TypeFunPtr TEST = make((byte)2,TypeTuple.TEST,TypeInteger.BOT,1);
+ public static TypeFunPtr TEST0 = make((byte)3,TypeTuple.TEST,TypeInteger.BOT,3);
+ public static TypeFunPtr MAIN = makeFun(TypeTuple.MAIN,Type.BOTTOM);
+ public static void gather(ArrayList<Type> ts) { ts.add(TEST); ts.add(TEST0); ts.add(BOT); ts.add(MAIN); }
@Override
Type xmeet(Type t) {
TypeFunPtr that = (TypeFunPtr) t;
- return TypeFunPtr.make(xmeet0(that),(TypeTuple)_sig.meet(that._sig), _fidxs | that._fidxs);
+ return TypeFunPtr.make(xmeet0(that),(TypeTuple)_sig.meet(that._sig), _ret.meet(that._ret),_fidxs | that._fidxs);
}
@Override
- public TypeFunPtr dual() { return TypeFunPtr.make(dual0(), _sig.dual(), ~_fidxs); }
+ public TypeFunPtr dual() { return TypeFunPtr.make(dual0(), _sig.dual(), _ret.dual(), ~_fidxs); }
// RHS is NIL
- @Override public Type meet0() { return _nil==3 ? this : make((byte)3,_sig,_fidxs); }
+ @Override public Type meet0() { return _nil==3 ? this : make((byte)3,_sig,_ret,_fidxs); }
@Override public TypeFunPtr glb() { throw Utils.TODO(); }
- @Override public boolean isConstant() { return Long.bitCount(_fidxs)==1; }
+ @Override public boolean isConstant() { return _nil==2 && Long.bitCount(_fidxs)==1; }
@Override public int log_size() { return 2; } // (1<<2)==4-byte pointers
+ public Type arg(int i) { return _sig._types[i]; }
+ public long fidxs() { return _fidxs; }
+
@Override
- int hash() { return Utils.fold(_sig.hashCode() ^ _fidxs ^ super.hash()); }
+ int hash() { return Utils.fold(_sig.hashCode() ^ _ret.hashCode() ^ _fidxs ^ super.hash()); }
@Override
boolean eq(Type t) {
TypeFunPtr ptr = (TypeFunPtr)t; // Invariant
- return _sig == ptr._sig && _fidxs == ptr._fidxs && super.eq(ptr);
+ return _sig == ptr._sig && _ret == ptr._ret && _fidxs == ptr._fidxs && super.eq(ptr);
}
+ public void setName(String name) {
+ assert _name==null || _name.equals(name);
+ assert _fidxs > 0 && Long.bitCount(_fidxs) == 1;
+ _name = name;
+ }
@Override public String str() { return print(new SB()).toString(); }
@Override public SB print(SB sb) { return _print(sb,false); }
@@ -88,15 +101,22 @@ public class TypeFunPtr extends TypeNil {
private static SB _print(SB sb, boolean g, Type t) { return g ? t.gprint(sb) : t.print(sb); }
private SB _print(SB sb, boolean g) {
sb.p(x()).p("{ ");
- for( int i=1; i<_sig._types.length; i++ )
- _print(sb,g,_sig._types[i]).p(" ");
- _print(sb.p("-> "),g,_sig._types[0]).p(" #");
- long fidxs = isHigh() ? ~_fidxs : _fidxs;
- String fidx = fidxs==0 ? ""
- : Long.bitCount(fidxs) == 1 ? ""+Long.numberOfTrailingZeros(fidxs)
- : fidxs == -1 ? "ALL"
- : "b"+Long.toBinaryString(fidxs); // Just some function bits
- return sb.p(fidx).p("}").p(q());
+ if( _name!=null ) sb.p(_name);
+ else {
+ for( Type t : _sig._types )
+ _print(sb,g,t).p(" ");
+ _print(sb.p("-> "),g,_ret).p(" #");
+ long fidxs = isHigh() ? ~_fidxs : _fidxs;
+ String fidx = fidxs==0 ? ""
+ : Long.bitCount(fidxs) == 1 ? ""+Long.numberOfTrailingZeros(fidxs)
+ : fidxs == -1 ? "ALL"
+ : "b"+Long.toBinaryString(fidxs); // Just some function bits
+ sb.p(fidx);
+ }
+ return sb.p("}").p(q());
}
+ // Usage: for( long fidxs=fidxs(); fidxs!=0; fidxs=nextFIDX(fidxs) { int fidxs = Long.numberOfTrailingZeros(fidxs); ... }
+ public static long nextFIDX(long fidxs) { return fidxs & (fidxs-1); }
+
}
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/type/TypeTuple.java b/chapter18/src/main/java/com/seaofnodes/simple/type/TypeTuple.java
index be4c18b1..6d3a2b69 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/type/TypeTuple.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/type/TypeTuple.java
@@ -10,20 +10,28 @@ public class TypeTuple extends Type {
private TypeTuple(Type[] types) { super(TTUPLE); _types = types; }
public static TypeTuple make(Type... types) { return new TypeTuple(types).intern(); }
- private static final TypeTuple TEST = make(TypeInteger.BOT,TypeMemPtr.TEST);
- public static final TypeTuple START = make(Type.CONTROL,TypeMem.TOP,TypeInteger.BOT);
- public static final TypeTuple SIGTEST = make(TypeInteger.BOT,TypeInteger.BOT);
- public static final TypeTuple SIGBOT = make(Type.BOTTOM);
- public static final TypeTuple SIGTOP = SIGBOT.dual();
- public static void gather(ArrayList<Type> ts) { ts.add(TEST); ts.add(START); ts.add(SIGTEST); }
+ public static final TypeTuple BOT = new TypeTuple(new Type[0]).intern();
+ public static final TypeTuple TOP = new TypeTuple(null).intern();
+
+ public static final TypeTuple TEST = make(TypeInteger.BOT,TypeMemPtr.TEST);
+ public static final TypeTuple START= make(Type.CONTROL,TypeMem.TOP,TypeInteger.BOT);
+ public static final TypeTuple MAIN = make(TypeInteger.BOT);
+ public static final TypeTuple RET = make(Type.CONTROL,TypeMem.BOT,Type.BOTTOM);
+
+ public static final TypeTuple IF_BOTH = make(new Type[]{Type. CONTROL,Type. CONTROL});
+ public static final TypeTuple IF_NEITHER = make(new Type[]{Type.XCONTROL,Type.XCONTROL});
+ public static final TypeTuple IF_TRUE = make(new Type[]{Type. CONTROL,Type.XCONTROL});
+ public static final TypeTuple IF_FALSE = make(new Type[]{Type.XCONTROL,Type. CONTROL});
+
+ public static void gather(ArrayList<Type> ts) { ts.add(BOT); ts.add(TEST); ts.add(START); ts.add(MAIN); ts.add(IF_TRUE); }
@Override
Type xmeet(Type other) {
TypeTuple tt = (TypeTuple)other; // contract from xmeet
- if( this==SIGTOP ) return other;
- if( tt ==SIGTOP ) return this ;
+ if( this==TOP ) return other;
+ if( tt ==TOP ) return this ;
if( _types.length != tt._types.length )
- return SIGBOT;
+ return BOT;
Type[] ts = new Type[_types.length];
for( int i=0; i<_types.length; i++ )
ts[i] = _types[i].meet(tt._types[i]);
@@ -31,6 +39,8 @@ public class TypeTuple extends Type {
}
@Override public TypeTuple dual() {
+ if( this==TOP ) return BOT;
+ if( this==BOT ) return TOP;
Type[] ts = new Type[_types.length];
for( int i=0; i<_types.length; i++ )
ts[i] = _types[i].dual();
@@ -45,41 +55,37 @@ public class TypeTuple extends Type {
return make(ts);
}
+ @Override public String str() { return print(new SB()).toString(); }
+
@Override public SB print(SB sb) {
+ if( this==TOP ) return sb.p("[TOP]");
+ if( this==BOT ) return sb.p("[BOT]");
sb.p("[ ");
for( Type t : _types )
t.print(sb).p(", ");
return sb.unchar(2).p("]");
}
@Override public SB gprint(SB sb) {
+ if( this==TOP ) return sb.p("[TOP]");
+ if( this==BOT ) return sb.p("[BOT]");
sb.p("[ ");
for( Type t : _types )
t.gprint(sb).p(", ");
return sb.unchar(2).p("]");
}
- @Override public String str() {
- SB sb = new SB().p("[ ");
- for( Type t : _types )
- sb.p(t.str()).p(", ");
- return sb.unchar(2).p("]").toString();
- }
-
- public static final TypeTuple IF_BOTH = make(new Type[]{Type. CONTROL,Type. CONTROL});
- public static final TypeTuple IF_NEITHER = make(new Type[]{Type.XCONTROL,Type.XCONTROL});
- public static final TypeTuple IF_TRUE = make(new Type[]{Type. CONTROL,Type.XCONTROL});
- public static final TypeTuple IF_FALSE = make(new Type[]{Type.XCONTROL,Type. CONTROL});
-
@Override
int hash() {
int sum = 0;
- for( Type type : _types ) sum ^= type.hashCode();
+ if( _types!=null ) for( Type type : _types ) sum ^= type.hashCode();
return sum;
}
@Override
boolean eq( Type t ) {
TypeTuple tt = (TypeTuple)t; // Contract
+ if( _types==null && tt._types==null ) return true;
+ if( _types==null || tt._types==null ) return false;
if( _types.length != tt._types.length ) return false;
for( int i=0; i<_types.length; i++ )
if( _types[i]!=tt._types[i] )