1 /*
   2  * Copyright (c) 2018, 2026, Oracle and/or its affiliates. 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 "code/vmreg.inline.hpp"
  26 #include "gc/shared/barrierSet.hpp"
  27 #include "gc/shared/c2/barrierSetC2.hpp"
  28 #include "gc/shared/tlab_globals.hpp"
  29 #include "opto/arraycopynode.hpp"
  30 #include "opto/block.hpp"
  31 #include "opto/convertnode.hpp"
  32 #include "opto/graphKit.hpp"
  33 #include "opto/idealKit.hpp"
  34 #include "opto/macro.hpp"
  35 #include "opto/narrowptrnode.hpp"
  36 #include "opto/output.hpp"
  37 #include "opto/regalloc.hpp"
  38 #include "opto/runtime.hpp"
  39 #include "utilities/macros.hpp"
  40 #include CPU_HEADER(gc/shared/barrierSetAssembler)
  41 
  42 // By default this is a no-op.
  43 void BarrierSetC2::resolve_address(C2Access& access) const { }
  44 
  45 void* C2ParseAccess::barrier_set_state() const {
  46   return _kit->barrier_set_state();
  47 }
  48 
  49 PhaseGVN& C2ParseAccess::gvn() const { return _kit->gvn(); }
  50 
  51 bool C2Access::needs_cpu_membar() const {
  52   bool mismatched   = (_decorators & C2_MISMATCHED) != 0;
  53   bool is_unordered = (_decorators & MO_UNORDERED) != 0;
  54 
  55   bool anonymous = (_decorators & C2_UNSAFE_ACCESS) != 0;
  56   bool in_heap   = (_decorators & IN_HEAP) != 0;
  57   bool in_native = (_decorators & IN_NATIVE) != 0;
  58   bool is_mixed  = !in_heap && !in_native;
  59 
  60   bool is_write  = (_decorators & C2_WRITE_ACCESS) != 0;
  61   bool is_read   = (_decorators & C2_READ_ACCESS) != 0;
  62   bool is_atomic = is_read && is_write;
  63 
  64   if (is_atomic) {
  65     // Atomics always need to be wrapped in CPU membars
  66     return true;
  67   }
  68 
  69   if (anonymous) {
  70     // We will need memory barriers unless we can determine a unique
  71     // alias category for this reference.  (Note:  If for some reason
  72     // the barriers get omitted and the unsafe reference begins to "pollute"
  73     // the alias analysis of the rest of the graph, either Compile::can_alias
  74     // or Compile::must_alias will throw a diagnostic assert.)
  75     if (is_mixed || !is_unordered || (mismatched && !_addr.type()->isa_aryptr())) {
  76       return true;
  77     }
  78   } else {
  79     assert(!is_mixed, "not unsafe");
  80   }
  81 
  82   return false;
  83 }
  84 
  85 static BarrierSetC2State* barrier_set_state() {
  86   return reinterpret_cast<BarrierSetC2State*>(Compile::current()->barrier_set_state());
  87 }
  88 
  89 RegMask& BarrierStubC2::live() const {
  90   return *barrier_set_state()->live(_node);
  91 }
  92 
  93 BarrierStubC2::BarrierStubC2(const MachNode* node)
  94   : _node(node),
  95     _entry(),
  96     _continuation(),
  97     _preserve(live()) {}
  98 
  99 Label* BarrierStubC2::entry() {
 100   // The _entry will never be bound when in_scratch_emit_size() is true.
 101   // However, we still need to return a label that is not bound now, but
 102   // will eventually be bound. Any eventually bound label will do, as it
 103   // will only act as a placeholder, so we return the _continuation label.
 104   return Compile::current()->output()->in_scratch_emit_size() ? &_continuation : &_entry;
 105 }
 106 
 107 Label* BarrierStubC2::continuation() {
 108   return &_continuation;
 109 }
 110 
 111 uint8_t BarrierStubC2::barrier_data() const {
 112   return _node->barrier_data();
 113 }
 114 
 115 void BarrierStubC2::preserve(Register r) {
 116   const VMReg vm_reg = r->as_VMReg();
 117   assert(vm_reg->is_Register(), "r must be a general-purpose register");
 118   _preserve.insert(OptoReg::as_OptoReg(vm_reg));
 119 }
 120 
 121 void BarrierStubC2::dont_preserve(Register r) {
 122   VMReg vm_reg = r->as_VMReg();
 123   assert(vm_reg->is_Register(), "r must be a general-purpose register");
 124   // Subtract the given register and all its sub-registers (e.g. {R11, R11_H}
 125   // for r11 in aarch64).
 126   do {
 127     _preserve.remove(OptoReg::as_OptoReg(vm_reg));
 128     vm_reg = vm_reg->next();
 129   } while (vm_reg->is_Register() && !vm_reg->is_concrete());
 130 }
 131 
 132 bool BarrierStubC2::is_preserved(Register r) const {
 133   const VMReg vm_reg = r->as_VMReg();
 134   assert(vm_reg->is_Register(), "r must be a general-purpose register");
 135   return _preserve.member(OptoReg::as_OptoReg(vm_reg));
 136 }
 137 
 138 const RegMask& BarrierStubC2::preserve_set() const {
 139   return _preserve;
 140 }
 141 
 142 Node* BarrierSetC2::store_at_resolved(C2Access& access, C2AccessValue& val) const {
 143   DecoratorSet decorators = access.decorators();
 144 
 145   bool mismatched = (decorators & C2_MISMATCHED) != 0;
 146   bool unaligned = (decorators & C2_UNALIGNED) != 0;
 147   bool unsafe = (decorators & C2_UNSAFE_ACCESS) != 0;
 148   bool requires_atomic_access = (decorators & MO_UNORDERED) == 0;
 149 
 150   MemNode::MemOrd mo = access.mem_node_mo();
 151 
 152   Node* store;
 153   BasicType bt = access.type();
 154   if (access.is_parse_access()) {
 155     C2ParseAccess& parse_access = static_cast<C2ParseAccess&>(access);
 156 
 157     GraphKit* kit = parse_access.kit();
 158     store = kit->store_to_memory(kit->control(), access.addr().node(), val.node(), bt,
 159                                  mo, requires_atomic_access, unaligned, mismatched,
 160                                  unsafe, access.barrier_data());
 161   } else {
 162     assert(access.is_opt_access(), "either parse or opt access");
 163     C2OptAccess& opt_access = static_cast<C2OptAccess&>(access);
 164     Node* ctl = opt_access.ctl();
 165     MergeMemNode* mm = opt_access.mem();
 166     PhaseGVN& gvn = opt_access.gvn();
 167     const TypePtr* adr_type = access.addr().type();
 168     int alias = gvn.C->get_alias_index(adr_type);
 169     Node* mem = mm->memory_at(alias);
 170 
 171     StoreNode* st = StoreNode::make(gvn, ctl, mem, access.addr().node(), adr_type, val.node(), bt, mo, requires_atomic_access);
 172     if (unaligned) {
 173       st->set_unaligned_access();
 174     }
 175     if (mismatched) {
 176       st->set_mismatched_access();
 177     }
 178     st->set_barrier_data(access.barrier_data());
 179     store = gvn.transform(st);
 180     if (store == st) {
 181       mm->set_memory_at(alias, st);
 182     }
 183   }
 184   access.set_raw_access(store);
 185 
 186   return store;
 187 }
 188 
 189 Node* BarrierSetC2::load_at_resolved(C2Access& access, const Type* val_type) const {
 190   DecoratorSet decorators = access.decorators();
 191 
 192   Node* adr = access.addr().node();
 193   const TypePtr* adr_type = access.addr().type();
 194 
 195   bool mismatched = (decorators & C2_MISMATCHED) != 0;
 196   bool requires_atomic_access = (decorators & MO_UNORDERED) == 0;
 197   bool unaligned = (decorators & C2_UNALIGNED) != 0;
 198   bool control_dependent = (decorators & C2_CONTROL_DEPENDENT_LOAD) != 0;
 199   bool unknown_control = (decorators & C2_UNKNOWN_CONTROL_LOAD) != 0;
 200   bool unsafe = (decorators & C2_UNSAFE_ACCESS) != 0;
 201   bool immutable = (decorators & C2_IMMUTABLE_MEMORY) != 0;
 202 
 203   MemNode::MemOrd mo = access.mem_node_mo();
 204   LoadNode::ControlDependency dep = unknown_control ? LoadNode::UnknownControl : LoadNode::DependsOnlyOnTest;
 205 
 206   Node* load;
 207   if (access.is_parse_access()) {
 208     C2ParseAccess& parse_access = static_cast<C2ParseAccess&>(access);
 209     GraphKit* kit = parse_access.kit();
 210     Node* control = control_dependent ? kit->control() : nullptr;
 211 
 212     if (immutable) {
 213       Compile* C = Compile::current();
 214       Node* mem = kit->immutable_memory();
 215       load = LoadNode::make(kit->gvn(), control, mem, adr,
 216                             adr_type, val_type, access.type(), mo, dep, requires_atomic_access,
 217                             unaligned, mismatched, unsafe, access.barrier_data());
 218       load = kit->gvn().transform(load);
 219     } else {
 220       load = kit->make_load(control, adr, val_type, access.type(), mo,
 221                             dep, requires_atomic_access, unaligned, mismatched, unsafe,
 222                             access.barrier_data());
 223     }
 224   } else {
 225     assert(access.is_opt_access(), "either parse or opt access");
 226     C2OptAccess& opt_access = static_cast<C2OptAccess&>(access);
 227     Node* control = control_dependent ? opt_access.ctl() : nullptr;
 228     MergeMemNode* mm = opt_access.mem();
 229     PhaseGVN& gvn = opt_access.gvn();
 230     Node* mem = mm->memory_at(gvn.C->get_alias_index(adr_type));
 231     load = LoadNode::make(gvn, control, mem, adr, adr_type, val_type, access.type(), mo, dep,
 232                           requires_atomic_access, unaligned, mismatched, unsafe, access.barrier_data());
 233     load = gvn.transform(load);
 234   }
 235   access.set_raw_access(load);
 236 
 237   return load;
 238 }
 239 
 240 class C2AccessFence: public StackObj {
 241   C2Access& _access;
 242   Node* _leading_membar;
 243 
 244 public:
 245   C2AccessFence(C2Access& access) :
 246     _access(access), _leading_membar(nullptr) {
 247     GraphKit* kit = nullptr;
 248     if (access.is_parse_access()) {
 249       C2ParseAccess& parse_access = static_cast<C2ParseAccess&>(access);
 250       kit = parse_access.kit();
 251     }
 252     DecoratorSet decorators = access.decorators();
 253 
 254     bool is_write = (decorators & C2_WRITE_ACCESS) != 0;
 255     bool is_read = (decorators & C2_READ_ACCESS) != 0;
 256     bool is_atomic = is_read && is_write;
 257 
 258     bool is_volatile = (decorators & MO_SEQ_CST) != 0;
 259     bool is_release = (decorators & MO_RELEASE) != 0;
 260 
 261     if (is_atomic) {
 262       assert(kit != nullptr, "unsupported at optimization time");
 263       // Memory-model-wise, a LoadStore acts like a little synchronized
 264       // block, so needs barriers on each side.  These don't translate
 265       // into actual barriers on most machines, but we still need rest of
 266       // compiler to respect ordering.
 267       if (is_release) {
 268         _leading_membar = kit->insert_mem_bar(Op_MemBarRelease);
 269       } else if (is_volatile) {
 270         if (support_IRIW_for_not_multiple_copy_atomic_cpu) {
 271           _leading_membar = kit->insert_mem_bar(Op_MemBarVolatile);
 272         } else {
 273           _leading_membar = kit->insert_mem_bar(Op_MemBarRelease);
 274         }
 275       }
 276     } else if (is_write) {
 277       // If reference is volatile, prevent following memory ops from
 278       // floating down past the volatile write.  Also prevents commoning
 279       // another volatile read.
 280       if (is_volatile || is_release) {
 281         assert(kit != nullptr, "unsupported at optimization time");
 282         _leading_membar = kit->insert_mem_bar(Op_MemBarRelease);
 283       }
 284     } else {
 285       // Memory barrier to prevent normal and 'unsafe' accesses from
 286       // bypassing each other.  Happens after null checks, so the
 287       // exception paths do not take memory state from the memory barrier,
 288       // so there's no problems making a strong assert about mixing users
 289       // of safe & unsafe memory.
 290       if (is_volatile && support_IRIW_for_not_multiple_copy_atomic_cpu) {
 291         assert(kit != nullptr, "unsupported at optimization time");
 292         _leading_membar = kit->insert_mem_bar(Op_MemBarVolatile);
 293       }
 294     }
 295 
 296     if (access.needs_cpu_membar()) {
 297       assert(kit != nullptr, "unsupported at optimization time");
 298       kit->insert_mem_bar(Op_MemBarCPUOrder);
 299     }
 300 
 301     if (is_atomic) {
 302       // 4984716: MemBars must be inserted before this
 303       //          memory node in order to avoid a false
 304       //          dependency which will confuse the scheduler.
 305       access.set_memory();
 306     }
 307   }
 308 
 309   ~C2AccessFence() {
 310     GraphKit* kit = nullptr;
 311     if (_access.is_parse_access()) {
 312       C2ParseAccess& parse_access = static_cast<C2ParseAccess&>(_access);
 313       kit = parse_access.kit();
 314     }
 315     DecoratorSet decorators = _access.decorators();
 316 
 317     bool is_write = (decorators & C2_WRITE_ACCESS) != 0;
 318     bool is_read = (decorators & C2_READ_ACCESS) != 0;
 319     bool is_atomic = is_read && is_write;
 320 
 321     bool is_volatile = (decorators & MO_SEQ_CST) != 0;
 322     bool is_acquire = (decorators & MO_ACQUIRE) != 0;
 323 
 324     // If reference is volatile, prevent following volatiles ops from
 325     // floating up before the volatile access.
 326     if (_access.needs_cpu_membar()) {
 327       kit->insert_mem_bar(Op_MemBarCPUOrder);
 328     }
 329 
 330     if (is_atomic) {
 331       assert(kit != nullptr, "unsupported at optimization time");
 332       if (is_acquire || is_volatile) {
 333         Node* n = _access.raw_access();
 334         Node* mb = kit->insert_mem_bar(Op_MemBarAcquire, n);
 335         if (_leading_membar != nullptr) {
 336           MemBarNode::set_load_store_pair(_leading_membar->as_MemBar(), mb->as_MemBar());
 337         }
 338       }
 339     } else if (is_write) {
 340       // If not multiple copy atomic, we do the MemBarVolatile before the load.
 341       if (is_volatile && !support_IRIW_for_not_multiple_copy_atomic_cpu) {
 342         assert(kit != nullptr, "unsupported at optimization time");
 343         Node* n = _access.raw_access();
 344         Node* mb = kit->insert_mem_bar(Op_MemBarVolatile, n); // Use fat membar
 345         if (_leading_membar != nullptr) {
 346           MemBarNode::set_store_pair(_leading_membar->as_MemBar(), mb->as_MemBar());
 347         }
 348       }
 349     } else {
 350       if (is_volatile || is_acquire) {
 351         assert(kit != nullptr, "unsupported at optimization time");
 352         Node* n = _access.raw_access();
 353         assert(_leading_membar == nullptr || support_IRIW_for_not_multiple_copy_atomic_cpu, "no leading membar expected");
 354         Node* mb = kit->insert_mem_bar(Op_MemBarAcquire, n);
 355         mb->as_MemBar()->set_trailing_load();
 356       }
 357     }
 358   }
 359 };
 360 
 361 Node* BarrierSetC2::store_at(C2Access& access, C2AccessValue& val) const {
 362   C2AccessFence fence(access);
 363   resolve_address(access);
 364   return store_at_resolved(access, val);
 365 }
 366 
 367 Node* BarrierSetC2::load_at(C2Access& access, const Type* val_type) const {
 368   C2AccessFence fence(access);
 369   resolve_address(access);
 370   return load_at_resolved(access, val_type);
 371 }
 372 
 373 MemNode::MemOrd C2Access::mem_node_mo() const {
 374   bool is_write = (_decorators & C2_WRITE_ACCESS) != 0;
 375   bool is_read = (_decorators & C2_READ_ACCESS) != 0;
 376   if ((_decorators & MO_SEQ_CST) != 0) {
 377     if (is_write && is_read) {
 378       // For atomic operations
 379       return MemNode::seqcst;
 380     } else if (is_write) {
 381       return MemNode::release;
 382     } else {
 383       assert(is_read, "what else?");
 384       return MemNode::acquire;
 385     }
 386   } else if ((_decorators & MO_RELEASE) != 0) {
 387     return MemNode::release;
 388   } else if ((_decorators & MO_ACQUIRE) != 0) {
 389     return MemNode::acquire;
 390   } else if (is_write) {
 391     // Volatile fields need releasing stores.
 392     // Non-volatile fields also need releasing stores if they hold an
 393     // object reference, because the object reference might point to
 394     // a freshly created object.
 395     // Conservatively release stores of object references.
 396     return StoreNode::release_if_reference(_type);
 397   } else {
 398     return MemNode::unordered;
 399   }
 400 }
 401 
 402 void C2Access::fixup_decorators() {
 403   bool default_mo = (_decorators & MO_DECORATOR_MASK) == 0;
 404   bool anonymous = (_decorators & C2_UNSAFE_ACCESS) != 0;
 405 
 406   bool is_read = (_decorators & C2_READ_ACCESS) != 0;
 407   bool is_write = (_decorators & C2_WRITE_ACCESS) != 0;
 408 
 409   _decorators = AccessInternal::decorator_fixup(_decorators, _type);
 410 
 411   if (is_read && !is_write && anonymous) {
 412     // To be valid, unsafe loads may depend on other conditions than
 413     // the one that guards them: pin the Load node
 414     _decorators |= C2_CONTROL_DEPENDENT_LOAD;
 415     _decorators |= C2_UNKNOWN_CONTROL_LOAD;
 416     const TypePtr* adr_type = _addr.type();
 417     Node* adr = _addr.node();
 418     if (!needs_cpu_membar() && adr_type->isa_instptr()) {
 419       assert(adr_type->meet(TypePtr::NULL_PTR) != adr_type->remove_speculative(), "should be not null");
 420       intptr_t offset = Type::OffsetBot;
 421       AddPNode::Ideal_base_and_offset(adr, &gvn(), offset);
 422       if (offset >= 0) {
 423         int s = Klass::layout_helper_size_in_bytes(adr_type->isa_instptr()->instance_klass()->layout_helper());
 424         if (offset < s) {
 425           // Guaranteed to be a valid access, no need to pin it
 426           _decorators ^= C2_CONTROL_DEPENDENT_LOAD;
 427           _decorators ^= C2_UNKNOWN_CONTROL_LOAD;
 428         }
 429       }
 430     }
 431   }
 432 }
 433 
 434 //--------------------------- atomic operations---------------------------------
 435 
 436 void BarrierSetC2::pin_atomic_op(C2AtomicParseAccess& access) const {
 437   // SCMemProjNodes represent the memory state of a LoadStore. Their
 438   // main role is to prevent LoadStore nodes from being optimized away
 439   // when their results aren't used.
 440   assert(access.is_parse_access(), "entry not supported at optimization time");
 441   C2ParseAccess& parse_access = static_cast<C2ParseAccess&>(access);
 442   GraphKit* kit = parse_access.kit();
 443   Node* load_store = access.raw_access();
 444   assert(load_store != nullptr, "must pin atomic op");
 445   Node* proj = kit->gvn().transform(new SCMemProjNode(load_store));
 446   kit->set_memory(proj, access.alias_idx());
 447 }
 448 
 449 void C2AtomicParseAccess::set_memory() {
 450   Node *mem = _kit->memory(_alias_idx);
 451   _memory = mem;
 452 }
 453 
 454 Node* BarrierSetC2::atomic_cmpxchg_val_at_resolved(C2AtomicParseAccess& access, Node* expected_val,
 455                                                    Node* new_val, const Type* value_type) const {
 456   GraphKit* kit = access.kit();
 457   MemNode::MemOrd mo = access.mem_node_mo();
 458   Node* mem = access.memory();
 459 
 460   Node* adr = access.addr().node();
 461   const TypePtr* adr_type = access.addr().type();
 462 
 463   Node* load_store = nullptr;
 464 
 465   if (access.is_oop()) {
 466 #ifdef _LP64
 467     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 468       Node *newval_enc = kit->gvn().transform(new EncodePNode(new_val, new_val->bottom_type()->make_narrowoop()));
 469       Node *oldval_enc = kit->gvn().transform(new EncodePNode(expected_val, expected_val->bottom_type()->make_narrowoop()));
 470       load_store = new CompareAndExchangeNNode(kit->control(), mem, adr, newval_enc, oldval_enc, adr_type, value_type->make_narrowoop(), mo);
 471     } else
 472 #endif
 473     {
 474       load_store = new CompareAndExchangePNode(kit->control(), mem, adr, new_val, expected_val, adr_type, value_type->is_oopptr(), mo);
 475     }
 476   } else {
 477     switch (access.type()) {
 478       case T_BYTE: {
 479         load_store = new CompareAndExchangeBNode(kit->control(), mem, adr, new_val, expected_val, adr_type, mo);
 480         break;
 481       }
 482       case T_SHORT: {
 483         load_store = new CompareAndExchangeSNode(kit->control(), mem, adr, new_val, expected_val, adr_type, mo);
 484         break;
 485       }
 486       case T_INT: {
 487         load_store = new CompareAndExchangeINode(kit->control(), mem, adr, new_val, expected_val, adr_type, mo);
 488         break;
 489       }
 490       case T_LONG: {
 491         load_store = new CompareAndExchangeLNode(kit->control(), mem, adr, new_val, expected_val, adr_type, mo);
 492         break;
 493       }
 494       default:
 495         ShouldNotReachHere();
 496     }
 497   }
 498 
 499   load_store->as_LoadStore()->set_barrier_data(access.barrier_data());
 500   load_store = kit->gvn().transform(load_store);
 501 
 502   access.set_raw_access(load_store);
 503   pin_atomic_op(access);
 504 
 505 #ifdef _LP64
 506   if (access.is_oop() && adr->bottom_type()->is_ptr_to_narrowoop()) {
 507     return kit->gvn().transform(new DecodeNNode(load_store, load_store->get_ptr_type()));
 508   }
 509 #endif
 510 
 511   return load_store;
 512 }
 513 
 514 Node* BarrierSetC2::atomic_cmpxchg_bool_at_resolved(C2AtomicParseAccess& access, Node* expected_val,
 515                                                     Node* new_val, const Type* value_type) const {
 516   GraphKit* kit = access.kit();
 517   DecoratorSet decorators = access.decorators();
 518   MemNode::MemOrd mo = access.mem_node_mo();
 519   Node* mem = access.memory();
 520   bool is_weak_cas = (decorators & C2_WEAK_CMPXCHG) != 0;
 521   Node* load_store = nullptr;
 522   Node* adr = access.addr().node();
 523 
 524   if (access.is_oop()) {
 525 #ifdef _LP64
 526     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 527       Node *newval_enc = kit->gvn().transform(new EncodePNode(new_val, new_val->bottom_type()->make_narrowoop()));
 528       Node *oldval_enc = kit->gvn().transform(new EncodePNode(expected_val, expected_val->bottom_type()->make_narrowoop()));
 529       if (is_weak_cas) {
 530         load_store = new WeakCompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo);
 531       } else {
 532         load_store = new CompareAndSwapNNode(kit->control(), mem, adr, newval_enc, oldval_enc, mo);
 533       }
 534     } else
 535 #endif
 536     {
 537       if (is_weak_cas) {
 538         load_store = new WeakCompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo);
 539       } else {
 540         load_store = new CompareAndSwapPNode(kit->control(), mem, adr, new_val, expected_val, mo);
 541       }
 542     }
 543   } else {
 544     switch(access.type()) {
 545       case T_BYTE: {
 546         if (is_weak_cas) {
 547           load_store = new WeakCompareAndSwapBNode(kit->control(), mem, adr, new_val, expected_val, mo);
 548         } else {
 549           load_store = new CompareAndSwapBNode(kit->control(), mem, adr, new_val, expected_val, mo);
 550         }
 551         break;
 552       }
 553       case T_SHORT: {
 554         if (is_weak_cas) {
 555           load_store = new WeakCompareAndSwapSNode(kit->control(), mem, adr, new_val, expected_val, mo);
 556         } else {
 557           load_store = new CompareAndSwapSNode(kit->control(), mem, adr, new_val, expected_val, mo);
 558         }
 559         break;
 560       }
 561       case T_INT: {
 562         if (is_weak_cas) {
 563           load_store = new WeakCompareAndSwapINode(kit->control(), mem, adr, new_val, expected_val, mo);
 564         } else {
 565           load_store = new CompareAndSwapINode(kit->control(), mem, adr, new_val, expected_val, mo);
 566         }
 567         break;
 568       }
 569       case T_LONG: {
 570         if (is_weak_cas) {
 571           load_store = new WeakCompareAndSwapLNode(kit->control(), mem, adr, new_val, expected_val, mo);
 572         } else {
 573           load_store = new CompareAndSwapLNode(kit->control(), mem, adr, new_val, expected_val, mo);
 574         }
 575         break;
 576       }
 577       default:
 578         ShouldNotReachHere();
 579     }
 580   }
 581 
 582   load_store->as_LoadStore()->set_barrier_data(access.barrier_data());
 583   load_store = kit->gvn().transform(load_store);
 584 
 585   access.set_raw_access(load_store);
 586   pin_atomic_op(access);
 587 
 588   return load_store;
 589 }
 590 
 591 Node* BarrierSetC2::atomic_xchg_at_resolved(C2AtomicParseAccess& access, Node* new_val, const Type* value_type) const {
 592   GraphKit* kit = access.kit();
 593   Node* mem = access.memory();
 594   Node* adr = access.addr().node();
 595   const TypePtr* adr_type = access.addr().type();
 596   Node* load_store = nullptr;
 597 
 598   if (access.is_oop()) {
 599 #ifdef _LP64
 600     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 601       Node *newval_enc = kit->gvn().transform(new EncodePNode(new_val, new_val->bottom_type()->make_narrowoop()));
 602       load_store = kit->gvn().transform(new GetAndSetNNode(kit->control(), mem, adr, newval_enc, adr_type, value_type->make_narrowoop()));
 603     } else
 604 #endif
 605     {
 606       load_store = new GetAndSetPNode(kit->control(), mem, adr, new_val, adr_type, value_type->is_oopptr());
 607     }
 608   } else  {
 609     switch (access.type()) {
 610       case T_BYTE:
 611         load_store = new GetAndSetBNode(kit->control(), mem, adr, new_val, adr_type);
 612         break;
 613       case T_SHORT:
 614         load_store = new GetAndSetSNode(kit->control(), mem, adr, new_val, adr_type);
 615         break;
 616       case T_INT:
 617         load_store = new GetAndSetINode(kit->control(), mem, adr, new_val, adr_type);
 618         break;
 619       case T_LONG:
 620         load_store = new GetAndSetLNode(kit->control(), mem, adr, new_val, adr_type);
 621         break;
 622       default:
 623         ShouldNotReachHere();
 624     }
 625   }
 626 
 627   load_store->as_LoadStore()->set_barrier_data(access.barrier_data());
 628   load_store = kit->gvn().transform(load_store);
 629 
 630   access.set_raw_access(load_store);
 631   pin_atomic_op(access);
 632 
 633 #ifdef _LP64
 634   if (access.is_oop() && adr->bottom_type()->is_ptr_to_narrowoop()) {
 635     return kit->gvn().transform(new DecodeNNode(load_store, load_store->get_ptr_type()));
 636   }
 637 #endif
 638 
 639   return load_store;
 640 }
 641 
 642 Node* BarrierSetC2::atomic_add_at_resolved(C2AtomicParseAccess& access, Node* new_val, const Type* value_type) const {
 643   Node* load_store = nullptr;
 644   GraphKit* kit = access.kit();
 645   Node* adr = access.addr().node();
 646   const TypePtr* adr_type = access.addr().type();
 647   Node* mem = access.memory();
 648 
 649   switch(access.type()) {
 650     case T_BYTE:
 651       load_store = new GetAndAddBNode(kit->control(), mem, adr, new_val, adr_type);
 652       break;
 653     case T_SHORT:
 654       load_store = new GetAndAddSNode(kit->control(), mem, adr, new_val, adr_type);
 655       break;
 656     case T_INT:
 657       load_store = new GetAndAddINode(kit->control(), mem, adr, new_val, adr_type);
 658       break;
 659     case T_LONG:
 660       load_store = new GetAndAddLNode(kit->control(), mem, adr, new_val, adr_type);
 661       break;
 662     default:
 663       ShouldNotReachHere();
 664   }
 665 
 666   load_store->as_LoadStore()->set_barrier_data(access.barrier_data());
 667   load_store = kit->gvn().transform(load_store);
 668 
 669   access.set_raw_access(load_store);
 670   pin_atomic_op(access);
 671 
 672   return load_store;
 673 }
 674 
 675 Node* BarrierSetC2::atomic_cmpxchg_val_at(C2AtomicParseAccess& access, Node* expected_val,
 676                                           Node* new_val, const Type* value_type) const {
 677   C2AccessFence fence(access);
 678   resolve_address(access);
 679   return atomic_cmpxchg_val_at_resolved(access, expected_val, new_val, value_type);
 680 }
 681 
 682 Node* BarrierSetC2::atomic_cmpxchg_bool_at(C2AtomicParseAccess& access, Node* expected_val,
 683                                            Node* new_val, const Type* value_type) const {
 684   C2AccessFence fence(access);
 685   resolve_address(access);
 686   return atomic_cmpxchg_bool_at_resolved(access, expected_val, new_val, value_type);
 687 }
 688 
 689 Node* BarrierSetC2::atomic_xchg_at(C2AtomicParseAccess& access, Node* new_val, const Type* value_type) const {
 690   C2AccessFence fence(access);
 691   resolve_address(access);
 692   return atomic_xchg_at_resolved(access, new_val, value_type);
 693 }
 694 
 695 Node* BarrierSetC2::atomic_add_at(C2AtomicParseAccess& access, Node* new_val, const Type* value_type) const {
 696   C2AccessFence fence(access);
 697   resolve_address(access);
 698   return atomic_add_at_resolved(access, new_val, value_type);
 699 }
 700 
 701 int BarrierSetC2::arraycopy_payload_base_offset(bool is_array) {
 702   // Exclude the header but include array length to copy by 8 bytes words.
 703   // Can't use base_offset_in_bytes(bt) since basic type is unknown.
 704   int base_off = is_array ? arrayOopDesc::length_offset_in_bytes() :
 705                             instanceOopDesc::base_offset_in_bytes();
 706   // base_off:
 707   // 4  - compact headers
 708   // 8  - 32-bit VM
 709   // 12 - 64-bit VM, compressed klass
 710   // 16 - 64-bit VM, normal klass
 711   if (base_off % BytesPerLong != 0) {
 712     if (is_array) {
 713       // Exclude length to copy by 8 bytes words.
 714       base_off += sizeof(int);
 715     } else {
 716       if (!UseCompactObjectHeaders) {
 717         // Include klass to copy by 8 bytes words.
 718         base_off = instanceOopDesc::klass_offset_in_bytes();
 719       }
 720     }
 721     assert(base_off % BytesPerLong == 0 || UseCompactObjectHeaders, "expect 8 bytes alignment");
 722   }
 723   return base_off;
 724 }
 725 
 726 void BarrierSetC2::clone(GraphKit* kit, Node* src_base, Node* dst_base, Node* size, bool is_array) const {
 727   int base_off = arraycopy_payload_base_offset(is_array);
 728 
 729   Node* payload_size = size;
 730   Node* offset = kit->MakeConX(base_off);
 731   payload_size = kit->gvn().transform(new SubXNode(payload_size, offset));
 732   if (is_array) {
 733     // Ensure the array payload size is rounded up to the next BytesPerLong
 734     // multiple when converting to double-words. This is necessary because array
 735     // size does not include object alignment padding, so it might not be a
 736     // multiple of BytesPerLong for sub-long element types.
 737     payload_size = kit->gvn().transform(new AddXNode(payload_size, kit->MakeConX(BytesPerLong - 1)));
 738   }
 739   payload_size = kit->gvn().transform(new URShiftXNode(payload_size, kit->intcon(LogBytesPerLong)));
 740   ArrayCopyNode* ac = ArrayCopyNode::make(kit, false, src_base, offset, dst_base, offset, payload_size, true, false);
 741   if (is_array) {
 742     ac->set_clone_array();
 743   } else {
 744     ac->set_clone_inst();
 745   }
 746   Node* n = kit->gvn().transform(ac);
 747   if (n == ac) {
 748     const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
 749     ac->set_adr_type(TypeRawPtr::BOTTOM);
 750     kit->set_predefined_output_for_runtime_call(ac, ac->in(TypeFunc::Memory), raw_adr_type);
 751   } else {
 752     kit->set_all_memory(n);
 753   }
 754 }
 755 
 756 Node* BarrierSetC2::obj_allocate(PhaseMacroExpand* macro, Node* mem, Node* toobig_false, Node* size_in_bytes,
 757                                  Node*& i_o, Node*& needgc_ctrl,
 758                                  Node*& fast_oop_ctrl, Node*& fast_oop_rawmem,
 759                                  intx prefetch_lines) const {
 760   assert(UseTLAB, "Only for TLAB enabled allocations");
 761 
 762   Node* thread = macro->transform_later(new ThreadLocalNode());
 763   Node* tlab_top_adr = macro->off_heap_plus_addr(thread, in_bytes(JavaThread::tlab_top_offset()));
 764   Node* tlab_end_adr = macro->off_heap_plus_addr(thread, in_bytes(JavaThread::tlab_end_offset()));
 765 
 766   // Load TLAB end.
 767   //
 768   // Note: We set the control input on "tlab_end" and "old_tlab_top" to work around
 769   //       a bug where these values were being moved across
 770   //       a safepoint.  These are not oops, so they cannot be include in the oop
 771   //       map, but they can be changed by a GC.   The proper way to fix this would
 772   //       be to set the raw memory state when generating a  SafepointNode.  However
 773   //       this will require extensive changes to the loop optimization in order to
 774   //       prevent a degradation of the optimization.
 775   //       See comment in memnode.hpp, around line 227 in class LoadPNode.
 776   Node* tlab_end = macro->make_load_raw(toobig_false, mem, tlab_end_adr, 0, TypeRawPtr::BOTTOM, T_ADDRESS);
 777 
 778   // Load the TLAB top.
 779   Node* old_tlab_top = new LoadPNode(toobig_false, mem, tlab_top_adr, TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM, MemNode::unordered);
 780   macro->transform_later(old_tlab_top);
 781 
 782   // Add to heap top to get a new TLAB top
 783   Node* new_tlab_top = AddPNode::make_off_heap(old_tlab_top, size_in_bytes);
 784   macro->transform_later(new_tlab_top);
 785 
 786   // Check against TLAB end
 787   Node* tlab_full = new CmpPNode(new_tlab_top, tlab_end);
 788   macro->transform_later(tlab_full);
 789 
 790   Node* needgc_bol = new BoolNode(tlab_full, BoolTest::ge);
 791   macro->transform_later(needgc_bol);
 792   IfNode* needgc_iff = new IfNode(toobig_false, needgc_bol, PROB_UNLIKELY_MAG(4), COUNT_UNKNOWN);
 793   macro->transform_later(needgc_iff);
 794 
 795   // Plug the failing-heap-space-need-gc test into the slow-path region
 796   Node* needgc_true = new IfTrueNode(needgc_iff);
 797   macro->transform_later(needgc_true);
 798   needgc_ctrl = needgc_true;
 799 
 800   // No need for a GC.
 801   Node* needgc_false = new IfFalseNode(needgc_iff);
 802   macro->transform_later(needgc_false);
 803 
 804   // Fast path:
 805   i_o = macro->prefetch_allocation(i_o, needgc_false, mem,
 806                                    old_tlab_top, new_tlab_top, prefetch_lines);
 807 
 808   // Store the modified TLAB top back down.
 809   Node* store_tlab_top = new StorePNode(needgc_false, mem, tlab_top_adr,
 810                    TypeRawPtr::BOTTOM, new_tlab_top, MemNode::unordered);
 811   macro->transform_later(store_tlab_top);
 812 
 813   fast_oop_ctrl = needgc_false;
 814   fast_oop_rawmem = store_tlab_top;
 815   return old_tlab_top;
 816 }
 817 
 818 const TypeFunc* BarrierSetC2::_clone_type_Type = nullptr;
 819 
 820 void BarrierSetC2::make_clone_type() {
 821   assert(BarrierSetC2::_clone_type_Type == nullptr, "should be");
 822   // Create input type (domain)
 823   int argcnt = NOT_LP64(3) LP64_ONLY(4);
 824   const Type** const domain_fields = TypeTuple::fields(argcnt);
 825   int argp = TypeFunc::Parms;
 826   domain_fields[argp++] = TypeInstPtr::NOTNULL;  // src
 827   domain_fields[argp++] = TypeInstPtr::NOTNULL;  // dst
 828   domain_fields[argp++] = TypeX_X;               // size lower
 829   LP64_ONLY(domain_fields[argp++] = Type::HALF); // size upper
 830   assert(argp == TypeFunc::Parms+argcnt, "correct decoding");
 831   const TypeTuple* const domain = TypeTuple::make(TypeFunc::Parms + argcnt, domain_fields);
 832 
 833   // Create result type (range)
 834   const Type** const range_fields = TypeTuple::fields(0);
 835   const TypeTuple* const range = TypeTuple::make(TypeFunc::Parms + 0, range_fields);
 836 
 837   BarrierSetC2::_clone_type_Type = TypeFunc::make(domain, range);
 838 }
 839 
 840 inline const TypeFunc* BarrierSetC2::clone_type() {
 841   assert(BarrierSetC2::_clone_type_Type != nullptr, "should be initialized");
 842   return BarrierSetC2::_clone_type_Type;
 843 }
 844 
 845 #define XTOP LP64_ONLY(COMMA phase->top())
 846 
 847 void BarrierSetC2::clone_in_runtime(PhaseMacroExpand* phase, ArrayCopyNode* ac,
 848                                     address clone_addr, const char* clone_name) const {
 849   Node* const ctrl = ac->in(TypeFunc::Control);
 850   Node* const mem  = ac->in(TypeFunc::Memory);
 851   Node* const src  = ac->in(ArrayCopyNode::Src);
 852   Node* const dst  = ac->in(ArrayCopyNode::Dest);
 853   Node* const size = ac->in(ArrayCopyNode::Length);
 854 
 855   assert(size->bottom_type()->base() == Type_X,
 856          "Should be of object size type (int for 32 bits, long for 64 bits)");
 857 
 858   // The native clone we are calling here expects the object size in words.
 859   // Add header/offset size to payload size to get object size.
 860 
 861   // We need the full object size - payload (already aligned) plus base offset (which is not always aligned, so round *up*),
 862   // because clone_in_runtime copies the whole object from 0 to end.
 863   Node* const base_offset = phase->MakeConX((arraycopy_payload_base_offset(ac->is_clone_array()) + (BytesPerLong - 1)) >> LogBytesPerLong);
 864   Node* const full_size = phase->transform_later(new AddXNode(size, base_offset));
 865 
 866   // HeapAccess<>::clone expects size in heap words.
 867   // For 64-bits platforms, this is a no-operation.
 868   // For 32-bits platforms, we need to multiply full_size by HeapWordsPerLong (2).
 869   Node* const full_size_in_heap_words = phase->transform_later(new LShiftXNode(full_size, phase->intcon(LogHeapWordsPerLong)));
 870 
 871   Node* const call = phase->make_leaf_call(ctrl,
 872                                            mem,
 873                                            clone_type(),
 874                                            clone_addr,
 875                                            clone_name,
 876                                            TypeRawPtr::BOTTOM,
 877                                            src, dst, full_size_in_heap_words XTOP);
 878   phase->transform_later(call);
 879   phase->igvn().replace_node(ac, call);
 880 }
 881 
 882 void BarrierSetC2::clone_at_expansion(PhaseMacroExpand* phase, ArrayCopyNode* ac) const {
 883   Node* ctrl = ac->in(TypeFunc::Control);
 884   Node* mem = ac->in(TypeFunc::Memory);
 885   Node* src = ac->in(ArrayCopyNode::Src);
 886   Node* src_offset = ac->in(ArrayCopyNode::SrcPos);
 887   Node* dest = ac->in(ArrayCopyNode::Dest);
 888   Node* dest_offset = ac->in(ArrayCopyNode::DestPos);
 889   Node* length = ac->in(ArrayCopyNode::Length);
 890 
 891   Node* payload_src = phase->basic_plus_adr(src, src_offset);
 892   Node* payload_dst = phase->basic_plus_adr(dest, dest_offset);
 893 
 894   if (should_copy_int_prefix(phase, ac)) {
 895     mem = arraycopy_copy_int_prefix(phase, ctrl, mem, payload_src, payload_dst);
 896 
 897     // We've copied the prefix, bump the pointers.
 898     payload_src = phase->basic_plus_adr(src, payload_src, BytesPerInt);
 899     payload_dst = phase->basic_plus_adr(dest, payload_dst, BytesPerInt);
 900   }
 901 
 902   // Bulk copy.
 903   const char* copyfunc_name = "arraycopy";
 904   address     copyfunc_addr = phase->basictype2arraycopy(T_LONG, nullptr, nullptr, true, copyfunc_name, true);
 905 
 906   const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
 907   const TypeFunc* call_type = OptoRuntime::fast_arraycopy_Type();
 908 
 909   Node* call = phase->make_leaf_call(ctrl, mem, call_type, copyfunc_addr, copyfunc_name, raw_adr_type, payload_src, payload_dst, length XTOP);
 910   phase->transform_later(call);
 911 
 912   phase->igvn().replace_node(ac, call);
 913 }
 914 
 915 bool BarrierSetC2::should_copy_int_prefix(PhaseMacroExpand* phase, ArrayCopyNode* ac) const {
 916   // We do our bulk copy in longs. If base offset is not aligned, then we must copy the prefix separately.
 917   // With CompactObjectHeaders, the base offset for an instance is 4 bytes.
 918   // We cannot simply expand the copy to the previous long-alignment, as that will copy the object header,
 919   // which is stateful with COH - it contains hash and lock bits that are specific to the instance.
 920 
 921   // Skip this when src has an array type. With StressReflectiveCode, the
 922   // instance path of the clone can be live in the IR even when the type system
 923   // knows src is an array. The pre-copy is unnecessary on such paths (they
 924   // are unreachable at runtime), and creating a LoadNode at the array length
 925   // offset would assert (LoadRangeNode required).
 926   Node* src = ac->in(ArrayCopyNode::Src);
 927   if (phase->igvn().type(src)->isa_aryptr()) {
 928     return false;
 929   }
 930 
 931   int base_off = arraycopy_payload_base_offset(ac->is_clone_array());
 932   if (is_aligned(base_off, BytesPerLong)) {
 933     // We're aligned, no need to copy anything separately.
 934     return false;
 935   }
 936 
 937   assert(UseCompactObjectHeaders, "non-aligned base offset only possible with compact object headers");
 938   assert(is_aligned(base_off, BytesPerInt), "must be 4-bytes aligned");
 939   return true;
 940 }
 941 
 942 MergeMemNode* BarrierSetC2::arraycopy_copy_int_prefix(PhaseMacroExpand* phase, Node* ctrl, Node* mem, Node* src, Node* dst) const {
 943   // Manual load/store of one int.
 944   MergeMemNode* mm = phase->transform_later(MergeMemNode::make(mem))->as_MergeMem();
 945   const TypePtr* s_adr_type = phase->igvn().type(src)->is_ptr();
 946   const TypePtr* d_adr_type = phase->igvn().type(dst)->is_ptr();
 947   uint s_alias_idx = phase->C->get_alias_index(s_adr_type);
 948   uint d_alias_idx = phase->C->get_alias_index(d_adr_type);
 949   // This copies the first 4 bytes after the compact header (hash field or first instance field) as a raw int.
 950   // The actual field at this offset may be a narrowOop, so the load/store must be marked as mismatched to
 951   // avoid StoreN-vs-StoreI assertion failures during IGVN.
 952   Node* load_prefix = phase->transform_later(
 953       LoadNode::make(phase->igvn(), ctrl, mm->memory_at(s_alias_idx), src, s_adr_type,
 954                       TypeInt::INT, T_INT, MemNode::unordered, LoadNode::DependsOnlyOnTest,
 955                       false /*require_atomic_access*/, false /*unaligned*/, true /*mismatched*/));
 956   Node* store_prefix = phase->transform_later(
 957       StoreNode::make(phase->igvn(), ctrl, mm->memory_at(d_alias_idx), dst, d_adr_type,
 958                       load_prefix, T_INT, MemNode::unordered));
 959   store_prefix->as_Store()->set_mismatched_access();
 960   mm->set_memory_at(d_alias_idx, store_prefix);
 961   return mm;
 962 }
 963 
 964 #undef XTOP
 965 
 966 static bool block_has_safepoint(const Block* block, uint from, uint to) {
 967   for (uint i = from; i < to; i++) {
 968     if (block->get_node(i)->is_MachSafePoint()) {
 969       // Safepoint found
 970       return true;
 971     }
 972   }
 973 
 974   // Safepoint not found
 975   return false;
 976 }
 977 
 978 static bool block_has_safepoint(const Block* block) {
 979   return block_has_safepoint(block, 0, block->number_of_nodes());
 980 }
 981 
 982 static uint block_index(const Block* block, const Node* node) {
 983   for (uint j = 0; j < block->number_of_nodes(); ++j) {
 984     if (block->get_node(j) == node) {
 985       return j;
 986     }
 987   }
 988   ShouldNotReachHere();
 989   return 0;
 990 }
 991 
 992 // Look through various node aliases
 993 static const Node* look_through_node(const Node* node) {
 994   while (node != nullptr) {
 995     const Node* new_node = node;
 996     if (node->is_Mach()) {
 997       const MachNode* const node_mach = node->as_Mach();
 998       if (node_mach->ideal_Opcode() == Op_CheckCastPP) {
 999         new_node = node->in(1);
1000       }
1001       if (node_mach->is_SpillCopy()) {
1002         new_node = node->in(1);
1003       }
1004     }
1005     if (new_node == node || new_node == nullptr) {
1006       break;
1007     } else {
1008       node = new_node;
1009     }
1010   }
1011 
1012   return node;
1013 }
1014 
1015 // Whether the given offset is undefined.
1016 static bool is_undefined(intptr_t offset) {
1017   return offset == Type::OffsetTop;
1018 }
1019 
1020 // Whether the given offset is unknown.
1021 static bool is_unknown(intptr_t offset) {
1022   return offset == Type::OffsetBot;
1023 }
1024 
1025 // Whether the given offset is concrete (defined and compile-time known).
1026 static bool is_concrete(intptr_t offset) {
1027   return !is_undefined(offset) && !is_unknown(offset);
1028 }
1029 
1030 // Compute base + offset components of the memory address accessed by mach.
1031 // Return a node representing the base address, or null if the base cannot be
1032 // found or the offset is undefined or a concrete negative value. If a non-null
1033 // base is returned, the offset is a concrete, nonnegative value or unknown.
1034 static const Node* get_base_and_offset(const MachNode* mach, intptr_t& offset) {
1035   const TypePtr* adr_type = nullptr;
1036   offset = 0;
1037   const Node* base = mach->get_base_and_disp(offset, adr_type);
1038 
1039   if (base == nullptr || base == NodeSentinel) {
1040     return nullptr;
1041   }
1042 
1043   if (offset == 0 && base->is_Mach() && base->as_Mach()->ideal_Opcode() == Op_AddP) {
1044     // The memory address is computed by 'base' and fed to 'mach' via an
1045     // indirect memory operand (indicated by offset == 0). The ultimate base and
1046     // offset can be fetched directly from the inputs and Ideal type of 'base'.
1047     const TypeOopPtr* oopptr = base->bottom_type()->isa_oopptr();
1048     if (oopptr == nullptr) return nullptr;
1049     offset = oopptr->offset();
1050     // Even if 'base' is not an Ideal AddP node anymore, Matcher::ReduceInst()
1051     // guarantees that the base address is still available at the same slot.
1052     base = base->in(AddPNode::Base);
1053     assert(base != nullptr, "");
1054   }
1055 
1056   if (is_undefined(offset) || (is_concrete(offset) && offset < 0)) {
1057     return nullptr;
1058   }
1059 
1060   return look_through_node(base);
1061 }
1062 
1063 // Whether a phi node corresponds to an array allocation.
1064 // This test is incomplete: in some edge cases, it might return false even
1065 // though the node does correspond to an array allocation.
1066 static bool is_array_allocation(const Node* phi) {
1067   precond(phi->is_Phi());
1068   // Check whether phi has a successor cast (CheckCastPP) to Java array pointer,
1069   // possibly below spill copies and other cast nodes. Limit the exploration to
1070   // a single path from the phi node consisting of these node types.
1071   const Node* current = phi;
1072   while (true) {
1073     const Node* next = nullptr;
1074     for (DUIterator_Fast imax, i = current->fast_outs(imax); i < imax; i++) {
1075       if (!current->fast_out(i)->isa_Mach()) {
1076         continue;
1077       }
1078       const MachNode* succ = current->fast_out(i)->as_Mach();
1079       if (succ->ideal_Opcode() == Op_CheckCastPP) {
1080         if (succ->get_ptr_type()->isa_aryptr()) {
1081           // Cast to Java array pointer: phi corresponds to an array allocation.
1082           return true;
1083         }
1084         // Other cast: record as candidate for further exploration.
1085         next = succ;
1086       } else if (succ->is_SpillCopy() && next == nullptr) {
1087         // Spill copy, and no better candidate found: record as candidate.
1088         next = succ;
1089       }
1090     }
1091     if (next == nullptr) {
1092       // No evidence found that phi corresponds to an array allocation, and no
1093       // candidates available to continue exploring.
1094       return false;
1095     }
1096     // Continue exploring from the best candidate found.
1097     current = next;
1098   }
1099   ShouldNotReachHere();
1100 }
1101 
1102 bool BarrierSetC2::is_allocation(const Node* node) {
1103   assert(node->is_Phi(), "expected phi node");
1104   if (node->req() != 3) {
1105     return false;
1106   }
1107   const Node* const fast_node = node->in(2);
1108   if (!fast_node->is_Mach()) {
1109     return false;
1110   }
1111   const MachNode* const fast_mach = fast_node->as_Mach();
1112   if (fast_mach->ideal_Opcode() != Op_LoadP) {
1113     return false;
1114   }
1115   intptr_t offset;
1116   const Node* const base = get_base_and_offset(fast_mach, offset);
1117   if (base == nullptr || !base->is_Mach() || !is_concrete(offset)) {
1118     return false;
1119   }
1120   const MachNode* const base_mach = base->as_Mach();
1121   if (base_mach->ideal_Opcode() != Op_ThreadLocal) {
1122     return false;
1123   }
1124   return offset == in_bytes(Thread::tlab_top_offset());
1125 }
1126 
1127 void BarrierSetC2::elide_dominated_barriers(Node_List& accesses, Node_List& access_dominators) const {
1128   Compile* const C = Compile::current();
1129   PhaseCFG* const cfg = C->cfg();
1130 
1131   for (uint i = 0; i < accesses.size(); i++) {
1132     MachNode* const access = accesses.at(i)->as_Mach();
1133     intptr_t access_offset;
1134     const Node* const access_obj = get_base_and_offset(access, access_offset);
1135     Block* const access_block = cfg->get_block_for_node(access);
1136     const uint access_index = block_index(access_block, access);
1137 
1138     if (access_obj == nullptr) {
1139       // No information available
1140       continue;
1141     }
1142 
1143     for (uint j = 0; j < access_dominators.size(); j++) {
1144      const  Node* const mem = access_dominators.at(j);
1145       if (mem->is_Phi()) {
1146         assert(is_allocation(mem), "expected allocation phi node");
1147         if (mem != access_obj) {
1148           continue;
1149         }
1150         if (is_unknown(access_offset) && !is_array_allocation(mem)) {
1151           // The accessed address has an unknown offset, but the allocated
1152           // object cannot be determined to be an array. Avoid eliding in this
1153           // case, to be on the safe side.
1154           continue;
1155         }
1156         assert((is_concrete(access_offset) && access_offset >= 0) || (is_unknown(access_offset) && is_array_allocation(mem)),
1157                "candidate allocation-dominated access offsets must be either concrete and nonnegative, or unknown (for array allocations only)");
1158       } else {
1159         // Access node
1160         const MachNode* const mem_mach = mem->as_Mach();
1161         intptr_t mem_offset;
1162         const Node* const mem_obj = get_base_and_offset(mem_mach, mem_offset);
1163 
1164         if (mem_obj == nullptr ||
1165             !is_concrete(access_offset) ||
1166             !is_concrete(mem_offset)) {
1167           // No information available
1168           continue;
1169         }
1170 
1171         if (mem_obj != access_obj || mem_offset != access_offset) {
1172           // Not the same addresses, not a candidate
1173           continue;
1174         }
1175         assert(is_concrete(access_offset) && access_offset >= 0,
1176                "candidate non-allocation-dominated access offsets must be concrete and nonnegative");
1177       }
1178 
1179       Block* mem_block = cfg->get_block_for_node(mem);
1180       const uint mem_index = block_index(mem_block, mem);
1181 
1182       if (access_block == mem_block) {
1183         // Earlier accesses in the same block
1184         if (mem_index < access_index && !block_has_safepoint(mem_block, mem_index + 1, access_index)) {
1185           elide_dominated_barrier(access, mem->is_Mach() ? mem->as_Mach() : nullptr);
1186         }
1187       } else if (mem_block->dominates(access_block)) {
1188         // Dominating block? Look around for safepoints
1189         ResourceMark rm;
1190         Block_List stack;
1191         VectorSet visited;
1192         stack.push(access_block);
1193         bool safepoint_found = block_has_safepoint(access_block);
1194         while (!safepoint_found && stack.size() > 0) {
1195           const Block* const block = stack.pop();
1196           if (visited.test_set(block->_pre_order)) {
1197             continue;
1198           }
1199           if (block_has_safepoint(block)) {
1200             safepoint_found = true;
1201             break;
1202           }
1203           if (block == mem_block) {
1204             continue;
1205           }
1206 
1207           // Push predecessor blocks
1208           for (uint p = 1; p < block->num_preds(); ++p) {
1209             Block* const pred = cfg->get_block_for_node(block->pred(p));
1210             stack.push(pred);
1211           }
1212         }
1213 
1214         if (!safepoint_found) {
1215           elide_dominated_barrier(access, mem->is_Mach() ? mem->as_Mach() : nullptr);
1216         }
1217       }
1218     }
1219   }
1220 }
1221 
1222 void BarrierSetC2::compute_liveness_at_stubs() const {
1223   ResourceMark rm;
1224   Compile* const C = Compile::current();
1225   Arena* const A = Thread::current()->resource_area();
1226   PhaseCFG* const cfg = C->cfg();
1227   PhaseRegAlloc* const regalloc = C->regalloc();
1228   RegMask* const live = NEW_ARENA_ARRAY(A, RegMask, cfg->number_of_blocks() * sizeof(RegMask));
1229   BarrierSetAssembler* const bs = BarrierSet::barrier_set()->barrier_set_assembler();
1230   BarrierSetC2State* bs_state = barrier_set_state();
1231   Block_List worklist;
1232 
1233   for (uint i = 0; i < cfg->number_of_blocks(); ++i) {
1234     new ((void*)(live + i)) RegMask();
1235     worklist.push(cfg->get_block(i));
1236   }
1237 
1238   while (worklist.size() > 0) {
1239     const Block* const block = worklist.pop();
1240     RegMask& old_live = live[block->_pre_order];
1241     RegMask new_live;
1242 
1243     // Initialize to union of successors
1244     for (uint i = 0; i < block->_num_succs; i++) {
1245       const uint succ_id = block->_succs[i]->_pre_order;
1246       new_live.or_with(live[succ_id]);
1247     }
1248 
1249     // Walk block backwards, computing liveness
1250     for (int i = block->number_of_nodes() - 1; i >= 0; --i) {
1251       const Node* const node = block->get_node(i);
1252 
1253       // If this node tracks out-liveness, update it
1254       if (!bs_state->needs_livein_data()) {
1255         RegMask* const regs = bs_state->live(node);
1256         if (regs != nullptr) {
1257           regs->or_with(new_live);
1258         }
1259       }
1260 
1261       // Remove def bits
1262       const OptoReg::Name first = bs->refine_register(node, regalloc->get_reg_first(node));
1263       const OptoReg::Name second = bs->refine_register(node, regalloc->get_reg_second(node));
1264       if (first != OptoReg::Bad) {
1265         new_live.remove(first);
1266       }
1267       if (second != OptoReg::Bad) {
1268         new_live.remove(second);
1269       }
1270 
1271       // Add use bits
1272       for (uint j = 1; j < node->req(); ++j) {
1273         const Node* const use = node->in(j);
1274         const OptoReg::Name first = bs->refine_register(use, regalloc->get_reg_first(use));
1275         const OptoReg::Name second = bs->refine_register(use, regalloc->get_reg_second(use));
1276         if (first != OptoReg::Bad) {
1277           new_live.insert(first);
1278         }
1279         if (second != OptoReg::Bad) {
1280           new_live.insert(second);
1281         }
1282       }
1283 
1284       // If this node tracks in-liveness, update it
1285       if (bs_state->needs_livein_data()) {
1286         RegMask* const regs = bs_state->live(node);
1287         if (regs != nullptr) {
1288           regs->or_with(new_live);
1289         }
1290       }
1291     }
1292 
1293     // Now at block top, see if we have any changes
1294     new_live.subtract(old_live);
1295     if (!new_live.is_empty()) {
1296       // Liveness has refined, update and propagate to prior blocks
1297       old_live.or_with(new_live);
1298       for (uint i = 1; i < block->num_preds(); ++i) {
1299         Block* const pred = cfg->get_block_for_node(block->pred(i));
1300         worklist.push(pred);
1301       }
1302     }
1303   }
1304 }