1 /*
   2  * Copyright (c) 2012, 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.hotspot.replacements;
  26 
  27 import static jdk.vm.ci.code.MemoryBarriers.STORE_LOAD;
  28 import static org.graalvm.compiler.hotspot.GraalHotSpotVMConfig.INJECTED_VMCONFIG;
  29 import static org.graalvm.compiler.hotspot.GraalHotSpotVMConfigBase.INJECTED_METAACCESS;
  30 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.cardTableShift;
  31 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.dirtyCardValue;
  32 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.g1CardQueueBufferOffset;
  33 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.g1CardQueueIndexOffset;
  34 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.g1SATBQueueBufferOffset;
  35 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.g1SATBQueueIndexOffset;
  36 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.g1SATBQueueMarkingOffset;
  37 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.g1YoungCardValue;
  38 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.registerAsWord;
  39 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.verifyOop;
  40 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.verifyOops;
  41 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.wordSize;
  42 import static org.graalvm.compiler.nodes.extended.BranchProbabilityNode.FREQUENT_PROBABILITY;
  43 import static org.graalvm.compiler.nodes.extended.BranchProbabilityNode.LIKELY_PROBABILITY;
  44 import static org.graalvm.compiler.nodes.extended.BranchProbabilityNode.NOT_FREQUENT_PROBABILITY;
  45 import static org.graalvm.compiler.nodes.extended.BranchProbabilityNode.probability;
  46 import static org.graalvm.compiler.replacements.SnippetTemplate.DEFAULT_REPLACER;
  47 
  48 import org.graalvm.compiler.api.replacements.Snippet;
  49 import org.graalvm.compiler.api.replacements.Snippet.ConstantParameter;
  50 import org.graalvm.compiler.core.common.CompressEncoding;
  51 import org.graalvm.compiler.core.common.GraalOptions;
  52 import org.graalvm.compiler.core.common.spi.ForeignCallDescriptor;
  53 import org.graalvm.compiler.debug.DebugHandlersFactory;
  54 import org.graalvm.compiler.graph.Node.ConstantNodeParameter;
  55 import org.graalvm.compiler.graph.Node.NodeIntrinsic;
  56 import org.graalvm.compiler.hotspot.GraalHotSpotVMConfig;
  57 import org.graalvm.compiler.hotspot.meta.HotSpotProviders;
  58 import org.graalvm.compiler.hotspot.meta.HotSpotRegistersProvider;
  59 import org.graalvm.compiler.hotspot.nodes.G1ArrayRangePostWriteBarrier;
  60 import org.graalvm.compiler.hotspot.nodes.G1ArrayRangePreWriteBarrier;
  61 import org.graalvm.compiler.hotspot.nodes.G1PostWriteBarrier;
  62 import org.graalvm.compiler.hotspot.nodes.G1PreWriteBarrier;
  63 import org.graalvm.compiler.hotspot.nodes.G1ReferentFieldReadBarrier;
  64 import org.graalvm.compiler.hotspot.nodes.GraalHotSpotVMConfigNode;
  65 import org.graalvm.compiler.hotspot.nodes.HotSpotCompressionNode;
  66 import org.graalvm.compiler.hotspot.nodes.SerialArrayRangeWriteBarrier;
  67 import org.graalvm.compiler.hotspot.nodes.SerialWriteBarrier;
  68 import org.graalvm.compiler.hotspot.nodes.VMErrorNode;
  69 import org.graalvm.compiler.nodes.NamedLocationIdentity;
  70 import org.graalvm.compiler.nodes.NodeView;
  71 import org.graalvm.compiler.nodes.PiNode;
  72 import org.graalvm.compiler.nodes.StructuredGraph;
  73 import org.graalvm.compiler.nodes.ValueNode;
  74 import org.graalvm.compiler.nodes.extended.FixedValueAnchorNode;
  75 import org.graalvm.compiler.nodes.extended.ForeignCallNode;
  76 import org.graalvm.compiler.nodes.extended.MembarNode;
  77 import org.graalvm.compiler.nodes.extended.NullCheckNode;
  78 import org.graalvm.compiler.nodes.memory.HeapAccess.BarrierType;
  79 import org.graalvm.compiler.nodes.memory.address.AddressNode;
  80 import org.graalvm.compiler.nodes.memory.address.AddressNode.Address;
  81 import org.graalvm.compiler.nodes.memory.address.OffsetAddressNode;
  82 import org.graalvm.compiler.nodes.spi.LoweringTool;
  83 import org.graalvm.compiler.nodes.type.NarrowOopStamp;
  84 import org.graalvm.compiler.options.OptionValues;
  85 import org.graalvm.compiler.replacements.Log;
  86 import org.graalvm.compiler.replacements.ReplacementsUtil;
  87 import org.graalvm.compiler.replacements.SnippetCounter;
  88 import org.graalvm.compiler.replacements.SnippetCounter.Group;
  89 import org.graalvm.compiler.replacements.SnippetTemplate.AbstractTemplates;
  90 import org.graalvm.compiler.replacements.SnippetTemplate.Arguments;
  91 import org.graalvm.compiler.replacements.SnippetTemplate.SnippetInfo;
  92 import org.graalvm.compiler.replacements.Snippets;
  93 import org.graalvm.compiler.replacements.nodes.AssertionNode;
  94 import org.graalvm.compiler.replacements.nodes.DirectStoreNode;
  95 import org.graalvm.compiler.word.Word;
  96 import jdk.internal.vm.compiler.word.LocationIdentity;
  97 import jdk.internal.vm.compiler.word.Pointer;
  98 import jdk.internal.vm.compiler.word.UnsignedWord;
  99 import jdk.internal.vm.compiler.word.WordFactory;
 100 
 101 import jdk.vm.ci.code.Register;
 102 import jdk.vm.ci.code.TargetDescription;
 103 import jdk.vm.ci.meta.JavaKind;
 104 
 105 public class WriteBarrierSnippets implements Snippets {
 106 
 107     static class Counters {
 108         Counters(SnippetCounter.Group.Factory factory) {
 109             Group countersWriteBarriers = factory.createSnippetCounterGroup("WriteBarriers");
 110             serialWriteBarrierCounter = new SnippetCounter(countersWriteBarriers, "serialWriteBarrier", "Number of Serial Write Barriers");
 111             g1AttemptedPreWriteBarrierCounter = new SnippetCounter(countersWriteBarriers, "g1AttemptedPreWriteBarrier", "Number of attempted G1 Pre Write Barriers");
 112             g1EffectivePreWriteBarrierCounter = new SnippetCounter(countersWriteBarriers, "g1EffectivePreWriteBarrier", "Number of effective G1 Pre Write Barriers");
 113             g1ExecutedPreWriteBarrierCounter = new SnippetCounter(countersWriteBarriers, "g1ExecutedPreWriteBarrier", "Number of executed G1 Pre Write Barriers");
 114             g1AttemptedPostWriteBarrierCounter = new SnippetCounter(countersWriteBarriers, "g1AttemptedPostWriteBarrier", "Number of attempted G1 Post Write Barriers");
 115             g1EffectiveAfterXORPostWriteBarrierCounter = new SnippetCounter(countersWriteBarriers, "g1EffectiveAfterXORPostWriteBarrier",
 116                             "Number of effective G1 Post Write Barriers (after passing the XOR test)");
 117             g1EffectiveAfterNullPostWriteBarrierCounter = new SnippetCounter(countersWriteBarriers, "g1EffectiveAfterNullPostWriteBarrier",
 118                             "Number of effective G1 Post Write Barriers (after passing the NULL test)");
 119             g1ExecutedPostWriteBarrierCounter = new SnippetCounter(countersWriteBarriers, "g1ExecutedPostWriteBarrier", "Number of executed G1 Post Write Barriers");
 120 
 121         }
 122 
 123         final SnippetCounter serialWriteBarrierCounter;
 124         final SnippetCounter g1AttemptedPreWriteBarrierCounter;
 125         final SnippetCounter g1EffectivePreWriteBarrierCounter;
 126         final SnippetCounter g1ExecutedPreWriteBarrierCounter;
 127         final SnippetCounter g1AttemptedPostWriteBarrierCounter;
 128         final SnippetCounter g1EffectiveAfterXORPostWriteBarrierCounter;
 129         final SnippetCounter g1EffectiveAfterNullPostWriteBarrierCounter;
 130         final SnippetCounter g1ExecutedPostWriteBarrierCounter;
 131     }
 132 
 133     public static final LocationIdentity GC_CARD_LOCATION = NamedLocationIdentity.mutable("GC-Card");
 134     public static final LocationIdentity GC_LOG_LOCATION = NamedLocationIdentity.mutable("GC-Log");
 135     public static final LocationIdentity GC_INDEX_LOCATION = NamedLocationIdentity.mutable("GC-Index");
 136 
 137     private static void serialWriteBarrier(Pointer ptr, Counters counters) {
 138         counters.serialWriteBarrierCounter.inc();
 139         final long startAddress = GraalHotSpotVMConfigNode.cardTableAddress();
 140         Word base = (Word) ptr.unsignedShiftRight(cardTableShift(INJECTED_VMCONFIG));
 141         if (((int) startAddress) == startAddress && GraalHotSpotVMConfigNode.isCardTableAddressConstant()) {
 142             base.writeByte((int) startAddress, (byte) 0, GC_CARD_LOCATION);
 143         } else {
 144             base.writeByte(WordFactory.unsigned(startAddress), (byte) 0, GC_CARD_LOCATION);
 145         }
 146     }
 147 
 148     @Snippet
 149     public static void serialImpreciseWriteBarrier(Object object, @ConstantParameter boolean verifyBarrier, @ConstantParameter Counters counters) {
 150         if (verifyBarrier) {
 151             verifyNotArray(object);
 152         }
 153         serialWriteBarrier(Word.objectToTrackedPointer(object), counters);
 154     }
 155 
 156     @Snippet
 157     public static void serialPreciseWriteBarrier(Address address, @ConstantParameter Counters counters) {
 158         serialWriteBarrier(Word.fromAddress(address), counters);
 159     }
 160 
 161     @Snippet
 162     public static void serialArrayRangeWriteBarrier(Address address, int length, @ConstantParameter int elementStride) {
 163         if (length == 0) {
 164             return;
 165         }
 166         int cardShift = cardTableShift(INJECTED_VMCONFIG);
 167         final long cardStart = GraalHotSpotVMConfigNode.cardTableAddress();
 168         long start = getPointerToFirstArrayElement(address, length, elementStride) >>> cardShift;
 169         long end = getPointerToLastArrayElement(address, length, elementStride) >>> cardShift;
 170         long count = end - start + 1;
 171         while (count-- > 0) {
 172             DirectStoreNode.storeBoolean((start + cardStart) + count, false, JavaKind.Boolean);
 173         }
 174     }
 175 
 176     @Snippet
 177     public static void g1PreWriteBarrier(Address address, Object object, Object expectedObject, @ConstantParameter boolean doLoad, @ConstantParameter boolean nullCheck,
 178                     @ConstantParameter Register threadRegister, @ConstantParameter boolean trace, @ConstantParameter Counters counters) {
 179         if (nullCheck) {
 180             NullCheckNode.nullCheck(address);
 181         }
 182         Word thread = registerAsWord(threadRegister);
 183         verifyOop(object);
 184         Object fixedExpectedObject = FixedValueAnchorNode.getObject(expectedObject);
 185         Word field = Word.fromAddress(address);
 186         Pointer previousOop = Word.objectToTrackedPointer(fixedExpectedObject);
 187         byte markingValue = thread.readByte(g1SATBQueueMarkingOffset(INJECTED_VMCONFIG));
 188         int gcCycle = 0;
 189         if (trace) {
 190             Pointer gcTotalCollectionsAddress = WordFactory.pointer(HotSpotReplacementsUtil.gcTotalCollectionsAddress(INJECTED_VMCONFIG));
 191             gcCycle = (int) gcTotalCollectionsAddress.readLong(0);
 192             log(trace, "[%d] G1-Pre Thread %p Object %p\n", gcCycle, thread.rawValue(), Word.objectToTrackedPointer(object).rawValue());
 193             log(trace, "[%d] G1-Pre Thread %p Expected Object %p\n", gcCycle, thread.rawValue(), Word.objectToTrackedPointer(fixedExpectedObject).rawValue());
 194             log(trace, "[%d] G1-Pre Thread %p Field %p\n", gcCycle, thread.rawValue(), field.rawValue());
 195             log(trace, "[%d] G1-Pre Thread %p Marking %d\n", gcCycle, thread.rawValue(), markingValue);
 196             log(trace, "[%d] G1-Pre Thread %p DoLoad %d\n", gcCycle, thread.rawValue(), doLoad ? 1L : 0L);
 197         }
 198         counters.g1AttemptedPreWriteBarrierCounter.inc();
 199         // If the concurrent marker is enabled, the barrier is issued.
 200         if (probability(NOT_FREQUENT_PROBABILITY, markingValue != (byte) 0)) {
 201             // If the previous value has to be loaded (before the write), the load is issued.
 202             // The load is always issued except the cases of CAS and referent field.
 203             if (probability(LIKELY_PROBABILITY, doLoad)) {
 204                 previousOop = Word.objectToTrackedPointer(field.readObject(0, BarrierType.NONE));
 205                 if (trace) {
 206                     log(trace, "[%d] G1-Pre Thread %p Previous Object %p\n ", gcCycle, thread.rawValue(), previousOop.rawValue());
 207                     verifyOop(previousOop.toObject());
 208                 }
 209             }
 210             counters.g1EffectivePreWriteBarrierCounter.inc();
 211             // If the previous value is null the barrier should not be issued.
 212             if (probability(FREQUENT_PROBABILITY, previousOop.notEqual(0))) {
 213                 counters.g1ExecutedPreWriteBarrierCounter.inc();
 214                 // If the thread-local SATB buffer is full issue a native call which will
 215                 // initialize a new one and add the entry.
 216                 Word indexAddress = thread.add(g1SATBQueueIndexOffset(INJECTED_VMCONFIG));
 217                 Word indexValue = indexAddress.readWord(0);
 218                 if (probability(FREQUENT_PROBABILITY, indexValue.notEqual(0))) {
 219                     Word bufferAddress = thread.readWord(g1SATBQueueBufferOffset(INJECTED_VMCONFIG));
 220                     Word nextIndex = indexValue.subtract(wordSize());
 221                     Word logAddress = bufferAddress.add(nextIndex);
 222                     // Log the object to be marked as well as update the SATB's buffer next index.
 223                     logAddress.writeWord(0, previousOop, GC_LOG_LOCATION);
 224                     indexAddress.writeWord(0, nextIndex, GC_INDEX_LOCATION);
 225                 } else {
 226                     g1PreBarrierStub(G1WBPRECALL, previousOop.toObject());
 227                 }
 228             }
 229         }
 230     }
 231 
 232     @Snippet
 233     public static void g1PostWriteBarrier(Address address, Object object, Object value, @ConstantParameter boolean usePrecise, @ConstantParameter boolean verifyBarrier,
 234                     @ConstantParameter Register threadRegister, @ConstantParameter boolean trace, @ConstantParameter Counters counters) {
 235         Word thread = registerAsWord(threadRegister);
 236         Object fixedValue = FixedValueAnchorNode.getObject(value);
 237         verifyOop(object);
 238         verifyOop(fixedValue);
 239         validateObject(object, fixedValue);
 240         Pointer oop;
 241         if (usePrecise) {
 242             oop = Word.fromAddress(address);
 243         } else {
 244             if (verifyBarrier) {
 245                 verifyNotArray(object);
 246             }
 247             oop = Word.objectToTrackedPointer(object);
 248         }
 249         int gcCycle = 0;
 250         if (trace) {
 251             Pointer gcTotalCollectionsAddress = WordFactory.pointer(HotSpotReplacementsUtil.gcTotalCollectionsAddress(INJECTED_VMCONFIG));
 252             gcCycle = (int) gcTotalCollectionsAddress.readLong(0);
 253             log(trace, "[%d] G1-Post Thread: %p Object: %p\n", gcCycle, thread.rawValue(), Word.objectToTrackedPointer(object).rawValue());
 254             log(trace, "[%d] G1-Post Thread: %p Field: %p\n", gcCycle, thread.rawValue(), oop.rawValue());
 255         }
 256         Pointer writtenValue = Word.objectToTrackedPointer(fixedValue);
 257         // The result of the xor reveals whether the installed pointer crosses heap regions.
 258         // In case it does the write barrier has to be issued.
 259         final int logOfHeapRegionGrainBytes = GraalHotSpotVMConfigNode.logOfHeapRegionGrainBytes();
 260         UnsignedWord xorResult = (oop.xor(writtenValue)).unsignedShiftRight(logOfHeapRegionGrainBytes);
 261 
 262         // Calculate the address of the card to be enqueued to the
 263         // thread local card queue.
 264         UnsignedWord cardBase = oop.unsignedShiftRight(cardTableShift(INJECTED_VMCONFIG));
 265         final long startAddress = GraalHotSpotVMConfigNode.cardTableAddress();
 266         int displacement = 0;
 267         if (((int) startAddress) == startAddress && GraalHotSpotVMConfigNode.isCardTableAddressConstant()) {
 268             displacement = (int) startAddress;
 269         } else {
 270             cardBase = cardBase.add(WordFactory.unsigned(startAddress));
 271         }
 272         Word cardAddress = (Word) cardBase.add(displacement);
 273 
 274         counters.g1AttemptedPostWriteBarrierCounter.inc();
 275         if (probability(FREQUENT_PROBABILITY, xorResult.notEqual(0))) {
 276             counters.g1EffectiveAfterXORPostWriteBarrierCounter.inc();
 277 
 278             // If the written value is not null continue with the barrier addition.
 279             if (probability(FREQUENT_PROBABILITY, writtenValue.notEqual(0))) {
 280                 byte cardByte = cardAddress.readByte(0, GC_CARD_LOCATION);
 281                 counters.g1EffectiveAfterNullPostWriteBarrierCounter.inc();
 282 
 283                 // If the card is already dirty, (hence already enqueued) skip the insertion.
 284                 if (probability(NOT_FREQUENT_PROBABILITY, cardByte != g1YoungCardValue(INJECTED_VMCONFIG))) {
 285                     MembarNode.memoryBarrier(STORE_LOAD, GC_CARD_LOCATION);
 286                     byte cardByteReload = cardAddress.readByte(0, GC_CARD_LOCATION);
 287                     if (probability(NOT_FREQUENT_PROBABILITY, cardByteReload != dirtyCardValue(INJECTED_VMCONFIG))) {
 288                         log(trace, "[%d] G1-Post Thread: %p Card: %p \n", gcCycle, thread.rawValue(), WordFactory.unsigned((int) cardByte).rawValue());
 289                         cardAddress.writeByte(0, (byte) 0, GC_CARD_LOCATION);
 290                         counters.g1ExecutedPostWriteBarrierCounter.inc();
 291 
 292                         // If the thread local card queue is full, issue a native call which will
 293                         // initialize a new one and add the card entry.
 294                         Word indexAddress = thread.add(g1CardQueueIndexOffset(INJECTED_VMCONFIG));
 295                         Word indexValue = thread.readWord(g1CardQueueIndexOffset(INJECTED_VMCONFIG));
 296                         if (probability(FREQUENT_PROBABILITY, indexValue.notEqual(0))) {
 297                             Word bufferAddress = thread.readWord(g1CardQueueBufferOffset(INJECTED_VMCONFIG));
 298                             Word nextIndex = indexValue.subtract(wordSize());
 299                             Word logAddress = bufferAddress.add(nextIndex);
 300                             // Log the object to be scanned as well as update
 301                             // the card queue's next index.
 302                             logAddress.writeWord(0, cardAddress, GC_LOG_LOCATION);
 303                             indexAddress.writeWord(0, nextIndex, GC_INDEX_LOCATION);
 304                         } else {
 305                             g1PostBarrierStub(G1WBPOSTCALL, cardAddress);
 306                         }
 307                     }
 308                 }
 309             }
 310         }
 311     }
 312 
 313     private static void verifyNotArray(Object object) {
 314         if (object != null) {
 315             // Manually build the null check and cast because we're in snippet that's lowered late.
 316             AssertionNode.assertion(false, !PiNode.piCastNonNull(object, Object.class).getClass().isArray(), "imprecise card mark used with array");
 317         }
 318     }
 319 
 320     @Snippet
 321     public static void g1ArrayRangePreWriteBarrier(Address address, int length, @ConstantParameter int elementStride, @ConstantParameter Register threadRegister) {
 322         Word thread = registerAsWord(threadRegister);
 323         byte markingValue = thread.readByte(g1SATBQueueMarkingOffset(INJECTED_VMCONFIG));
 324         // If the concurrent marker is not enabled or the vector length is zero, return.
 325         if (markingValue == (byte) 0 || length == 0) {
 326             return;
 327         }
 328         Word bufferAddress = thread.readWord(g1SATBQueueBufferOffset(INJECTED_VMCONFIG));
 329         Word indexAddress = thread.add(g1SATBQueueIndexOffset(INJECTED_VMCONFIG));
 330         long indexValue = indexAddress.readWord(0).rawValue();
 331         final int scale = ReplacementsUtil.arrayIndexScale(INJECTED_METAACCESS, JavaKind.Object);
 332         long start = getPointerToFirstArrayElement(address, length, elementStride);
 333 
 334         for (int i = 0; i < length; i++) {
 335             Word arrElemPtr = WordFactory.pointer(start + i * scale);
 336             Pointer oop = Word.objectToTrackedPointer(arrElemPtr.readObject(0, BarrierType.NONE));
 337             verifyOop(oop.toObject());
 338             if (oop.notEqual(0)) {
 339                 if (indexValue != 0) {
 340                     indexValue = indexValue - wordSize();
 341                     Word logAddress = bufferAddress.add(WordFactory.unsigned(indexValue));
 342                     // Log the object to be marked as well as update the SATB's buffer next index.
 343                     logAddress.writeWord(0, oop, GC_LOG_LOCATION);
 344                     indexAddress.writeWord(0, WordFactory.unsigned(indexValue), GC_INDEX_LOCATION);
 345                 } else {
 346                     g1PreBarrierStub(G1WBPRECALL, oop.toObject());
 347                 }
 348             }
 349         }
 350     }
 351 
 352     @Snippet
 353     public static void g1ArrayRangePostWriteBarrier(Address address, int length, @ConstantParameter int elementStride, @ConstantParameter Register threadRegister) {
 354         if (length == 0) {
 355             return;
 356         }
 357         Word thread = registerAsWord(threadRegister);
 358         Word bufferAddress = thread.readWord(g1CardQueueBufferOffset(INJECTED_VMCONFIG));
 359         Word indexAddress = thread.add(g1CardQueueIndexOffset(INJECTED_VMCONFIG));
 360         long indexValue = thread.readWord(g1CardQueueIndexOffset(INJECTED_VMCONFIG)).rawValue();
 361 
 362         int cardShift = cardTableShift(INJECTED_VMCONFIG);
 363         final long cardStart = GraalHotSpotVMConfigNode.cardTableAddress();
 364         long start = getPointerToFirstArrayElement(address, length, elementStride) >>> cardShift;
 365         long end = getPointerToLastArrayElement(address, length, elementStride) >>> cardShift;
 366         long count = end - start + 1;
 367 
 368         while (count-- > 0) {
 369             Word cardAddress = WordFactory.unsigned((start + cardStart) + count);
 370             byte cardByte = cardAddress.readByte(0, GC_CARD_LOCATION);
 371             // If the card is already dirty, (hence already enqueued) skip the insertion.
 372             if (probability(NOT_FREQUENT_PROBABILITY, cardByte != g1YoungCardValue(INJECTED_VMCONFIG))) {
 373                 MembarNode.memoryBarrier(STORE_LOAD, GC_CARD_LOCATION);
 374                 byte cardByteReload = cardAddress.readByte(0, GC_CARD_LOCATION);
 375                 if (probability(NOT_FREQUENT_PROBABILITY, cardByteReload != dirtyCardValue(INJECTED_VMCONFIG))) {
 376                     cardAddress.writeByte(0, (byte) 0, GC_CARD_LOCATION);
 377                     // If the thread local card queue is full, issue a native call which will
 378                     // initialize a new one and add the card entry.
 379                     if (indexValue != 0) {
 380                         indexValue = indexValue - wordSize();
 381                         Word logAddress = bufferAddress.add(WordFactory.unsigned(indexValue));
 382                         // Log the object to be scanned as well as update
 383                         // the card queue's next index.
 384                         logAddress.writeWord(0, cardAddress, GC_LOG_LOCATION);
 385                         indexAddress.writeWord(0, WordFactory.unsigned(indexValue), GC_INDEX_LOCATION);
 386                     } else {
 387                         g1PostBarrierStub(G1WBPOSTCALL, cardAddress);
 388                     }
 389                 }
 390             }
 391         }
 392     }
 393 
 394     private static long getPointerToFirstArrayElement(Address address, int length, int elementStride) {
 395         long result = Word.fromAddress(address).rawValue();
 396         if (elementStride < 0) {
 397             // the address points to the place after the last array element
 398             result = result + elementStride * length;
 399         }
 400         return result;
 401     }
 402 
 403     private static long getPointerToLastArrayElement(Address address, int length, int elementStride) {
 404         long result = Word.fromAddress(address).rawValue();
 405         if (elementStride < 0) {
 406             // the address points to the place after the last array element
 407             result = result + elementStride;
 408         } else {
 409             result = result + (length - 1) * elementStride;
 410         }
 411         return result;
 412     }
 413 
 414     public static final ForeignCallDescriptor G1WBPRECALL = new ForeignCallDescriptor("write_barrier_pre", void.class, Object.class);
 415 
 416     @NodeIntrinsic(ForeignCallNode.class)
 417     private static native void g1PreBarrierStub(@ConstantNodeParameter ForeignCallDescriptor descriptor, Object object);
 418 
 419     public static final ForeignCallDescriptor G1WBPOSTCALL = new ForeignCallDescriptor("write_barrier_post", void.class, Word.class);
 420 
 421     @NodeIntrinsic(ForeignCallNode.class)
 422     public static native void g1PostBarrierStub(@ConstantNodeParameter ForeignCallDescriptor descriptor, Word card);
 423 
 424     public static class Templates extends AbstractTemplates {
 425 
 426         private final SnippetInfo serialImpreciseWriteBarrier = snippet(WriteBarrierSnippets.class, "serialImpreciseWriteBarrier", GC_CARD_LOCATION);
 427         private final SnippetInfo serialPreciseWriteBarrier = snippet(WriteBarrierSnippets.class, "serialPreciseWriteBarrier", GC_CARD_LOCATION);
 428         private final SnippetInfo serialArrayRangeWriteBarrier = snippet(WriteBarrierSnippets.class, "serialArrayRangeWriteBarrier");
 429         private final SnippetInfo g1PreWriteBarrier = snippet(WriteBarrierSnippets.class, "g1PreWriteBarrier", GC_INDEX_LOCATION, GC_LOG_LOCATION);
 430         private final SnippetInfo g1ReferentReadBarrier = snippet(WriteBarrierSnippets.class, "g1PreWriteBarrier", GC_INDEX_LOCATION, GC_LOG_LOCATION);
 431         private final SnippetInfo g1PostWriteBarrier = snippet(WriteBarrierSnippets.class, "g1PostWriteBarrier", GC_CARD_LOCATION, GC_INDEX_LOCATION, GC_LOG_LOCATION);
 432         private final SnippetInfo g1ArrayRangePreWriteBarrier = snippet(WriteBarrierSnippets.class, "g1ArrayRangePreWriteBarrier", GC_INDEX_LOCATION, GC_LOG_LOCATION);
 433         private final SnippetInfo g1ArrayRangePostWriteBarrier = snippet(WriteBarrierSnippets.class, "g1ArrayRangePostWriteBarrier", GC_CARD_LOCATION, GC_INDEX_LOCATION, GC_LOG_LOCATION);
 434 
 435         private final CompressEncoding oopEncoding;
 436         private final Counters counters;
 437         private final boolean verifyBarrier;
 438         private final long gcTotalCollectionsAddress;
 439 
 440         public Templates(OptionValues options, Iterable<DebugHandlersFactory> factories, Group.Factory factory, HotSpotProviders providers, TargetDescription target,
 441                         GraalHotSpotVMConfig config) {
 442             super(options, factories, providers, providers.getSnippetReflection(), target);
 443             this.oopEncoding = config.useCompressedOops ? config.getOopEncoding() : null;
 444             this.verifyBarrier = ReplacementsUtil.REPLACEMENTS_ASSERTIONS_ENABLED || config.verifyBeforeGC || config.verifyAfterGC;
 445             this.gcTotalCollectionsAddress = config.gcTotalCollectionsAddress();
 446             this.counters = new Counters(factory);
 447         }
 448 
 449         public boolean traceBarrier(StructuredGraph graph) {
 450             long startCycle = GraalOptions.GCDebugStartCycle.getValue(graph.getOptions());
 451             return startCycle > 0 && ((Pointer) WordFactory.pointer(gcTotalCollectionsAddress)).readLong(0) > startCycle;
 452         }
 453 
 454         public void lower(SerialWriteBarrier writeBarrier, LoweringTool tool) {
 455             Arguments args;
 456             if (writeBarrier.usePrecise()) {
 457                 args = new Arguments(serialPreciseWriteBarrier, writeBarrier.graph().getGuardsStage(), tool.getLoweringStage());
 458                 args.add("address", writeBarrier.getAddress());
 459             } else {
 460                 args = new Arguments(serialImpreciseWriteBarrier, writeBarrier.graph().getGuardsStage(), tool.getLoweringStage());
 461                 OffsetAddressNode address = (OffsetAddressNode) writeBarrier.getAddress();
 462                 args.add("object", address.getBase());
 463                 args.addConst("verifyBarrier", verifyBarrier);
 464             }
 465             args.addConst("counters", counters);
 466             template(writeBarrier, args).instantiate(providers.getMetaAccess(), writeBarrier, DEFAULT_REPLACER, args);
 467         }
 468 
 469         public void lower(SerialArrayRangeWriteBarrier arrayRangeWriteBarrier, LoweringTool tool) {
 470             Arguments args = new Arguments(serialArrayRangeWriteBarrier, arrayRangeWriteBarrier.graph().getGuardsStage(), tool.getLoweringStage());
 471             args.add("address", arrayRangeWriteBarrier.getAddress());
 472             args.add("length", arrayRangeWriteBarrier.getLength());
 473             args.addConst("elementStride", arrayRangeWriteBarrier.getElementStride());
 474             template(arrayRangeWriteBarrier, args).instantiate(providers.getMetaAccess(), arrayRangeWriteBarrier, DEFAULT_REPLACER, args);
 475         }
 476 
 477         public void lower(G1PreWriteBarrier writeBarrierPre, HotSpotRegistersProvider registers, LoweringTool tool) {
 478             Arguments args = new Arguments(g1PreWriteBarrier, writeBarrierPre.graph().getGuardsStage(), tool.getLoweringStage());
 479             AddressNode address = writeBarrierPre.getAddress();
 480             args.add("address", address);
 481             if (address instanceof OffsetAddressNode) {
 482                 args.add("object", ((OffsetAddressNode) address).getBase());
 483             } else {
 484                 args.add("object", null);
 485             }
 486 
 487             ValueNode expected = writeBarrierPre.getExpectedObject();
 488             if (expected != null && expected.stamp(NodeView.DEFAULT) instanceof NarrowOopStamp) {
 489                 assert oopEncoding != null;
 490                 expected = HotSpotCompressionNode.uncompress(expected, oopEncoding);
 491             }
 492             args.add("expectedObject", expected);
 493 
 494             args.addConst("doLoad", writeBarrierPre.doLoad());
 495             args.addConst("nullCheck", writeBarrierPre.getNullCheck());
 496             args.addConst("threadRegister", registers.getThreadRegister());
 497             args.addConst("trace", traceBarrier(writeBarrierPre.graph()));
 498             args.addConst("counters", counters);
 499             template(writeBarrierPre, args).instantiate(providers.getMetaAccess(), writeBarrierPre, DEFAULT_REPLACER, args);
 500         }
 501 
 502         public void lower(G1ReferentFieldReadBarrier readBarrier, HotSpotRegistersProvider registers, LoweringTool tool) {
 503             Arguments args = new Arguments(g1ReferentReadBarrier, readBarrier.graph().getGuardsStage(), tool.getLoweringStage());
 504             AddressNode address = readBarrier.getAddress();
 505             args.add("address", address);
 506             if (address instanceof OffsetAddressNode) {
 507                 args.add("object", ((OffsetAddressNode) address).getBase());
 508             } else {
 509                 args.add("object", null);
 510             }
 511 
 512             ValueNode expected = readBarrier.getExpectedObject();
 513             if (expected != null && expected.stamp(NodeView.DEFAULT) instanceof NarrowOopStamp) {
 514                 assert oopEncoding != null;
 515                 expected = HotSpotCompressionNode.uncompress(expected, oopEncoding);
 516             }
 517 
 518             args.add("expectedObject", expected);
 519             args.addConst("doLoad", readBarrier.doLoad());
 520             args.addConst("nullCheck", false);
 521             args.addConst("threadRegister", registers.getThreadRegister());
 522             args.addConst("trace", traceBarrier(readBarrier.graph()));
 523             args.addConst("counters", counters);
 524             template(readBarrier, args).instantiate(providers.getMetaAccess(), readBarrier, DEFAULT_REPLACER, args);
 525         }
 526 
 527         public void lower(G1PostWriteBarrier writeBarrierPost, HotSpotRegistersProvider registers, LoweringTool tool) {
 528             StructuredGraph graph = writeBarrierPost.graph();
 529             if (writeBarrierPost.alwaysNull()) {
 530                 graph.removeFixed(writeBarrierPost);
 531                 return;
 532             }
 533             Arguments args = new Arguments(g1PostWriteBarrier, graph.getGuardsStage(), tool.getLoweringStage());
 534             AddressNode address = writeBarrierPost.getAddress();
 535             args.add("address", address);
 536             if (address instanceof OffsetAddressNode) {
 537                 args.add("object", ((OffsetAddressNode) address).getBase());
 538             } else {
 539                 assert writeBarrierPost.usePrecise() : "found imprecise barrier that's not an object access " + writeBarrierPost;
 540                 args.add("object", null);
 541             }
 542 
 543             ValueNode value = writeBarrierPost.getValue();
 544             if (value.stamp(NodeView.DEFAULT) instanceof NarrowOopStamp) {
 545                 assert oopEncoding != null;
 546                 value = HotSpotCompressionNode.uncompress(value, oopEncoding);
 547             }
 548             args.add("value", value);
 549 
 550             args.addConst("usePrecise", writeBarrierPost.usePrecise());
 551             args.addConst("verifyBarrier", verifyBarrier);
 552             args.addConst("threadRegister", registers.getThreadRegister());
 553             args.addConst("trace", traceBarrier(writeBarrierPost.graph()));
 554             args.addConst("counters", counters);
 555             template(writeBarrierPost, args).instantiate(providers.getMetaAccess(), writeBarrierPost, DEFAULT_REPLACER, args);
 556         }
 557 
 558         public void lower(G1ArrayRangePreWriteBarrier arrayRangeWriteBarrier, HotSpotRegistersProvider registers, LoweringTool tool) {
 559             Arguments args = new Arguments(g1ArrayRangePreWriteBarrier, arrayRangeWriteBarrier.graph().getGuardsStage(), tool.getLoweringStage());
 560             args.add("address", arrayRangeWriteBarrier.getAddress());
 561             args.add("length", arrayRangeWriteBarrier.getLength());
 562             args.addConst("elementStride", arrayRangeWriteBarrier.getElementStride());
 563             args.addConst("threadRegister", registers.getThreadRegister());
 564             template(arrayRangeWriteBarrier, args).instantiate(providers.getMetaAccess(), arrayRangeWriteBarrier, DEFAULT_REPLACER, args);
 565         }
 566 
 567         public void lower(G1ArrayRangePostWriteBarrier arrayRangeWriteBarrier, HotSpotRegistersProvider registers, LoweringTool tool) {
 568             Arguments args = new Arguments(g1ArrayRangePostWriteBarrier, arrayRangeWriteBarrier.graph().getGuardsStage(), tool.getLoweringStage());
 569             args.add("address", arrayRangeWriteBarrier.getAddress());
 570             args.add("length", arrayRangeWriteBarrier.getLength());
 571             args.addConst("elementStride", arrayRangeWriteBarrier.getElementStride());
 572             args.addConst("threadRegister", registers.getThreadRegister());
 573             template(arrayRangeWriteBarrier, args).instantiate(providers.getMetaAccess(), arrayRangeWriteBarrier, DEFAULT_REPLACER, args);
 574         }
 575     }
 576 
 577     /**
 578      * Log method of debugging purposes.
 579      */
 580     public static void log(boolean enabled, String format, long value) {
 581         if (enabled) {
 582             Log.printf(format, value);
 583         }
 584     }
 585 
 586     public static void log(boolean enabled, String format, long value1, long value2) {
 587         if (enabled) {
 588             Log.printf(format, value1, value2);
 589         }
 590     }
 591 
 592     public static void log(boolean enabled, String format, long value1, long value2, long value3) {
 593         if (enabled) {
 594             Log.printf(format, value1, value2, value3);
 595         }
 596     }
 597 
 598     /**
 599      * Validation helper method which performs sanity checks on write operations. The addresses of
 600      * both the object and the value being written are checked in order to determine if they reside
 601      * in a valid heap region. If an object is stale, an invalid access is performed in order to
 602      * prematurely crash the VM and debug the stack trace of the faulty method.
 603      */
 604     public static void validateObject(Object parent, Object child) {
 605         if (verifyOops(INJECTED_VMCONFIG) && child != null) {
 606             Word parentWord = Word.objectToTrackedPointer(parent);
 607             Word childWord = Word.objectToTrackedPointer(child);
 608             if (!validateOop(VALIDATE_OBJECT, parentWord, childWord)) {
 609                 log(true, "Verification ERROR, Parent: %p Child: %p\n", parentWord.rawValue(), childWord.rawValue());
 610                 VMErrorNode.vmError("Verification ERROR, Parent: %p\n", parentWord.rawValue());
 611             }
 612         }
 613     }
 614 
 615     public static final ForeignCallDescriptor VALIDATE_OBJECT = new ForeignCallDescriptor("validate_object", boolean.class, Word.class, Word.class);
 616 
 617     @NodeIntrinsic(ForeignCallNode.class)
 618     private static native boolean validateOop(@ConstantNodeParameter ForeignCallDescriptor descriptor, Word parent, Word object);
 619 
 620 }