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 "gc/shenandoah/mode/shenandoahMode.hpp"
  37 #include "opto/arraycopynode.hpp"
  38 #include "opto/escape.hpp"
  39 #include "opto/graphKit.hpp"
  40 #include "opto/idealKit.hpp"
  41 #include "opto/macro.hpp"
  42 #include "opto/movenode.hpp"
  43 #include "opto/narrowptrnode.hpp"
  44 #include "opto/rootnode.hpp"
  45 #include "opto/runtime.hpp"
  46 
  47 ShenandoahBarrierSetC2* ShenandoahBarrierSetC2::bsc2() {
  48   return reinterpret_cast<ShenandoahBarrierSetC2*>(BarrierSet::barrier_set()->barrier_set_c2());
  49 }
  50 
  51 ShenandoahBarrierSetC2State::ShenandoahBarrierSetC2State(Arena* comp_arena)
  52   : _iu_barriers(new (comp_arena) GrowableArray<ShenandoahIUBarrierNode*>(comp_arena, 8,  0, NULL)),
  53     _load_reference_barriers(new (comp_arena) GrowableArray<ShenandoahLoadReferenceBarrierNode*>(comp_arena, 8,  0, NULL)) {
  54 }
  55 
  56 int ShenandoahBarrierSetC2State::iu_barriers_count() const {
  57   return _iu_barriers->length();
  58 }
  59 
  60 ShenandoahIUBarrierNode* ShenandoahBarrierSetC2State::iu_barrier(int idx) const {
  61   return _iu_barriers->at(idx);
  62 }
  63 
  64 void ShenandoahBarrierSetC2State::add_iu_barrier(ShenandoahIUBarrierNode* n) {
  65   assert(!_iu_barriers->contains(n), "duplicate entry in barrier list");
  66   _iu_barriers->append(n);
  67 }
  68 
  69 void ShenandoahBarrierSetC2State::remove_iu_barrier(ShenandoahIUBarrierNode* n) {
  70   _iu_barriers->remove_if_existing(n);
  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_iu_barrier(GraphKit* kit, Node* obj) const {
  93   if (ShenandoahIUBarrier) {
  94     return kit->gvn().transform(new ShenandoahIUBarrierNode(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::YOUNG_MARKING | ShenandoahHeap::OLD_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 Shenandoah 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_strong)) ||
 308          (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong_narrow)) ||
 309          (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak)) ||
 310          (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak_narrow)) ||
 311          (entry_point == CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom));
 312 }
 313 
 314 bool ShenandoahBarrierSetC2::is_shenandoah_marking_if(PhaseTransform *phase, Node* n) {
 315   if (n->Opcode() != Op_If) {
 316     return false;
 317   }
 318 
 319   Node* bol = n->in(1);
 320   assert(bol->is_Bool(), "");
 321   Node* cmpx = bol->in(1);
 322   if (bol->as_Bool()->_test._test == BoolTest::ne &&
 323       cmpx->is_Cmp() && cmpx->in(2) == phase->intcon(0) &&
 324       is_shenandoah_state_load(cmpx->in(1)->in(1)) &&
 325       cmpx->in(1)->in(2)->is_Con() &&
 326       cmpx->in(1)->in(2) == phase->intcon(ShenandoahHeap::YOUNG_MARKING | ShenandoahHeap::OLD_MARKING)) {
 327     return true;
 328   }
 329 
 330   return false;
 331 }
 332 
 333 bool ShenandoahBarrierSetC2::is_shenandoah_state_load(Node* n) {
 334   if (!n->is_Load()) return false;
 335   const int state_offset = in_bytes(ShenandoahThreadLocalData::gc_state_offset());
 336   return n->in(2)->is_AddP() && n->in(2)->in(2)->Opcode() == Op_ThreadLocal
 337          && n->in(2)->in(3)->is_Con()
 338          && n->in(2)->in(3)->bottom_type()->is_intptr_t()->get_con() == state_offset;
 339 }
 340 
 341 void ShenandoahBarrierSetC2::shenandoah_write_barrier_pre(GraphKit* kit,
 342                                                           bool do_load,
 343                                                           Node* obj,
 344                                                           Node* adr,
 345                                                           uint alias_idx,
 346                                                           Node* val,
 347                                                           const TypeOopPtr* val_type,
 348                                                           Node* pre_val,
 349                                                           BasicType bt) const {
 350   if (ShenandoahSATBBarrier) {
 351     IdealKit ideal(kit);
 352     kit->sync_kit(ideal);
 353 
 354     satb_write_barrier_pre(kit, do_load, obj, adr, alias_idx, val, val_type, pre_val, bt);
 355 
 356     ideal.sync_kit(kit);
 357     kit->final_sync(ideal);
 358   }
 359 }
 360 
 361 // Helper that guards and inserts a pre-barrier.
 362 void ShenandoahBarrierSetC2::insert_pre_barrier(GraphKit* kit, Node* base_oop, Node* offset,
 363                                                 Node* pre_val, bool need_mem_bar) const {
 364   // We could be accessing the referent field of a reference object. If so, when Shenandoah
 365   // is enabled, we need to log the value in the referent field in an SATB buffer.
 366   // This routine performs some compile time filters and generates suitable
 367   // runtime filters that guard the pre-barrier code.
 368   // Also add memory barrier for non volatile load from the referent field
 369   // to prevent commoning of loads across safepoint.
 370 
 371   // Some compile time checks.
 372 
 373   // If offset is a constant, is it java_lang_ref_Reference::_reference_offset?
 374   const TypeX* otype = offset->find_intptr_t_type();
 375   if (otype != NULL && otype->is_con() &&
 376       otype->get_con() != java_lang_ref_Reference::referent_offset()) {
 377     // Constant offset but not the reference_offset so just return
 378     return;
 379   }
 380 
 381   // We only need to generate the runtime guards for instances.
 382   const TypeOopPtr* btype = base_oop->bottom_type()->isa_oopptr();
 383   if (btype != NULL) {
 384     if (btype->isa_aryptr()) {
 385       // Array type so nothing to do
 386       return;
 387     }
 388 
 389     const TypeInstPtr* itype = btype->isa_instptr();
 390     if (itype != NULL) {
 391       // Can the klass of base_oop be statically determined to be
 392       // _not_ a sub-class of Reference and _not_ Object?
 393       ciKlass* klass = itype->klass();
 394       if ( klass->is_loaded() &&
 395           !klass->is_subtype_of(kit->env()->Reference_klass()) &&
 396           !kit->env()->Object_klass()->is_subtype_of(klass)) {
 397         return;
 398       }
 399     }
 400   }
 401 
 402   // The compile time filters did not reject base_oop/offset so
 403   // we need to generate the following runtime filters
 404   //
 405   // if (offset == java_lang_ref_Reference::_reference_offset) {
 406   //   if (instance_of(base, java.lang.ref.Reference)) {
 407   //     pre_barrier(_, pre_val, ...);
 408   //   }
 409   // }
 410 
 411   float likely   = PROB_LIKELY(  0.999);
 412   float unlikely = PROB_UNLIKELY(0.999);
 413 
 414   IdealKit ideal(kit);
 415 
 416   Node* referent_off = __ ConX(java_lang_ref_Reference::referent_offset());
 417 
 418   __ if_then(offset, BoolTest::eq, referent_off, unlikely); {
 419       // Update graphKit memory and control from IdealKit.
 420       kit->sync_kit(ideal);
 421 
 422       Node* ref_klass_con = kit->makecon(TypeKlassPtr::make(kit->env()->Reference_klass()));
 423       Node* is_instof = kit->gen_instanceof(base_oop, ref_klass_con);
 424 
 425       // Update IdealKit memory and control from graphKit.
 426       __ sync_kit(kit);
 427 
 428       Node* one = __ ConI(1);
 429       // is_instof == 0 if base_oop == NULL
 430       __ if_then(is_instof, BoolTest::eq, one, unlikely); {
 431 
 432         // Update graphKit from IdeakKit.
 433         kit->sync_kit(ideal);
 434 
 435         // Use the pre-barrier to record the value in the referent field
 436         satb_write_barrier_pre(kit, false /* do_load */,
 437                                NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,
 438                                pre_val /* pre_val */,
 439                                T_OBJECT);
 440         if (need_mem_bar) {
 441           // Add memory barrier to prevent commoning reads from this field
 442           // across safepoint since GC can change its value.
 443           kit->insert_mem_bar(Op_MemBarCPUOrder);
 444         }
 445         // Update IdealKit from graphKit.
 446         __ sync_kit(kit);
 447 
 448       } __ end_if(); // _ref_type != ref_none
 449   } __ end_if(); // offset == referent_offset
 450 
 451   // Final sync IdealKit and GraphKit.
 452   kit->final_sync(ideal);
 453 }
 454 
 455 Node* ShenandoahBarrierSetC2::byte_map_base_node(GraphKit* kit) const {
 456   BarrierSet* bs = BarrierSet::barrier_set();
 457   ShenandoahBarrierSet* ctbs = barrier_set_cast<ShenandoahBarrierSet>(bs);
 458   CardTable::CardValue* card_table_base = ctbs->card_table()->byte_map_base();
 459   if (card_table_base != NULL) {
 460     return kit->makecon(TypeRawPtr::make((address)card_table_base));
 461   } else {
 462     return kit->null();
 463   }
 464 }
 465 
 466 void ShenandoahBarrierSetC2::post_barrier(GraphKit* kit,
 467                                           Node* ctl,
 468                                           Node* oop_store,
 469                                           Node* obj,
 470                                           Node* adr,
 471                                           uint  adr_idx,
 472                                           Node* val,
 473                                           BasicType bt,
 474                                           bool use_precise) const {
 475   if (!ShenandoahHeap::heap()->mode()->is_generational()) {
 476     return;
 477   }
 478 
 479   ShenandoahBarrierSet* ctbs = barrier_set_cast<ShenandoahBarrierSet>(BarrierSet::barrier_set());
 480   CardTable* ct = ctbs->card_table();
 481   // No store check needed if we're storing a NULL or an old object
 482   // (latter case is probably a string constant). The concurrent
 483   // mark sweep garbage collector, however, needs to have all nonNull
 484   // oop updates flagged via card-marks.
 485   if (val != NULL && val->is_Con()) {
 486     // must be either an oop or NULL
 487     const Type* t = val->bottom_type();
 488     if (t == TypePtr::NULL_PTR || t == Type::TOP)
 489       // stores of null never (?) need barriers
 490       return;
 491   }
 492 
 493   if (ReduceInitialCardMarks && obj == kit->just_allocated_object(kit->control())) {
 494     // We can skip marks on a freshly-allocated object in Eden.
 495     // Keep this code in sync with new_deferred_store_barrier() in runtime.cpp.
 496     // That routine informs GC to take appropriate compensating steps,
 497     // upon a slow-path allocation, so as to make this card-mark
 498     // elision safe.
 499     return;
 500   }
 501 
 502   if (!use_precise) {
 503     // All card marks for a (non-array) instance are in one place:
 504     adr = obj;
 505   }
 506   // (Else it's an array (or unknown), and we want more precise card marks.)
 507   assert(adr != NULL, "");
 508 
 509   IdealKit ideal(kit, true);
 510 
 511   // Convert the pointer to an int prior to doing math on it
 512   Node* cast = __ CastPX(__ ctrl(), adr);
 513 
 514   // Divide by card size
 515   Node* card_offset = __ URShiftX( cast, __ ConI(CardTable::card_shift) );
 516 
 517   // Combine card table base and card offset
 518   Node* card_adr = __ AddP(__ top(), byte_map_base_node(kit), card_offset );
 519 
 520   // Get the alias_index for raw card-mark memory
 521   int adr_type = Compile::AliasIdxRaw;
 522   Node*   zero = __ ConI(0); // Dirty card value
 523 
 524   if (UseCondCardMark) {
 525     // The classic GC reference write barrier is typically implemented
 526     // as a store into the global card mark table.  Unfortunately
 527     // unconditional stores can result in false sharing and excessive
 528     // coherence traffic as well as false transactional aborts.
 529     // UseCondCardMark enables MP "polite" conditional card mark
 530     // stores.  In theory we could relax the load from ctrl() to
 531     // no_ctrl, but that doesn't buy much latitude.
 532     Node* card_val = __ load( __ ctrl(), card_adr, TypeInt::BYTE, T_BYTE, adr_type);
 533     __ if_then(card_val, BoolTest::ne, zero);
 534   }
 535 
 536   // Smash zero into card
 537   __ store(__ ctrl(), card_adr, zero, T_BYTE, adr_type, MemNode::unordered);
 538 
 539   if (UseCondCardMark) {
 540     __ end_if();
 541   }
 542 
 543   // Final sync IdealKit and GraphKit.
 544   kit->final_sync(ideal);
 545 }
 546 
 547 #undef __
 548 
 549 const TypeFunc* ShenandoahBarrierSetC2::write_ref_field_pre_entry_Type() {
 550   const Type **fields = TypeTuple::fields(2);
 551   fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL; // original field value
 552   fields[TypeFunc::Parms+1] = TypeRawPtr::NOTNULL; // thread
 553   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2, fields);
 554 
 555   // create result type (range)
 556   fields = TypeTuple::fields(0);
 557   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+0, fields);
 558 
 559   return TypeFunc::make(domain, range);
 560 }
 561 
 562 const TypeFunc* ShenandoahBarrierSetC2::shenandoah_clone_barrier_Type() {
 563   const Type **fields = TypeTuple::fields(1);
 564   fields[TypeFunc::Parms+0] = TypeOopPtr::NOTNULL; // src oop
 565   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+1, fields);
 566 
 567   // create result type (range)
 568   fields = TypeTuple::fields(0);
 569   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+0, fields);
 570 
 571   return TypeFunc::make(domain, range);
 572 }
 573 
 574 const TypeFunc* ShenandoahBarrierSetC2::shenandoah_load_reference_barrier_Type() {
 575   const Type **fields = TypeTuple::fields(2);
 576   fields[TypeFunc::Parms+0] = TypeOopPtr::BOTTOM; // original field value
 577   fields[TypeFunc::Parms+1] = TypeRawPtr::BOTTOM; // original load address
 578 
 579   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2, fields);
 580 
 581   // create result type (range)
 582   fields = TypeTuple::fields(1);
 583   fields[TypeFunc::Parms+0] = TypeOopPtr::BOTTOM;
 584   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+1, fields);
 585 
 586   return TypeFunc::make(domain, range);
 587 }
 588 
 589 Node* ShenandoahBarrierSetC2::store_at_resolved(C2Access& access, C2AccessValue& val) const {
 590   DecoratorSet decorators = access.decorators();
 591 
 592   const TypePtr* adr_type = access.addr().type();
 593   Node* adr = access.addr().node();
 594 
 595   bool anonymous = (decorators & ON_UNKNOWN_OOP_REF) != 0;
 596   bool on_heap = (decorators & IN_HEAP) != 0;
 597 
 598   if (!access.is_oop() || (!on_heap && !anonymous)) {
 599     return BarrierSetC2::store_at_resolved(access, val);
 600   }
 601 
 602   if (access.is_parse_access()) {
 603     C2ParseAccess& parse_access = static_cast<C2ParseAccess&>(access);
 604     GraphKit* kit = parse_access.kit();
 605 
 606     uint adr_idx = kit->C->get_alias_index(adr_type);
 607     assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
 608     Node* value = val.node();
 609     value = shenandoah_iu_barrier(kit, value);
 610     val.set_node(value);
 611     shenandoah_write_barrier_pre(kit, true /* do_load */, /*kit->control(),*/ access.base(), adr, adr_idx, val.node(),
 612                                  static_cast<const TypeOopPtr*>(val.type()), NULL /* pre_val */, access.type());
 613 
 614     Node* result = BarrierSetC2::store_at_resolved(access, val);
 615     bool is_array = (decorators & IS_ARRAY) != 0;
 616     bool use_precise = is_array || anonymous;
 617     post_barrier(kit, kit->control(), access.raw_access(), access.base(), adr, adr_idx, val.node(), access.type(), use_precise);
 618     return result;
 619   } else {
 620     assert(access.is_opt_access(), "only for optimization passes");
 621     assert(((decorators & C2_TIGHTLY_COUPLED_ALLOC) != 0 || !ShenandoahSATBBarrier) && (decorators & C2_ARRAY_COPY) != 0, "unexpected caller of this code");
 622     C2OptAccess& opt_access = static_cast<C2OptAccess&>(access);
 623     PhaseGVN& gvn =  opt_access.gvn();
 624 
 625     if (ShenandoahIUBarrier) {
 626       Node* enqueue = gvn.transform(new ShenandoahIUBarrierNode(val.node()));
 627       val.set_node(enqueue);
 628     }
 629     return BarrierSetC2::store_at_resolved(access, val);
 630   }
 631 }
 632 
 633 Node* ShenandoahBarrierSetC2::load_at_resolved(C2Access& access, const Type* val_type) const {
 634   // 1: non-reference load, no additional barrier is needed
 635   if (!access.is_oop()) {
 636     return BarrierSetC2::load_at_resolved(access, val_type);;
 637   }
 638 
 639   Node* load = BarrierSetC2::load_at_resolved(access, val_type);
 640   DecoratorSet decorators = access.decorators();
 641   BasicType type = access.type();
 642 
 643   // 2: apply LRB if needed
 644   if (ShenandoahBarrierSet::need_load_reference_barrier(decorators, type)) {
 645     load = new ShenandoahLoadReferenceBarrierNode(NULL, load, decorators);
 646     if (access.is_parse_access()) {
 647       load = static_cast<C2ParseAccess &>(access).kit()->gvn().transform(load);
 648     } else {
 649       load = static_cast<C2OptAccess &>(access).gvn().transform(load);
 650     }
 651   }
 652 
 653   // 3: apply keep-alive barrier for java.lang.ref.Reference if needed
 654   if (ShenandoahBarrierSet::need_keep_alive_barrier(decorators, type)) {
 655     Node* top = Compile::current()->top();
 656     Node* adr = access.addr().node();
 657     Node* offset = adr->is_AddP() ? adr->in(AddPNode::Offset) : top;
 658     Node* obj = access.base();
 659 
 660     bool unknown = (decorators & ON_UNKNOWN_OOP_REF) != 0;
 661     bool on_weak_ref = (decorators & (ON_WEAK_OOP_REF | ON_PHANTOM_OOP_REF)) != 0;
 662     bool keep_alive = (decorators & AS_NO_KEEPALIVE) == 0;
 663 
 664     // If we are reading the value of the referent field of a Reference
 665     // object (either by using Unsafe directly or through reflection)
 666     // then, if SATB is enabled, we need to record the referent in an
 667     // SATB log buffer using the pre-barrier mechanism.
 668     // Also we need to add memory barrier to prevent commoning reads
 669     // from this field across safepoint since GC can change its value.
 670     if (!on_weak_ref || (unknown && (offset == top || obj == top)) || !keep_alive) {
 671       return load;
 672     }
 673 
 674     assert(access.is_parse_access(), "entry not supported at optimization time");
 675     C2ParseAccess& parse_access = static_cast<C2ParseAccess&>(access);
 676     GraphKit* kit = parse_access.kit();
 677     bool mismatched = (decorators & C2_MISMATCHED) != 0;
 678     bool is_unordered = (decorators & MO_UNORDERED) != 0;
 679     bool in_native = (decorators & IN_NATIVE) != 0;
 680     bool need_cpu_mem_bar = !is_unordered || mismatched || in_native;
 681 
 682     if (on_weak_ref) {
 683       // Use the pre-barrier to record the value in the referent field
 684       satb_write_barrier_pre(kit, false /* do_load */,
 685                              NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,
 686                              load /* pre_val */, T_OBJECT);
 687       // Add memory barrier to prevent commoning reads from this field
 688       // across safepoint since GC can change its value.
 689       kit->insert_mem_bar(Op_MemBarCPUOrder);
 690     } else if (unknown) {
 691       // We do not require a mem bar inside pre_barrier if need_mem_bar
 692       // is set: the barriers would be emitted by us.
 693       insert_pre_barrier(kit, obj, offset, load, !need_cpu_mem_bar);
 694     }
 695   }
 696 
 697   return load;
 698 }
 699 
 700 Node* ShenandoahBarrierSetC2::atomic_cmpxchg_val_at_resolved(C2AtomicParseAccess& access, Node* expected_val,
 701                                                              Node* new_val, const Type* value_type) const {
 702   GraphKit* kit = access.kit();
 703   if (access.is_oop()) {
 704     new_val = shenandoah_iu_barrier(kit, new_val);
 705     shenandoah_write_barrier_pre(kit, false /* do_load */,
 706                                  NULL, NULL, max_juint, NULL, NULL,
 707                                  expected_val /* pre_val */, T_OBJECT);
 708 
 709     MemNode::MemOrd mo = access.mem_node_mo();
 710     Node* mem = access.memory();
 711     Node* adr = access.addr().node();
 712     const TypePtr* adr_type = access.addr().type();
 713     Node* load_store = NULL;
 714 
 715 #ifdef _LP64
 716     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 717       Node *newval_enc = kit->gvn().transform(new EncodePNode(new_val, new_val->bottom_type()->make_narrowoop()));
 718       Node *oldval_enc = kit->gvn().transform(new EncodePNode(expected_val, expected_val->bottom_type()->make_narrowoop()));
 719       if (ShenandoahCASBarrier) {
 720         load_store = kit->gvn().transform(new ShenandoahCompareAndExchangeNNode(kit->control(), mem, adr, newval_enc, oldval_enc, adr_type, value_type->make_narrowoop(), mo));
 721       } else {
 722         load_store = kit->gvn().transform(new CompareAndExchangeNNode(kit->control(), mem, adr, newval_enc, oldval_enc, adr_type, value_type->make_narrowoop(), mo));
 723       }
 724     } else
 725 #endif
 726     {
 727       if (ShenandoahCASBarrier) {
 728         load_store = kit->gvn().transform(new ShenandoahCompareAndExchangePNode(kit->control(), mem, adr, new_val, expected_val, adr_type, value_type->is_oopptr(), mo));
 729       } else {
 730         load_store = kit->gvn().transform(new CompareAndExchangePNode(kit->control(), mem, adr, new_val, expected_val, adr_type, value_type->is_oopptr(), mo));
 731       }
 732     }
 733 
 734     access.set_raw_access(load_store);
 735     pin_atomic_op(access);
 736 
 737 #ifdef _LP64
 738     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 739       load_store = kit->gvn().transform(new DecodeNNode(load_store, load_store->get_ptr_type()));
 740     }
 741 #endif
 742     load_store = kit->gvn().transform(new ShenandoahLoadReferenceBarrierNode(NULL, load_store, access.decorators()));
 743     post_barrier(kit, kit->control(), access.raw_access(), access.base(), access.addr().node(), access.alias_idx(), new_val, T_OBJECT, true);
 744     return load_store;
 745   }
 746   return BarrierSetC2::atomic_cmpxchg_val_at_resolved(access, expected_val, new_val, value_type);
 747 }
 748 
 749 Node* ShenandoahBarrierSetC2::atomic_cmpxchg_bool_at_resolved(C2AtomicParseAccess& access, Node* expected_val,
 750                                                               Node* new_val, const Type* value_type) const {
 751   GraphKit* kit = access.kit();
 752   if (access.is_oop()) {
 753     new_val = shenandoah_iu_barrier(kit, new_val);
 754     shenandoah_write_barrier_pre(kit, false /* do_load */,
 755                                  NULL, NULL, max_juint, NULL, NULL,
 756                                  expected_val /* pre_val */, T_OBJECT);
 757     DecoratorSet decorators = access.decorators();
 758     MemNode::MemOrd mo = access.mem_node_mo();
 759     Node* mem = access.memory();
 760     bool is_weak_cas = (decorators & C2_WEAK_CMPXCHG) != 0;
 761     Node* load_store = NULL;
 762     Node* adr = access.addr().node();
 763 #ifdef _LP64
 764     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 765       Node *newval_enc = kit->gvn().transform(new EncodePNode(new_val, new_val->bottom_type()->make_narrowoop()));
 766       Node *oldval_enc = kit->gvn().transform(new EncodePNode(expected_val, expected_val->bottom_type()->make_narrowoop()));
 767       if (ShenandoahCASBarrier) {
 768         if (is_weak_cas) {
 769           load_store = kit->gvn().transform(new ShenandoahWeakCompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
 770         } else {
 771           load_store = kit->gvn().transform(new ShenandoahCompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
 772         }
 773       } else {
 774         if (is_weak_cas) {
 775           load_store = kit->gvn().transform(new WeakCompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
 776         } else {
 777           load_store = kit->gvn().transform(new CompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo));
 778         }
 779       }
 780     } else
 781 #endif
 782     {
 783       if (ShenandoahCASBarrier) {
 784         if (is_weak_cas) {
 785           load_store = kit->gvn().transform(new ShenandoahWeakCompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
 786         } else {
 787           load_store = kit->gvn().transform(new ShenandoahCompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
 788         }
 789       } else {
 790         if (is_weak_cas) {
 791           load_store = kit->gvn().transform(new WeakCompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
 792         } else {
 793           load_store = kit->gvn().transform(new CompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo));
 794         }
 795       }
 796     }
 797     access.set_raw_access(load_store);
 798     pin_atomic_op(access);
 799     post_barrier(kit, kit->control(), access.raw_access(), access.base(),
 800                  access.addr().node(), access.alias_idx(), new_val, T_OBJECT, true);
 801     return load_store;
 802   }
 803   return BarrierSetC2::atomic_cmpxchg_bool_at_resolved(access, expected_val, new_val, value_type);
 804 }
 805 
 806 Node* ShenandoahBarrierSetC2::atomic_xchg_at_resolved(C2AtomicParseAccess& access, Node* val, const Type* value_type) const {
 807   GraphKit* kit = access.kit();
 808   if (access.is_oop()) {
 809     val = shenandoah_iu_barrier(kit, val);
 810   }
 811   Node* result = BarrierSetC2::atomic_xchg_at_resolved(access, val, value_type);
 812   if (access.is_oop()) {
 813     result = kit->gvn().transform(new ShenandoahLoadReferenceBarrierNode(NULL, result, access.decorators()));
 814     shenandoah_write_barrier_pre(kit, false /* do_load */,
 815                                  NULL, NULL, max_juint, NULL, NULL,
 816                                  result /* pre_val */, T_OBJECT);
 817     post_barrier(kit, kit->control(), access.raw_access(), access.base(),
 818                  access.addr().node(), access.alias_idx(), val, T_OBJECT, true);
 819   }
 820   return result;
 821 }
 822 
 823 // Support for GC barriers emitted during parsing
 824 bool ShenandoahBarrierSetC2::is_gc_barrier_node(Node* node) const {
 825   if (node->Opcode() == Op_ShenandoahLoadReferenceBarrier) return true;
 826   if (node->Opcode() != Op_CallLeaf && node->Opcode() != Op_CallLeafNoFP) {
 827     return false;
 828   }
 829   CallLeafNode *call = node->as_CallLeaf();
 830   if (call->_name == NULL) {
 831     return false;
 832   }
 833 
 834   return strcmp(call->_name, "shenandoah_clone_barrier") == 0 ||
 835          strcmp(call->_name, "shenandoah_cas_obj") == 0 ||
 836          strcmp(call->_name, "shenandoah_wb_pre") == 0;
 837 }
 838 
 839 Node* ShenandoahBarrierSetC2::step_over_gc_barrier(Node* c) const {
 840   if (c == NULL) {
 841     return c;
 842   }
 843   if (c->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
 844     return c->in(ShenandoahLoadReferenceBarrierNode::ValueIn);
 845   }
 846   if (c->Opcode() == Op_ShenandoahIUBarrier) {
 847     c = c->in(1);
 848   }
 849   return c;
 850 }
 851 
 852 bool ShenandoahBarrierSetC2::expand_barriers(Compile* C, PhaseIterGVN& igvn) const {
 853   return !ShenandoahBarrierC2Support::expand(C, igvn);
 854 }
 855 
 856 bool ShenandoahBarrierSetC2::optimize_loops(PhaseIdealLoop* phase, LoopOptsMode mode, VectorSet& visited, Node_Stack& nstack, Node_List& worklist) const {
 857   if (mode == LoopOptsShenandoahExpand) {
 858     assert(UseShenandoahGC, "only for shenandoah");
 859     ShenandoahBarrierC2Support::pin_and_expand(phase);
 860     return true;
 861   } else if (mode == LoopOptsShenandoahPostExpand) {
 862     assert(UseShenandoahGC, "only for shenandoah");
 863     visited.clear();
 864     ShenandoahBarrierC2Support::optimize_after_expansion(visited, nstack, worklist, phase);
 865     return true;
 866   }
 867   return false;
 868 }
 869 
 870 bool ShenandoahBarrierSetC2::array_copy_requires_gc_barriers(bool tightly_coupled_alloc, BasicType type, bool is_clone, bool is_clone_instance, ArrayCopyPhase phase) const {
 871   bool is_oop = is_reference_type(type);
 872   if (!is_oop) {
 873     return false;
 874   }
 875   if (ShenandoahSATBBarrier && tightly_coupled_alloc) {
 876     if (phase == Optimization) {
 877       return false;
 878     }
 879     return !is_clone;
 880   }
 881   if (phase == Optimization) {
 882     return !ShenandoahIUBarrier;
 883   }
 884   return true;
 885 }
 886 
 887 bool ShenandoahBarrierSetC2::clone_needs_barrier(Node* src, PhaseGVN& gvn) {
 888   const TypeOopPtr* src_type = gvn.type(src)->is_oopptr();
 889   if (src_type->isa_instptr() != NULL) {
 890     ciInstanceKlass* ik = src_type->klass()->as_instance_klass();
 891     if ((src_type->klass_is_exact() || (!ik->is_interface() && !ik->has_subklass())) && !ik->has_injected_fields()) {
 892       if (ik->has_object_fields()) {
 893         return true;
 894       } else {
 895         if (!src_type->klass_is_exact()) {
 896           Compile::current()->dependencies()->assert_leaf_type(ik);
 897         }
 898       }
 899     } else {
 900       return true;
 901     }
 902   } else if (src_type->isa_aryptr()) {
 903     BasicType src_elem  = src_type->klass()->as_array_klass()->element_type()->basic_type();
 904     if (is_reference_type(src_elem)) {
 905       return true;
 906     }
 907   } else {
 908     return true;
 909   }
 910   return false;
 911 }
 912 
 913 void ShenandoahBarrierSetC2::clone_at_expansion(PhaseMacroExpand* phase, ArrayCopyNode* ac) const {
 914   Node* ctrl = ac->in(TypeFunc::Control);
 915   Node* mem = ac->in(TypeFunc::Memory);
 916   Node* src_base = ac->in(ArrayCopyNode::Src);
 917   Node* src_offset = ac->in(ArrayCopyNode::SrcPos);
 918   Node* dest_base = ac->in(ArrayCopyNode::Dest);
 919   Node* dest_offset = ac->in(ArrayCopyNode::DestPos);
 920   Node* length = ac->in(ArrayCopyNode::Length);
 921 
 922   Node* src = phase->basic_plus_adr(src_base, src_offset);
 923   Node* dest = phase->basic_plus_adr(dest_base, dest_offset);
 924 
 925   if (ShenandoahCloneBarrier && clone_needs_barrier(src, phase->igvn())) {
 926     // Check if heap is has forwarded objects. If it does, we need to call into the special
 927     // routine that would fix up source references before we can continue.
 928 
 929     enum { _heap_stable = 1, _heap_unstable, PATH_LIMIT };
 930     Node* region = new RegionNode(PATH_LIMIT);
 931     Node* mem_phi = new PhiNode(region, Type::MEMORY, TypeRawPtr::BOTTOM);
 932 
 933     Node* thread = phase->transform_later(new ThreadLocalNode());
 934     Node* offset = phase->igvn().MakeConX(in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
 935     Node* gc_state_addr = phase->transform_later(new AddPNode(phase->C->top(), thread, offset));
 936 
 937     uint gc_state_idx = Compile::AliasIdxRaw;
 938     const TypePtr* gc_state_adr_type = NULL; // debug-mode-only argument
 939     debug_only(gc_state_adr_type = phase->C->get_adr_type(gc_state_idx));
 940 
 941     Node* gc_state    = phase->transform_later(new LoadBNode(ctrl, mem, gc_state_addr, gc_state_adr_type, TypeInt::BYTE, MemNode::unordered));
 942     int flags = ShenandoahHeap::HAS_FORWARDED;
 943     if (ShenandoahIUBarrier) {
 944       flags |= ShenandoahHeap::YOUNG_MARKING;
 945     }
 946     Node* stable_and  = phase->transform_later(new AndINode(gc_state, phase->igvn().intcon(flags)));
 947     Node* stable_cmp  = phase->transform_later(new CmpINode(stable_and, phase->igvn().zerocon(T_INT)));
 948     Node* stable_test = phase->transform_later(new BoolNode(stable_cmp, BoolTest::ne));
 949 
 950     IfNode* stable_iff  = phase->transform_later(new IfNode(ctrl, stable_test, PROB_UNLIKELY(0.999), COUNT_UNKNOWN))->as_If();
 951     Node* stable_ctrl   = phase->transform_later(new IfFalseNode(stable_iff));
 952     Node* unstable_ctrl = phase->transform_later(new IfTrueNode(stable_iff));
 953 
 954     // Heap is stable, no need to do anything additional
 955     region->init_req(_heap_stable, stable_ctrl);
 956     mem_phi->init_req(_heap_stable, mem);
 957 
 958     // Heap is unstable, call into clone barrier stub
 959     Node* call = phase->make_leaf_call(unstable_ctrl, mem,
 960                     ShenandoahBarrierSetC2::shenandoah_clone_barrier_Type(),
 961                     CAST_FROM_FN_PTR(address, ShenandoahRuntime::shenandoah_clone_barrier),
 962                     "shenandoah_clone",
 963                     TypeRawPtr::BOTTOM,
 964                     src_base);
 965     call = phase->transform_later(call);
 966 
 967     ctrl = phase->transform_later(new ProjNode(call, TypeFunc::Control));
 968     mem = phase->transform_later(new ProjNode(call, TypeFunc::Memory));
 969     region->init_req(_heap_unstable, ctrl);
 970     mem_phi->init_req(_heap_unstable, mem);
 971 
 972     // Wire up the actual arraycopy stub now
 973     ctrl = phase->transform_later(region);
 974     mem = phase->transform_later(mem_phi);
 975 
 976     const char* name = "arraycopy";
 977     call = phase->make_leaf_call(ctrl, mem,
 978                                  OptoRuntime::fast_arraycopy_Type(),
 979                                  phase->basictype2arraycopy(T_LONG, NULL, NULL, true, name, true),
 980                                  name, TypeRawPtr::BOTTOM,
 981                                  src, dest, length
 982                                  LP64_ONLY(COMMA phase->top()));
 983     call = phase->transform_later(call);
 984 
 985     // Hook up the whole thing into the graph
 986     phase->igvn().replace_node(ac, call);
 987   } else {
 988     BarrierSetC2::clone_at_expansion(phase, ac);
 989   }
 990 }
 991 
 992 
 993 // Support for macro expanded GC barriers
 994 void ShenandoahBarrierSetC2::register_potential_barrier_node(Node* node) const {
 995   if (node->Opcode() == Op_ShenandoahIUBarrier) {
 996     state()->add_iu_barrier((ShenandoahIUBarrierNode*) node);
 997   }
 998   if (node->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
 999     state()->add_load_reference_barrier((ShenandoahLoadReferenceBarrierNode*) node);
1000   }
1001 }
1002 
1003 void ShenandoahBarrierSetC2::unregister_potential_barrier_node(Node* node) const {
1004   if (node->Opcode() == Op_ShenandoahIUBarrier) {
1005     state()->remove_iu_barrier((ShenandoahIUBarrierNode*) node);
1006   }
1007   if (node->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
1008     state()->remove_load_reference_barrier((ShenandoahLoadReferenceBarrierNode*) node);
1009   }
1010 }
1011 
1012 void ShenandoahBarrierSetC2::eliminate_gc_barrier(PhaseMacroExpand* macro, Node* node) const {
1013   if (is_shenandoah_wb_pre_call(node)) {
1014     shenandoah_eliminate_wb_pre(node, &macro->igvn());
1015   }
1016   if (node->Opcode() == Op_CastP2X && ShenandoahHeap::heap()->mode()->is_generational()) {
1017     assert(node->Opcode() == Op_CastP2X, "ConvP2XNode required");
1018      Node *shift = node->unique_out();
1019      Node *addp = shift->unique_out();
1020      for (DUIterator_Last jmin, j = addp->last_outs(jmin); j >= jmin; --j) {
1021        Node *mem = addp->last_out(j);
1022        if (UseCondCardMark && mem->is_Load()) {
1023          assert(mem->Opcode() == Op_LoadB, "unexpected code shape");
1024          // The load is checking if the card has been written so
1025          // replace it with zero to fold the test.
1026          macro->replace_node(mem, macro->intcon(0));
1027          continue;
1028        }
1029        assert(mem->is_Store(), "store required");
1030        macro->replace_node(mem, mem->in(MemNode::Memory));
1031      }
1032   }
1033 }
1034 
1035 void ShenandoahBarrierSetC2::shenandoah_eliminate_wb_pre(Node* call, PhaseIterGVN* igvn) const {
1036   assert(UseShenandoahGC && is_shenandoah_wb_pre_call(call), "");
1037   Node* c = call->as_Call()->proj_out(TypeFunc::Control);
1038   c = c->unique_ctrl_out();
1039   assert(c->is_Region() && c->req() == 3, "where's the pre barrier control flow?");
1040   c = c->unique_ctrl_out();
1041   assert(c->is_Region() && c->req() == 3, "where's the pre barrier control flow?");
1042   Node* iff = c->in(1)->is_IfProj() ? c->in(1)->in(0) : c->in(2)->in(0);
1043   assert(iff->is_If(), "expect test");
1044   if (!is_shenandoah_marking_if(igvn, iff)) {
1045     c = c->unique_ctrl_out();
1046     assert(c->is_Region() && c->req() == 3, "where's the pre barrier control flow?");
1047     iff = c->in(1)->is_IfProj() ? c->in(1)->in(0) : c->in(2)->in(0);
1048     assert(is_shenandoah_marking_if(igvn, iff), "expect marking test");
1049   }
1050   Node* cmpx = iff->in(1)->in(1);
1051   igvn->replace_node(cmpx, igvn->makecon(TypeInt::CC_EQ));
1052   igvn->rehash_node_delayed(call);
1053   call->del_req(call->req()-1);
1054 }
1055 
1056 void ShenandoahBarrierSetC2::enqueue_useful_gc_barrier(PhaseIterGVN* igvn, Node* node) const {
1057   if (node->Opcode() == Op_AddP && ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(node)) {
1058     igvn->add_users_to_worklist(node);
1059   }
1060 }
1061 
1062 void ShenandoahBarrierSetC2::eliminate_useless_gc_barriers(Unique_Node_List &useful, Compile* C) const {
1063   for (uint i = 0; i < useful.size(); i++) {
1064     Node* n = useful.at(i);
1065     if (n->Opcode() == Op_AddP && ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(n)) {
1066       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1067         C->record_for_igvn(n->fast_out(i));
1068       }
1069     }
1070   }
1071   for (int i = state()->iu_barriers_count() - 1; i >= 0; i--) {
1072     ShenandoahIUBarrierNode* n = state()->iu_barrier(i);
1073     if (!useful.member(n)) {
1074       state()->remove_iu_barrier(n);
1075     }
1076   }
1077   for (int i = state()->load_reference_barriers_count() - 1; i >= 0; i--) {
1078     ShenandoahLoadReferenceBarrierNode* n = state()->load_reference_barrier(i);
1079     if (!useful.member(n)) {
1080       state()->remove_load_reference_barrier(n);
1081     }
1082   }
1083 }
1084 
1085 void* ShenandoahBarrierSetC2::create_barrier_state(Arena* comp_arena) const {
1086   return new(comp_arena) ShenandoahBarrierSetC2State(comp_arena);
1087 }
1088 
1089 ShenandoahBarrierSetC2State* ShenandoahBarrierSetC2::state() const {
1090   return reinterpret_cast<ShenandoahBarrierSetC2State*>(Compile::current()->barrier_set_state());
1091 }
1092 
1093 // If the BarrierSetC2 state has kept macro nodes in its compilation unit state to be
1094 // expanded later, then now is the time to do so.
1095 bool ShenandoahBarrierSetC2::expand_macro_nodes(PhaseMacroExpand* macro) const { return false; }
1096 
1097 #ifdef ASSERT
1098 void ShenandoahBarrierSetC2::verify_gc_barriers(Compile* compile, CompilePhase phase) const {
1099   if (ShenandoahVerifyOptoBarriers && phase == BarrierSetC2::BeforeMacroExpand) {
1100     ShenandoahBarrierC2Support::verify(Compile::current()->root());
1101   } else if (phase == BarrierSetC2::BeforeCodeGen) {
1102     // Verify Shenandoah pre-barriers
1103     const int marking_offset = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_active_offset());
1104 
1105     Unique_Node_List visited;
1106     Node_List worklist;
1107     // We're going to walk control flow backwards starting from the Root
1108     worklist.push(compile->root());
1109     while (worklist.size() > 0) {
1110       Node *x = worklist.pop();
1111       if (x == NULL || x == compile->top()) continue;
1112       if (visited.member(x)) {
1113         continue;
1114       } else {
1115         visited.push(x);
1116       }
1117 
1118       if (x->is_Region()) {
1119         for (uint i = 1; i < x->req(); i++) {
1120           worklist.push(x->in(i));
1121         }
1122       } else {
1123         worklist.push(x->in(0));
1124         // We are looking for the pattern:
1125         //                            /->ThreadLocal
1126         // If->Bool->CmpI->LoadB->AddP->ConL(marking_offset)
1127         //              \->ConI(0)
1128         // We want to verify that the If and the LoadB have the same control
1129         // See GraphKit::g1_write_barrier_pre()
1130         if (x->is_If()) {
1131           IfNode *iff = x->as_If();
1132           if (iff->in(1)->is_Bool() && iff->in(1)->in(1)->is_Cmp()) {
1133             CmpNode *cmp = iff->in(1)->in(1)->as_Cmp();
1134             if (cmp->Opcode() == Op_CmpI && cmp->in(2)->is_Con() && cmp->in(2)->bottom_type()->is_int()->get_con() == 0
1135                 && cmp->in(1)->is_Load()) {
1136               LoadNode *load = cmp->in(1)->as_Load();
1137               if (load->Opcode() == Op_LoadB && load->in(2)->is_AddP() && load->in(2)->in(2)->Opcode() == Op_ThreadLocal
1138                   && load->in(2)->in(3)->is_Con()
1139                   && load->in(2)->in(3)->bottom_type()->is_intptr_t()->get_con() == marking_offset) {
1140 
1141                 Node *if_ctrl = iff->in(0);
1142                 Node *load_ctrl = load->in(0);
1143 
1144                 if (if_ctrl != load_ctrl) {
1145                   // Skip possible CProj->NeverBranch in infinite loops
1146                   if ((if_ctrl->is_Proj() && if_ctrl->Opcode() == Op_CProj)
1147                       && (if_ctrl->in(0)->is_MultiBranch() && if_ctrl->in(0)->Opcode() == Op_NeverBranch)) {
1148                     if_ctrl = if_ctrl->in(0)->in(0);
1149                   }
1150                 }
1151                 assert(load_ctrl != NULL && if_ctrl == load_ctrl, "controls must match");
1152               }
1153             }
1154           }
1155         }
1156       }
1157     }
1158   }
1159 }
1160 #endif
1161 
1162 Node* ShenandoahBarrierSetC2::ideal_node(PhaseGVN* phase, Node* n, bool can_reshape) const {
1163   if (is_shenandoah_wb_pre_call(n)) {
1164     uint cnt = ShenandoahBarrierSetC2::write_ref_field_pre_entry_Type()->domain()->cnt();
1165     if (n->req() > cnt) {
1166       Node* addp = n->in(cnt);
1167       if (has_only_shenandoah_wb_pre_uses(addp)) {
1168         n->del_req(cnt);
1169         if (can_reshape) {
1170           phase->is_IterGVN()->_worklist.push(addp);
1171         }
1172         return n;
1173       }
1174     }
1175   }
1176   if (n->Opcode() == Op_CmpP) {
1177     Node* in1 = n->in(1);
1178     Node* in2 = n->in(2);
1179 
1180     // If one input is NULL, then step over the strong LRB barriers on the other input
1181     if (in1->bottom_type() == TypePtr::NULL_PTR &&
1182         !((in2->Opcode() == Op_ShenandoahLoadReferenceBarrier) &&
1183           !ShenandoahBarrierSet::is_strong_access(((ShenandoahLoadReferenceBarrierNode*)in2)->decorators()))) {
1184       in2 = step_over_gc_barrier(in2);
1185     }
1186     if (in2->bottom_type() == TypePtr::NULL_PTR &&
1187         !((in1->Opcode() == Op_ShenandoahLoadReferenceBarrier) &&
1188           !ShenandoahBarrierSet::is_strong_access(((ShenandoahLoadReferenceBarrierNode*)in1)->decorators()))) {
1189       in1 = step_over_gc_barrier(in1);
1190     }
1191 
1192     if (in1 != n->in(1)) {
1193       n->set_req_X(1, in1, phase);
1194       assert(in2 == n->in(2), "only one change");
1195       return n;
1196     }
1197     if (in2 != n->in(2)) {
1198       n->set_req_X(2, in2, phase);
1199       return n;
1200     }
1201   } else if (can_reshape &&
1202              n->Opcode() == Op_If &&
1203              ShenandoahBarrierC2Support::is_heap_stable_test(n) &&
1204              n->in(0) != NULL) {
1205     Node* dom = n->in(0);
1206     Node* prev_dom = n;
1207     int op = n->Opcode();
1208     int dist = 16;
1209     // Search up the dominator tree for another heap stable test
1210     while (dom->Opcode() != op    ||  // Not same opcode?
1211            !ShenandoahBarrierC2Support::is_heap_stable_test(dom) ||  // Not same input 1?
1212            prev_dom->in(0) != dom) {  // One path of test does not dominate?
1213       if (dist < 0) return NULL;
1214 
1215       dist--;
1216       prev_dom = dom;
1217       dom = IfNode::up_one_dom(dom);
1218       if (!dom) return NULL;
1219     }
1220 
1221     // Check that we did not follow a loop back to ourselves
1222     if (n == dom) {
1223       return NULL;
1224     }
1225 
1226     return n->as_If()->dominated_by(prev_dom, phase->is_IterGVN());
1227   }
1228 
1229   return NULL;
1230 }
1231 
1232 bool ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(Node* n) {
1233   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1234     Node* u = n->fast_out(i);
1235     if (!is_shenandoah_wb_pre_call(u)) {
1236       return false;
1237     }
1238   }
1239   return n->outcnt() > 0;
1240 }
1241 
1242 bool ShenandoahBarrierSetC2::final_graph_reshaping(Compile* compile, Node* n, uint opcode) const {
1243   switch (opcode) {
1244     case Op_CallLeaf:
1245     case Op_CallLeafNoFP: {
1246       assert (n->is_Call(), "");
1247       CallNode *call = n->as_Call();
1248       if (ShenandoahBarrierSetC2::is_shenandoah_wb_pre_call(call)) {
1249         uint cnt = ShenandoahBarrierSetC2::write_ref_field_pre_entry_Type()->domain()->cnt();
1250         if (call->req() > cnt) {
1251           assert(call->req() == cnt + 1, "only one extra input");
1252           Node *addp = call->in(cnt);
1253           assert(!ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(addp), "useless address computation?");
1254           call->del_req(cnt);
1255         }
1256       }
1257       return false;
1258     }
1259     case Op_ShenandoahCompareAndSwapP:
1260     case Op_ShenandoahCompareAndSwapN:
1261     case Op_ShenandoahWeakCompareAndSwapN:
1262     case Op_ShenandoahWeakCompareAndSwapP:
1263     case Op_ShenandoahCompareAndExchangeP:
1264     case Op_ShenandoahCompareAndExchangeN:
1265       return true;
1266     case Op_ShenandoahLoadReferenceBarrier:
1267       assert(false, "should have been expanded already");
1268       return true;
1269     default:
1270       return false;
1271   }
1272 }
1273 
1274 bool ShenandoahBarrierSetC2::escape_add_to_con_graph(ConnectionGraph* conn_graph, PhaseGVN* gvn, Unique_Node_List* delayed_worklist, Node* n, uint opcode) const {
1275   switch (opcode) {
1276     case Op_ShenandoahCompareAndExchangeP:
1277     case Op_ShenandoahCompareAndExchangeN:
1278       conn_graph->add_objload_to_connection_graph(n, delayed_worklist);
1279       // fallthrough
1280     case Op_ShenandoahWeakCompareAndSwapP:
1281     case Op_ShenandoahWeakCompareAndSwapN:
1282     case Op_ShenandoahCompareAndSwapP:
1283     case Op_ShenandoahCompareAndSwapN:
1284       conn_graph->add_to_congraph_unsafe_access(n, opcode, delayed_worklist);
1285       return true;
1286     case Op_StoreP: {
1287       Node* adr = n->in(MemNode::Address);
1288       const Type* adr_type = gvn->type(adr);
1289       // Pointer stores in Shenandoah barriers looks like unsafe access.
1290       // Ignore such stores to be able scalar replace non-escaping
1291       // allocations.
1292       if (adr_type->isa_rawptr() && adr->is_AddP()) {
1293         Node* base = conn_graph->get_addp_base(adr);
1294         if (base->Opcode() == Op_LoadP &&
1295           base->in(MemNode::Address)->is_AddP()) {
1296           adr = base->in(MemNode::Address);
1297           Node* tls = conn_graph->get_addp_base(adr);
1298           if (tls->Opcode() == Op_ThreadLocal) {
1299              int offs = (int) gvn->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
1300              const int buf_offset = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset());
1301              if (offs == buf_offset) {
1302                return true; // Pre barrier previous oop value store.
1303              }
1304           }
1305         }
1306       }
1307       return false;
1308     }
1309     case Op_ShenandoahIUBarrier:
1310       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), delayed_worklist);
1311       break;
1312     case Op_ShenandoahLoadReferenceBarrier:
1313       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(ShenandoahLoadReferenceBarrierNode::ValueIn), delayed_worklist);
1314       return true;
1315     default:
1316       // Nothing
1317       break;
1318   }
1319   return false;
1320 }
1321 
1322 bool ShenandoahBarrierSetC2::escape_add_final_edges(ConnectionGraph* conn_graph, PhaseGVN* gvn, Node* n, uint opcode) const {
1323   switch (opcode) {
1324     case Op_ShenandoahCompareAndExchangeP:
1325     case Op_ShenandoahCompareAndExchangeN: {
1326       Node *adr = n->in(MemNode::Address);
1327       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, adr, NULL);
1328       // fallthrough
1329     }
1330     case Op_ShenandoahCompareAndSwapP:
1331     case Op_ShenandoahCompareAndSwapN:
1332     case Op_ShenandoahWeakCompareAndSwapP:
1333     case Op_ShenandoahWeakCompareAndSwapN:
1334       return conn_graph->add_final_edges_unsafe_access(n, opcode);
1335     case Op_ShenandoahIUBarrier:
1336       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), NULL);
1337       return true;
1338     case Op_ShenandoahLoadReferenceBarrier:
1339       conn_graph->add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(ShenandoahLoadReferenceBarrierNode::ValueIn), NULL);
1340       return true;
1341     default:
1342       // Nothing
1343       break;
1344   }
1345   return false;
1346 }
1347 
1348 bool ShenandoahBarrierSetC2::escape_has_out_with_unsafe_object(Node* n) const {
1349   return n->has_out_with(Op_ShenandoahCompareAndExchangeP) || n->has_out_with(Op_ShenandoahCompareAndExchangeN) ||
1350          n->has_out_with(Op_ShenandoahCompareAndSwapP, Op_ShenandoahCompareAndSwapN, Op_ShenandoahWeakCompareAndSwapP, Op_ShenandoahWeakCompareAndSwapN);
1351 
1352 }
1353 
1354 bool ShenandoahBarrierSetC2::matcher_find_shared_post_visit(Matcher* matcher, Node* n, uint opcode) const {
1355   switch (opcode) {
1356     case Op_ShenandoahCompareAndExchangeP:
1357     case Op_ShenandoahCompareAndExchangeN:
1358     case Op_ShenandoahWeakCompareAndSwapP:
1359     case Op_ShenandoahWeakCompareAndSwapN:
1360     case Op_ShenandoahCompareAndSwapP:
1361     case Op_ShenandoahCompareAndSwapN: {   // Convert trinary to binary-tree
1362       Node* newval = n->in(MemNode::ValueIn);
1363       Node* oldval = n->in(LoadStoreConditionalNode::ExpectedIn);
1364       Node* pair = new BinaryNode(oldval, newval);
1365       n->set_req(MemNode::ValueIn,pair);
1366       n->del_req(LoadStoreConditionalNode::ExpectedIn);
1367       return true;
1368     }
1369     default:
1370       break;
1371   }
1372   return false;
1373 }
1374 
1375 bool ShenandoahBarrierSetC2::matcher_is_store_load_barrier(Node* x, uint xop) const {
1376   return xop == Op_ShenandoahCompareAndExchangeP ||
1377          xop == Op_ShenandoahCompareAndExchangeN ||
1378          xop == Op_ShenandoahWeakCompareAndSwapP ||
1379          xop == Op_ShenandoahWeakCompareAndSwapN ||
1380          xop == Op_ShenandoahCompareAndSwapN ||
1381          xop == Op_ShenandoahCompareAndSwapP;
1382 }