1 /*
   2  * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 package org.graalvm.compiler.nodes.calc;
  24 
  25 import static org.graalvm.compiler.nodeinfo.NodeCycles.CYCLES_1;
  26 import static org.graalvm.compiler.nodeinfo.NodeSize.SIZE_1;
  27 
  28 import java.io.Serializable;
  29 import java.util.function.Function;
  30 
  31 import org.graalvm.compiler.core.common.type.ArithmeticOpTable;
  32 import org.graalvm.compiler.core.common.type.ArithmeticOpTable.BinaryOp;
  33 import org.graalvm.compiler.core.common.type.Stamp;
  34 import org.graalvm.compiler.debug.GraalError;
  35 import org.graalvm.compiler.graph.Graph;
  36 import org.graalvm.compiler.graph.Node;
  37 import org.graalvm.compiler.graph.NodeClass;
  38 import org.graalvm.compiler.graph.iterators.NodePredicate;
  39 import org.graalvm.compiler.graph.spi.Canonicalizable;
  40 import org.graalvm.compiler.graph.spi.CanonicalizerTool;
  41 import org.graalvm.compiler.nodeinfo.NodeInfo;
  42 import org.graalvm.compiler.nodes.ArithmeticOperation;
  43 import org.graalvm.compiler.nodes.ConstantNode;
  44 import org.graalvm.compiler.nodes.StructuredGraph;
  45 import org.graalvm.compiler.nodes.ValueNode;
  46 import org.graalvm.compiler.nodes.ValuePhiNode;
  47 import org.graalvm.compiler.nodes.spi.ArithmeticLIRLowerable;
  48 import org.graalvm.compiler.nodes.spi.NodeValueMap;
  49 
  50 import jdk.vm.ci.meta.Constant;
  51 
  52 @NodeInfo(cycles = CYCLES_1, size = SIZE_1)
  53 public abstract class BinaryArithmeticNode<OP> extends BinaryNode implements ArithmeticOperation, ArithmeticLIRLowerable, Canonicalizable.Binary<ValueNode> {
  54 
  55     @SuppressWarnings("rawtypes") public static final NodeClass<BinaryArithmeticNode> TYPE = NodeClass.create(BinaryArithmeticNode.class);
  56 
  57     protected interface SerializableBinaryFunction<T> extends Function<ArithmeticOpTable, BinaryOp<T>>, Serializable {
  58     }
  59 
  60     protected final SerializableBinaryFunction<OP> getOp;
  61 
  62     protected BinaryArithmeticNode(NodeClass<? extends BinaryArithmeticNode<OP>> c, SerializableBinaryFunction<OP> getOp, ValueNode x, ValueNode y) {
  63         super(c, getOp.apply(ArithmeticOpTable.forStamp(x.stamp())).foldStamp(x.stamp(), y.stamp()), x, y);
  64         this.getOp = getOp;
  65     }
  66 
  67     protected final BinaryOp<OP> getOp(ValueNode forX, ValueNode forY) {
  68         ArithmeticOpTable table = ArithmeticOpTable.forStamp(forX.stamp());
  69         assert table.equals(ArithmeticOpTable.forStamp(forY.stamp()));
  70         return getOp.apply(table);
  71     }
  72 
  73     @Override
  74     public final BinaryOp<OP> getArithmeticOp() {
  75         return getOp(getX(), getY());
  76     }
  77 
  78     public boolean isAssociative() {
  79         return getArithmeticOp().isAssociative();
  80     }
  81 
  82     @Override
  83     public ValueNode canonical(CanonicalizerTool tool, ValueNode forX, ValueNode forY) {
  84         ValueNode result = tryConstantFold(getOp(forX, forY), forX, forY, stamp());
  85         if (result != null) {
  86             return result;
  87         }
  88         return this;
  89     }
  90 
  91     public static <OP> ConstantNode tryConstantFold(BinaryOp<OP> op, ValueNode forX, ValueNode forY, Stamp stamp) {
  92         if (forX.isConstant() && forY.isConstant()) {
  93             Constant ret = op.foldConstant(forX.asConstant(), forY.asConstant());
  94             if (ret != null) {
  95                 return ConstantNode.forPrimitive(stamp, ret);
  96             }
  97         }
  98         return null;
  99     }
 100 
 101     @Override
 102     public Stamp foldStamp(Stamp stampX, Stamp stampY) {
 103         assert stampX.isCompatible(x.stamp()) && stampY.isCompatible(y.stamp());
 104         return getArithmeticOp().foldStamp(stampX, stampY);
 105     }
 106 
 107     public static ValueNode add(StructuredGraph graph, ValueNode v1, ValueNode v2) {
 108         return graph.addOrUniqueWithInputs(AddNode.create(v1, v2));
 109     }
 110 
 111     public static ValueNode add(ValueNode v1, ValueNode v2) {
 112         return AddNode.create(v1, v2);
 113     }
 114 
 115     public static ValueNode mul(StructuredGraph graph, ValueNode v1, ValueNode v2) {
 116         return graph.addOrUniqueWithInputs(MulNode.create(v1, v2));
 117     }
 118 
 119     public static ValueNode mul(ValueNode v1, ValueNode v2) {
 120         return MulNode.create(v1, v2);
 121     }
 122 
 123     public static ValueNode sub(StructuredGraph graph, ValueNode v1, ValueNode v2) {
 124         return graph.addOrUniqueWithInputs(SubNode.create(v1, v2));
 125     }
 126 
 127     public static ValueNode sub(ValueNode v1, ValueNode v2) {
 128         return SubNode.create(v1, v2);
 129     }
 130 
 131     private enum ReassociateMatch {
 132         x,
 133         y;
 134 
 135         public ValueNode getValue(BinaryNode binary) {
 136             switch (this) {
 137                 case x:
 138                     return binary.getX();
 139                 case y:
 140                     return binary.getY();
 141                 default:
 142                     throw GraalError.shouldNotReachHere();
 143             }
 144         }
 145 
 146         public ValueNode getOtherValue(BinaryNode binary) {
 147             switch (this) {
 148                 case x:
 149                     return binary.getY();
 150                 case y:
 151                     return binary.getX();
 152                 default:
 153                     throw GraalError.shouldNotReachHere();
 154             }
 155         }
 156     }
 157 
 158     private static ReassociateMatch findReassociate(BinaryNode binary, NodePredicate criterion) {
 159         boolean resultX = criterion.apply(binary.getX());
 160         boolean resultY = criterion.apply(binary.getY());
 161         if (resultX && !resultY) {
 162             return ReassociateMatch.x;
 163         }
 164         if (!resultX && resultY) {
 165             return ReassociateMatch.y;
 166         }
 167         return null;
 168     }
 169 
 170     //@formatter:off
 171     /*
 172      * In reassociate, complexity comes from the handling of IntegerSub (non commutative) which can
 173      * be mixed with IntegerAdd. It first tries to find m1, m2 which match the criterion :
 174      * (a o m2) o m1
 175      * (m2 o a) o m1
 176      * m1 o (a o m2)
 177      * m1 o (m2 o a)
 178      * It then produces 4 boolean for the -/+ cases:
 179      * invertA : should the final expression be like *-a (rather than a+*)
 180      * aSub : should the final expression be like a-* (rather than a+*)
 181      * invertM1 : should the final expression contain -m1
 182      * invertM2 : should the final expression contain -m2
 183      *
 184      */
 185     //@formatter:on
 186     /**
 187      * Tries to re-associate values which satisfy the criterion. For example with a constantness
 188      * criterion: {@code (a + 2) + 1 => a + (1 + 2)}
 189      * <p>
 190      * This method accepts only {@linkplain BinaryOp#isAssociative() associative} operations such as
 191      * +, -, *, &amp;, | and ^
 192      *
 193      * @param forY
 194      * @param forX
 195      */
 196     public static ValueNode reassociate(BinaryArithmeticNode<?> node, NodePredicate criterion, ValueNode forX, ValueNode forY) {
 197         assert node.getOp(forX, forY).isAssociative();
 198         ReassociateMatch match1 = findReassociate(node, criterion);
 199         if (match1 == null) {
 200             return node;
 201         }
 202         ValueNode otherValue = match1.getOtherValue(node);
 203         boolean addSub = false;
 204         boolean subAdd = false;
 205         if (otherValue.getClass() != node.getClass()) {
 206             if (node instanceof AddNode && otherValue instanceof SubNode) {
 207                 addSub = true;
 208             } else if (node instanceof SubNode && otherValue instanceof AddNode) {
 209                 subAdd = true;
 210             } else {
 211                 return node;
 212             }
 213         }
 214         BinaryNode other = (BinaryNode) otherValue;
 215         ReassociateMatch match2 = findReassociate(other, criterion);
 216         if (match2 == null) {
 217             return node;
 218         }
 219         boolean invertA = false;
 220         boolean aSub = false;
 221         boolean invertM1 = false;
 222         boolean invertM2 = false;
 223         if (addSub) {
 224             invertM2 = match2 == ReassociateMatch.y;
 225             invertA = !invertM2;
 226         } else if (subAdd) {
 227             invertA = invertM2 = match1 == ReassociateMatch.x;
 228             invertM1 = !invertM2;
 229         } else if (node instanceof SubNode && other instanceof SubNode) {
 230             invertA = match1 == ReassociateMatch.x ^ match2 == ReassociateMatch.x;
 231             aSub = match1 == ReassociateMatch.y && match2 == ReassociateMatch.y;
 232             invertM1 = match1 == ReassociateMatch.y && match2 == ReassociateMatch.x;
 233             invertM2 = match1 == ReassociateMatch.x && match2 == ReassociateMatch.x;
 234         }
 235         assert !(invertM1 && invertM2) && !(invertA && aSub);
 236         ValueNode m1 = match1.getValue(node);
 237         ValueNode m2 = match2.getValue(other);
 238         ValueNode a = match2.getOtherValue(other);
 239         if (node instanceof AddNode || node instanceof SubNode) {
 240             ValueNode associated;
 241             if (invertM1) {
 242                 associated = BinaryArithmeticNode.sub(m2, m1);
 243             } else if (invertM2) {
 244                 associated = BinaryArithmeticNode.sub(m1, m2);
 245             } else {
 246                 associated = BinaryArithmeticNode.add(m1, m2);
 247             }
 248             if (invertA) {
 249                 return BinaryArithmeticNode.sub(associated, a);
 250             }
 251             if (aSub) {
 252                 return BinaryArithmeticNode.sub(a, associated);
 253             }
 254             return BinaryArithmeticNode.add(a, associated);
 255         } else if (node instanceof MulNode) {
 256             return BinaryArithmeticNode.mul(a, AddNode.mul(m1, m2));
 257         } else if (node instanceof AndNode) {
 258             return new AndNode(a, new AndNode(m1, m2));
 259         } else if (node instanceof OrNode) {
 260             return new OrNode(a, new OrNode(m1, m2));
 261         } else if (node instanceof XorNode) {
 262             return new XorNode(a, new XorNode(m1, m2));
 263         } else {
 264             throw GraalError.shouldNotReachHere();
 265         }
 266     }
 267 
 268     /**
 269      * Ensure a canonical ordering of inputs for commutative nodes to improve GVN results. Order the
 270      * inputs by increasing {@link Node#id} and call {@link Graph#findDuplicate(Node)} on the node
 271      * if it's currently in a graph. It's assumed that if there was a constant on the left it's been
 272      * moved to the right by other code and that ordering is left alone.
 273      *
 274      * @return the original node or another node with the same input ordering
 275      */
 276     @SuppressWarnings("deprecation")
 277     public BinaryNode maybeCommuteInputs() {
 278         assert this instanceof BinaryCommutative;
 279         if (!y.isConstant() && (x.isConstant() || x.getId() > y.getId())) {
 280             ValueNode tmp = x;
 281             x = y;
 282             y = tmp;
 283             if (graph() != null) {
 284                 // See if this node already exists
 285                 BinaryNode duplicate = graph().findDuplicate(this);
 286                 if (duplicate != null) {
 287                     return duplicate;
 288                 }
 289             }
 290         }
 291         return this;
 292     }
 293 
 294     /**
 295      * Determines if it would be better to swap the inputs in order to produce better assembly code.
 296      * First we try to pick a value which is dead after this use. If both values are dead at this
 297      * use then we try pick an induction variable phi to encourage the phi to live in a single
 298      * register.
 299      *
 300      * @param nodeValueMap
 301      * @return true if inputs should be swapped, false otherwise
 302      */
 303     protected boolean shouldSwapInputs(NodeValueMap nodeValueMap) {
 304         final boolean xHasOtherUsages = getX().hasUsagesOtherThan(this, nodeValueMap);
 305         final boolean yHasOtherUsages = getY().hasUsagesOtherThan(this, nodeValueMap);
 306 
 307         if (!getY().isConstant() && !yHasOtherUsages) {
 308             if (xHasOtherUsages == yHasOtherUsages) {
 309                 return getY() instanceof ValuePhiNode && getY().inputs().contains(this);
 310             } else {
 311                 return true;
 312             }
 313         }
 314         return false;
 315     }
 316 
 317 }