001/*
002 * Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved.
003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004 *
005 * This code is free software; you can redistribute it and/or modify it
006 * under the terms of the GNU General Public License version 2 only, as
007 * published by the Free Software Foundation.
008 *
009 * This code is distributed in the hope that it will be useful, but WITHOUT
010 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
011 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
012 * version 2 for more details (a copy is included in the LICENSE file that
013 * accompanied this code).
014 *
015 * You should have received a copy of the GNU General Public License version
016 * 2 along with this work; if not, write to the Free Software Foundation,
017 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
018 *
019 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
020 * or visit www.oracle.com if you need additional information or have any
021 * questions.
022 */
023package com.oracle.graal.phases.common;
024
025import java.util.*;
026
027import com.oracle.graal.debug.*;
028import jdk.internal.jvmci.meta.*;
029
030import com.oracle.graal.graph.*;
031import com.oracle.graal.nodeinfo.*;
032import com.oracle.graal.nodes.*;
033import com.oracle.graal.nodes.calc.*;
034import com.oracle.graal.nodes.extended.*;
035import com.oracle.graal.nodes.util.*;
036import com.oracle.graal.phases.*;
037import com.oracle.graal.phases.tiers.*;
038
039public class UseTrappingNullChecksPhase extends BasePhase<LowTierContext> {
040
041    private static final DebugMetric metricTrappingNullCheck = Debug.metric("TrappingNullCheck");
042    private static final DebugMetric metricTrappingNullCheckUnreached = Debug.metric("TrappingNullCheckUnreached");
043    private static final DebugMetric metricTrappingNullCheckDynamicDeoptimize = Debug.metric("TrappingNullCheckDynamicDeoptimize");
044
045    @Override
046    protected void run(StructuredGraph graph, LowTierContext context) {
047        if (context.getTarget().implicitNullCheckLimit <= 0) {
048            return;
049        }
050        assert graph.getGuardsStage().areFrameStatesAtDeopts();
051
052        for (DeoptimizeNode deopt : graph.getNodes(DeoptimizeNode.TYPE)) {
053            tryUseTrappingNullCheck(deopt, deopt.predecessor(), deopt.reason(), deopt.getSpeculation());
054        }
055        for (DynamicDeoptimizeNode deopt : graph.getNodes(DynamicDeoptimizeNode.TYPE)) {
056            tryUseTrappingNullCheck(context.getMetaAccess(), deopt);
057        }
058    }
059
060    private static void tryUseTrappingNullCheck(MetaAccessProvider metaAccessProvider, DynamicDeoptimizeNode deopt) {
061        Node predecessor = deopt.predecessor();
062        if (predecessor instanceof AbstractMergeNode) {
063            AbstractMergeNode merge = (AbstractMergeNode) predecessor;
064
065            // Process each predecessor at the merge, unpacking the reasons and speculations as
066            // needed.
067            ValueNode reason = deopt.getActionAndReason();
068            ValuePhiNode reasonPhi = null;
069            List<ValueNode> reasons = null;
070            int expectedPhis = 0;
071
072            if (reason instanceof ValuePhiNode) {
073                reasonPhi = (ValuePhiNode) reason;
074                if (reasonPhi.merge() != merge) {
075                    return;
076                }
077                reasons = reasonPhi.values().snapshot();
078                expectedPhis++;
079            } else if (!reason.isConstant()) {
080                return;
081            }
082
083            ValueNode speculation = deopt.getSpeculation();
084            ValuePhiNode speculationPhi = null;
085            List<ValueNode> speculations = null;
086            if (speculation instanceof ValuePhiNode) {
087                speculationPhi = (ValuePhiNode) speculation;
088                if (speculationPhi.merge() != merge) {
089                    return;
090                }
091                speculations = speculationPhi.values().snapshot();
092                expectedPhis++;
093            }
094
095            if (merge.phis().count() != expectedPhis) {
096                return;
097            }
098
099            int index = 0;
100            for (AbstractEndNode end : merge.cfgPredecessors().snapshot()) {
101                ValueNode thisReason = reasons != null ? reasons.get(index) : reason;
102                ValueNode thisSpeculation = speculations != null ? speculations.get(index++) : speculation;
103                if (!thisReason.isConstant() || !thisSpeculation.isConstant() || !thisSpeculation.asConstant().equals(JavaConstant.NULL_POINTER)) {
104                    continue;
105                }
106                DeoptimizationReason deoptimizationReason = metaAccessProvider.decodeDeoptReason(thisReason.asJavaConstant());
107                tryUseTrappingNullCheck(deopt, end.predecessor(), deoptimizationReason, null);
108            }
109        }
110    }
111
112    private static void tryUseTrappingNullCheck(AbstractDeoptimizeNode deopt, Node predecessor, DeoptimizationReason deoptimizationReason, JavaConstant speculation) {
113        if (deoptimizationReason != DeoptimizationReason.NullCheckException && deoptimizationReason != DeoptimizationReason.UnreachedCode) {
114            return;
115        }
116        if (speculation != null && !speculation.equals(JavaConstant.NULL_POINTER)) {
117            return;
118        }
119        if (predecessor instanceof AbstractMergeNode) {
120            AbstractMergeNode merge = (AbstractMergeNode) predecessor;
121            if (merge.phis().isEmpty()) {
122                for (AbstractEndNode end : merge.cfgPredecessors().snapshot()) {
123                    checkPredecessor(deopt, end.predecessor(), deoptimizationReason);
124                }
125            }
126        } else if (predecessor instanceof AbstractBeginNode) {
127            checkPredecessor(deopt, predecessor, deoptimizationReason);
128        }
129    }
130
131    private static void checkPredecessor(AbstractDeoptimizeNode deopt, Node predecessor, DeoptimizationReason deoptimizationReason) {
132        Node current = predecessor;
133        AbstractBeginNode branch = null;
134        while (current instanceof AbstractBeginNode) {
135            branch = (AbstractBeginNode) current;
136            if (branch.anchored().isNotEmpty()) {
137                // some input of the deopt framestate is anchored to this branch
138                return;
139            }
140            current = current.predecessor();
141        }
142        if (current instanceof IfNode) {
143            IfNode ifNode = (IfNode) current;
144            if (branch != ifNode.trueSuccessor()) {
145                return;
146            }
147            LogicNode condition = ifNode.condition();
148            if (condition instanceof IsNullNode) {
149                replaceWithTrappingNullCheck(deopt, ifNode, condition, deoptimizationReason);
150            }
151        }
152    }
153
154    private static void replaceWithTrappingNullCheck(AbstractDeoptimizeNode deopt, IfNode ifNode, LogicNode condition, DeoptimizationReason deoptimizationReason) {
155        metricTrappingNullCheck.increment();
156        if (deopt instanceof DynamicDeoptimizeNode) {
157            metricTrappingNullCheckDynamicDeoptimize.increment();
158        }
159        if (deoptimizationReason == DeoptimizationReason.UnreachedCode) {
160            metricTrappingNullCheckUnreached.increment();
161        }
162        IsNullNode isNullNode = (IsNullNode) condition;
163        AbstractBeginNode nonTrappingContinuation = ifNode.falseSuccessor();
164        AbstractBeginNode trappingContinuation = ifNode.trueSuccessor();
165        NullCheckNode trappingNullCheck = deopt.graph().add(new NullCheckNode(isNullNode.getValue()));
166        trappingNullCheck.setStateBefore(deopt.stateBefore());
167        deopt.graph().replaceSplit(ifNode, trappingNullCheck, nonTrappingContinuation);
168
169        /*
170         * We now have the pattern NullCheck/BeginNode/... It's possible some node is using the
171         * BeginNode as a guard input, so replace guard users of the Begin with the NullCheck and
172         * then remove the Begin from the graph.
173         */
174        nonTrappingContinuation.replaceAtUsages(InputType.Guard, trappingNullCheck);
175        if (nonTrappingContinuation instanceof BeginNode) {
176            FixedNode next = nonTrappingContinuation.next();
177            nonTrappingContinuation.clearSuccessors();
178            trappingNullCheck.setNext(next);
179            nonTrappingContinuation.safeDelete();
180        } else {
181            trappingNullCheck.setNext(nonTrappingContinuation);
182        }
183
184        GraphUtil.killCFG(trappingContinuation);
185        if (isNullNode.hasNoUsages()) {
186            GraphUtil.killWithUnusedFloatingInputs(isNullNode);
187        }
188    }
189}