summaryrefslogtreecommitdiff
path: root/chapter07/src/main/java
diff options
context:
space:
mode:
Diffstat (limited to 'chapter07/src/main/java')
-rw-r--r--chapter07/src/main/java/com/seaofnodes/simple/node/SubNode.java19
1 files changed, 19 insertions, 0 deletions
diff --git a/chapter07/src/main/java/com/seaofnodes/simple/node/SubNode.java b/chapter07/src/main/java/com/seaofnodes/simple/node/SubNode.java
index 1ab17b04..421e659b 100644
--- a/chapter07/src/main/java/com/seaofnodes/simple/node/SubNode.java
+++ b/chapter07/src/main/java/com/seaofnodes/simple/node/SubNode.java
@@ -34,6 +34,25 @@ public class SubNode extends Node {
@Override
public Node idealize() {
+ Node lhs = in(1);
+ Node rhs = in(2);
+ Type t1 = lhs._type;
+ Type t2 = rhs._type;
+
+ // Keep invalid operands for type checking.
+ if( t1 instanceof TypeInteger x && t2 instanceof TypeInteger y ) {
+ if( y.isConstant() && y.value()==0 ) return lhs;
+ if( x.isConstant() && x.value()==0 ) return new MinusNode(rhs);
+ }
+
+ // x - (-y) is x+y
+ if( rhs instanceof MinusNode minus )
+ return new AddNode(lhs,minus.in(1));
+
+ // (-x) - y is -(x+y)
+ if( lhs instanceof MinusNode minus )
+ return new MinusNode(new AddNode(minus.in(1),rhs).peephole());
+
return null;
}