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