1 /*
   2  * Copyright (c) 2011, 2018, 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.replacements.arraycopy;
  26 
  27 import static org.graalvm.compiler.nodes.extended.BranchProbabilityNode.FREQUENT_PROBABILITY;
  28 import static org.graalvm.compiler.nodes.extended.BranchProbabilityNode.LIKELY_PROBABILITY;
  29 import static org.graalvm.compiler.nodes.extended.BranchProbabilityNode.NOT_FREQUENT_PROBABILITY;
  30 import static org.graalvm.compiler.nodes.extended.BranchProbabilityNode.SLOW_PATH_PROBABILITY;
  31 import static org.graalvm.compiler.nodes.extended.BranchProbabilityNode.probability;
  32 
  33 import java.util.EnumMap;
  34 
  35 import jdk.internal.vm.compiler.collections.UnmodifiableEconomicMap;
  36 import org.graalvm.compiler.api.directives.GraalDirectives;
  37 import org.graalvm.compiler.api.replacements.Fold;
  38 import org.graalvm.compiler.api.replacements.Fold.InjectedParameter;
  39 import org.graalvm.compiler.api.replacements.Snippet;
  40 import org.graalvm.compiler.api.replacements.Snippet.ConstantParameter;
  41 import org.graalvm.compiler.api.replacements.SnippetReflectionProvider;
  42 import org.graalvm.compiler.debug.DebugHandlersFactory;
  43 import org.graalvm.compiler.debug.GraalError;
  44 import org.graalvm.compiler.graph.Node;
  45 import org.graalvm.compiler.nodes.CallTargetNode;
  46 import org.graalvm.compiler.nodes.DeoptimizeNode;
  47 import org.graalvm.compiler.nodes.InvokeNode;
  48 import org.graalvm.compiler.nodes.InvokeWithExceptionNode;
  49 import org.graalvm.compiler.nodes.NamedLocationIdentity;
  50 import org.graalvm.compiler.nodes.NodeView;
  51 import org.graalvm.compiler.nodes.PiNode;
  52 import org.graalvm.compiler.nodes.StructuredGraph;
  53 import org.graalvm.compiler.nodes.ValueNode;
  54 import org.graalvm.compiler.nodes.extended.RawLoadNode;
  55 import org.graalvm.compiler.nodes.extended.RawStoreNode;
  56 import org.graalvm.compiler.nodes.java.ArrayLengthNode;
  57 import org.graalvm.compiler.nodes.spi.LoweringTool;
  58 import org.graalvm.compiler.nodes.type.StampTool;
  59 import org.graalvm.compiler.nodes.util.GraphUtil;
  60 import org.graalvm.compiler.options.OptionValues;
  61 import org.graalvm.compiler.phases.util.Providers;
  62 import org.graalvm.compiler.replacements.ReplacementsUtil;
  63 import org.graalvm.compiler.replacements.SnippetCounter;
  64 import org.graalvm.compiler.replacements.SnippetCounter.Group;
  65 import org.graalvm.compiler.replacements.SnippetCounter.Group.Factory;
  66 import org.graalvm.compiler.replacements.SnippetIntegerHistogram;
  67 import org.graalvm.compiler.replacements.SnippetTemplate;
  68 import org.graalvm.compiler.replacements.SnippetTemplate.Arguments;
  69 import org.graalvm.compiler.replacements.SnippetTemplate.SnippetInfo;
  70 import org.graalvm.compiler.replacements.Snippets;
  71 import org.graalvm.compiler.replacements.nodes.BasicArrayCopyNode;
  72 import org.graalvm.compiler.replacements.nodes.ExplodeLoopNode;
  73 import org.graalvm.compiler.word.Word;
  74 import jdk.internal.vm.compiler.word.LocationIdentity;
  75 import jdk.internal.vm.compiler.word.Pointer;
  76 
  77 import jdk.vm.ci.code.TargetDescription;
  78 import jdk.vm.ci.meta.DeoptimizationAction;
  79 import jdk.vm.ci.meta.DeoptimizationReason;
  80 import jdk.vm.ci.meta.JavaKind;
  81 import jdk.vm.ci.meta.MetaAccessProvider;
  82 import jdk.vm.ci.meta.ResolvedJavaMethod;
  83 import jdk.vm.ci.meta.ResolvedJavaType;
  84 
  85 public abstract class ArrayCopySnippets implements Snippets {
  86 
  87     private enum ArrayCopyTypeCheck {
  88         UNDEFINED_ARRAY_TYPE_CHECK,
  89         // either we know that both objects are arrays and have the same type,
  90         // or we apply generic array copy snippet, which enforces type check
  91         NO_ARRAY_TYPE_CHECK,
  92         // can be used when we know that one of the objects is a primitive array
  93         HUB_BASED_ARRAY_TYPE_CHECK,
  94         // can be used when we know that one of the objects is an object array
  95         LAYOUT_HELPER_BASED_ARRAY_TYPE_CHECK
  96     }
  97 
  98     /** Marker value for the {@link InjectedParameter} injected parameter. */
  99     static final MetaAccessProvider INJECTED_META_ACCESS = null;
 100 
 101     public abstract Pointer loadHub(Object nonNullSrc);
 102 
 103     public abstract Pointer getDestElemClass(Pointer destKlass);
 104 
 105     public abstract Word getSuperCheckOffset(Pointer destElemKlass);
 106 
 107     public abstract int getReadLayoutHelper(Pointer srcHub);
 108 
 109     protected abstract int heapWordSize();
 110 
 111     @Snippet
 112     public void arraycopyZeroLengthSnippet(Object src, int srcPos, Object dest, int destPos, int length, @ConstantParameter ArrayCopyTypeCheck arrayTypeCheck,
 113                     @ConstantParameter Counters counters) {
 114         Object nonNullSrc = GraalDirectives.guardingNonNull(src);
 115         Object nonNullDest = GraalDirectives.guardingNonNull(dest);
 116         this.checkArrayTypes(nonNullSrc, nonNullDest, arrayTypeCheck);
 117         checkLimits(nonNullSrc, srcPos, nonNullDest, destPos, length, counters);
 118         counters.zeroLengthStaticCounter.inc();
 119     }
 120 
 121     @Snippet
 122     public void arraycopyExactSnippet(Object src, int srcPos, Object dest, int destPos, int length, @ConstantParameter ArrayCopyTypeCheck arrayTypeCheck,
 123                     @ConstantParameter JavaKind elementKind, @ConstantParameter SnippetCounter elementKindCounter, @ConstantParameter SnippetCounter elementKindCopiedCounter,
 124                     @ConstantParameter Counters counters) {
 125         Object nonNullSrc = GraalDirectives.guardingNonNull(src);
 126         Object nonNullDest = GraalDirectives.guardingNonNull(dest);
 127         checkArrayTypes(nonNullSrc, nonNullDest, arrayTypeCheck);
 128         checkLimits(nonNullSrc, srcPos, nonNullDest, destPos, length, counters);
 129         incrementLengthCounter(length, counters);
 130 
 131         elementKindCounter.inc();
 132         elementKindCopiedCounter.add(length);
 133         ArrayCopyCallNode.arraycopy(nonNullSrc, srcPos, nonNullDest, destPos, length, elementKind, heapWordSize());
 134     }
 135 
 136     @Snippet
 137     public void arraycopyUnrolledSnippet(Object src, int srcPos, Object dest, int destPos, int length, @ConstantParameter ArrayCopyTypeCheck arrayTypeCheck,
 138                     @ConstantParameter JavaKind elementKind, @ConstantParameter int unrolledLength, @ConstantParameter Counters counters) {
 139         Object nonNullSrc = GraalDirectives.guardingNonNull(src);
 140         Object nonNullDest = GraalDirectives.guardingNonNull(dest);
 141         checkArrayTypes(nonNullSrc, nonNullDest, arrayTypeCheck);
 142         checkLimits(nonNullSrc, srcPos, nonNullDest, destPos, length, counters);
 143         incrementLengthCounter(length, counters);
 144 
 145         unrolledArraycopyWork(nonNullSrc, srcPos, nonNullDest, destPos, unrolledLength, elementKind);
 146     }
 147 
 148     @Snippet
 149     public void arraycopyCheckcastSnippet(Object src, int srcPos, Object dest, int destPos, int length, @ConstantParameter ArrayCopyTypeCheck arrayTypeCheck,
 150                     @ConstantParameter Counters counters, @ConstantParameter SnippetInfo workSnippet, @ConstantParameter JavaKind elementKind) {
 151         Object nonNullSrc = GraalDirectives.guardingNonNull(src);
 152         Object nonNullDest = GraalDirectives.guardingNonNull(dest);
 153         checkArrayTypes(nonNullSrc, nonNullDest, arrayTypeCheck);
 154         checkLimits(nonNullSrc, srcPos, nonNullDest, destPos, length, counters);
 155         incrementLengthCounter(length, counters);
 156 
 157         ArrayCopyWithSlowPathNode.arraycopy(nonNullSrc, srcPos, nonNullDest, destPos, length, workSnippet, elementKind);
 158     }
 159 
 160     @Snippet
 161     public void arraycopyGenericSnippet(Object src, int srcPos, Object dest, int destPos, int length, @ConstantParameter ArrayCopyTypeCheck arrayTypeCheck, @ConstantParameter Counters counters,
 162                     @ConstantParameter SnippetInfo workSnippet, @ConstantParameter JavaKind elementKind) {
 163         Object nonNullSrc = GraalDirectives.guardingNonNull(src);
 164         Object nonNullDest = GraalDirectives.guardingNonNull(dest);
 165         checkArrayTypes(nonNullSrc, nonNullDest, arrayTypeCheck);
 166         checkLimits(nonNullSrc, srcPos, nonNullDest, destPos, length, counters);
 167         incrementLengthCounter(length, counters);
 168 
 169         ArrayCopyWithSlowPathNode.arraycopy(nonNullSrc, srcPos, nonNullDest, destPos, length, workSnippet, elementKind);
 170     }
 171 
 172     @Snippet
 173     public static void arraycopyNativeSnippet(Object src, int srcPos, Object dest, int destPos, int length, @ConstantParameter Counters counters) {
 174         // all checks are done in the native method, so no need to emit additional checks here
 175         incrementLengthCounter(length, counters);
 176         counters.systemArraycopyCounter.inc();
 177         counters.systemArraycopyCopiedCounter.add(length);
 178 
 179         System.arraycopy(src, srcPos, dest, destPos, length);
 180     }
 181 
 182     @Fold
 183     static LocationIdentity getArrayLocation(JavaKind kind) {
 184         return NamedLocationIdentity.getArrayLocation(kind);
 185     }
 186 
 187     private static void unrolledArraycopyWork(Object nonNullSrc, int srcPos, Object nonNullDest, int destPos, int length, JavaKind elementKind) {
 188         int scale = ReplacementsUtil.arrayIndexScale(INJECTED_META_ACCESS, elementKind);
 189         int arrayBaseOffset = ReplacementsUtil.getArrayBaseOffset(INJECTED_META_ACCESS, elementKind);
 190         LocationIdentity arrayLocation = getArrayLocation(elementKind);
 191 
 192         long sourceOffset = arrayBaseOffset + (long) srcPos * scale;
 193         long destOffset = arrayBaseOffset + (long) destPos * scale;
 194         long position = 0;
 195         long delta = scale;
 196         if (probability(NOT_FREQUENT_PROBABILITY, nonNullSrc == nonNullDest && srcPos < destPos)) {
 197             // bad aliased case so we need to copy the array from back to front
 198             position = (long) (length - 1) * scale;
 199             delta = -delta;
 200         }
 201 
 202         // the length was already checked before - we can emit unconditional instructions
 203         ExplodeLoopNode.explodeLoop();
 204         for (int iteration = 0; iteration < length; iteration++) {
 205             Object value = RawLoadNode.load(nonNullSrc, sourceOffset + position, elementKind, arrayLocation);
 206             RawStoreNode.storeObject(nonNullDest, destOffset + position, value, elementKind, arrayLocation, false);
 207             position += delta;
 208         }
 209     }
 210 
 211     @Snippet(allowPartialIntrinsicArgumentMismatch = true)
 212     public void checkcastArraycopyWithSlowPathWork(Object src, int srcPos, Object dest, int destPos, int length, @ConstantParameter Counters counters) {
 213         if (probability(FREQUENT_PROBABILITY, length > 0)) {
 214             Object nonNullSrc = PiNode.asNonNullObject(src);
 215             Object nonNullDest = PiNode.asNonNullObject(dest);
 216             Pointer srcKlass = loadHub(nonNullSrc);
 217             Pointer destKlass = loadHub(nonNullDest);
 218             if (probability(LIKELY_PROBABILITY, srcKlass == destKlass)) {
 219                 // no storecheck required.
 220                 counters.objectCheckcastSameTypeCounter.inc();
 221                 counters.objectCheckcastSameTypeCopiedCounter.add(length);
 222                 ArrayCopyCallNode.arraycopyObjectKillsAny(nonNullSrc, srcPos, nonNullDest, destPos, length, heapWordSize());
 223             } else {
 224                 Pointer destElemKlass = getDestElemClass(destKlass);
 225                 Word superCheckOffset = getSuperCheckOffset(destElemKlass);
 226 
 227                 counters.objectCheckcastDifferentTypeCounter.inc();
 228                 counters.objectCheckcastDifferentTypeCopiedCounter.add(length);
 229 
 230                 int copiedElements = CheckcastArrayCopyCallNode.checkcastArraycopy(nonNullSrc, srcPos, nonNullDest, destPos, length, superCheckOffset, destElemKlass, false);
 231                 if (probability(SLOW_PATH_PROBABILITY, copiedElements != 0)) {
 232                     /*
 233                      * the stub doesn't throw the ArrayStoreException, but returns the number of
 234                      * copied elements (xor'd with -1).
 235                      */
 236                     copiedElements ^= -1;
 237                     System.arraycopy(nonNullSrc, srcPos + copiedElements, nonNullDest, destPos + copiedElements, length - copiedElements);
 238                 }
 239             }
 240         }
 241     }
 242 
 243     @Snippet(allowPartialIntrinsicArgumentMismatch = true)
 244     public void genericArraycopyWithSlowPathWork(Object src, int srcPos, Object dest, int destPos, int length, @ConstantParameter Counters counters) {
 245         // The length > 0 check should not be placed here because generic array copy stub should
 246         // enforce type check. This is fine performance-wise because this snippet is rarely used.
 247         counters.genericArraycopyDifferentTypeCounter.inc();
 248         counters.genericArraycopyDifferentTypeCopiedCounter.add(length);
 249         int copiedElements = GenericArrayCopyCallNode.genericArraycopy(src, srcPos, dest, destPos, length);
 250         if (probability(SLOW_PATH_PROBABILITY, copiedElements != 0)) {
 251             /*
 252              * the stub doesn't throw the ArrayStoreException, but returns the number of copied
 253              * elements (xor'd with -1).
 254              */
 255             copiedElements ^= -1;
 256             System.arraycopy(src, srcPos + copiedElements, dest, destPos + copiedElements, length - copiedElements);
 257         }
 258     }
 259 
 260     private static void incrementLengthCounter(int length, Counters counters) {
 261         counters.lengthHistogram.inc(length);
 262     }
 263 
 264     private static void checkLimits(Object src, int srcPos, Object dest, int destPos, int length, Counters counters) {
 265         if (probability(SLOW_PATH_PROBABILITY, srcPos < 0) ||
 266                         probability(SLOW_PATH_PROBABILITY, destPos < 0) ||
 267                         probability(SLOW_PATH_PROBABILITY, length < 0) ||
 268                         probability(SLOW_PATH_PROBABILITY, srcPos > ArrayLengthNode.arrayLength(src) - length) ||
 269                         probability(SLOW_PATH_PROBABILITY, destPos > ArrayLengthNode.arrayLength(dest) - length)) {
 270             counters.checkAIOOBECounter.inc();
 271             DeoptimizeNode.deopt(DeoptimizationAction.None, DeoptimizationReason.RuntimeConstraint);
 272         }
 273         counters.checkSuccessCounter.inc();
 274     }
 275 
 276     private void checkArrayTypes(Object nonNullSrc, Object nonNullDest, ArrayCopyTypeCheck arrayTypeCheck) {
 277         if (arrayTypeCheck == ArrayCopyTypeCheck.NO_ARRAY_TYPE_CHECK) {
 278             // nothing to do
 279         } else if (arrayTypeCheck == ArrayCopyTypeCheck.HUB_BASED_ARRAY_TYPE_CHECK) {
 280             Pointer srcHub = loadHub(nonNullSrc);
 281             Pointer destHub = loadHub(nonNullDest);
 282             if (probability(SLOW_PATH_PROBABILITY, srcHub != destHub)) {
 283                 DeoptimizeNode.deopt(DeoptimizationAction.None, DeoptimizationReason.RuntimeConstraint);
 284             }
 285         } else if (arrayTypeCheck == ArrayCopyTypeCheck.LAYOUT_HELPER_BASED_ARRAY_TYPE_CHECK) {
 286             Pointer srcHub = loadHub(nonNullSrc);
 287             Pointer destHub = loadHub(nonNullDest);
 288             if (probability(SLOW_PATH_PROBABILITY, getReadLayoutHelper(srcHub) != getReadLayoutHelper(destHub))) {
 289                 DeoptimizeNode.deopt(DeoptimizationAction.None, DeoptimizationReason.RuntimeConstraint);
 290             }
 291         } else {
 292             ReplacementsUtil.staticAssert(false, "unknown array type check ", arrayTypeCheck);
 293         }
 294     }
 295 
 296     static class Counters {
 297         final SnippetCounter checkSuccessCounter;
 298         final SnippetCounter checkAIOOBECounter;
 299 
 300         final SnippetCounter zeroLengthStaticCounter;
 301         final SnippetIntegerHistogram lengthHistogram;
 302 
 303         final SnippetCounter systemArraycopyCounter;
 304         final SnippetCounter systemArraycopyCopiedCounter;
 305 
 306         final SnippetCounter genericArraycopyDifferentTypeCopiedCounter;
 307         final SnippetCounter genericArraycopyDifferentTypeCounter;
 308 
 309         final SnippetCounter objectCheckcastSameTypeCopiedCounter;
 310         final SnippetCounter objectCheckcastSameTypeCounter;
 311         final SnippetCounter objectCheckcastDifferentTypeCopiedCounter;
 312         final SnippetCounter objectCheckcastDifferentTypeCounter;
 313 
 314         final EnumMap<JavaKind, SnippetCounter> arraycopyCallCounters = new EnumMap<>(JavaKind.class);
 315         final EnumMap<JavaKind, SnippetCounter> arraycopyCallCopiedCounters = new EnumMap<>(JavaKind.class);
 316 
 317         Counters(SnippetCounter.Group.Factory factory) {
 318             final Group checkCounters = factory.createSnippetCounterGroup("System.arraycopy checkInputs");
 319             final Group callCounters = factory.createSnippetCounterGroup("System.arraycopy calls");
 320             final Group copiedElementsCounters = factory.createSnippetCounterGroup("System.arraycopy copied elements");
 321             final Group lengthCounters = factory.createSnippetCounterGroup("System.arraycopy with 0-length");
 322 
 323             checkSuccessCounter = new SnippetCounter(checkCounters, "checkSuccess", "checkSuccess");
 324             checkAIOOBECounter = new SnippetCounter(checkCounters, "checkAIOOBE", "checkAIOOBE");
 325 
 326             zeroLengthStaticCounter = new SnippetCounter(lengthCounters, "0-length copy static", "calls where the length is statically 0");
 327             lengthHistogram = new SnippetIntegerHistogram(lengthCounters, 2, "length", "length");
 328 
 329             systemArraycopyCounter = new SnippetCounter(callCounters, "native System.arraycopy", "JNI-based System.arraycopy call");
 330             systemArraycopyCopiedCounter = new SnippetCounter(copiedElementsCounters, "native System.arraycopy", "JNI-based System.arraycopy call");
 331 
 332             genericArraycopyDifferentTypeCounter = new SnippetCounter(callCounters, "generic[] stub", "generic arraycopy stub");
 333             genericArraycopyDifferentTypeCopiedCounter = new SnippetCounter(copiedElementsCounters, "generic[] stub", "generic arraycopy stub");
 334 
 335             objectCheckcastSameTypeCounter = new SnippetCounter(callCounters, "checkcast object[] (same-type)", "checkcast object[] stub but src.klass == dest.klass Object[] arrays");
 336             objectCheckcastSameTypeCopiedCounter = new SnippetCounter(copiedElementsCounters, "checkcast object[] (same-type)", "checkcast object[] stub but src.klass == dest.klass Object[] arrays");
 337             objectCheckcastDifferentTypeCounter = new SnippetCounter(callCounters, "checkcast object[] (store-check)", "checkcast object[] stub with store check");
 338             objectCheckcastDifferentTypeCopiedCounter = new SnippetCounter(copiedElementsCounters, "checkcast object[] (store-check)", "checkcast object[] stub with store check");
 339 
 340             createArraycopyCounter(JavaKind.Byte, callCounters, copiedElementsCounters);
 341             createArraycopyCounter(JavaKind.Boolean, callCounters, copiedElementsCounters);
 342             createArraycopyCounter(JavaKind.Char, callCounters, copiedElementsCounters);
 343             createArraycopyCounter(JavaKind.Short, callCounters, copiedElementsCounters);
 344             createArraycopyCounter(JavaKind.Int, callCounters, copiedElementsCounters);
 345             createArraycopyCounter(JavaKind.Long, callCounters, copiedElementsCounters);
 346             createArraycopyCounter(JavaKind.Float, callCounters, copiedElementsCounters);
 347             createArraycopyCounter(JavaKind.Double, callCounters, copiedElementsCounters);
 348             createArraycopyCounter(JavaKind.Object, callCounters, copiedElementsCounters);
 349         }
 350 
 351         void createArraycopyCounter(JavaKind kind, Group counters, Group copiedCounters) {
 352             arraycopyCallCounters.put(kind, new SnippetCounter(counters, kind + "[] stub", "arraycopy call for " + kind + "[] arrays"));
 353             arraycopyCallCopiedCounters.put(kind, new SnippetCounter(copiedCounters, kind + "[] stub", "arraycopy call for " + kind + "[] arrays"));
 354         }
 355     }
 356 
 357     public static class Templates extends SnippetTemplate.AbstractTemplates {
 358         private final SnippetInfo arraycopyGenericSnippet;
 359         private final SnippetInfo arraycopyUnrolledSnippet;
 360         private final SnippetInfo arraycopyExactSnippet;
 361         private final SnippetInfo arraycopyZeroLengthSnippet;
 362         private final SnippetInfo arraycopyCheckcastSnippet;
 363         private final SnippetInfo arraycopyNativeSnippet;
 364         private final SnippetInfo checkcastArraycopyWithSlowPathWork;
 365         private final SnippetInfo genericArraycopyWithSlowPathWork;
 366 
 367         private ResolvedJavaMethod originalArraycopy;
 368         private final Counters counters;
 369 
 370         public Templates(ArrayCopySnippets receiver, OptionValues options, Iterable<DebugHandlersFactory> factories, Factory factory, Providers providers,
 371                         SnippetReflectionProvider snippetReflection, TargetDescription target) {
 372             super(options, factories, providers, snippetReflection, target);
 373             this.counters = new Counters(factory);
 374 
 375             arraycopyGenericSnippet = snippet(receiver, "arraycopyGenericSnippet");
 376             arraycopyUnrolledSnippet = snippet(receiver, "arraycopyUnrolledSnippet");
 377             arraycopyExactSnippet = snippet(receiver, "arraycopyExactSnippet");
 378             arraycopyZeroLengthSnippet = snippet(receiver, "arraycopyZeroLengthSnippet");
 379             arraycopyCheckcastSnippet = snippet(receiver, "arraycopyCheckcastSnippet");
 380             arraycopyNativeSnippet = snippet(null, "arraycopyNativeSnippet");
 381             checkcastArraycopyWithSlowPathWork = snippet(receiver, "checkcastArraycopyWithSlowPathWork");
 382             genericArraycopyWithSlowPathWork = snippet(receiver, "genericArraycopyWithSlowPathWork");
 383         }
 384 
 385         protected SnippetInfo snippet(ArrayCopySnippets receiver, String methodName) {
 386             SnippetInfo info = snippet(ArrayCopySnippets.class, methodName, originalArraycopy(), receiver, LocationIdentity.any());
 387             return info;
 388         }
 389 
 390         public void lower(ArrayCopyNode arraycopy, LoweringTool tool) {
 391             JavaKind elementKind = selectComponentKind(arraycopy);
 392             SnippetInfo snippetInfo;
 393             ArrayCopyTypeCheck arrayTypeCheck;
 394 
 395             ResolvedJavaType srcType = StampTool.typeOrNull(arraycopy.getSource().stamp(NodeView.DEFAULT));
 396             ResolvedJavaType destType = StampTool.typeOrNull(arraycopy.getDestination().stamp(NodeView.DEFAULT));
 397             if (!canBeArray(srcType) || !canBeArray(destType)) {
 398                 // at least one of the objects is definitely not an array - use the native call
 399                 // right away as the copying will fail anyways
 400                 snippetInfo = arraycopyNativeSnippet;
 401                 arrayTypeCheck = ArrayCopyTypeCheck.UNDEFINED_ARRAY_TYPE_CHECK;
 402             } else {
 403                 ResolvedJavaType srcComponentType = srcType == null ? null : srcType.getComponentType();
 404                 ResolvedJavaType destComponentType = destType == null ? null : destType.getComponentType();
 405 
 406                 if (arraycopy.isExact()) {
 407                     // there is a sufficient type match - we don't need any additional type checks
 408                     snippetInfo = arraycopyExactSnippet;
 409                     arrayTypeCheck = ArrayCopyTypeCheck.NO_ARRAY_TYPE_CHECK;
 410                 } else if (srcComponentType == null && destComponentType == null) {
 411                     // we don't know anything about the types - use the generic copying
 412                     snippetInfo = arraycopyGenericSnippet;
 413                     // no need for additional type check to avoid duplicated work
 414                     arrayTypeCheck = ArrayCopyTypeCheck.NO_ARRAY_TYPE_CHECK;
 415                 } else if (srcComponentType != null && destComponentType != null) {
 416                     if (!srcComponentType.isPrimitive() && !destComponentType.isPrimitive()) {
 417                         // it depends on the array content if the copy succeeds - we need
 418                         // a type check for every store
 419                         snippetInfo = arraycopyCheckcastSnippet;
 420                         arrayTypeCheck = ArrayCopyTypeCheck.NO_ARRAY_TYPE_CHECK;
 421                     } else {
 422                         // one object is an object array, the other one is a primitive array.
 423                         // this copy will always fail - use the native call right away
 424                         assert !srcComponentType.equals(destComponentType) : "must be handled by arraycopy.isExact()";
 425                         snippetInfo = arraycopyNativeSnippet;
 426                         arrayTypeCheck = ArrayCopyTypeCheck.UNDEFINED_ARRAY_TYPE_CHECK;
 427                     }
 428                 } else {
 429                     ResolvedJavaType nonNullComponentType = srcComponentType != null ? srcComponentType : destComponentType;
 430                     if (nonNullComponentType.isPrimitive()) {
 431                         // one involved object is a primitive array - it is sufficient to directly
 432                         // compare the hub.
 433                         snippetInfo = arraycopyExactSnippet;
 434                         arrayTypeCheck = ArrayCopyTypeCheck.HUB_BASED_ARRAY_TYPE_CHECK;
 435                         elementKind = nonNullComponentType.getJavaKind();
 436                     } else {
 437                         // one involved object is an object array - the other array's element type
 438                         // may be primitive or object, hence we compare the layout helper.
 439                         snippetInfo = arraycopyCheckcastSnippet;
 440                         arrayTypeCheck = ArrayCopyTypeCheck.LAYOUT_HELPER_BASED_ARRAY_TYPE_CHECK;
 441                     }
 442                 }
 443             }
 444 
 445             // a few special cases that are easier to handle when all other variables already have a
 446             // value
 447             if (snippetInfo != arraycopyNativeSnippet && snippetInfo != arraycopyGenericSnippet && arraycopy.getLength().isConstant() && arraycopy.getLength().asJavaConstant().asLong() == 0) {
 448                 // Copying 0 element between object arrays with conflicting types will not throw an
 449                 // exception - once we pass the preliminary element type checks that we are not
 450                 // mixing arrays of different basic types, ArrayStoreException is only thrown when
 451                 // an *astore would have thrown it. Therefore, copying null between object arrays
 452                 // with conflicting types will also succeed (we do not optimize for such case here).
 453                 snippetInfo = arraycopyZeroLengthSnippet;
 454             } else if (snippetInfo == arraycopyExactSnippet && shouldUnroll(arraycopy.getLength())) {
 455                 snippetInfo = arraycopyUnrolledSnippet;
 456             }
 457 
 458             // create the snippet
 459             Arguments args = new Arguments(snippetInfo, arraycopy.graph().getGuardsStage(), tool.getLoweringStage());
 460             args.add("src", arraycopy.getSource());
 461             args.add("srcPos", arraycopy.getSourcePosition());
 462             args.add("dest", arraycopy.getDestination());
 463             args.add("destPos", arraycopy.getDestinationPosition());
 464             args.add("length", arraycopy.getLength());
 465             if (snippetInfo != arraycopyNativeSnippet) {
 466                 assert arrayTypeCheck != ArrayCopyTypeCheck.UNDEFINED_ARRAY_TYPE_CHECK;
 467                 args.addConst("arrayTypeCheck", arrayTypeCheck);
 468             }
 469             if (snippetInfo == arraycopyUnrolledSnippet) {
 470                 args.addConst("elementKind", elementKind != null ? elementKind : JavaKind.Illegal);
 471                 args.addConst("unrolledLength", arraycopy.getLength().asJavaConstant().asInt());
 472             }
 473             if (snippetInfo == arraycopyExactSnippet) {
 474                 assert elementKind != null;
 475                 args.addConst("elementKind", elementKind);
 476                 args.addConst("elementKindCounter", counters.arraycopyCallCounters.get(elementKind));
 477                 args.addConst("elementKindCopiedCounter", counters.arraycopyCallCopiedCounters.get(elementKind));
 478             }
 479             args.addConst("counters", counters);
 480             if (snippetInfo == arraycopyCheckcastSnippet) {
 481                 args.addConst("workSnippet", checkcastArraycopyWithSlowPathWork);
 482                 args.addConst("elementKind", JavaKind.Illegal);
 483             }
 484             if (snippetInfo == arraycopyGenericSnippet) {
 485                 args.addConst("workSnippet", genericArraycopyWithSlowPathWork);
 486                 args.addConst("elementKind", JavaKind.Illegal);
 487             }
 488 
 489             instantiate(args, arraycopy);
 490         }
 491 
 492         public void lower(ArrayCopyWithSlowPathNode arraycopy, LoweringTool tool) {
 493             StructuredGraph graph = arraycopy.graph();
 494             if (!graph.getGuardsStage().areFrameStatesAtDeopts()) {
 495                 // if an arraycopy contains a slow path, we can't lower it right away
 496                 return;
 497             }
 498 
 499             SnippetInfo snippetInfo = arraycopy.getSnippet();
 500             Arguments args = new Arguments(snippetInfo, graph.getGuardsStage(), tool.getLoweringStage());
 501             args.add("src", arraycopy.getSource());
 502             args.add("srcPos", arraycopy.getSourcePosition());
 503             args.add("dest", arraycopy.getDestination());
 504             args.add("destPos", arraycopy.getDestinationPosition());
 505             args.add("length", arraycopy.getLength());
 506             args.addConst("counters", counters);
 507             instantiate(args, arraycopy);
 508         }
 509 
 510         private static boolean canBeArray(ResolvedJavaType type) {
 511             return type == null || type.isJavaLangObject() || type.isArray();
 512         }
 513 
 514         public static JavaKind selectComponentKind(BasicArrayCopyNode arraycopy) {
 515             ResolvedJavaType srcType = StampTool.typeOrNull(arraycopy.getSource().stamp(NodeView.DEFAULT));
 516             ResolvedJavaType destType = StampTool.typeOrNull(arraycopy.getDestination().stamp(NodeView.DEFAULT));
 517 
 518             if (srcType == null || !srcType.isArray() || destType == null || !destType.isArray()) {
 519                 return null;
 520             }
 521             if (!destType.getComponentType().isAssignableFrom(srcType.getComponentType())) {
 522                 return null;
 523             }
 524             if (!arraycopy.isExact()) {
 525                 return null;
 526             }
 527             return srcType.getComponentType().getJavaKind();
 528         }
 529 
 530         private static boolean shouldUnroll(ValueNode length) {
 531             return length.isConstant() && length.asJavaConstant().asInt() <= 8 && length.asJavaConstant().asInt() != 0;
 532         }
 533 
 534         /**
 535          * Instantiate the snippet template and fix up the FrameState of any Invokes of
 536          * System.arraycopy and propagate the captured bci in the ArrayCopySlowPathNode.
 537          *
 538          * @param args
 539          * @param arraycopy
 540          */
 541         private void instantiate(Arguments args, BasicArrayCopyNode arraycopy) {
 542             StructuredGraph graph = arraycopy.graph();
 543             SnippetTemplate template = template(arraycopy, args);
 544             UnmodifiableEconomicMap<Node, Node> replacements = template.instantiate(providers.getMetaAccess(), arraycopy, SnippetTemplate.DEFAULT_REPLACER, args, false);
 545             for (Node originalNode : replacements.getKeys()) {
 546                 if (originalNode instanceof InvokeNode) {
 547                     InvokeNode invoke = (InvokeNode) replacements.get(originalNode);
 548                     assert invoke.asNode().graph() == graph;
 549                     CallTargetNode call = invoke.callTarget();
 550 
 551                     if (!call.targetMethod().equals(originalArraycopy)) {
 552                         throw new GraalError("unexpected invoke %s in snippet", call.targetMethod());
 553                     }
 554                     // Here we need to fix the bci of the invoke
 555                     InvokeNode newInvoke = invoke.replaceWithNewBci(arraycopy.getBci());
 556                     newInvoke.setStateDuring(null);
 557                     newInvoke.setStateAfter(null);
 558                     if (arraycopy.stateDuring() != null) {
 559                         newInvoke.setStateDuring(arraycopy.stateDuring());
 560                     } else {
 561                         assert arraycopy.stateAfter() != null : arraycopy;
 562                         newInvoke.setStateAfter(arraycopy.stateAfter());
 563                     }
 564                 } else if (originalNode instanceof InvokeWithExceptionNode) {
 565                     throw new GraalError("unexpected invoke with exception %s in snippet", originalNode);
 566                 } else if (originalNode instanceof ArrayCopyWithSlowPathNode) {
 567                     ArrayCopyWithSlowPathNode slowPath = (ArrayCopyWithSlowPathNode) replacements.get(originalNode);
 568                     assert arraycopy.stateAfter() != null : arraycopy;
 569                     assert slowPath.stateAfter() == arraycopy.stateAfter();
 570                     slowPath.setBci(arraycopy.getBci());
 571                 }
 572             }
 573             GraphUtil.killCFG(arraycopy);
 574         }
 575 
 576         private ResolvedJavaMethod originalArraycopy() throws GraalError {
 577             if (originalArraycopy == null) {
 578                 try {
 579                     originalArraycopy = findMethod(providers.getMetaAccess(), System.class, "arraycopy");
 580                 } catch (SecurityException e) {
 581                     throw new GraalError(e);
 582                 }
 583             }
 584             return originalArraycopy;
 585         }
 586     }
 587 }