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