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