1 /*
   2  * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2018, 2021, Red Hat, Inc. All rights reserved.
   4  * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
   5  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   6  *
   7  * This code is free software; you can redistribute it and/or modify it
   8  * under the terms of the GNU General Public License version 2 only, as
   9  * published by the Free Software Foundation.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  *
  25  */
  26 
  27 #include "gc/shenandoah/heuristics/shenandoahHeuristics.hpp"
  28 #include "gc/shenandoah/mode/shenandoahMode.hpp"
  29 #include "gc/shenandoah/shenandoahBarrierSet.hpp"
  30 #include "gc/shenandoah/shenandoahBarrierSetAssembler.hpp"
  31 #include "gc/shenandoah/shenandoahForwarding.hpp"
  32 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  33 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
  34 #include "gc/shenandoah/shenandoahRuntime.hpp"
  35 #include "gc/shenandoah/shenandoahThreadLocalData.hpp"
  36 #include "interpreter/interpreter.hpp"
  37 #include "runtime/javaThread.hpp"
  38 #include "runtime/sharedRuntime.hpp"
  39 #include "utilities/macros.hpp"
  40 #ifdef COMPILER1
  41 #include "c1/c1_LIRAssembler.hpp"
  42 #include "c1/c1_MacroAssembler.hpp"
  43 #include "gc/shenandoah/c1/shenandoahBarrierSetC1.hpp"
  44 #endif
  45 #ifdef COMPILER2
  46 #include "gc/shenandoah/c2/shenandoahBarrierSetC2.hpp"
  47 #endif
  48 
  49 #define __ masm->
  50 
  51 static void save_machine_state(MacroAssembler* masm, bool handle_gpr, bool handle_fp) {
  52   if (handle_gpr) {
  53     __ push_IU_state();
  54   }
  55 
  56   if (handle_fp) {
  57     // Some paths can be reached from the c2i adapter with live fp arguments in registers.
  58     assert(Argument::n_float_register_parameters_j == 8, "8 fp registers to save at java call");
  59 
  60     const int xmm_size = wordSize * 2;
  61     __ subptr(rsp, xmm_size * 8);
  62     __ movdbl(Address(rsp, xmm_size * 0), xmm0);
  63     __ movdbl(Address(rsp, xmm_size * 1), xmm1);
  64     __ movdbl(Address(rsp, xmm_size * 2), xmm2);
  65     __ movdbl(Address(rsp, xmm_size * 3), xmm3);
  66     __ movdbl(Address(rsp, xmm_size * 4), xmm4);
  67     __ movdbl(Address(rsp, xmm_size * 5), xmm5);
  68     __ movdbl(Address(rsp, xmm_size * 6), xmm6);
  69     __ movdbl(Address(rsp, xmm_size * 7), xmm7);
  70   }
  71 }
  72 
  73 static void restore_machine_state(MacroAssembler* masm, bool handle_gpr, bool handle_fp) {
  74   if (handle_fp) {
  75     const int xmm_size = wordSize * 2;
  76     __ movdbl(xmm0, Address(rsp, xmm_size * 0));
  77     __ movdbl(xmm1, Address(rsp, xmm_size * 1));
  78     __ movdbl(xmm2, Address(rsp, xmm_size * 2));
  79     __ movdbl(xmm3, Address(rsp, xmm_size * 3));
  80     __ movdbl(xmm4, Address(rsp, xmm_size * 4));
  81     __ movdbl(xmm5, Address(rsp, xmm_size * 5));
  82     __ movdbl(xmm6, Address(rsp, xmm_size * 6));
  83     __ movdbl(xmm7, Address(rsp, xmm_size * 7));
  84     __ addptr(rsp, xmm_size * 8);
  85   }
  86 
  87   if (handle_gpr) {
  88     __ pop_IU_state();
  89   }
  90 }
  91 
  92 void ShenandoahBarrierSetAssembler::arraycopy_prologue(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
  93                                                        Register src, Register dst, Register count) {
  94 
  95   bool dest_uninitialized = (decorators & IS_DEST_UNINITIALIZED) != 0;
  96 
  97   if (is_reference_type(type)) {
  98     if (ShenandoahCardBarrier) {
  99       bool checkcast = (decorators & ARRAYCOPY_CHECKCAST) != 0;
 100       bool disjoint = (decorators & ARRAYCOPY_DISJOINT) != 0;
 101       bool obj_int = (type == T_OBJECT) && UseCompressedOops;
 102 
 103       // We need to save the original element count because the array copy stub
 104       // will destroy the value and we need it for the card marking barrier.
 105       if (!checkcast) {
 106         if (!obj_int) {
 107           // Save count for barrier
 108           __ movptr(r11, count);
 109         } else if (disjoint) {
 110           // Save dst in r11 in the disjoint case
 111           __ movq(r11, dst);
 112         }
 113       }
 114     }
 115 
 116     if ((ShenandoahSATBBarrier && !dest_uninitialized) || ShenandoahLoadRefBarrier) {
 117       Register thread = r15_thread;
 118       assert_different_registers(src, dst, count, thread);
 119 
 120       Label L_done;
 121       // Short-circuit if count == 0.
 122       __ testptr(count, count);
 123       __ jcc(Assembler::zero, L_done);
 124 
 125       // Avoid runtime call when not active.
 126       Address gc_state(thread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
 127       int flags;
 128       if (ShenandoahSATBBarrier && dest_uninitialized) {
 129         flags = ShenandoahHeap::HAS_FORWARDED;
 130       } else {
 131         flags = ShenandoahHeap::HAS_FORWARDED | ShenandoahHeap::MARKING;
 132       }
 133       __ testb(gc_state, flags);
 134       __ jcc(Assembler::zero, L_done);
 135 
 136       save_machine_state(masm, /* handle_gpr = */ true, /* handle_fp = */ false);
 137 
 138       assert(src == rdi, "expected");
 139       assert(dst == rsi, "expected");
 140       assert(count == rdx, "expected");
 141       if (UseCompressedOops) {
 142         __ call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::arraycopy_barrier_narrow_oop),
 143                         src, dst, count);
 144       } else {
 145         __ call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::arraycopy_barrier_oop),
 146                         src, dst, count);
 147       }
 148 
 149       restore_machine_state(masm, /* handle_gpr = */ true, /* handle_fp = */ false);
 150 
 151       __ bind(L_done);
 152     }
 153   }
 154 
 155 }
 156 
 157 void ShenandoahBarrierSetAssembler::arraycopy_epilogue(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
 158                                                        Register src, Register dst, Register count) {
 159 
 160   if (ShenandoahCardBarrier && is_reference_type(type)) {
 161     bool checkcast = (decorators & ARRAYCOPY_CHECKCAST) != 0;
 162     bool disjoint = (decorators & ARRAYCOPY_DISJOINT) != 0;
 163     bool obj_int = (type == T_OBJECT) && UseCompressedOops;
 164     Register tmp = rax;
 165 
 166     if (!checkcast) {
 167       if (!obj_int) {
 168         // Save count for barrier
 169         count = r11;
 170       } else if (disjoint) {
 171         // Use the saved dst in the disjoint case
 172         dst = r11;
 173       }
 174     } else {
 175       tmp = rscratch1;
 176     }
 177     gen_write_ref_array_post_barrier(masm, decorators, dst, count, tmp);
 178   }
 179 }
 180 
 181 void ShenandoahBarrierSetAssembler::satb_barrier(MacroAssembler* masm,
 182                                                  Register obj,
 183                                                  Register pre_val,
 184                                                  Register tmp,
 185                                                  bool tosca_live,
 186                                                  bool expand_call) {
 187   assert(ShenandoahSATBBarrier, "Should be checked by caller");
 188 
 189   // If expand_call is true then we expand the call_VM_leaf macro
 190   // directly to skip generating the check by
 191   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
 192 
 193   const Register thread = r15_thread;
 194 
 195   Label done;
 196   Label runtime;
 197 
 198   assert(pre_val != noreg, "check this code");
 199 
 200   if (obj != noreg) {
 201     assert_different_registers(obj, pre_val, tmp);
 202     assert(pre_val != rax, "check this code");
 203   }
 204 
 205   Address index(thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_index_offset()));
 206   Address buffer(thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset()));
 207 
 208   Address gc_state(thread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
 209   __ testb(gc_state, ShenandoahHeap::MARKING);
 210   __ jcc(Assembler::zero, done);
 211 
 212   // Do we need to load the previous value?
 213   if (obj != noreg) {
 214     __ load_heap_oop(pre_val, Address(obj, 0), noreg, AS_RAW);
 215   }
 216 
 217   // Is the previous value null?
 218   __ cmpptr(pre_val, NULL_WORD);
 219   __ jcc(Assembler::equal, done);
 220 
 221   // Can we store original value in the thread's buffer?
 222   // Is index == 0?
 223   // (The index field is typed as size_t.)
 224 
 225   __ movptr(tmp, index);                   // tmp := *index_adr
 226   __ cmpptr(tmp, 0);                       // tmp == 0?
 227   __ jcc(Assembler::equal, runtime);       // If yes, goto runtime
 228 
 229   __ subptr(tmp, wordSize);                // tmp := tmp - wordSize
 230   __ movptr(index, tmp);                   // *index_adr := tmp
 231   __ addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
 232 
 233   // Record the previous value
 234   __ movptr(Address(tmp, 0), pre_val);
 235   __ jmp(done);
 236 
 237   __ bind(runtime);
 238   // save the live input values
 239   if(tosca_live) __ push(rax);
 240 
 241   if (obj != noreg && obj != rax)
 242     __ push(obj);
 243 
 244   if (pre_val != rax)
 245     __ push(pre_val);
 246 
 247   // Calling the runtime using the regular call_VM_leaf mechanism generates
 248   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
 249   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == nullptr.
 250   //
 251   // If we care generating the pre-barrier without a frame (e.g. in the
 252   // intrinsified Reference.get() routine) then ebp might be pointing to
 253   // the caller frame and so this check will most likely fail at runtime.
 254   //
 255   // Expanding the call directly bypasses the generation of the check.
 256   // So when we do not have have a full interpreter frame on the stack
 257   // expand_call should be passed true.
 258 
 259   // We move pre_val into c_rarg0 early, in order to avoid smashing it, should
 260   // pre_val be c_rarg1 (where the call prologue would copy thread argument).
 261   // Note: this should not accidentally smash thread, because thread is always r15.
 262   assert(thread != c_rarg0, "smashed arg");
 263   if (c_rarg0 != pre_val) {
 264     __ mov(c_rarg0, pre_val);
 265   }
 266 
 267   if (expand_call) {
 268     assert(pre_val != c_rarg1, "smashed arg");
 269     if (c_rarg1 != thread) {
 270       __ mov(c_rarg1, thread);
 271     }
 272     // Already moved pre_val into c_rarg0 above
 273     __ MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_barrier_pre), 1);
 274   } else {
 275     __ call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_barrier_pre), c_rarg0);
 276   }
 277 
 278   // save the live input values
 279   if (pre_val != rax)
 280     __ pop(pre_val);
 281 
 282   if (obj != noreg && obj != rax)
 283     __ pop(obj);
 284 
 285   if(tosca_live) __ pop(rax);
 286 
 287   __ bind(done);
 288 }
 289 
 290 void ShenandoahBarrierSetAssembler::load_reference_barrier(MacroAssembler* masm, Register dst, Address src, DecoratorSet decorators) {
 291   assert(ShenandoahLoadRefBarrier, "Should be enabled");
 292 
 293   bool is_strong  = ShenandoahBarrierSet::is_strong_access(decorators);
 294   bool is_weak    = ShenandoahBarrierSet::is_weak_access(decorators);
 295   bool is_phantom = ShenandoahBarrierSet::is_phantom_access(decorators);
 296   bool is_native  = ShenandoahBarrierSet::is_native_access(decorators);
 297   bool is_narrow  = UseCompressedOops && !is_native;
 298 
 299   Label heap_stable, not_cset;
 300 
 301   __ block_comment("load_reference_barrier { ");
 302 
 303   // Check if GC is active
 304   Register thread = r15_thread;
 305 
 306   Address gc_state(thread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
 307   int flags = ShenandoahHeap::HAS_FORWARDED;
 308   if (!is_strong) {
 309     flags |= ShenandoahHeap::WEAK_ROOTS;
 310   }
 311   __ testb(gc_state, flags);
 312   __ jcc(Assembler::zero, heap_stable);
 313 
 314   Register tmp1 = noreg, tmp2 = noreg;
 315   if (is_strong) {
 316     // Test for object in cset
 317     // Allocate temporary registers
 318     for (int i = 0; i < 8; i++) {
 319       Register r = as_Register(i);
 320       if (r != rsp && r != rbp && r != dst && r != src.base() && r != src.index()) {
 321         if (tmp1 == noreg) {
 322           tmp1 = r;
 323         } else {
 324           tmp2 = r;
 325           break;
 326         }
 327       }
 328     }
 329     assert(tmp1 != noreg, "tmp1 allocated");
 330     assert(tmp2 != noreg, "tmp2 allocated");
 331     assert_different_registers(tmp1, tmp2, src.base(), src.index());
 332     assert_different_registers(tmp1, tmp2, dst);
 333 
 334     __ push(tmp1);
 335     __ push(tmp2);
 336 
 337     // Optimized cset-test
 338     __ movptr(tmp1, dst);
 339     __ shrptr(tmp1, ShenandoahHeapRegion::region_size_bytes_shift_jint());
 340     __ movptr(tmp2, (intptr_t) ShenandoahHeap::in_cset_fast_test_addr());
 341     __ movbool(tmp1, Address(tmp1, tmp2, Address::times_1));
 342     __ testbool(tmp1);
 343     __ jcc(Assembler::zero, not_cset);
 344   }
 345 
 346   save_machine_state(masm, /* handle_gpr = */ false, /* handle_fp = */ true);
 347 
 348   // The rest is saved with the optimized path
 349 
 350   uint num_saved_regs = 4 + (dst != rax ? 1 : 0) + 4 + (UseAPX ? 16 : 0);
 351   __ subptr(rsp, num_saved_regs * wordSize);
 352   uint slot = num_saved_regs;
 353   if (dst != rax) {
 354     __ movptr(Address(rsp, (--slot) * wordSize), rax);
 355   }
 356   __ movptr(Address(rsp, (--slot) * wordSize), rcx);
 357   __ movptr(Address(rsp, (--slot) * wordSize), rdx);
 358   __ movptr(Address(rsp, (--slot) * wordSize), rdi);
 359   __ movptr(Address(rsp, (--slot) * wordSize), rsi);
 360   __ movptr(Address(rsp, (--slot) * wordSize), r8);
 361   __ movptr(Address(rsp, (--slot) * wordSize), r9);
 362   __ movptr(Address(rsp, (--slot) * wordSize), r10);
 363   __ movptr(Address(rsp, (--slot) * wordSize), r11);
 364   // Save APX extended registers r16–r31 if enabled
 365   if (UseAPX) {
 366     __ movptr(Address(rsp, (--slot) * wordSize), r16);
 367     __ movptr(Address(rsp, (--slot) * wordSize), r17);
 368     __ movptr(Address(rsp, (--slot) * wordSize), r18);
 369     __ movptr(Address(rsp, (--slot) * wordSize), r19);
 370     __ movptr(Address(rsp, (--slot) * wordSize), r20);
 371     __ movptr(Address(rsp, (--slot) * wordSize), r21);
 372     __ movptr(Address(rsp, (--slot) * wordSize), r22);
 373     __ movptr(Address(rsp, (--slot) * wordSize), r23);
 374     __ movptr(Address(rsp, (--slot) * wordSize), r24);
 375     __ movptr(Address(rsp, (--slot) * wordSize), r25);
 376     __ movptr(Address(rsp, (--slot) * wordSize), r26);
 377     __ movptr(Address(rsp, (--slot) * wordSize), r27);
 378     __ movptr(Address(rsp, (--slot) * wordSize), r28);
 379     __ movptr(Address(rsp, (--slot) * wordSize), r29);
 380     __ movptr(Address(rsp, (--slot) * wordSize), r30);
 381     __ movptr(Address(rsp, (--slot) * wordSize), r31);
 382   }
 383   // r12-r15 are callee saved in all calling conventions
 384   assert(slot == 0, "must use all slots");
 385 
 386   // Shuffle registers such that dst is in c_rarg0 and addr in c_rarg1.
 387   Register arg0 = c_rarg0, arg1 = c_rarg1;
 388   if (dst == arg1) {
 389     __ lea(arg0, src);
 390     __ xchgptr(arg1, arg0);
 391   } else {
 392     __ lea(arg1, src);
 393     __ movptr(arg0, dst);
 394   }
 395 
 396   if (is_strong) {
 397     if (is_narrow) {
 398       __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong_narrow), arg0, arg1);
 399     } else {
 400       __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong), arg0, arg1);
 401     }
 402   } else if (is_weak) {
 403     if (is_narrow) {
 404       __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak_narrow), arg0, arg1);
 405     } else {
 406       __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak), arg0, arg1);
 407     }
 408   } else {
 409     assert(is_phantom, "only remaining strength");
 410     assert(!is_narrow, "phantom access cannot be narrow");
 411     __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom), arg0, arg1);
 412   }
 413 
 414   // Restore APX extended registers r31–r16 if previously saved
 415   if (UseAPX) {
 416     __ movptr(r31, Address(rsp, (slot++) * wordSize));
 417     __ movptr(r30, Address(rsp, (slot++) * wordSize));
 418     __ movptr(r29, Address(rsp, (slot++) * wordSize));
 419     __ movptr(r28, Address(rsp, (slot++) * wordSize));
 420     __ movptr(r27, Address(rsp, (slot++) * wordSize));
 421     __ movptr(r26, Address(rsp, (slot++) * wordSize));
 422     __ movptr(r25, Address(rsp, (slot++) * wordSize));
 423     __ movptr(r24, Address(rsp, (slot++) * wordSize));
 424     __ movptr(r23, Address(rsp, (slot++) * wordSize));
 425     __ movptr(r22, Address(rsp, (slot++) * wordSize));
 426     __ movptr(r21, Address(rsp, (slot++) * wordSize));
 427     __ movptr(r20, Address(rsp, (slot++) * wordSize));
 428     __ movptr(r19, Address(rsp, (slot++) * wordSize));
 429     __ movptr(r18, Address(rsp, (slot++) * wordSize));
 430     __ movptr(r17, Address(rsp, (slot++) * wordSize));
 431     __ movptr(r16, Address(rsp, (slot++) * wordSize));
 432   }
 433   __ movptr(r11, Address(rsp, (slot++) * wordSize));
 434   __ movptr(r10, Address(rsp, (slot++) * wordSize));
 435   __ movptr(r9,  Address(rsp, (slot++) * wordSize));
 436   __ movptr(r8,  Address(rsp, (slot++) * wordSize));
 437   __ movptr(rsi, Address(rsp, (slot++) * wordSize));
 438   __ movptr(rdi, Address(rsp, (slot++) * wordSize));
 439   __ movptr(rdx, Address(rsp, (slot++) * wordSize));
 440   __ movptr(rcx, Address(rsp, (slot++) * wordSize));
 441 
 442   if (dst != rax) {
 443     __ movptr(dst, rax);
 444     __ movptr(rax, Address(rsp, (slot++) * wordSize));
 445   }
 446 
 447   assert(slot == num_saved_regs, "must use all slots");
 448   __ addptr(rsp, num_saved_regs * wordSize);
 449 
 450   restore_machine_state(masm, /* handle_gpr = */ false, /* handle_fp = */ true);
 451 
 452   __ bind(not_cset);
 453 
 454   if  (is_strong) {
 455     __ pop(tmp2);
 456     __ pop(tmp1);
 457   }
 458 
 459   __ bind(heap_stable);
 460 
 461   __ block_comment("} load_reference_barrier");
 462 }
 463 
 464 //
 465 // Arguments:
 466 //
 467 // Inputs:
 468 //   src:        oop location, might be clobbered
 469 //   tmp1:       scratch register, might not be valid.
 470 //
 471 // Output:
 472 //   dst:        oop loaded from src location
 473 //
 474 // Kill:
 475 //   tmp1 (if it is valid)
 476 //
 477 void ShenandoahBarrierSetAssembler::load_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
 478              Register dst, Address src, Register tmp1) {
 479   // 1: non-reference load, no additional barrier is needed
 480   if (!is_reference_type(type)) {
 481     BarrierSetAssembler::load_at(masm, decorators, type, dst, src, tmp1);
 482     return;
 483   }
 484 
 485   assert((decorators & ON_UNKNOWN_OOP_REF) == 0, "Not expected");
 486 
 487   // 2: load a reference from src location and apply LRB if needed
 488   if (ShenandoahBarrierSet::need_load_reference_barrier(decorators, type)) {
 489     Register result_dst = dst;
 490     bool use_tmp1_for_dst = false;
 491 
 492     // Preserve src location for LRB
 493     if (dst == src.base() || dst == src.index()) {
 494     // Use tmp1 for dst if possible, as it is not used in BarrierAssembler::load_at()
 495       if (tmp1->is_valid() && tmp1 != src.base() && tmp1 != src.index()) {
 496         dst = tmp1;
 497         use_tmp1_for_dst = true;
 498       } else {
 499         dst = rdi;
 500         __ push(dst);
 501       }
 502       assert_different_registers(dst, src.base(), src.index());
 503     }
 504 
 505     BarrierSetAssembler::load_at(masm, decorators, type, dst, src, tmp1);
 506 
 507     load_reference_barrier(masm, dst, src, decorators);
 508 
 509     // Move loaded oop to final destination
 510     if (dst != result_dst) {
 511       __ movptr(result_dst, dst);
 512 
 513       if (!use_tmp1_for_dst) {
 514         __ pop(dst);
 515       }
 516 
 517       dst = result_dst;
 518     }
 519   } else {
 520     BarrierSetAssembler::load_at(masm, decorators, type, dst, src, tmp1);
 521   }
 522 
 523   // 3: apply keep-alive barrier if needed
 524   if (ShenandoahBarrierSet::need_keep_alive_barrier(decorators, type)) {
 525     save_machine_state(masm, /* handle_gpr = */ true, /* handle_fp = */ true);
 526 
 527     assert_different_registers(dst, tmp1, r15_thread);
 528     // Generate the SATB pre-barrier code to log the value of
 529     // the referent field in an SATB buffer.
 530     satb_barrier(masm /* masm */,
 531                  noreg /* obj */,
 532                  dst /* pre_val */,
 533                  tmp1 /* tmp */,
 534                  true /* tosca_live */,
 535                  true /* expand_call */);
 536 
 537     restore_machine_state(masm, /* handle_gpr = */ true, /* handle_fp = */ true);
 538   }
 539 }
 540 
 541 void ShenandoahBarrierSetAssembler::card_barrier(MacroAssembler* masm, Register obj) {
 542   assert(ShenandoahCardBarrier, "Should have been checked by caller");
 543 
 544   // Does a store check for the oop in register obj. The content of
 545   // register obj is destroyed afterwards.
 546   __ shrptr(obj, CardTable::card_shift());
 547 
 548   // We'll use this register as the TLS base address and also later on
 549   // to hold the byte_map_base.
 550   Register thread = r15_thread;
 551   Register tmp = rscratch1;
 552 
 553   Address curr_ct_holder_addr(thread, in_bytes(ShenandoahThreadLocalData::card_table_offset()));
 554   __ movptr(tmp, curr_ct_holder_addr);
 555   Address card_addr(tmp, obj, Address::times_1);
 556 
 557   int dirty = CardTable::dirty_card_val();
 558   if (UseCondCardMark) {
 559     Label L_already_dirty;
 560     __ cmpb(card_addr, dirty);
 561     __ jccb(Assembler::equal, L_already_dirty);
 562     __ movb(card_addr, dirty);
 563     __ bind(L_already_dirty);
 564   } else {
 565     __ movb(card_addr, dirty);
 566   }
 567 }
 568 
 569 void ShenandoahBarrierSetAssembler::store_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
 570               Address dst, Register val, Register tmp1, Register tmp2, Register tmp3) {
 571 
 572   // 1: non-reference types require no barriers
 573   if (!is_reference_type(type)) {
 574     BarrierSetAssembler::store_at(masm, decorators, type, dst, val, tmp1, tmp2, tmp3);
 575     return;
 576   }
 577 
 578   // Flatten object address right away for simplicity: likely needed by barriers
 579   assert_different_registers(val, tmp1, tmp2, tmp3, r15_thread);
 580   if (dst.index() == noreg && dst.disp() == 0) {
 581     if (dst.base() != tmp1) {
 582       __ movptr(tmp1, dst.base());
 583     }
 584   } else {
 585     __ lea(tmp1, dst);
 586   }
 587 
 588   bool storing_non_null = (val != noreg);
 589 
 590   // 2: pre-barrier: SATB needs the previous value
 591   if (ShenandoahBarrierSet::need_satb_barrier(decorators, type)) {
 592     satb_barrier(masm,
 593                  tmp1 /* obj */,
 594                  tmp2 /* pre_val */,
 595                  tmp3 /* tmp */,
 596                  storing_non_null /* tosca_live */,
 597                  false /* expand_call */);
 598   }
 599 
 600   // Store!
 601   BarrierSetAssembler::store_at(masm, decorators, type, Address(tmp1, 0), val, noreg, noreg, noreg);
 602 
 603   // 3: post-barrier: card barrier needs store address
 604   if (ShenandoahBarrierSet::need_card_barrier(decorators, type) && storing_non_null) {
 605     card_barrier(masm, tmp1);
 606   }
 607 }
 608 
 609 void ShenandoahBarrierSetAssembler::try_resolve_jobject_in_native(MacroAssembler* masm, Register jni_env,
 610                                                                   Register obj, Register tmp, Label& slowpath) {
 611   Label done;
 612   // Resolve jobject
 613   BarrierSetAssembler::try_resolve_jobject_in_native(masm, jni_env, obj, tmp, slowpath);
 614 
 615   // Check for null.
 616   __ testptr(obj, obj);
 617   __ jcc(Assembler::zero, done);
 618 
 619   Address gc_state(jni_env, ShenandoahThreadLocalData::gc_state_offset() - JavaThread::jni_environment_offset());
 620   __ testb(gc_state, ShenandoahHeap::EVACUATION);
 621   __ jccb(Assembler::notZero, slowpath);
 622   __ bind(done);
 623 }
 624 
 625 #ifdef COMPILER2
 626 void ShenandoahBarrierSetAssembler::try_resolve_weak_handle_in_c2(MacroAssembler* masm, Register obj, Label& slowpath) {
 627   Label done;
 628 
 629   // Resolve weak handle using the standard implementation.
 630   BarrierSetAssembler::try_resolve_weak_handle_in_c2(masm, obj, slowpath);
 631 
 632   // Check if the reference is null, and if it is, take the fast path.
 633   __ testptr(obj, obj);
 634   __ jcc(Assembler::zero, done);
 635 
 636   Address gc_state(r15_thread, ShenandoahThreadLocalData::gc_state_offset());
 637 
 638   // Check if the heap is under weak-reference/roots processing, in
 639   // which case we need to take the slow path.
 640   __ testb(gc_state, ShenandoahHeap::WEAK_ROOTS);
 641   __ jcc(Assembler::notZero, slowpath);
 642   __ bind(done);
 643 }
 644 #endif // COMPILER2
 645 
 646 // Special Shenandoah CAS implementation that handles false negatives
 647 // due to concurrent evacuation.
 648 void ShenandoahBarrierSetAssembler::cmpxchg_oop(MacroAssembler* masm,
 649                                                 Register res, Address addr, Register oldval, Register newval,
 650                                                 bool exchange, Register tmp1, Register tmp2) {
 651   assert(ShenandoahCASBarrier, "Should only be used when CAS barrier is enabled");
 652   assert(oldval == rax, "must be in rax for implicit use in cmpxchg");
 653   assert_different_registers(oldval, tmp1, tmp2);
 654   assert_different_registers(newval, tmp1, tmp2);
 655 
 656   Label L_success, L_failure;
 657 
 658   // Remember oldval for retry logic below
 659   if (UseCompressedOops) {
 660     __ movl(tmp1, oldval);
 661   } else {
 662     __ movptr(tmp1, oldval);
 663   }
 664 
 665   // Step 1. Fast-path.
 666   //
 667   // Try to CAS with given arguments. If successful, then we are done.
 668 
 669   if (UseCompressedOops) {
 670     __ lock();
 671     __ cmpxchgl(newval, addr);
 672   } else {
 673     __ lock();
 674     __ cmpxchgptr(newval, addr);
 675   }
 676   __ jcc(Assembler::equal, L_success);
 677 
 678   // Step 2. CAS had failed. This may be a false negative.
 679   //
 680   // The trouble comes when we compare the to-space pointer with the from-space
 681   // pointer to the same object. To resolve this, it will suffice to resolve
 682   // the value from memory -- this will give both to-space pointers.
 683   // If they mismatch, then it was a legitimate failure.
 684   //
 685   // Before reaching to resolve sequence, see if we can avoid the whole shebang
 686   // with filters.
 687 
 688   // Filter: when offending in-memory value is null, the failure is definitely legitimate
 689   __ testptr(oldval, oldval);
 690   __ jcc(Assembler::zero, L_failure);
 691 
 692   // Filter: when heap is stable, the failure is definitely legitimate
 693   const Register thread = r15_thread;
 694   Address gc_state(thread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
 695   __ testb(gc_state, ShenandoahHeap::HAS_FORWARDED);
 696   __ jcc(Assembler::zero, L_failure);
 697 
 698   if (UseCompressedOops) {
 699     __ movl(tmp2, oldval);
 700     __ decode_heap_oop(tmp2);
 701   } else {
 702     __ movptr(tmp2, oldval);
 703   }
 704 
 705   // Decode offending in-memory value.
 706   // Test if-forwarded
 707   __ testb(Address(tmp2, oopDesc::mark_offset_in_bytes()), markWord::marked_value);
 708   __ jcc(Assembler::noParity, L_failure);  // When odd number of bits, then not forwarded
 709   __ jcc(Assembler::zero, L_failure);      // When it is 00, then also not forwarded
 710 
 711   // Load and mask forwarding pointer
 712   __ movptr(tmp2, Address(tmp2, oopDesc::mark_offset_in_bytes()));
 713   __ shrptr(tmp2, 2);
 714   __ shlptr(tmp2, 2);
 715 
 716   if (UseCompressedOops) {
 717     __ decode_heap_oop(tmp1); // decode for comparison
 718   }
 719 
 720   // Now we have the forwarded offender in tmp2.
 721   // Compare and if they don't match, we have legitimate failure
 722   __ cmpptr(tmp1, tmp2);
 723   __ jcc(Assembler::notEqual, L_failure);
 724 
 725   // Step 3. Need to fix the memory ptr before continuing.
 726   //
 727   // At this point, we have from-space oldval in the register, and its to-space
 728   // address is in tmp2. Let's try to update it into memory. We don't care if it
 729   // succeeds or not. If it does, then the retrying CAS would see it and succeed.
 730   // If this fixup fails, this means somebody else beat us to it, and necessarily
 731   // with to-space ptr store. We still have to do the retry, because the GC might
 732   // have updated the reference for us.
 733 
 734   if (UseCompressedOops) {
 735     __ encode_heap_oop(tmp2); // previously decoded at step 2.
 736   }
 737 
 738   if (UseCompressedOops) {
 739     __ lock();
 740     __ cmpxchgl(tmp2, addr);
 741   } else {
 742     __ lock();
 743     __ cmpxchgptr(tmp2, addr);
 744   }
 745 
 746   // Step 4. Try to CAS again.
 747   //
 748   // This is guaranteed not to have false negatives, because oldval is definitely
 749   // to-space, and memory pointer is to-space as well. Nothing is able to store
 750   // from-space ptr into memory anymore. Make sure oldval is restored, after being
 751   // garbled during retries.
 752   //
 753   if (UseCompressedOops) {
 754     __ movl(oldval, tmp2);
 755   } else {
 756     __ movptr(oldval, tmp2);
 757   }
 758 
 759   if (UseCompressedOops) {
 760     __ lock();
 761     __ cmpxchgl(newval, addr);
 762   } else {
 763     __ lock();
 764     __ cmpxchgptr(newval, addr);
 765   }
 766   if (!exchange) {
 767     __ jccb(Assembler::equal, L_success); // fastpath, peeking into Step 5, no need to jump
 768   }
 769 
 770   // Step 5. If we need a boolean result out of CAS, set the flag appropriately.
 771   // and promote the result. Note that we handle the flag from both the 1st and 2nd CAS.
 772   // Otherwise, failure witness for CAE is in oldval on all paths, and we can return.
 773 
 774   if (exchange) {
 775     __ bind(L_failure);
 776     __ bind(L_success);
 777   } else {
 778     assert(res != noreg, "need result register");
 779 
 780     Label exit;
 781     __ bind(L_failure);
 782     __ xorptr(res, res);
 783     __ jmpb(exit);
 784 
 785     __ bind(L_success);
 786     __ movptr(res, 1);
 787     __ bind(exit);
 788   }
 789 }
 790 
 791 #ifdef PRODUCT
 792 #define BLOCK_COMMENT(str) /* nothing */
 793 #else
 794 #define BLOCK_COMMENT(str) __ block_comment(str)
 795 #endif
 796 
 797 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
 798 
 799 #define TIMES_OOP (UseCompressedOops ? Address::times_4 : Address::times_8)
 800 
 801 void ShenandoahBarrierSetAssembler::gen_write_ref_array_post_barrier(MacroAssembler* masm, DecoratorSet decorators,
 802                                                                      Register addr, Register count,
 803                                                                      Register tmp) {
 804   assert(ShenandoahCardBarrier, "Should have been checked by caller");
 805 
 806   Label L_loop, L_done;
 807   const Register end = count;
 808   assert_different_registers(addr, end);
 809 
 810   // Zero count? Nothing to do.
 811   __ testl(count, count);
 812   __ jccb(Assembler::zero, L_done);
 813 
 814   const Register thread = r15_thread;
 815   Address curr_ct_holder_addr(thread, in_bytes(ShenandoahThreadLocalData::card_table_offset()));
 816   __ movptr(tmp, curr_ct_holder_addr);
 817 
 818   __ leaq(end, Address(addr, count, TIMES_OOP, 0));  // end == addr+count*oop_size
 819   __ subptr(end, BytesPerHeapOop); // end - 1 to make inclusive
 820   __ shrptr(addr, CardTable::card_shift());
 821   __ shrptr(end, CardTable::card_shift());
 822   __ subptr(end, addr); // end --> cards count
 823 
 824   __ addptr(addr, tmp);
 825 
 826   __ BIND(L_loop);
 827   __ movb(Address(addr, count, Address::times_1), 0);
 828   __ decrement(count);
 829   __ jccb(Assembler::greaterEqual, L_loop);
 830 
 831   __ BIND(L_done);
 832 }
 833 
 834 #undef __
 835 
 836 #ifdef COMPILER1
 837 
 838 #define __ ce->masm()->
 839 
 840 void ShenandoahBarrierSetAssembler::gen_pre_barrier_stub(LIR_Assembler* ce, ShenandoahPreBarrierStub* stub) {
 841   ShenandoahBarrierSetC1* bs = (ShenandoahBarrierSetC1*)BarrierSet::barrier_set()->barrier_set_c1();
 842   // At this point we know that marking is in progress.
 843   // If do_load() is true then we have to emit the
 844   // load of the previous value; otherwise it has already
 845   // been loaded into _pre_val.
 846 
 847   __ bind(*stub->entry());
 848   assert(stub->pre_val()->is_register(), "Precondition.");
 849 
 850   Register pre_val_reg = stub->pre_val()->as_register();
 851 
 852   if (stub->do_load()) {
 853     ce->mem2reg(stub->addr(), stub->pre_val(), T_OBJECT, stub->patch_code(), stub->info(), false /*wide*/);
 854   }
 855 
 856   __ cmpptr(pre_val_reg, NULL_WORD);
 857   __ jcc(Assembler::equal, *stub->continuation());
 858   ce->store_parameter(stub->pre_val()->as_register(), 0);
 859   __ call(RuntimeAddress(bs->pre_barrier_c1_runtime_code_blob()->code_begin()));
 860   __ jmp(*stub->continuation());
 861 
 862 }
 863 
 864 void ShenandoahBarrierSetAssembler::gen_load_reference_barrier_stub(LIR_Assembler* ce, ShenandoahLoadReferenceBarrierStub* stub) {
 865   ShenandoahBarrierSetC1* bs = (ShenandoahBarrierSetC1*)BarrierSet::barrier_set()->barrier_set_c1();
 866   __ bind(*stub->entry());
 867 
 868   DecoratorSet decorators = stub->decorators();
 869   bool is_strong  = ShenandoahBarrierSet::is_strong_access(decorators);
 870   bool is_weak    = ShenandoahBarrierSet::is_weak_access(decorators);
 871   bool is_phantom = ShenandoahBarrierSet::is_phantom_access(decorators);
 872   bool is_native  = ShenandoahBarrierSet::is_native_access(decorators);
 873 
 874   Register obj = stub->obj()->as_register();
 875   Register res = stub->result()->as_register();
 876   Register addr = stub->addr()->as_pointer_register();
 877   Register tmp1 = stub->tmp1()->as_register();
 878   Register tmp2 = stub->tmp2()->as_register();
 879   assert_different_registers(obj, res, addr, tmp1, tmp2);
 880 
 881   Label slow_path;
 882 
 883   assert(res == rax, "result must arrive in rax");
 884 
 885   if (res != obj) {
 886     __ mov(res, obj);
 887   }
 888 
 889   if (is_strong) {
 890     // Check for object being in the collection set.
 891     __ mov(tmp1, res);
 892     __ shrptr(tmp1, ShenandoahHeapRegion::region_size_bytes_shift_jint());
 893     __ movptr(tmp2, (intptr_t) ShenandoahHeap::in_cset_fast_test_addr());
 894     __ movbool(tmp2, Address(tmp2, tmp1, Address::times_1));
 895     __ testbool(tmp2);
 896     __ jcc(Assembler::zero, *stub->continuation());
 897   }
 898 
 899   __ bind(slow_path);
 900   ce->store_parameter(res, 0);
 901   ce->store_parameter(addr, 1);
 902   if (is_strong) {
 903     if (is_native) {
 904       __ call(RuntimeAddress(bs->load_reference_barrier_strong_native_rt_code_blob()->code_begin()));
 905     } else {
 906       __ call(RuntimeAddress(bs->load_reference_barrier_strong_rt_code_blob()->code_begin()));
 907     }
 908   } else if (is_weak) {
 909     __ call(RuntimeAddress(bs->load_reference_barrier_weak_rt_code_blob()->code_begin()));
 910   } else {
 911     assert(is_phantom, "only remaining strength");
 912     __ call(RuntimeAddress(bs->load_reference_barrier_phantom_rt_code_blob()->code_begin()));
 913   }
 914   __ jmp(*stub->continuation());
 915 }
 916 
 917 #undef __
 918 
 919 #define __ sasm->
 920 
 921 void ShenandoahBarrierSetAssembler::generate_c1_pre_barrier_runtime_stub(StubAssembler* sasm) {
 922   __ prologue("shenandoah_pre_barrier", false);
 923   // arg0 : previous value of memory
 924 
 925   __ push(rax);
 926   __ push(rdx);
 927 
 928   const Register pre_val = rax;
 929   const Register thread = r15_thread;
 930   const Register tmp = rdx;
 931 
 932   Address queue_index(thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_index_offset()));
 933   Address buffer(thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset()));
 934 
 935   Label done;
 936   Label runtime;
 937 
 938   // Is SATB still active?
 939   Address gc_state(thread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
 940   __ testb(gc_state, ShenandoahHeap::MARKING);
 941   __ jcc(Assembler::zero, done);
 942 
 943   // Can we store original value in the thread's buffer?
 944 
 945   __ movptr(tmp, queue_index);
 946   __ testptr(tmp, tmp);
 947   __ jcc(Assembler::zero, runtime);
 948   __ subptr(tmp, wordSize);
 949   __ movptr(queue_index, tmp);
 950   __ addptr(tmp, buffer);
 951 
 952   // prev_val (rax)
 953   __ load_parameter(0, pre_val);
 954   __ movptr(Address(tmp, 0), pre_val);
 955   __ jmp(done);
 956 
 957   __ bind(runtime);
 958 
 959   __ save_live_registers_no_oop_map(true);
 960 
 961   // load the pre-value
 962   __ load_parameter(0, rcx);
 963   __ call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_barrier_pre), rcx);
 964 
 965   __ restore_live_registers(true);
 966 
 967   __ bind(done);
 968 
 969   __ pop(rdx);
 970   __ pop(rax);
 971 
 972   __ epilogue();
 973 }
 974 
 975 void ShenandoahBarrierSetAssembler::generate_c1_load_reference_barrier_runtime_stub(StubAssembler* sasm, DecoratorSet decorators) {
 976   __ prologue("shenandoah_load_reference_barrier", false);
 977   // arg0 : object to be resolved
 978 
 979   __ save_live_registers_no_oop_map(true);
 980 
 981   bool is_strong  = ShenandoahBarrierSet::is_strong_access(decorators);
 982   bool is_weak    = ShenandoahBarrierSet::is_weak_access(decorators);
 983   bool is_phantom = ShenandoahBarrierSet::is_phantom_access(decorators);
 984   bool is_native  = ShenandoahBarrierSet::is_native_access(decorators);
 985 
 986   __ load_parameter(0, c_rarg0);
 987   __ load_parameter(1, c_rarg1);
 988   if (is_strong) {
 989     if (is_native) {
 990       __ call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong), c_rarg0, c_rarg1);
 991     } else {
 992       if (UseCompressedOops) {
 993         __ call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong_narrow), c_rarg0, c_rarg1);
 994       } else {
 995         __ call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong), c_rarg0, c_rarg1);
 996       }
 997     }
 998   } else if (is_weak) {
 999     assert(!is_native, "weak must not be called off-heap");
1000     if (UseCompressedOops) {
1001       __ call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak_narrow), c_rarg0, c_rarg1);
1002     } else {
1003       __ call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak), c_rarg0, c_rarg1);
1004     }
1005   } else {
1006     assert(is_phantom, "only remaining strength");
1007     assert(is_native, "phantom must only be called off-heap");
1008     __ call_VM_leaf(CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom), c_rarg0, c_rarg1);
1009   }
1010 
1011   __ restore_live_registers_except_rax(true);
1012 
1013   __ epilogue();
1014 }
1015 
1016 #undef __
1017 
1018 #endif // COMPILER1
1019 
1020 #ifdef COMPILER2
1021 #undef __
1022 #define __ masm->
1023 
1024 bool ShenandoahBarrierStubC2::push_save_register_if_live(MacroAssembler* masm, Register reg) {
1025   if (is_live(reg)) {
1026     push_save_register(masm, reg);
1027     return true;
1028   } else {
1029     return false;
1030   }
1031 }
1032 
1033 void ShenandoahBarrierStubC2::push_save_register(MacroAssembler* masm, Register reg) {
1034   __ movptr(Address(rsp, push_save_slot()), reg);
1035 }
1036 
1037 void ShenandoahBarrierStubC2::pop_save_register(MacroAssembler* masm, Register reg) {
1038   __ movptr(reg, Address(rsp, pop_save_slot()));
1039 }
1040 
1041 bool ShenandoahBarrierStubC2::is_live(Register reg) {
1042   // TODO: Precompute the generic register map for faster lookups.
1043   RegMaskIterator rmi(preserve_set());
1044   while (rmi.has_next()) {
1045     const OptoReg::Name opto_reg = rmi.next();
1046     const VMReg vm_reg = OptoReg::as_VMReg(opto_reg);
1047     if (vm_reg->is_Register()) {
1048       if (reg == vm_reg->as_Register()) {
1049         return true;
1050       }
1051     } else if (vm_reg->is_KRegister()) {
1052       // Do not care, skip.
1053     } else if (vm_reg->is_XMMRegister()) {
1054       // Do not care, skip.
1055     } else {
1056       fatal("Unexpected register type");
1057     }
1058   }
1059   return false;
1060 }
1061 
1062 Register ShenandoahBarrierStubC2::select_temp_register(bool& selected_live, Address addr, Register reg1) {
1063   Register tmp = noreg;
1064   Register fallback_live = noreg;
1065 
1066   // Try to select non-live first:
1067   for (int i = 0; i < Register::available_gp_registers(); i++) {
1068     Register r = as_Register(i);
1069     if (r != rsp && r != rbp && r != r12_heapbase && r != r15_thread &&
1070         r != reg1 && r != addr.base() && r != addr.index()) {
1071       if (!is_live(r)) {
1072         tmp = r;
1073         break;
1074       } else if (fallback_live == noreg) {
1075         fallback_live = r;
1076       }
1077     }
1078   }
1079 
1080   // If we could not find a non-live register, select the live fallback:
1081   if (tmp == noreg) {
1082     tmp = fallback_live;
1083     selected_live = true;
1084   } else {
1085     selected_live = false;
1086   }
1087 
1088   assert(tmp != noreg, "successfully selected");
1089   assert_different_registers(tmp, reg1);
1090   assert_different_registers(tmp, addr.base());
1091   assert_different_registers(tmp, addr.index());
1092   return tmp;
1093 }
1094 
1095 void ShenandoahBarrierSetAssembler::gc_state_check_c2(MacroAssembler* masm, const char test_state, BarrierStubC2* slow_stub) {
1096   Assembler::InlineSkippedInstructionsCounter skip_counter(masm);
1097 
1098   if (ShenandoahGCStateCheckRemove) {
1099     // Unrealistic: remove all barrier fastpath checks.
1100   } else if (ShenandoahGCStateCheckHotpatch) {
1101     // In the ideal world, we would hot-patch the branch to slow stub with a single
1102     // (unconditional) jump or nop, based on our current GC state. Unconditional jump
1103     // to near target within the nmethod (at 32-bit offset) takes 5 bytes.
1104     __ nop(5);
1105   } else {
1106     Address gc_state_fast(r15_thread, in_bytes(ShenandoahThreadLocalData::gc_state_fast_offset()));
1107     __ testb(gc_state_fast, ShenandoahThreadLocalData::gc_state_to_fast(test_state));
1108     __ jcc(Assembler::notZero, *slow_stub->entry());
1109     __ bind(*slow_stub->continuation());
1110   }
1111 }
1112 
1113 void ShenandoahBarrierSetAssembler::load_c2(const MachNode* node, MacroAssembler* masm, Register dst, Address src, bool narrow) {
1114   // Do the actual load. This load is the candidate for implicit null check, and MUST come first.
1115   if (narrow) {
1116     __ movl(dst, src);
1117   } else {
1118     __ movq(dst, src);
1119   }
1120 
1121   // Post-barrier: LRB
1122   if (ShenandoahBarrierStubC2::needs_slow_barrier(node)) {
1123     ShenandoahBarrierStubC2* const stub = ShenandoahBarrierStubC2::create(node, dst, src, narrow, false);
1124     char check = 0;
1125     check |= ShenandoahBarrierStubC2::needs_keep_alive_barrier(node)    ? ShenandoahHeap::MARKING : 0;
1126     check |= ShenandoahBarrierStubC2::needs_load_ref_barrier(node)      ? ShenandoahHeap::HAS_FORWARDED : 0;
1127     check |= ShenandoahBarrierStubC2::needs_load_ref_barrier_weak(node) ? ShenandoahHeap::WEAK_ROOTS : 0;
1128     gc_state_check_c2(masm, check, stub);
1129   }
1130 }
1131 
1132 void ShenandoahBarrierSetAssembler::store_c2(const MachNode* node, MacroAssembler* masm,
1133                                              Address dst, bool dst_narrow,
1134                                              Register src, bool src_narrow,
1135                                              Register tmp) {
1136 
1137   // Pre-barrier: SATB, keep-alive the current memory value.
1138   if (ShenandoahBarrierStubC2::needs_slow_barrier(node)) {
1139     assert(!ShenandoahBarrierStubC2::needs_load_ref_barrier(node), "Should not be required for stores");
1140     ShenandoahBarrierStubC2* const stub = ShenandoahBarrierStubC2::create(node, tmp, dst, dst_narrow, true);
1141     gc_state_check_c2(masm, ShenandoahHeap::MARKING, stub);
1142   }
1143 
1144   // Need to encode into tmp, because we cannot clobber src.
1145   // TODO: Maybe there is a matcher way to test that src is unused after this?
1146   if (dst_narrow && !src_narrow) {
1147     __ movq(tmp, src);
1148     if (ShenandoahBarrierStubC2::src_not_null(node)) {
1149       __ encode_heap_oop_not_null(tmp);
1150     } else {
1151       __ encode_heap_oop(tmp);
1152     }
1153     src = tmp;
1154   }
1155 
1156   // Do the actual store
1157   if (dst_narrow) {
1158     __ movl(dst, src);
1159   } else {
1160     __ movq(dst, src);
1161   }
1162 
1163   // Post-barrier: card updates.
1164   if (ShenandoahBarrierStubC2::needs_card_barrier(node)) {
1165     card_barrier_c2(masm, dst, tmp);
1166   }
1167 }
1168 
1169 void ShenandoahBarrierSetAssembler::compare_and_set_c2(const MachNode* node, MacroAssembler* masm,
1170                                                        Register res, Address addr,
1171                                                        Register oldval, Register newval, Register tmp,
1172                                                        bool narrow) {
1173 
1174   assert(oldval == rax, "must be in rax for implicit use in cmpxchg");
1175 
1176   // Oldval and newval can be in the same register, but all other registers should be
1177   // distinct for extra safety, as we shuffle register values around.
1178   assert_different_registers(oldval, tmp, addr.base(), addr.index());
1179   assert_different_registers(newval, tmp, addr.base(), addr.index());
1180 
1181   // Pre-barrier covers several things:
1182   //  a. Avoids false positives from CAS encountering to-space memory values.
1183   //  b. Satisfies the need for LRB for the CAE result.
1184   //  c. Records old value for the sake of SATB.
1185   //
1186   // (a) and (b) are covered because load barrier does memory location fixup.
1187   // (c) is covered by KA on the current memory value.
1188   if (ShenandoahBarrierStubC2::needs_slow_barrier(node)) {
1189     ShenandoahBarrierStubC2* const stub = ShenandoahBarrierStubC2::create(node, tmp, addr, narrow, true);
1190     char check = 0;
1191     check |= ShenandoahBarrierStubC2::needs_keep_alive_barrier(node) ? ShenandoahHeap::MARKING : 0;
1192     check |= ShenandoahBarrierStubC2::needs_load_ref_barrier(node)   ? ShenandoahHeap::HAS_FORWARDED : 0;
1193     assert(!ShenandoahBarrierStubC2::needs_load_ref_barrier_weak(node), "Not supported for CAS");
1194     gc_state_check_c2(masm, check, stub);
1195   }
1196 
1197   // CAS!
1198   __ lock();
1199   if (narrow) {
1200     __ cmpxchgl(newval, addr);
1201   } else {
1202     __ cmpxchgptr(newval, addr);
1203   }
1204 
1205   // If we need a boolean result out of CAS, set the flag appropriately and promote the result.
1206   if (res != noreg) {
1207     __ setcc(Assembler::equal, res);
1208   }
1209 
1210   // Post-barrier deals with card updates.
1211   if (ShenandoahBarrierStubC2::needs_card_barrier(node)) {
1212     card_barrier_c2(masm, addr, tmp);
1213   }
1214 }
1215 
1216 void ShenandoahBarrierSetAssembler::get_and_set_c2(const MachNode* node, MacroAssembler* masm, Register newval, Address addr, Register tmp, bool narrow) {
1217   assert_different_registers(newval, tmp, addr.base(), addr.index());
1218 
1219   // Pre-barrier covers several things:
1220   //  a. Satisfies the need for LRB for the GAS result.
1221   //  b. Records old value for the sake of SATB.
1222   //
1223   // (a) is covered because load barrier does memory location fixup.
1224   // (b) is covered by KA on the current memory value.
1225   if (ShenandoahBarrierStubC2::needs_slow_barrier(node)) {
1226     ShenandoahBarrierStubC2* const stub = ShenandoahBarrierStubC2::create(node, tmp, addr, narrow, true);
1227     char check = 0;
1228     check |= ShenandoahBarrierStubC2::needs_keep_alive_barrier(node) ? ShenandoahHeap::MARKING : 0;
1229     check |= ShenandoahBarrierStubC2::needs_load_ref_barrier(node)   ? ShenandoahHeap::HAS_FORWARDED : 0;
1230     assert(!ShenandoahBarrierStubC2::needs_load_ref_barrier_weak(node), "Not supported for GAS");
1231     gc_state_check_c2(masm, check, stub);
1232   }
1233 
1234   if (narrow) {
1235     __ xchgl(newval, addr);
1236   } else {
1237     __ xchgq(newval, addr);
1238   }
1239 
1240   // Post-barrier deals with card updates.
1241   if (ShenandoahBarrierStubC2::needs_card_barrier(node)) {
1242     card_barrier_c2(masm, addr, tmp);
1243   }
1244 }
1245 
1246 void ShenandoahBarrierSetAssembler::card_barrier_c2(MacroAssembler* masm, Address dst, Register tmp) {
1247   Assembler::InlineSkippedInstructionsCounter skip_counter(masm);
1248 
1249   // TODO: Might be a good place to implement some filters here.
1250   // For example, G1 only flips card marks for stores within a single region.
1251 
1252   __ lea(tmp, dst);
1253   __ shrptr(tmp, CardTable::card_shift());
1254   __ addptr(tmp, Address(r15_thread, in_bytes(ShenandoahThreadLocalData::card_table_offset())));
1255   Address card_address(tmp, 0);
1256 
1257   assert(CardTable::dirty_card_val() == 0, "Encoding assumption");
1258   Label L_done;
1259   if (UseCondCardMark) {
1260     __ cmpb(card_address, 0);
1261     __ jccb(Assembler::equal, L_done);
1262   }
1263   if (UseCompressedOops && CompressedOops::base() == nullptr) {
1264     __ movb(card_address, r12);
1265   } else {
1266     __ movb(card_address, 0);
1267   }
1268   __ bind(L_done);
1269 }
1270 
1271 void ShenandoahBarrierStubC2::keepalive(MacroAssembler* masm, Register obj, Register tmp1, Register tmp2) {
1272   Address index(r15_thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_index_offset()));
1273   Address buffer(r15_thread, in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset()));
1274 
1275   Label L_fast, L_done;
1276 
1277   // If another barrier is enabled as well, do a runtime check for a specific barrier.
1278   if (_needs_load_ref_barrier) {
1279     Address gc_state(r15_thread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
1280     __ testb(gc_state, ShenandoahHeap::MARKING);
1281     __ jccb(Assembler::zero, L_done);
1282   }
1283 
1284   // Check if buffer is already full. Go slow, if so.
1285   __ movptr(tmp1, index);
1286   __ testptr(tmp1, tmp1);
1287   __ jccb(Assembler::notZero, L_fast);
1288 
1289   // Slow-path: call runtime to handle.
1290   {
1291     // Shuffle in the arguments. The end result should be:
1292     //   c_rarg0 <-- obj
1293     //
1294     // Save clobbered registers before overwriting them.
1295     bool clobbered_c_rarg0 = false;
1296     if (c_rarg0 != obj) {
1297       clobbered_c_rarg0 = push_save_register_if_live(masm, c_rarg0);
1298       __ mov(c_rarg0, obj);
1299     }
1300 
1301     // Go to runtime stub and handle the rest there.
1302     __ call(RuntimeAddress(keepalive_runtime_entry_addr()));
1303 
1304     // Restore the clobbered registers.
1305     if (clobbered_c_rarg0) {
1306       pop_save_register(masm, c_rarg0);
1307     }
1308     __ jmpb(L_done);
1309   }
1310 
1311   // Fast-path: put object into buffer.
1312   __ bind(L_fast);
1313   __ subptr(tmp1, wordSize);
1314   __ movptr(index, tmp1);
1315   __ addptr(tmp1, buffer);
1316   __ movptr(Address(tmp1, 0), obj);
1317 
1318   __ bind(L_done);
1319 }
1320 
1321 void ShenandoahBarrierStubC2::lrb(MacroAssembler* masm, Register obj, Address addr, Register tmp) {
1322   Label L_done;
1323 
1324   // If another barrier is enabled as well, do a runtime check for a specific barrier.
1325   if (_needs_keep_alive_barrier) {
1326     Address gc_state(r15_thread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
1327     __ testb(gc_state, ShenandoahHeap::HAS_FORWARDED | (_needs_load_ref_weak_barrier ? ShenandoahHeap::WEAK_ROOTS : 0));
1328     __ jccb(Assembler::zero, L_done);
1329   }
1330 
1331   // Weak/phantom loads are handled in slow path.
1332   if (!_needs_load_ref_weak_barrier) {
1333     // Compute the cset bitmap index
1334     __ movptr(tmp, obj);
1335     __ shrptr(tmp, ShenandoahHeapRegion::region_size_bytes_shift_jint());
1336 
1337     // If cset address is in good spot to just use it as offset. It almost always is.
1338     Address cset_addr_arg;
1339     intptr_t cset_addr = (intptr_t) ShenandoahHeap::in_cset_fast_test_addr();
1340     if ((cset_addr >> 3) < INT32_MAX) {
1341       assert(is_aligned(cset_addr, 8), "Sanity");
1342       cset_addr_arg = Address(tmp, checked_cast<int>(cset_addr >> 3), Address::times_8);
1343     } else {
1344       __ addptr(tmp, cset_addr);
1345       cset_addr_arg = Address(tmp, 0);
1346     }
1347 
1348     // Cset-check. Fall-through to slow if in collection set.
1349     __ cmpb(cset_addr_arg, 0);
1350     __ jccb(Assembler::equal, L_done);
1351   }
1352 
1353   // Slow path
1354   {
1355     assert_different_registers(rax, c_rarg0, c_rarg1);
1356 
1357     // Shuffle in the arguments. The end result should be:
1358     //   c_rarg0 <-- obj
1359     //   c_rarg1 <-- lea(addr)
1360     //
1361     // Save clobbered registers before overwriting them, unless they
1362     // carry obj, which would be overwritten on return.
1363     bool clobbered_c_rarg0 = false;
1364     bool clobbered_c_rarg1 = false;
1365     bool clobbered_rax = false;
1366 
1367     if (obj == c_rarg0) {
1368       clobbered_c_rarg1 = push_save_register_if_live(masm, c_rarg1);
1369       __ lea(c_rarg1, addr);
1370     } else if (obj == c_rarg1) {
1371       // Set up arguments in reverse, and then flip them
1372       clobbered_c_rarg0 = push_save_register_if_live(masm, c_rarg0);
1373       __ lea(c_rarg0, addr);
1374       __ xchgptr(c_rarg0, c_rarg1);
1375     } else {
1376       assert_different_registers(obj, c_rarg0, c_rarg1);
1377       clobbered_c_rarg0 = push_save_register_if_live(masm, c_rarg0);
1378       clobbered_c_rarg1 = push_save_register_if_live(masm, c_rarg1);
1379       __ lea(c_rarg1, addr);
1380       __ movptr(c_rarg0, obj);
1381     }
1382     if (obj != rax) {
1383       clobbered_rax = push_save_register_if_live(masm, rax);
1384     }
1385 
1386     // Go to runtime stub and handle the rest there.
1387     __ call(RuntimeAddress(lrb_runtime_entry_addr()));
1388 
1389     // Save the result where needed and restore the clobbered registers.
1390     if (obj != rax) {
1391       __ movptr(obj, rax);
1392     }
1393     if (clobbered_rax) {
1394       pop_save_register(masm, rax);
1395     }
1396     if (clobbered_c_rarg1) {
1397       pop_save_register(masm, c_rarg1);
1398     }
1399     if (clobbered_c_rarg0) {
1400       pop_save_register(masm, c_rarg0);
1401     }
1402   }
1403 
1404   __ bind(L_done);
1405 }
1406 
1407 #undef __
1408 #define __ masm.
1409 
1410 void ShenandoahBarrierStubC2::emit_code(MacroAssembler& masm) {
1411   assert(_needs_keep_alive_barrier || _needs_load_ref_barrier, "Why are you here?");
1412 
1413   __ bind(*entry());
1414 
1415   Label L_done;
1416 
1417   // If we need to load ourselves, do it here.
1418   if (_do_load) {
1419     if (_narrow) {
1420       __ movl(_obj, _addr);
1421     } else {
1422       __ movq(_obj, _addr);
1423     }
1424   }
1425 
1426   // If the object is null, there is no point in applying barriers.
1427   if (_narrow) {
1428     __ testl(_obj, _obj);
1429   } else {
1430     __ testptr(_obj, _obj);
1431   }
1432   __ jcc(Assembler::zero, L_done);
1433 
1434   // Barriers need temp to work, allocate one now.
1435   bool tmp_live;
1436   Register tmp = select_temp_register(tmp_live, _addr, _obj);
1437   if (tmp_live) {
1438     push_save_register(&masm, tmp);
1439   }
1440 
1441   // If object is narrow, we need to decode it first: barrier checks need full oops.
1442   if (_narrow) {
1443     __ decode_heap_oop_not_null(_obj);
1444   }
1445 
1446   // Go for barriers. If both barriers are required (rare), do a runtime check for enabled barrier.
1447   if (_needs_keep_alive_barrier) {
1448     keepalive(&masm, _obj, tmp, noreg);
1449   }
1450   if (_needs_load_ref_barrier) {
1451     lrb(&masm, _obj, _addr, tmp);
1452   }
1453 
1454   if (tmp_live) {
1455     pop_save_register(&masm, tmp);
1456   }
1457 
1458   // If object is narrow, we need to encode it before exiting.
1459   // For encoding, dst can only turn null if we are dealing with weak loads.
1460   // Otherwise, we have already null-checked. We can skip all this if we performed
1461   // the load ourselves, which means the value is not used by caller.
1462   if (_narrow && !_do_load) {
1463     if (_needs_load_ref_weak_barrier) {
1464       __ encode_heap_oop(_obj);
1465     } else {
1466       __ encode_heap_oop_not_null(_obj);
1467     }
1468   }
1469   __ bind(L_done);
1470   __ jmp(*continuation());
1471 }
1472 
1473 Label* ShenandoahBarrierStubC2::entry() {
1474   return BarrierStubC2::entry();
1475 }
1476 
1477 ShenandoahBarrierStubC2::ShenandoahBarrierStubC2(const MachNode* node, Register obj, Address addr, bool narrow, bool do_load, int offset) : BarrierStubC2(node),
1478   _obj(obj),
1479   _addr(addr),
1480   _do_load(do_load),
1481   _narrow(narrow),
1482   _maybe_null(!src_not_null(node)),
1483   _needs_load_ref_barrier(needs_load_ref_barrier(node)),
1484   _needs_load_ref_weak_barrier(needs_load_ref_barrier_weak(node)),
1485   _needs_keep_alive_barrier(needs_keep_alive_barrier(node)),
1486   _fastpath_branch_offset(),
1487   _test_and_branch_reachable(),
1488   _skip_trampoline(),
1489   _test_and_branch_reachable_entry() {
1490 
1491   ShenandoahBarrierStubC2(node, obj, addr, narrow, do_load);
1492 }
1493 #undef __
1494 #endif