1 /*
   2  * Copyright (c) 2018, 2023, Red Hat, Inc. 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 #include "precompiled.hpp"
  26 #include "classfile/javaClasses.hpp"
  27 #include "gc/shared/barrierSet.hpp"
  28 #include "gc/shenandoah/shenandoahBarrierSet.hpp"
  29 #include "gc/shenandoah/shenandoahForwarding.hpp"
  30 #include "gc/shenandoah/shenandoahHeap.hpp"
  31 #include "gc/shenandoah/shenandoahRuntime.hpp"
  32 #include "gc/shenandoah/shenandoahThreadLocalData.hpp"
  33 #include "gc/shenandoah/c2/shenandoahBarrierSetC2.hpp"
  34 #include "gc/shenandoah/c2/shenandoahSupport.hpp"
  35 #include "gc/shenandoah/heuristics/shenandoahHeuristics.hpp"
  36 #include "opto/arraycopynode.hpp"
  37 #include "opto/escape.hpp"
  38 #include "opto/graphKit.hpp"
  39 #include "opto/idealKit.hpp"
  40 #include "opto/macro.hpp"
  41 #include "opto/movenode.hpp"
  42 #include "opto/narrowptrnode.hpp"
  43 #include "opto/rootnode.hpp"
  44 #include "opto/runtime.hpp"
  45 
  46 ShenandoahBarrierSetC2* ShenandoahBarrierSetC2::bsc2() {
  47   return reinterpret_cast<ShenandoahBarrierSetC2*>(BarrierSet::barrier_set()->barrier_set_c2());
  48 }
  49 
  50 ShenandoahBarrierSetC2State::ShenandoahBarrierSetC2State(Arena* comp_arena)
  51   : _iu_barriers(new (comp_arena) GrowableArray<ShenandoahIUBarrierNode*>(comp_arena, 8,  0, nullptr)),
  52     _load_reference_barriers(new (comp_arena) GrowableArray<ShenandoahLoadReferenceBarrierNode*>(comp_arena, 8,  0, nullptr)) {
  53 }
  54 
  55 int ShenandoahBarrierSetC2State::iu_barriers_count() const {
  56   return _iu_barriers->length();
  57 }
  58 
  59 ShenandoahIUBarrierNode* ShenandoahBarrierSetC2State::iu_barrier(int idx) const {
  60   return _iu_barriers->at(idx);
  61 }
  62 
  63 void ShenandoahBarrierSetC2State::add_iu_barrier(ShenandoahIUBarrierNode* n) {
  64   assert(!_iu_barriers->contains(n), "duplicate entry in barrier list");
  65   _iu_barriers->append(n);
  66 }
  67 
  68 void ShenandoahBarrierSetC2State::remove_iu_barrier(ShenandoahIUBarrierNode* n) {
  69   _iu_barriers->remove_if_existing(n);
  70 }
  71 
  72 int ShenandoahBarrierSetC2State::load_reference_barriers_count() const {
  73   return _load_reference_barriers->length();
  74 }
  75 
  76 ShenandoahLoadReferenceBarrierNode* ShenandoahBarrierSetC2State::load_reference_barrier(int idx) const {
  77   return _load_reference_barriers->at(idx);
  78 }
  79 
  80 void ShenandoahBarrierSetC2State::add_load_reference_barrier(ShenandoahLoadReferenceBarrierNode * n) {
  81   assert(!_load_reference_barriers->contains(n), "duplicate entry in barrier list");
  82   _load_reference_barriers->append(n);
  83 }
  84 
  85 void ShenandoahBarrierSetC2State::remove_load_reference_barrier(ShenandoahLoadReferenceBarrierNode * n) {
  86   if (_load_reference_barriers->contains(n)) {
  87     _load_reference_barriers->remove(n);
  88   }
  89 }
  90 
  91 Node* ShenandoahBarrierSetC2::shenandoah_iu_barrier(GraphKit* kit, Node* obj) const {
  92   if (ShenandoahIUBarrier) {
  93     return kit->gvn().transform(new ShenandoahIUBarrierNode(obj));
  94   }
  95   return obj;
  96 }
  97 
  98 #define __ kit->
  99 
 100 bool ShenandoahBarrierSetC2::satb_can_remove_pre_barrier(GraphKit* kit, PhaseValues* phase, Node* adr,
 101                                                          BasicType bt, uint adr_idx) const {
 102   intptr_t offset = 0;
 103   Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset);
 104   AllocateNode* alloc = AllocateNode::Ideal_allocation(base);
 105 
 106   if (offset == Type::OffsetBot) {
 107     return false; // cannot unalias unless there are precise offsets
 108   }
 109 
 110   if (alloc == nullptr) {
 111     return false; // No allocation found
 112   }
 113 
 114   intptr_t size_in_bytes = type2aelembytes(bt);
 115 
 116   Node* mem = __ memory(adr_idx); // start searching here...
 117 
 118   for (int cnt = 0; cnt < 50; cnt++) {
 119 
 120     if (mem->is_Store()) {
 121 
 122       Node* st_adr = mem->in(MemNode::Address);
 123       intptr_t st_offset = 0;
 124       Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_offset);
 125 
 126       if (st_base == nullptr) {
 127         break; // inscrutable pointer
 128       }
 129 
 130       // Break we have found a store with same base and offset as ours so break
 131       if (st_base == base && st_offset == offset) {
 132         break;
 133       }
 134 
 135       if (st_offset != offset && st_offset != Type::OffsetBot) {
 136         const int MAX_STORE = BytesPerLong;
 137         if (st_offset >= offset + size_in_bytes ||
 138             st_offset <= offset - MAX_STORE ||
 139             st_offset <= offset - mem->as_Store()->memory_size()) {
 140           // Success:  The offsets are provably independent.
 141           // (You may ask, why not just test st_offset != offset and be done?
 142           // The answer is that stores of different sizes can co-exist
 143           // in the same sequence of RawMem effects.  We sometimes initialize
 144           // a whole 'tile' of array elements with a single jint or jlong.)
 145           mem = mem->in(MemNode::Memory);
 146           continue; // advance through independent store memory
 147         }
 148       }
 149 
 150       if (st_base != base
 151           && MemNode::detect_ptr_independence(base, alloc, st_base,
 152                                               AllocateNode::Ideal_allocation(st_base),
 153                                               phase)) {
 154         // Success:  The bases are provably independent.
 155         mem = mem->in(MemNode::Memory);
 156         continue; // advance through independent store memory
 157       }
 158     } else if (mem->is_Proj() && mem->in(0)->is_Initialize()) {
 159 
 160       InitializeNode* st_init = mem->in(0)->as_Initialize();
 161       AllocateNode* st_alloc = st_init->allocation();
 162 
 163       // Make sure that we are looking at the same allocation site.
 164       // The alloc variable is guaranteed to not be null here from earlier check.
 165       if (alloc == st_alloc) {
 166         // Check that the initialization is storing null so that no previous store
 167         // has been moved up and directly write a reference
 168         Node* captured_store = st_init->find_captured_store(offset,
 169                                                             type2aelembytes(T_OBJECT),
 170                                                             phase);
 171         if (captured_store == nullptr || captured_store == st_init->zero_memory()) {
 172           return true;
 173         }
 174       }
 175     }
 176 
 177     // Unless there is an explicit 'continue', we must bail out here,
 178     // because 'mem' is an inscrutable memory state (e.g., a call).
 179     break;
 180   }
 181 
 182   return false;
 183 }
 184 
 185 #undef __
 186 #define __ ideal.
 187 
 188 void ShenandoahBarrierSetC2::satb_write_barrier_pre(GraphKit* kit,
 189                                                     bool do_load,
 190                                                     Node* obj,
 191                                                     Node* adr,
 192                                                     uint alias_idx,
 193                                                     Node* val,
 194                                                     const TypeOopPtr* val_type,
 195                                                     Node* pre_val,
 196                                                     BasicType bt) const {
 197   // Some sanity checks
 198   // Note: val is unused in this routine.
 199 
 200   if (do_load) {
 201     // We need to generate the load of the previous value
 202     assert(adr != nullptr, "where are loading from?");
 203     assert(pre_val == nullptr, "loaded already?");
 204     assert(val_type != nullptr, "need a type");
 205 
 206     if (ReduceInitialCardMarks
 207         && satb_can_remove_pre_barrier(kit, &kit->gvn(), adr, bt, alias_idx)) {
 208       return;
 209     }
 210 
 211   } else {
 212     // In this case both val_type and alias_idx are unused.
 213     assert(pre_val != nullptr, "must be loaded already");
 214     // Nothing to be done if pre_val is null.
 215     if (pre_val->bottom_type() == TypePtr::NULL_PTR) return;
 216     assert(pre_val->bottom_type()->basic_type() == T_OBJECT, "or we shouldn't be here");
 217   }
 218   assert(bt == T_OBJECT, "or we shouldn't be here");
 219 
 220   IdealKit ideal(kit, true);
 221 
 222   Node* tls = __ thread(); // ThreadLocalStorage
 223 
 224   Node* no_base = __ top();
 225   Node* zero  = __ ConI(0);
 226   Node* zeroX = __ ConX(0);
 227 
 228   float likely  = PROB_LIKELY(0.999);
 229   float unlikely  = PROB_UNLIKELY(0.999);
 230 
 231   // Offsets into the thread
 232   const int index_offset   = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_index_offset());
 233   const int buffer_offset  = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset());
 234 
 235   // Now the actual pointers into the thread
 236   Node* buffer_adr  = __ AddP(no_base, tls, __ ConX(buffer_offset));
 237   Node* index_adr   = __ AddP(no_base, tls, __ ConX(index_offset));
 238 
 239   // Now some of the values
 240   Node* marking;
 241   Node* gc_state = __ AddP(no_base, tls, __ ConX(in_bytes(ShenandoahThreadLocalData::gc_state_offset())));
 242   Node* ld = __ load(__ ctrl(), gc_state, TypeInt::BYTE, T_BYTE, Compile::AliasIdxRaw);
 243   marking = __ AndI(ld, __ ConI(ShenandoahHeap::MARKING));
 244   assert(ShenandoahBarrierC2Support::is_gc_state_load(ld), "Should match the shape");
 245 
 246   // if (!marking)
 247   __ if_then(marking, BoolTest::ne, zero, unlikely); {
 248     BasicType index_bt = TypeX_X->basic_type();
 249     assert(sizeof(size_t) == type2aelembytes(index_bt), "Loading Shenandoah SATBMarkQueue::_index with wrong size.");
 250     Node* index   = __ load(__ ctrl(), index_adr, TypeX_X, index_bt, Compile::AliasIdxRaw);
 251 
 252     if (do_load) {
 253       // load original value
 254       // alias_idx correct??
 255       pre_val = __ load(__ ctrl(), adr, val_type, bt, alias_idx);
 256     }
 257 
 258     // if (pre_val != nullptr)
 259     __ if_then(pre_val, BoolTest::ne, kit->null()); {
 260       Node* buffer  = __ load(__ ctrl(), buffer_adr, TypeRawPtr::NOTNULL, T_ADDRESS, Compile::AliasIdxRaw);
 261 
 262       // is the queue for this thread full?
 263       __ if_then(index, BoolTest::ne, zeroX, likely); {
 264 
 265         // decrement the index
 266         Node* next_index = kit->gvn().transform(new SubXNode(index, __ ConX(sizeof(intptr_t))));
 267 
 268         // Now get the buffer location we will log the previous value into and store it
 269         Node *log_addr = __ AddP(no_base, buffer, next_index);
 270         __ store(__ ctrl(), log_addr, pre_val, T_OBJECT, Compile::AliasIdxRaw, MemNode::unordered);
 271         // update the index
 272         __ store(__ ctrl(), index_adr, next_index, index_bt, Compile::AliasIdxRaw, MemNode::unordered);
 273 
 274       } __ else_(); {
 275 
 276         // logging buffer is full, call the runtime
 277         const TypeFunc *tf = ShenandoahBarrierSetC2::write_ref_field_pre_entry_Type();
 278         __ make_leaf_call(tf, CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_ref_field_pre_entry), "shenandoah_wb_pre", pre_val, tls);
 279       } __ end_if();  // (!index)
 280     } __ end_if();  // (pre_val != nullptr)
 281   } __ end_if();  // (!marking)
 282 
 283   // Final sync IdealKit and GraphKit.
 284   kit->final_sync(ideal);
 285 
 286   if (ShenandoahSATBBarrier && adr != nullptr) {
 287     Node* c = kit->control();
 288     Node* call = c->in(1)->in(1)->in(1)->in(0);
 289     assert(is_shenandoah_wb_pre_call(call), "shenandoah_wb_pre call expected");
 290     call->add_req(adr);
 291   }
 292 }
 293 
 294 bool ShenandoahBarrierSetC2::is_shenandoah_wb_pre_call(Node* call) {
 295   return call->is_CallLeaf() &&
 296          call->as_CallLeaf()->entry_point() == CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_ref_field_pre_entry);
 297 }
 298 
 299 bool ShenandoahBarrierSetC2::is_shenandoah_lrb_call(Node* call) {
 300   if (!call->is_CallLeaf()) {
 301     return false;
 302   }
 303 
 304   address entry_point = call->as_CallLeaf()->entry_point();
 305   return (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong)) ||
 306          (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong_narrow)) ||
 307          (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak)) ||
 308          (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak_narrow)) ||
 309          (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom));
 310 }
 311 
 312 bool ShenandoahBarrierSetC2::is_shenandoah_marking_if(PhaseValues* phase, Node* n) {
 313   if (n->Opcode() != Op_If) {
 314     return false;
 315   }
 316 
 317   Node* bol = n->in(1);
 318   assert(bol->is_Bool(), "");
 319   Node* cmpx = bol->in(1);
 320   if (bol->as_Bool()->_test._test == BoolTest::ne &&
 321       cmpx->is_Cmp() && cmpx->in(2) == phase->intcon(0) &&
 322       is_shenandoah_state_load(cmpx->in(1)->in(1)) &&
 323       cmpx->in(1)->in(2)->is_Con() &&
 324       cmpx->in(1)->in(2) == phase->intcon(ShenandoahHeap::MARKING)) {
 325     return true;
 326   }
 327 
 328   return false;
 329 }
 330 
 331 bool ShenandoahBarrierSetC2::is_shenandoah_state_load(Node* n) {
 332   if (!n->is_Load()) return false;
 333   const int state_offset = in_bytes(ShenandoahThreadLocalData::gc_state_offset());
 334   return n->in(2)->is_AddP() && n->in(2)->in(2)->Opcode() == Op_ThreadLocal
 335          && n->in(2)->in(3)->is_Con()
 336          && n->in(2)->in(3)->bottom_type()->is_intptr_t()->get_con() == state_offset;
 337 }
 338 
 339 void ShenandoahBarrierSetC2::shenandoah_write_barrier_pre(GraphKit* kit,
 340                                                           bool do_load,
 341                                                           Node* obj,
 342                                                           Node* adr,
 343                                                           uint alias_idx,
 344                                                           Node* val,
 345                                                           const TypeOopPtr* val_type,
 346                                                           Node* pre_val,
 347                                                           BasicType bt) const {
 348   if (ShenandoahSATBBarrier) {
 349     IdealKit ideal(kit);
 350     kit->sync_kit(ideal);
 351 
 352     satb_write_barrier_pre(kit, do_load, obj, adr, alias_idx, val, val_type, pre_val, bt);
 353 
 354     ideal.sync_kit(kit);
 355     kit->final_sync(ideal);
 356   }
 357 }
 358 
 359 // Helper that guards and inserts a pre-barrier.
 360 void ShenandoahBarrierSetC2::insert_pre_barrier(GraphKit* kit, Node* base_oop, Node* offset,
 361                                                 Node* pre_val, bool need_mem_bar) const {
 362   // We could be accessing the referent field of a reference object. If so, when Shenandoah
 363   // is enabled, we need to log the value in the referent field in an SATB buffer.
 364   // This routine performs some compile time filters and generates suitable
 365   // runtime filters that guard the pre-barrier code.
 366   // Also add memory barrier for non volatile load from the referent field
 367   // to prevent commoning of loads across safepoint.
 368 
 369   // Some compile time checks.
 370 
 371   // If offset is a constant, is it java_lang_ref_Reference::_reference_offset?
 372   const TypeX* otype = offset->find_intptr_t_type();
 373   if (otype != nullptr && otype->is_con() &&
 374       otype->get_con() != java_lang_ref_Reference::referent_offset()) {
 375     // Constant offset but not the reference_offset so just return
 376     return;
 377   }
 378 
 379   // We only need to generate the runtime guards for instances.
 380   const TypeOopPtr* btype = base_oop->bottom_type()->isa_oopptr();
 381   if (btype != nullptr) {
 382     if (btype->isa_aryptr()) {
 383       // Array type so nothing to do
 384       return;
 385     }
 386 
 387     const TypeInstPtr* itype = btype->isa_instptr();
 388     if (itype != nullptr) {
 389       // Can the klass of base_oop be statically determined to be
 390       // _not_ a sub-class of Reference and _not_ Object?
 391       ciKlass* klass = itype->instance_klass();
 392       if (klass->is_loaded() &&
 393           !klass->is_subtype_of(kit->env()->Reference_klass()) &&
 394           !kit->env()->Object_klass()->is_subtype_of(klass)) {
 395         return;
 396       }
 397     }
 398   }
 399 
 400   // The compile time filters did not reject base_oop/offset so
 401   // we need to generate the following runtime filters
 402   //
 403   // if (offset == java_lang_ref_Reference::_reference_offset) {
 404   //   if (instance_of(base, java.lang.ref.Reference)) {
 405   //     pre_barrier(_, pre_val, ...);
 406   //   }
 407   // }
 408 
 409   float likely   = PROB_LIKELY(  0.999);
 410   float unlikely = PROB_UNLIKELY(0.999);
 411 
 412   IdealKit ideal(kit);
 413 
 414   Node* referent_off = __ ConX(java_lang_ref_Reference::referent_offset());
 415 
 416   __ if_then(offset, BoolTest::eq, referent_off, unlikely); {
 417       // Update graphKit memory and control from IdealKit.
 418       kit->sync_kit(ideal);
 419 
 420       Node* ref_klass_con = kit->makecon(TypeKlassPtr::make(kit->env()->Reference_klass()));
 421       Node* is_instof = kit->gen_instanceof(base_oop, ref_klass_con);
 422 
 423       // Update IdealKit memory and control from graphKit.
 424       __ sync_kit(kit);
 425 
 426       Node* one = __ ConI(1);
 427       // is_instof == 0 if base_oop == nullptr
 428       __ if_then(is_instof, BoolTest::eq, one, unlikely); {
 429 
 430         // Update graphKit from IdeakKit.
 431         kit->sync_kit(ideal);
 432 
 433         // Use the pre-barrier to record the value in the referent field
 434         satb_write_barrier_pre(kit, false /* do_load */,
 435                                nullptr /* obj */, nullptr /* adr */, max_juint /* alias_idx */, nullptr /* val */, nullptr /* val_type */,
 436                                pre_val /* pre_val */,
 437                                T_OBJECT);
 438         if (need_mem_bar) {
 439           // Add memory barrier to prevent commoning reads from this field
 440           // across safepoint since GC can change its value.
 441           kit->insert_mem_bar(Op_MemBarCPUOrder);
 442         }
 443         // Update IdealKit from graphKit.
 444         __ sync_kit(kit);
 445 
 446       } __ end_if(); // _ref_type != ref_none
 447   } __ end_if(); // offset == referent_offset
 448 
 449   // Final sync IdealKit and GraphKit.
 450   kit->final_sync(ideal);
 451 }
 452 
 453 #undef __
 454 
 455 const TypeFunc* ShenandoahBarrierSetC2::write_ref_field_pre_entry_Type() {
 456   const Type **fields = TypeTuple::fields(2);
 457   fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL; // original field value
 458   fields[TypeFunc::Parms+1] = TypeRawPtr::NOTNULL; // thread
 459   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2, fields);
 460 
 461   // create result type (range)
 462   fields = TypeTuple::fields(0);
 463   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+0, fields);
 464 
 465   return TypeFunc::make(domain, range);
 466 }
 467 
 468 const TypeFunc* ShenandoahBarrierSetC2::shenandoah_clone_barrier_Type() {
 469   const Type **fields = TypeTuple::fields(1);
 470   fields[TypeFunc::Parms+0] = TypeOopPtr::NOTNULL; // src oop
 471   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+1, fields);
 472 
 473   // create result type (range)
 474   fields = TypeTuple::fields(0);
 475   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+0, fields);
 476 
 477   return TypeFunc::make(domain, range);
 478 }
 479 
 480 const TypeFunc* ShenandoahBarrierSetC2::shenandoah_load_reference_barrier_Type() {
 481   const Type **fields = TypeTuple::fields(2);
 482   fields[TypeFunc::Parms+0] = TypeOopPtr::BOTTOM; // original field value
 483   fields[TypeFunc::Parms+1] = TypeRawPtr::BOTTOM; // original load address
 484 
 485   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2, fields);
 486 
 487   // create result type (range)
 488   fields = TypeTuple::fields(1);
 489   fields[TypeFunc::Parms+0] = TypeOopPtr::BOTTOM;
 490   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+1, fields);
 491 
 492   return TypeFunc::make(domain, range);
 493 }
 494 
 495 Node* ShenandoahBarrierSetC2::store_at_resolved(C2Access& access, C2AccessValue& val) const {
 496   DecoratorSet decorators = access.decorators();
 497 
 498   const TypePtr* adr_type = access.addr().type();
 499   Node* adr = access.addr().node();
 500 
 501   if (!access.is_oop()) {
 502     return BarrierSetC2::store_at_resolved(access, val);
 503   }
 504 
 505   if (access.is_parse_access()) {
 506     C2ParseAccess& parse_access = static_cast<C2ParseAccess&>(access);
 507     GraphKit* kit = parse_access.kit();
 508 
 509     uint adr_idx = kit->C->get_alias_index(adr_type);
 510     assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
 511     Node* value = val.node();
 512     value = shenandoah_iu_barrier(kit, value);
 513     val.set_node(value);
 514     shenandoah_write_barrier_pre(kit, true /* do_load */, /*kit->control(),*/ access.base(), adr, adr_idx, val.node(),
 515                                  static_cast<const TypeOopPtr*>(val.type()), nullptr /* pre_val */, access.type());
 516   } else {
 517     assert(access.is_opt_access(), "only for optimization passes");
 518     assert(((decorators & C2_TIGHTLY_COUPLED_ALLOC) != 0 || !ShenandoahSATBBarrier) && (decorators & C2_ARRAY_COPY) != 0, "unexpected caller of this code");
 519     C2OptAccess& opt_access = static_cast<C2OptAccess&>(access);
 520     PhaseGVN& gvn =  opt_access.gvn();
 521 
 522     if (ShenandoahIUBarrier) {
 523       Node* enqueue = gvn.transform(new ShenandoahIUBarrierNode(val.node()));
 524       val.set_node(enqueue);
 525     }
 526   }
 527   return BarrierSetC2::store_at_resolved(access, val);
 528 }
 529 
 530 Node* ShenandoahBarrierSetC2::load_at_resolved(C2Access& access, const Type* val_type) const {
 531   // 1: non-reference load, no additional barrier is needed
 532   if (!access.is_oop()) {
 533     return BarrierSetC2::load_at_resolved(access, val_type);
 534   }
 535 
 536   Node* load = BarrierSetC2::load_at_resolved(access, val_type);
 537   DecoratorSet decorators = access.decorators();
 538   BasicType type = access.type();
 539 
 540   // 2: apply LRB if needed
 541   if (ShenandoahBarrierSet::need_load_reference_barrier(decorators, type)) {
 542     load = new ShenandoahLoadReferenceBarrierNode(nullptr, load, decorators);
 543     if (access.is_parse_access()) {
 544       load = static_cast<C2ParseAccess &>(access).kit()->gvn().transform(load);
 545     } else {
 546       load = static_cast<C2OptAccess &>(access).gvn().transform(load);
 547     }
 548   }
 549 
 550   // 3: apply keep-alive barrier for java.lang.ref.Reference if needed
 551   if (ShenandoahBarrierSet::need_keep_alive_barrier(decorators, type)) {
 552     Node* top = Compile::current()->top();
 553     Node* adr = access.addr().node();
 554     Node* offset = adr->is_AddP() ? adr->in(AddPNode::Offset) : top;
 555     Node* obj = access.base();
 556 
 557     bool unknown = (decorators & ON_UNKNOWN_OOP_REF) != 0;
 558     bool on_weak_ref = (decorators & (ON_WEAK_OOP_REF | ON_PHANTOM_OOP_REF)) != 0;
 559     bool keep_alive = (decorators & AS_NO_KEEPALIVE) == 0;
 560 
 561     // If we are reading the value of the referent field of a Reference
 562     // object (either by using Unsafe directly or through reflection)
 563     // then, if SATB is enabled, we need to record the referent in an
 564     // SATB log buffer using the pre-barrier mechanism.
 565     // Also we need to add memory barrier to prevent commoning reads
 566     // from this field across safepoint since GC can change its value.
 567     if (!on_weak_ref || (unknown && (offset == top || obj == top)) || !keep_alive) {
 568       return load;
 569     }
 570 
 571     assert(access.is_parse_access(), "entry not supported at optimization time");
 572     C2ParseAccess& parse_access = static_cast<C2ParseAccess&>(access);
 573     GraphKit* kit = parse_access.kit();
 574     bool mismatched = (decorators & C2_MISMATCHED) != 0;
 575     bool is_unordered = (decorators & MO_UNORDERED) != 0;
 576     bool in_native = (decorators & IN_NATIVE) != 0;
 577     bool need_cpu_mem_bar = !is_unordered || mismatched || in_native;
 578 
 579     if (on_weak_ref) {
 580       // Use the pre-barrier to record the value in the referent field
 581       satb_write_barrier_pre(kit, false /* do_load */,
 582                              nullptr /* obj */, nullptr /* adr */, max_juint /* alias_idx */, nullptr /* val */, nullptr /* val_type */,
 583                              load /* pre_val */, T_OBJECT);
 584       // Add memory barrier to prevent commoning reads from this field
 585       // across safepoint since GC can change its value.
 586       kit->insert_mem_bar(Op_MemBarCPUOrder);
 587     } else if (unknown) {
 588       // We do not require a mem bar inside pre_barrier if need_mem_bar
 589       // is set: the barriers would be emitted by us.
 590       insert_pre_barrier(kit, obj, offset, load, !need_cpu_mem_bar);
 591     }
 592   }
 593 
 594   return load;
 595 }
 596 
 597 Node* ShenandoahBarrierSetC2::atomic_cmpxchg_val_at_resolved(C2AtomicParseAccess& access, Node* expected_val,
 598                                                    Node* new_val, const Type* value_type) const {
 599   GraphKit* kit = access.kit();
 600   if (access.is_oop()) {
 601     new_val = shenandoah_iu_barrier(kit, new_val);
 602     shenandoah_write_barrier_pre(kit, false /* do_load */,
 603                                  nullptr, nullptr, max_juint, nullptr, nullptr,
 604                                  expected_val /* pre_val */, T_OBJECT);
 605 
 606     MemNode::MemOrd mo = access.mem_node_mo();
 607     Node* mem = access.memory();
 608     Node* adr = access.addr().node();
 609     const TypePtr* adr_type = access.addr().type();
 610     Node* load_store = nullptr;
 611 
 612 #ifdef _LP64
 613     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 614       Node *newval_enc = kit->gvn().transform(new EncodePNode(new_val, new_val->bottom_type()->make_narrowoop()));
 615       Node *oldval_enc = kit->gvn().transform(new EncodePNode(expected_val, expected_val->bottom_type()->make_narrowoop()));
 616       if (ShenandoahCASBarrier) {
 617         load_store = kit->gvn().transform(new ShenandoahCompareAndExchangeNNode(kit->control(), mem, adr, newval_enc, oldval_enc, adr_type, value_type->make_narrowoop(), mo));
 618       } else {
 619         load_store = kit->gvn().transform(new CompareAndExchangeNNode(kit->control(), mem, adr, newval_enc, oldval_enc, adr_type, value_type->make_narrowoop(), mo));
 620       }
 621     } else
 622 #endif
 623     {
 624       if (ShenandoahCASBarrier) {
 625         load_store = kit->gvn().transform(new ShenandoahCompareAndExchangePNode(kit->control(), mem, adr, new_val, expected_val, adr_type, value_type->is_oopptr(), mo));
 626       } else {
 627         load_store = kit->gvn().transform(new CompareAndExchangePNode(kit->control(), mem, adr, new_val, expected_val, adr_type, value_type->is_oopptr(), mo));
 628       }
 629     }
 630 
 631     access.set_raw_access(load_store);
 632     pin_atomic_op(access);
 633 
 634 #ifdef _LP64
 635     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 636       load_store = kit->gvn().transform(new DecodeNNode(load_store, load_store->get_ptr_type()));
 637     }
 638 #endif
 639     load_store = kit->gvn().transform(new ShenandoahLoadReferenceBarrierNode(nullptr, load_store, access.decorators()));
 640     return load_store;
 641   }
 642   return BarrierSetC2::atomic_cmpxchg_val_at_resolved(access, expected_val, new_val, value_type);
 643 }
 644 
 645 Node* ShenandoahBarrierSetC2::atomic_cmpxchg_bool_at_resolved(C2AtomicParseAccess& access, Node* expected_val,
 646                                                               Node* new_val, const Type* value_type) const {
 647   GraphKit* kit = access.kit();
 648   if (access.is_oop()) {
 649     new_val = shenandoah_iu_barrier(kit, new_val);
 650     shenandoah_write_barrier_pre(kit, false /* do_load */,
 651                                  nullptr, nullptr, max_juint, nullptr, nullptr,
 652                                  expected_val /* pre_val */, T_OBJECT);
 653     DecoratorSet decorators = access.decorators();
 654     MemNode::MemOrd mo = access.mem_node_mo();
 655     Node* mem = access.memory();
 656     bool is_weak_cas = (decorators & C2_WEAK_CMPXCHG) != 0;
 657     Node* load_store = nullptr;
 658     Node* adr = access.addr().node();
 659 #ifdef _LP64
 660     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 661       Node *newval_enc = kit->gvn().transform(new EncodePNode(new_val, new_val->bottom_type()->make_narrowoop()));
 662       Node *oldval_enc = kit->gvn().transform(new EncodePNode(expected_val, expected_val->bottom_type()->make_narrowoop()));
 663       if (ShenandoahCASBarrier) {
 664         if (is_weak_cas) {
 665           load_store = kit->gvn().transform(new ShenandoahWeakCompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
 666         } else {
 667           load_store = kit->gvn().transform(new ShenandoahCompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
 668         }
 669       } else {
 670         if (is_weak_cas) {
 671           load_store = kit->gvn().transform(new WeakCompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
 672         } else {
 673           load_store = kit->gvn().transform(new CompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
 674         }
 675       }
 676     } else
 677 #endif
 678     {
 679       if (ShenandoahCASBarrier) {
 680         if (is_weak_cas) {
 681           load_store = kit->gvn().transform(new ShenandoahWeakCompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
 682         } else {
 683           load_store = kit->gvn().transform(new ShenandoahCompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
 684         }
 685       } else {
 686         if (is_weak_cas) {
 687           load_store = kit->gvn().transform(new WeakCompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
 688         } else {
 689           load_store = kit->gvn().transform(new CompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
 690         }
 691       }
 692     }
 693     access.set_raw_access(load_store);
 694     pin_atomic_op(access);
 695     return load_store;
 696   }
 697   return BarrierSetC2::atomic_cmpxchg_bool_at_resolved(access, expected_val, new_val, value_type);
 698 }
 699 
 700 Node* ShenandoahBarrierSetC2::atomic_xchg_at_resolved(C2AtomicParseAccess& access, Node* val, const Type* value_type) const {
 701   GraphKit* kit = access.kit();
 702   if (access.is_oop()) {
 703     val = shenandoah_iu_barrier(kit, val);
 704   }
 705   Node* result = BarrierSetC2::atomic_xchg_at_resolved(access, val, value_type);
 706   if (access.is_oop()) {
 707     result = kit->gvn().transform(new ShenandoahLoadReferenceBarrierNode(nullptr, result, access.decorators()));
 708     shenandoah_write_barrier_pre(kit, false /* do_load */,
 709                                  nullptr, nullptr, max_juint, nullptr, nullptr,
 710                                  result /* pre_val */, T_OBJECT);
 711   }
 712   return result;
 713 }
 714 
 715 
 716 bool ShenandoahBarrierSetC2::is_gc_pre_barrier_node(Node* node) const {
 717   return is_shenandoah_wb_pre_call(node);
 718 }
 719 
 720 // Support for GC barriers emitted during parsing
 721 bool ShenandoahBarrierSetC2::is_gc_barrier_node(Node* node) const {
 722   if (node->Opcode() == Op_ShenandoahLoadReferenceBarrier || node->Opcode() == Op_ShenandoahIUBarrier) return true;
 723   if (node->Opcode() != Op_CallLeaf && node->Opcode() != Op_CallLeafNoFP) {
 724     return false;
 725   }
 726   CallLeafNode *call = node->as_CallLeaf();
 727   if (call->_name == nullptr) {
 728     return false;
 729   }
 730 
 731   return strcmp(call->_name, "shenandoah_clone_barrier") == 0 ||
 732          strcmp(call->_name, "shenandoah_cas_obj") == 0 ||
 733          strcmp(call->_name, "shenandoah_wb_pre") == 0;
 734 }
 735 
 736 Node* ShenandoahBarrierSetC2::step_over_gc_barrier(Node* c) const {
 737   if (c == nullptr) {
 738     return c;
 739   }
 740   if (c->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
 741     return c->in(ShenandoahLoadReferenceBarrierNode::ValueIn);
 742   }
 743   if (c->Opcode() == Op_ShenandoahIUBarrier) {
 744     c = c->in(1);
 745   }
 746   return c;
 747 }
 748 
 749 bool ShenandoahBarrierSetC2::expand_barriers(Compile* C, PhaseIterGVN& igvn) const {
 750   return !ShenandoahBarrierC2Support::expand(C, igvn);
 751 }
 752 
 753 bool ShenandoahBarrierSetC2::optimize_loops(PhaseIdealLoop* phase, LoopOptsMode mode, VectorSet& visited, Node_Stack& nstack, Node_List& worklist) const {
 754   if (mode == LoopOptsShenandoahExpand) {
 755     assert(UseShenandoahGC, "only for shenandoah");
 756     ShenandoahBarrierC2Support::pin_and_expand(phase);
 757     return true;
 758   } else if (mode == LoopOptsShenandoahPostExpand) {
 759     assert(UseShenandoahGC, "only for shenandoah");
 760     visited.clear();
 761     ShenandoahBarrierC2Support::optimize_after_expansion(visited, nstack, worklist, phase);
 762     return true;
 763   }
 764   return false;
 765 }
 766 
 767 bool ShenandoahBarrierSetC2::array_copy_requires_gc_barriers(bool tightly_coupled_alloc, BasicType type, bool is_clone, bool is_clone_instance, ArrayCopyPhase phase) const {
 768   bool is_oop = is_reference_type(type);
 769   if (!is_oop) {
 770     return false;
 771   }
 772   if (ShenandoahSATBBarrier && tightly_coupled_alloc) {
 773     if (phase == Optimization) {
 774       return false;
 775     }
 776     return !is_clone;
 777   }
 778   if (phase == Optimization) {
 779     return !ShenandoahIUBarrier;
 780   }
 781   return true;
 782 }
 783 
 784 bool ShenandoahBarrierSetC2::clone_needs_barrier(Node* src, PhaseGVN& gvn) {
 785   const TypeOopPtr* src_type = gvn.type(src)->is_oopptr();
 786   if (src_type->isa_instptr() != nullptr) {
 787     ciInstanceKlass* ik = src_type->is_instptr()->instance_klass();
 788     if ((src_type->klass_is_exact() || !ik->has_subklass()) && !ik->has_injected_fields()) {
 789       if (ik->has_object_fields()) {
 790         return true;
 791       } else {
 792         if (!src_type->klass_is_exact()) {
 793           Compile::current()->dependencies()->assert_leaf_type(ik);
 794         }
 795       }
 796     } else {
 797       return true;
 798         }
 799   } else if (src_type->isa_aryptr()) {
 800     BasicType src_elem = src_type->isa_aryptr()->elem()->array_element_basic_type();
 801     if (is_reference_type(src_elem, true)) {
 802       return true;
 803     }
 804   } else {
 805     return true;
 806   }
 807   return false;
 808 }
 809 
 810 void ShenandoahBarrierSetC2::clone_at_expansion(PhaseMacroExpand* phase, ArrayCopyNode* ac) const {
 811   Node* ctrl = ac->in(TypeFunc::Control);
 812   Node* mem = ac->in(TypeFunc::Memory);
 813   Node* src_base = ac->in(ArrayCopyNode::Src);
 814   Node* src_offset = ac->in(ArrayCopyNode::SrcPos);
 815   Node* dest_base = ac->in(ArrayCopyNode::Dest);
 816   Node* dest_offset = ac->in(ArrayCopyNode::DestPos);
 817   Node* length = ac->in(ArrayCopyNode::Length);
 818 
 819   Node* src = phase->basic_plus_adr(src_base, src_offset);
 820   Node* dest = phase->basic_plus_adr(dest_base, dest_offset);
 821 
 822   if (ShenandoahCloneBarrier && clone_needs_barrier(src, phase->igvn())) {
 823     // Check if heap is has forwarded objects. If it does, we need to call into the special
 824     // routine that would fix up source references before we can continue.
 825 
 826     enum { _heap_stable = 1, _heap_unstable, PATH_LIMIT };
 827     Node* region = new RegionNode(PATH_LIMIT);
 828     Node* mem_phi = new PhiNode(region, Type::MEMORY, TypeRawPtr::BOTTOM);
 829 
 830     Node* thread = phase->transform_later(new ThreadLocalNode());
 831     Node* offset = phase->igvn().MakeConX(in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
 832     Node* gc_state_addr = phase->transform_later(new AddPNode(phase->C->top(), thread, offset));
 833 
 834     uint gc_state_idx = Compile::AliasIdxRaw;
 835     const TypePtr* gc_state_adr_type = nullptr; // debug-mode-only argument
 836     debug_only(gc_state_adr_type = phase->C->get_adr_type(gc_state_idx));
 837 
 838     Node* gc_state    = phase->transform_later(new LoadBNode(ctrl, mem, gc_state_addr, gc_state_adr_type, TypeInt::BYTE, MemNode::unordered));
 839     int flags = ShenandoahHeap::HAS_FORWARDED;
 840     if (ShenandoahIUBarrier) {
 841       flags |= ShenandoahHeap::MARKING;
 842     }
 843     Node* stable_and  = phase->transform_later(new AndINode(gc_state, phase->igvn().intcon(flags)));
 844     Node* stable_cmp  = phase->transform_later(new CmpINode(stable_and, phase->igvn().zerocon(T_INT)));
 845     Node* stable_test = phase->transform_later(new BoolNode(stable_cmp, BoolTest::ne));
 846 
 847     IfNode* stable_iff  = phase->transform_later(new IfNode(ctrl, stable_test, PROB_UNLIKELY(0.999), COUNT_UNKNOWN))->as_If();
 848     Node* stable_ctrl   = phase->transform_later(new IfFalseNode(stable_iff));
 849     Node* unstable_ctrl = phase->transform_later(new IfTrueNode(stable_iff));
 850 
 851     // Heap is stable, no need to do anything additional
 852     region->init_req(_heap_stable, stable_ctrl);
 853     mem_phi->init_req(_heap_stable, mem);
 854 
 855     // Heap is unstable, call into clone barrier stub
 856     Node* call = phase->make_leaf_call(unstable_ctrl, mem,
 857                     ShenandoahBarrierSetC2::shenandoah_clone_barrier_Type(),
 858                     CAST_FROM_FN_PTR(address, ShenandoahRuntime::shenandoah_clone_barrier),
 859                     "shenandoah_clone",
 860                     TypeRawPtr::BOTTOM,
 861                     src_base);
 862     call = phase->transform_later(call);
 863 
 864     ctrl = phase->transform_later(new ProjNode(call, TypeFunc::Control));
 865     mem = phase->transform_later(new ProjNode(call, TypeFunc::Memory));
 866     region->init_req(_heap_unstable, ctrl);
 867     mem_phi->init_req(_heap_unstable, mem);
 868 
 869     // Wire up the actual arraycopy stub now
 870     ctrl = phase->transform_later(region);
 871     mem = phase->transform_later(mem_phi);
 872 
 873     const char* name = "arraycopy";
 874     call = phase->make_leaf_call(ctrl, mem,
 875                                  OptoRuntime::fast_arraycopy_Type(),
 876                                  phase->basictype2arraycopy(T_LONG, nullptr, nullptr, true, name, true),
 877                                  name, TypeRawPtr::BOTTOM,
 878                                  src, dest, length
 879                                  LP64_ONLY(COMMA phase->top()));
 880     call = phase->transform_later(call);
 881 
 882     // Hook up the whole thing into the graph
 883     phase->igvn().replace_node(ac, call);
 884   } else {
 885     BarrierSetC2::clone_at_expansion(phase, ac);
 886   }
 887 }
 888 
 889 
 890 // Support for macro expanded GC barriers
 891 void ShenandoahBarrierSetC2::register_potential_barrier_node(Node* node) const {
 892   if (node->Opcode() == Op_ShenandoahIUBarrier) {
 893     state()->add_iu_barrier((ShenandoahIUBarrierNode*) node);
 894   }
 895   if (node->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
 896     state()->add_load_reference_barrier((ShenandoahLoadReferenceBarrierNode*) node);
 897   }
 898 }
 899 
 900 void ShenandoahBarrierSetC2::unregister_potential_barrier_node(Node* node) const {
 901   if (node->Opcode() == Op_ShenandoahIUBarrier) {
 902     state()->remove_iu_barrier((ShenandoahIUBarrierNode*) node);
 903   }
 904   if (node->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
 905     state()->remove_load_reference_barrier((ShenandoahLoadReferenceBarrierNode*) node);
 906   }
 907 }
 908 
 909 void ShenandoahBarrierSetC2::eliminate_gc_barrier(PhaseMacroExpand* macro, Node* n) const {
 910   if (is_shenandoah_wb_pre_call(n)) {
 911     shenandoah_eliminate_wb_pre(n, &macro->igvn());
 912   }
 913 }
 914 
 915 void ShenandoahBarrierSetC2::shenandoah_eliminate_wb_pre(Node* call, PhaseIterGVN* igvn) const {
 916   assert(UseShenandoahGC && is_shenandoah_wb_pre_call(call), "");
 917   Node* c = call->as_Call()->proj_out(TypeFunc::Control);
 918   c = c->unique_ctrl_out();
 919   assert(c->is_Region() && c->req() == 3, "where's the pre barrier control flow?");
 920   c = c->unique_ctrl_out();
 921   assert(c->is_Region() && c->req() == 3, "where's the pre barrier control flow?");
 922   Node* iff = c->in(1)->is_IfProj() ? c->in(1)->in(0) : c->in(2)->in(0);
 923   assert(iff->is_If(), "expect test");
 924   if (!is_shenandoah_marking_if(igvn, iff)) {
 925     c = c->unique_ctrl_out();
 926     assert(c->is_Region() && c->req() == 3, "where's the pre barrier control flow?");
 927     iff = c->in(1)->is_IfProj() ? c->in(1)->in(0) : c->in(2)->in(0);
 928     assert(is_shenandoah_marking_if(igvn, iff), "expect marking test");
 929   }
 930   Node* cmpx = iff->in(1)->in(1);
 931   igvn->replace_node(cmpx, igvn->makecon(TypeInt::CC_EQ));
 932   igvn->rehash_node_delayed(call);
 933   call->del_req(call->req()-1);
 934 }
 935 
 936 void ShenandoahBarrierSetC2::enqueue_useful_gc_barrier(PhaseIterGVN* igvn, Node* node) const {
 937   if (node->Opcode() == Op_AddP && ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(node)) {
 938     igvn->add_users_to_worklist(node);
 939   }
 940 }
 941 
 942 void ShenandoahBarrierSetC2::eliminate_useless_gc_barriers(Unique_Node_List &useful, Compile* C) const {
 943   for (uint i = 0; i < useful.size(); i++) {
 944     Node* n = useful.at(i);
 945     if (n->Opcode() == Op_AddP && ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(n)) {
 946       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
 947         C->record_for_igvn(n->fast_out(i));
 948       }
 949     }
 950   }
 951   for (int i = state()->iu_barriers_count() - 1; i >= 0; i--) {
 952     ShenandoahIUBarrierNode* n = state()->iu_barrier(i);
 953     if (!useful.member(n)) {
 954       state()->remove_iu_barrier(n);
 955     }
 956   }
 957   for (int i = state()->load_reference_barriers_count() - 1; i >= 0; i--) {
 958     ShenandoahLoadReferenceBarrierNode* n = state()->load_reference_barrier(i);
 959     if (!useful.member(n)) {
 960       state()->remove_load_reference_barrier(n);
 961     }
 962   }
 963 }
 964 
 965 void* ShenandoahBarrierSetC2::create_barrier_state(Arena* comp_arena) const {
 966   return new(comp_arena) ShenandoahBarrierSetC2State(comp_arena);
 967 }
 968 
 969 ShenandoahBarrierSetC2State* ShenandoahBarrierSetC2::state() const {
 970   return reinterpret_cast<ShenandoahBarrierSetC2State*>(Compile::current()->barrier_set_state());
 971 }
 972 
 973 // If the BarrierSetC2 state has kept macro nodes in its compilation unit state to be
 974 // expanded later, then now is the time to do so.
 975 bool ShenandoahBarrierSetC2::expand_macro_nodes(PhaseMacroExpand* macro) const { return false; }
 976 
 977 #ifdef ASSERT
 978 void ShenandoahBarrierSetC2::verify_gc_barriers(Compile* compile, CompilePhase phase) const {
 979   if (ShenandoahVerifyOptoBarriers && phase == BarrierSetC2::BeforeMacroExpand) {
 980     ShenandoahBarrierC2Support::verify(Compile::current()->root());
 981   } else if (phase == BarrierSetC2::BeforeCodeGen) {
 982     // Verify Shenandoah pre-barriers
 983     const int marking_offset = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_active_offset());
 984 
 985     Unique_Node_List visited;
 986     Node_List worklist;
 987     // We're going to walk control flow backwards starting from the Root
 988     worklist.push(compile->root());
 989     while (worklist.size() > 0) {
 990       Node *x = worklist.pop();
 991       if (x == nullptr || x == compile->top()) continue;
 992       if (visited.member(x)) {
 993         continue;
 994       } else {
 995         visited.push(x);
 996       }
 997 
 998       if (x->is_Region()) {
 999         for (uint i = 1; i < x->req(); i++) {
1000           worklist.push(x->in(i));
1001         }
1002       } else {
1003         worklist.push(x->in(0));
1004         // We are looking for the pattern:
1005         //                            /->ThreadLocal
1006         // If->Bool->CmpI->LoadB->AddP->ConL(marking_offset)
1007         //              \->ConI(0)
1008         // We want to verify that the If and the LoadB have the same control
1009         // See GraphKit::g1_write_barrier_pre()
1010         if (x->is_If()) {
1011           IfNode *iff = x->as_If();
1012           if (iff->in(1)->is_Bool() && iff->in(1)->in(1)->is_Cmp()) {
1013             CmpNode *cmp = iff->in(1)->in(1)->as_Cmp();
1014             if (cmp->Opcode() == Op_CmpI && cmp->in(2)->is_Con() && cmp->in(2)->bottom_type()->is_int()->get_con() == 0
1015                 && cmp->in(1)->is_Load()) {
1016               LoadNode *load = cmp->in(1)->as_Load();
1017               if (load->Opcode() == Op_LoadB && load->in(2)->is_AddP() && load->in(2)->in(2)->Opcode() == Op_ThreadLocal
1018                   && load->in(2)->in(3)->is_Con()
1019                   && load->in(2)->in(3)->bottom_type()->is_intptr_t()->get_con() == marking_offset) {
1020 
1021                 Node *if_ctrl = iff->in(0);
1022                 Node *load_ctrl = load->in(0);
1023 
1024                 if (if_ctrl != load_ctrl) {
1025                   // Skip possible CProj->NeverBranch in infinite loops
1026                   if ((if_ctrl->is_Proj() && if_ctrl->Opcode() == Op_CProj)
1027                       && if_ctrl->in(0)->is_NeverBranch()) {
1028                     if_ctrl = if_ctrl->in(0)->in(0);
1029                   }
1030                 }
1031                 assert(load_ctrl != nullptr && if_ctrl == load_ctrl, "controls must match");
1032               }
1033             }
1034           }
1035         }
1036       }
1037     }
1038   }
1039 }
1040 #endif
1041 
1042 Node* ShenandoahBarrierSetC2::ideal_node(PhaseGVN* phase, Node* n, bool can_reshape) const {
1043   if (is_shenandoah_wb_pre_call(n)) {
1044     uint cnt = ShenandoahBarrierSetC2::write_ref_field_pre_entry_Type()->domain()->cnt();
1045     if (n->req() > cnt) {
1046       Node* addp = n->in(cnt);
1047       if (has_only_shenandoah_wb_pre_uses(addp)) {
1048         n->del_req(cnt);
1049         if (can_reshape) {
1050           phase->is_IterGVN()->_worklist.push(addp);
1051         }
1052         return n;
1053       }
1054     }
1055   }
1056   if (n->Opcode() == Op_CmpP) {
1057     Node* in1 = n->in(1);
1058     Node* in2 = n->in(2);
1059 
1060     // If one input is null, then step over the strong LRB barriers on the other input
1061     if (in1->bottom_type() == TypePtr::NULL_PTR &&
1062         !((in2->Opcode() == Op_ShenandoahLoadReferenceBarrier) &&
1063           !ShenandoahBarrierSet::is_strong_access(((ShenandoahLoadReferenceBarrierNode*)in2)->decorators()))) {
1064       in2 = step_over_gc_barrier(in2);
1065     }
1066     if (in2->bottom_type() == TypePtr::NULL_PTR &&
1067         !((in1->Opcode() == Op_ShenandoahLoadReferenceBarrier) &&
1068           !ShenandoahBarrierSet::is_strong_access(((ShenandoahLoadReferenceBarrierNode*)in1)->decorators()))) {
1069       in1 = step_over_gc_barrier(in1);
1070     }
1071 
1072     if (in1 != n->in(1)) {
1073       n->set_req_X(1, in1, phase);
1074       assert(in2 == n->in(2), "only one change");
1075       return n;
1076     }
1077     if (in2 != n->in(2)) {
1078       n->set_req_X(2, in2, phase);
1079       return n;
1080     }
1081   } else if (can_reshape &&
1082              n->Opcode() == Op_If &&
1083              ShenandoahBarrierC2Support::is_heap_stable_test(n) &&
1084              n->in(0) != nullptr &&
1085              n->outcnt() == 2) {
1086     Node* dom = n->in(0);
1087     Node* prev_dom = n;
1088     int op = n->Opcode();
1089     int dist = 16;
1090     // Search up the dominator tree for another heap stable test
1091     while (dom->Opcode() != op    ||  // Not same opcode?
1092            !ShenandoahBarrierC2Support::is_heap_stable_test(dom) ||  // Not same input 1?
1093            prev_dom->in(0) != dom) {  // One path of test does not dominate?
1094       if (dist < 0) return nullptr;
1095 
1096       dist--;
1097       prev_dom = dom;
1098       dom = IfNode::up_one_dom(dom);
1099       if (!dom) return nullptr;
1100     }
1101 
1102     // Check that we did not follow a loop back to ourselves
1103     if (n == dom) {
1104       return nullptr;
1105     }
1106 
1107     return n->as_If()->dominated_by(prev_dom, phase->is_IterGVN(), false);
1108   }
1109 
1110   return nullptr;
1111 }
1112 
1113 bool ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(Node* n) {
1114   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1115     Node* u = n->fast_out(i);
1116     if (!is_shenandoah_wb_pre_call(u)) {
1117       return false;
1118     }
1119   }
1120   return n->outcnt() > 0;
1121 }
1122 
1123 bool ShenandoahBarrierSetC2::final_graph_reshaping(Compile* compile, Node* n, uint opcode, Unique_Node_List& dead_nodes) const {
1124   switch (opcode) {
1125     case Op_CallLeaf:
1126     case Op_CallLeafNoFP: {
1127       assert (n->is_Call(), "");
1128       CallNode *call = n->as_Call();
1129       if (ShenandoahBarrierSetC2::is_shenandoah_wb_pre_call(call)) {
1130         uint cnt = ShenandoahBarrierSetC2::write_ref_field_pre_entry_Type()->domain()->cnt();
1131         if (call->req() > cnt) {
1132           assert(call->req() == cnt + 1, "only one extra input");
1133           Node *addp = call->in(cnt);
1134           assert(!ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(addp), "useless address computation?");
1135           call->del_req(cnt);
1136         }
1137       }
1138       return false;
1139     }
1140     case Op_ShenandoahCompareAndSwapP:
1141     case Op_ShenandoahCompareAndSwapN:
1142     case Op_ShenandoahWeakCompareAndSwapN:
1143     case Op_ShenandoahWeakCompareAndSwapP:
1144     case Op_ShenandoahCompareAndExchangeP:
1145     case Op_ShenandoahCompareAndExchangeN:
1146       return true;
1147     case Op_ShenandoahLoadReferenceBarrier:
1148       assert(false, "should have been expanded already");
1149       return true;
1150     default:
1151       return false;
1152   }
1153 }
1154 
1155 bool ShenandoahBarrierSetC2::escape_add_to_con_graph(ConnectionGraph* conn_graph, PhaseGVN* gvn, Unique_Node_List* delayed_worklist, Node* n, uint opcode) const {
1156   switch (opcode) {
1157     case Op_ShenandoahCompareAndExchangeP:
1158     case Op_ShenandoahCompareAndExchangeN:
1159       conn_graph->add_objload_to_connection_graph(n, delayed_worklist);
1160       // fallthrough
1161     case Op_ShenandoahWeakCompareAndSwapP:
1162     case Op_ShenandoahWeakCompareAndSwapN:
1163     case Op_ShenandoahCompareAndSwapP:
1164     case Op_ShenandoahCompareAndSwapN:
1165       conn_graph->add_to_congraph_unsafe_access(n, opcode, delayed_worklist);
1166       return true;
1167     case Op_StoreP: {
1168       Node* adr = n->in(MemNode::Address);
1169       const Type* adr_type = gvn->type(adr);
1170       // Pointer stores in Shenandoah barriers looks like unsafe access.
1171       // Ignore such stores to be able scalar replace non-escaping
1172       // allocations.
1173       if (adr_type->isa_rawptr() && adr->is_AddP()) {
1174         Node* base = conn_graph->get_addp_base(adr);
1175         if (base->Opcode() == Op_LoadP &&
1176           base->in(MemNode::Address)->is_AddP()) {
1177           adr = base->in(MemNode::Address);
1178           Node* tls = conn_graph->get_addp_base(adr);
1179           if (tls->Opcode() == Op_ThreadLocal) {
1180              int offs = (int) gvn->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
1181              const int buf_offset = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset());
1182              if (offs == buf_offset) {
1183                return true; // Pre barrier previous oop value store.
1184              }
1185           }
1186         }
1187       }
1188       return false;
1189     }
1190     case Op_ShenandoahIUBarrier:
1191       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), delayed_worklist);
1192       break;
1193     case Op_ShenandoahLoadReferenceBarrier:
1194       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(ShenandoahLoadReferenceBarrierNode::ValueIn), delayed_worklist);
1195       return true;
1196     default:
1197       // Nothing
1198       break;
1199   }
1200   return false;
1201 }
1202 
1203 bool ShenandoahBarrierSetC2::escape_add_final_edges(ConnectionGraph* conn_graph, PhaseGVN* gvn, Node* n, uint opcode) const {
1204   switch (opcode) {
1205     case Op_ShenandoahCompareAndExchangeP:
1206     case Op_ShenandoahCompareAndExchangeN: {
1207       Node *adr = n->in(MemNode::Address);
1208       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, adr, nullptr);
1209       // fallthrough
1210     }
1211     case Op_ShenandoahCompareAndSwapP:
1212     case Op_ShenandoahCompareAndSwapN:
1213     case Op_ShenandoahWeakCompareAndSwapP:
1214     case Op_ShenandoahWeakCompareAndSwapN:
1215       return conn_graph->add_final_edges_unsafe_access(n, opcode);
1216     case Op_ShenandoahIUBarrier:
1217       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), nullptr);
1218       return true;
1219     case Op_ShenandoahLoadReferenceBarrier:
1220       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(ShenandoahLoadReferenceBarrierNode::ValueIn), nullptr);
1221       return true;
1222     default:
1223       // Nothing
1224       break;
1225   }
1226   return false;
1227 }
1228 
1229 bool ShenandoahBarrierSetC2::escape_has_out_with_unsafe_object(Node* n) const {
1230   return n->has_out_with(Op_ShenandoahCompareAndExchangeP) || n->has_out_with(Op_ShenandoahCompareAndExchangeN) ||
1231          n->has_out_with(Op_ShenandoahCompareAndSwapP, Op_ShenandoahCompareAndSwapN, Op_ShenandoahWeakCompareAndSwapP, Op_ShenandoahWeakCompareAndSwapN);
1232 
1233 }
1234 
1235 bool ShenandoahBarrierSetC2::matcher_find_shared_post_visit(Matcher* matcher, Node* n, uint opcode) const {
1236   switch (opcode) {
1237     case Op_ShenandoahCompareAndExchangeP:
1238     case Op_ShenandoahCompareAndExchangeN:
1239     case Op_ShenandoahWeakCompareAndSwapP:
1240     case Op_ShenandoahWeakCompareAndSwapN:
1241     case Op_ShenandoahCompareAndSwapP:
1242     case Op_ShenandoahCompareAndSwapN: {   // Convert trinary to binary-tree
1243       Node* newval = n->in(MemNode::ValueIn);
1244       Node* oldval = n->in(LoadStoreConditionalNode::ExpectedIn);
1245       Node* pair = new BinaryNode(oldval, newval);
1246       n->set_req(MemNode::ValueIn,pair);
1247       n->del_req(LoadStoreConditionalNode::ExpectedIn);
1248       return true;
1249     }
1250     default:
1251       break;
1252   }
1253   return false;
1254 }
1255 
1256 bool ShenandoahBarrierSetC2::matcher_is_store_load_barrier(Node* x, uint xop) const {
1257   return xop == Op_ShenandoahCompareAndExchangeP ||
1258          xop == Op_ShenandoahCompareAndExchangeN ||
1259          xop == Op_ShenandoahWeakCompareAndSwapP ||
1260          xop == Op_ShenandoahWeakCompareAndSwapN ||
1261          xop == Op_ShenandoahCompareAndSwapN ||
1262          xop == Op_ShenandoahCompareAndSwapP;
1263 }