1 /*
   2  * Copyright (c) 2012, 2025, 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 "ci/ciFlatArrayKlass.hpp"
  26 #include "gc/shared/barrierSet.hpp"
  27 #include "gc/shared/tlab_globals.hpp"
  28 #include "opto/arraycopynode.hpp"
  29 #include "oops/objArrayKlass.hpp"
  30 #include "opto/convertnode.hpp"
  31 #include "opto/vectornode.hpp"
  32 #include "opto/graphKit.hpp"
  33 #include "opto/macro.hpp"
  34 #include "opto/runtime.hpp"
  35 #include "opto/castnode.hpp"
  36 #include "runtime/stubRoutines.hpp"
  37 #include "utilities/align.hpp"
  38 #include "utilities/powerOfTwo.hpp"
  39 
  40 void PhaseMacroExpand::insert_mem_bar(Node** ctrl, Node** mem, int opcode, Node* precedent) {
  41   MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);
  42   mb->init_req(TypeFunc::Control, *ctrl);
  43   mb->init_req(TypeFunc::Memory, *mem);
  44   transform_later(mb);
  45   *ctrl = new ProjNode(mb,TypeFunc::Control);
  46   transform_later(*ctrl);
  47   Node* mem_proj = new ProjNode(mb,TypeFunc::Memory);
  48   transform_later(mem_proj);
  49   *mem = mem_proj;
  50 }
  51 
  52 Node* PhaseMacroExpand::array_element_address(Node* ary, Node* idx, BasicType elembt) {
  53   uint shift  = exact_log2(type2aelembytes(elembt));
  54   uint header = arrayOopDesc::base_offset_in_bytes(elembt);
  55   Node* base =  basic_plus_adr(ary, header);
  56 #ifdef _LP64
  57   // see comment in GraphKit::array_element_address
  58   int index_max = max_jint - 1;  // array size is max_jint, index is one less
  59   const TypeLong* lidxtype = TypeLong::make(CONST64(0), index_max, Type::WidenMax);
  60   idx = transform_later( new ConvI2LNode(idx, lidxtype) );
  61 #endif
  62   Node* scale = new LShiftXNode(idx, intcon(shift));
  63   transform_later(scale);
  64   return basic_plus_adr(ary, base, scale);
  65 }
  66 
  67 Node* PhaseMacroExpand::ConvI2L(Node* offset) {
  68   return transform_later(new ConvI2LNode(offset));
  69 }
  70 
  71 Node* PhaseMacroExpand::make_leaf_call(Node* ctrl, Node* mem,
  72                                        const TypeFunc* call_type, address call_addr,
  73                                        const char* call_name,
  74                                        const TypePtr* adr_type,
  75                                        Node* parm0, Node* parm1,
  76                                        Node* parm2, Node* parm3,
  77                                        Node* parm4, Node* parm5,
  78                                        Node* parm6, Node* parm7) {
  79   Node* call = new CallLeafNoFPNode(call_type, call_addr, call_name, adr_type);
  80   call->init_req(TypeFunc::Control, ctrl);
  81   call->init_req(TypeFunc::I_O    , top());
  82   call->init_req(TypeFunc::Memory , mem);
  83   call->init_req(TypeFunc::ReturnAdr, top());
  84   call->init_req(TypeFunc::FramePtr, top());
  85 
  86   // Hook each parm in order.  Stop looking at the first null.
  87   if (parm0 != nullptr) { call->init_req(TypeFunc::Parms+0, parm0);
  88   if (parm1 != nullptr) { call->init_req(TypeFunc::Parms+1, parm1);
  89   if (parm2 != nullptr) { call->init_req(TypeFunc::Parms+2, parm2);
  90   if (parm3 != nullptr) { call->init_req(TypeFunc::Parms+3, parm3);
  91   if (parm4 != nullptr) { call->init_req(TypeFunc::Parms+4, parm4);
  92   if (parm5 != nullptr) { call->init_req(TypeFunc::Parms+5, parm5);
  93   if (parm6 != nullptr) { call->init_req(TypeFunc::Parms+6, parm6);
  94   if (parm7 != nullptr) { call->init_req(TypeFunc::Parms+7, parm7);
  95     /* close each nested if ===> */  } } } } } } } }
  96   assert(call->in(call->req()-1) != nullptr, "must initialize all parms");
  97 
  98   return call;
  99 }
 100 
 101 
 102 //------------------------------generate_guard---------------------------
 103 // Helper function for generating guarded fast-slow graph structures.
 104 // The given 'test', if true, guards a slow path.  If the test fails
 105 // then a fast path can be taken.  (We generally hope it fails.)
 106 // In all cases, GraphKit::control() is updated to the fast path.
 107 // The returned value represents the control for the slow path.
 108 // The return value is never 'top'; it is either a valid control
 109 // or null if it is obvious that the slow path can never be taken.
 110 // Also, if region and the slow control are not null, the slow edge
 111 // is appended to the region.
 112 Node* PhaseMacroExpand::generate_guard(Node** ctrl, Node* test, RegionNode* region, float true_prob) {
 113   if ((*ctrl)->is_top()) {
 114     // Already short circuited.
 115     return nullptr;
 116   }
 117   // Build an if node and its projections.
 118   // If test is true we take the slow path, which we assume is uncommon.
 119   if (_igvn.type(test) == TypeInt::ZERO) {
 120     // The slow branch is never taken.  No need to build this guard.
 121     return nullptr;
 122   }
 123 
 124   IfNode* iff = new IfNode(*ctrl, test, true_prob, COUNT_UNKNOWN);
 125   transform_later(iff);
 126 
 127   Node* if_slow = new IfTrueNode(iff);
 128   transform_later(if_slow);
 129 
 130   if (region != nullptr) {
 131     region->add_req(if_slow);
 132   }
 133 
 134   Node* if_fast = new IfFalseNode(iff);
 135   transform_later(if_fast);
 136 
 137   *ctrl = if_fast;
 138 
 139   return if_slow;
 140 }
 141 
 142 Node* PhaseMacroExpand::generate_slow_guard(Node** ctrl, Node* test, RegionNode* region) {
 143   return generate_guard(ctrl, test, region, PROB_UNLIKELY_MAG(3));
 144 }
 145 
 146 inline Node* PhaseMacroExpand::generate_fair_guard(Node** ctrl, Node* test, RegionNode* region) {
 147   return generate_guard(ctrl, test, region, PROB_FAIR);
 148 }
 149 
 150 void PhaseMacroExpand::generate_negative_guard(Node** ctrl, Node* index, RegionNode* region) {
 151   if ((*ctrl)->is_top())
 152     return;                // already stopped
 153   if (_igvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 154     return;                // index is already adequately typed
 155   Node* cmp_lt = new CmpINode(index, intcon(0));
 156   transform_later(cmp_lt);
 157   Node* bol_lt = new BoolNode(cmp_lt, BoolTest::lt);
 158   transform_later(bol_lt);
 159   generate_guard(ctrl, bol_lt, region, PROB_MIN);
 160 }
 161 
 162 void PhaseMacroExpand::generate_limit_guard(Node** ctrl, Node* offset, Node* subseq_length, Node* array_length, RegionNode* region) {
 163   if ((*ctrl)->is_top())
 164     return;                // already stopped
 165   bool zero_offset = _igvn.type(offset) == TypeInt::ZERO;
 166   if (zero_offset && subseq_length->eqv_uncast(array_length))
 167     return;                // common case of whole-array copy
 168   Node* last = subseq_length;
 169   if (!zero_offset) {            // last += offset
 170     last = new AddINode(last, offset);
 171     transform_later(last);
 172   }
 173   Node* cmp_lt = new CmpUNode(array_length, last);
 174   transform_later(cmp_lt);
 175   Node* bol_lt = new BoolNode(cmp_lt, BoolTest::lt);
 176   transform_later(bol_lt);
 177   generate_guard(ctrl, bol_lt, region, PROB_MIN);
 178 }
 179 
 180 //
 181 // Partial in-lining handling for smaller conjoint/disjoint array copies having
 182 // length(in bytes) less than ArrayOperationPartialInlineSize.
 183 //  if (length <= ArrayOperationPartialInlineSize) {
 184 //    partial_inlining_block:
 185 //      mask = Mask_Gen
 186 //      vload = LoadVectorMasked src , mask
 187 //      StoreVectorMasked dst, mask, vload
 188 //  } else {
 189 //    stub_block:
 190 //      callstub array_copy
 191 //  }
 192 //  exit_block:
 193 //    Phi = label partial_inlining_block:mem , label stub_block:mem (filled by caller)
 194 //    mem = MergeMem (Phi)
 195 //    control = stub_block
 196 //
 197 //  Exit_block and associated phi(memory) are partially initialized for partial_in-lining_block
 198 //  edges. Remaining edges for exit_block coming from stub_block are connected by the caller
 199 //  post stub nodes creation.
 200 //
 201 
 202 void PhaseMacroExpand::generate_partial_inlining_block(Node** ctrl, MergeMemNode** mem, const TypePtr* adr_type,
 203                                                        RegionNode** exit_block, Node** result_memory, Node* length,
 204                                                        Node* src_start, Node* dst_start, BasicType type) {
 205   const TypePtr *src_adr_type = _igvn.type(src_start)->isa_ptr();
 206   Node* inline_block = nullptr;
 207   Node* stub_block = nullptr;
 208 
 209   int const_len = -1;
 210   const TypeInt* lty = nullptr;
 211   uint shift  = exact_log2(type2aelembytes(type));
 212   if (length->Opcode() == Op_ConvI2L) {
 213     lty = _igvn.type(length->in(1))->isa_int();
 214   } else  {
 215     lty = _igvn.type(length)->isa_int();
 216   }
 217   if (lty && lty->is_con()) {
 218     const_len = lty->get_con() << shift;
 219   }
 220 
 221   // Return if copy length is greater than partial inline size limit or
 222   // target does not supports masked load/stores.
 223   int lane_count = ArrayCopyNode::get_partial_inline_vector_lane_count(type, const_len);
 224   if ( const_len > ArrayOperationPartialInlineSize ||
 225       !Matcher::match_rule_supported_vector(Op_LoadVectorMasked, lane_count, type)  ||
 226       !Matcher::match_rule_supported_vector(Op_StoreVectorMasked, lane_count, type) ||
 227       !Matcher::match_rule_supported_vector(Op_VectorMaskGen, lane_count, type)) {
 228     return;
 229   }
 230 
 231   int inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(type);
 232   Node* casted_length = new CastLLNode(*ctrl, length, TypeLong::make(0, inline_limit, Type::WidenMin));
 233   transform_later(casted_length);
 234   Node* copy_bytes = new LShiftXNode(length, intcon(shift));
 235   transform_later(copy_bytes);
 236 
 237   Node* cmp_le = new CmpULNode(copy_bytes, longcon(ArrayOperationPartialInlineSize));
 238   transform_later(cmp_le);
 239   Node* bol_le = new BoolNode(cmp_le, BoolTest::le);
 240   transform_later(bol_le);
 241   inline_block  = generate_guard(ctrl, bol_le, nullptr, PROB_FAIR);
 242   stub_block = *ctrl;
 243 
 244   Node* mask_gen = VectorMaskGenNode::make(casted_length, type);
 245   transform_later(mask_gen);
 246 
 247   unsigned vec_size = lane_count *  type2aelembytes(type);
 248   if (C->max_vector_size() < vec_size) {
 249     C->set_max_vector_size(vec_size);
 250   }
 251 
 252   const TypeVect * vt = TypeVect::make(type, lane_count);
 253   Node* mm = (*mem)->memory_at(C->get_alias_index(src_adr_type));
 254   Node* masked_load = new LoadVectorMaskedNode(inline_block, mm, src_start,
 255                                                src_adr_type, vt, mask_gen);
 256   transform_later(masked_load);
 257 
 258   mm = (*mem)->memory_at(C->get_alias_index(adr_type));
 259   Node* masked_store = new StoreVectorMaskedNode(inline_block, mm, dst_start,
 260                                                  masked_load, adr_type, mask_gen);
 261   transform_later(masked_store);
 262 
 263   // Convergence region for inline_block and stub_block.
 264   *exit_block = new RegionNode(3);
 265   transform_later(*exit_block);
 266   (*exit_block)->init_req(1, inline_block);
 267   *result_memory = new PhiNode(*exit_block, Type::MEMORY, adr_type);
 268   transform_later(*result_memory);
 269   (*result_memory)->init_req(1, masked_store);
 270 
 271   *ctrl = stub_block;
 272 }
 273 
 274 
 275 Node* PhaseMacroExpand::generate_nonpositive_guard(Node** ctrl, Node* index, bool never_negative) {
 276   if ((*ctrl)->is_top())  return nullptr;
 277 
 278   if (_igvn.type(index)->higher_equal(TypeInt::POS1)) // [1,maxint]
 279     return nullptr;                // index is already adequately typed
 280   Node* cmp_le = new CmpINode(index, intcon(0));
 281   transform_later(cmp_le);
 282   BoolTest::mask le_or_eq = (never_negative ? BoolTest::eq : BoolTest::le);
 283   Node* bol_le = new BoolNode(cmp_le, le_or_eq);
 284   transform_later(bol_le);
 285   Node* is_notp = generate_guard(ctrl, bol_le, nullptr, PROB_MIN);
 286 
 287   return is_notp;
 288 }
 289 
 290 Node* PhaseMacroExpand::mark_word_test(Node** ctrl, Node* obj, MergeMemNode* mem, uintptr_t mask_val, RegionNode* region) {
 291   // Load markword and check if obj is locked
 292   Node* mark = make_load(nullptr, mem->memory_at(Compile::AliasIdxRaw), obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
 293   Node* locked_bit = MakeConX(markWord::unlocked_value);
 294   locked_bit = transform_later(new AndXNode(locked_bit, mark));
 295   Node* cmp = transform_later(new CmpXNode(locked_bit, MakeConX(0)));
 296   Node* is_unlocked = transform_later(new BoolNode(cmp, BoolTest::ne));
 297   IfNode* iff = transform_later(new IfNode(*ctrl, is_unlocked, PROB_MAX, COUNT_UNKNOWN))->as_If();
 298   Node* locked_region = transform_later(new RegionNode(3));
 299   Node* mark_phi = transform_later(new PhiNode(locked_region, TypeX_X));
 300 
 301   // Unlocked: Use bits from mark word
 302   locked_region->init_req(1, transform_later(new IfTrueNode(iff)));
 303   mark_phi->init_req(1, mark);
 304 
 305   // Locked: Load prototype header from klass
 306   *ctrl = transform_later(new IfFalseNode(iff));
 307   // Make loads control dependent to make sure they are only executed if array is locked
 308   Node* klass_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
 309   Node* klass = transform_later(LoadKlassNode::make(_igvn, C->immutable_memory(), klass_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
 310   Node* proto_adr = basic_plus_adr(klass, in_bytes(Klass::prototype_header_offset()));
 311   Node* proto = transform_later(LoadNode::make(_igvn, *ctrl, C->immutable_memory(), proto_adr, proto_adr->bottom_type()->is_ptr(), TypeX_X, TypeX_X->basic_type(), MemNode::unordered));
 312 
 313   locked_region->init_req(2, *ctrl);
 314   mark_phi->init_req(2, proto);
 315   *ctrl = locked_region;
 316 
 317   // Now check if mark word bits are set
 318   Node* mask = MakeConX(mask_val);
 319   Node* masked = transform_later(new AndXNode(mark_phi, mask));
 320   cmp = transform_later(new CmpXNode(masked, mask));
 321   Node* bol = transform_later(new BoolNode(cmp, BoolTest::eq));
 322   return generate_fair_guard(ctrl, bol, region);
 323 }
 324 
 325 Node* PhaseMacroExpand::generate_flat_array_guard(Node** ctrl, Node* array, MergeMemNode* mem, RegionNode* region) {
 326   return mark_word_test(ctrl, array, mem, markWord::flat_array_bit_in_place, region);
 327 }
 328 
 329 Node* PhaseMacroExpand::generate_null_free_array_guard(Node** ctrl, Node* array, MergeMemNode* mem, RegionNode* region) {
 330   return mark_word_test(ctrl, array, mem, markWord::null_free_array_bit_in_place, region);
 331 }
 332 
 333 void PhaseMacroExpand::finish_arraycopy_call(Node* call, Node** ctrl, MergeMemNode** mem, const TypePtr* adr_type) {
 334   transform_later(call);
 335 
 336   *ctrl = new ProjNode(call,TypeFunc::Control);
 337   transform_later(*ctrl);
 338   Node* newmem = new ProjNode(call, TypeFunc::Memory);
 339   transform_later(newmem);
 340 
 341   uint alias_idx = C->get_alias_index(adr_type);
 342   if (alias_idx != Compile::AliasIdxBot) {
 343     *mem = MergeMemNode::make(*mem);
 344     (*mem)->set_memory_at(alias_idx, newmem);
 345   } else {
 346     *mem = MergeMemNode::make(newmem);
 347   }
 348   transform_later(*mem);
 349 }
 350 
 351 address PhaseMacroExpand::basictype2arraycopy(BasicType t,
 352                                               Node* src_offset,
 353                                               Node* dest_offset,
 354                                               bool disjoint_bases,
 355                                               const char* &name,
 356                                               bool dest_uninitialized) {
 357   const TypeInt* src_offset_inttype  = _igvn.find_int_type(src_offset);
 358   const TypeInt* dest_offset_inttype = _igvn.find_int_type(dest_offset);
 359 
 360   bool aligned = false;
 361   bool disjoint = disjoint_bases;
 362 
 363   // if the offsets are the same, we can treat the memory regions as
 364   // disjoint, because either the memory regions are in different arrays,
 365   // or they are identical (which we can treat as disjoint.)  We can also
 366   // treat a copy with a destination index  less that the source index
 367   // as disjoint since a low->high copy will work correctly in this case.
 368   if (src_offset_inttype != nullptr && src_offset_inttype->is_con() &&
 369       dest_offset_inttype != nullptr && dest_offset_inttype->is_con()) {
 370     // both indices are constants
 371     int s_offs = src_offset_inttype->get_con();
 372     int d_offs = dest_offset_inttype->get_con();
 373     int element_size = type2aelembytes(t);
 374     aligned = ((arrayOopDesc::base_offset_in_bytes(t) + (uint)s_offs * element_size) % HeapWordSize == 0) &&
 375               ((arrayOopDesc::base_offset_in_bytes(t) + (uint)d_offs * element_size) % HeapWordSize == 0);
 376     if (s_offs >= d_offs)  disjoint = true;
 377   } else if (src_offset == dest_offset && src_offset != nullptr) {
 378     // This can occur if the offsets are identical non-constants.
 379     disjoint = true;
 380   }
 381 
 382   return StubRoutines::select_arraycopy_function(t, aligned, disjoint, name, dest_uninitialized);
 383 }
 384 
 385 #define XTOP LP64_ONLY(COMMA top())
 386 
 387 // Generate an optimized call to arraycopy.
 388 // Caller must guard against non-arrays.
 389 // Caller must determine a common array basic-type for both arrays.
 390 // Caller must validate offsets against array bounds.
 391 // The slow_region has already collected guard failure paths
 392 // (such as out of bounds length or non-conformable array types).
 393 // The generated code has this shape, in general:
 394 //
 395 //     if (length == 0)  return   // via zero_path
 396 //     slowval = -1
 397 //     if (types unknown) {
 398 //       slowval = call generic copy loop
 399 //       if (slowval == 0)  return  // via checked_path
 400 //     } else if (indexes in bounds) {
 401 //       if ((is object array) && !(array type check)) {
 402 //         slowval = call checked copy loop
 403 //         if (slowval == 0)  return  // via checked_path
 404 //       } else {
 405 //         call bulk copy loop
 406 //         return  // via fast_path
 407 //       }
 408 //     }
 409 //     // adjust params for remaining work:
 410 //     if (slowval != -1) {
 411 //       n = -1^slowval; src_offset += n; dest_offset += n; length -= n
 412 //     }
 413 //   slow_region:
 414 //     call slow arraycopy(src, src_offset, dest, dest_offset, length)
 415 //     return  // via slow_call_path
 416 //
 417 // This routine is used from several intrinsics:  System.arraycopy,
 418 // Object.clone (the array subcase), and Arrays.copyOf[Range].
 419 //
 420 Node* PhaseMacroExpand::generate_arraycopy(ArrayCopyNode *ac, AllocateArrayNode* alloc,
 421                                            Node** ctrl, MergeMemNode* mem, Node** io,
 422                                            const TypePtr* adr_type,
 423                                            BasicType basic_elem_type,
 424                                            Node* src,  Node* src_offset,
 425                                            Node* dest, Node* dest_offset,
 426                                            Node* copy_length,
 427                                            Node* dest_length,
 428                                            bool disjoint_bases,
 429                                            bool length_never_negative,
 430                                            RegionNode* slow_region) {
 431   if (slow_region == nullptr) {
 432     slow_region = new RegionNode(1);
 433     transform_later(slow_region);
 434   }
 435 
 436   Node* original_dest = dest;
 437   bool  dest_needs_zeroing   = false;
 438   bool  acopy_to_uninitialized = false;
 439   Node* init_value = nullptr;
 440   Node* raw_init_value = nullptr;
 441 
 442   // See if this is the initialization of a newly-allocated array.
 443   // If so, we will take responsibility here for initializing it to zero.
 444   // (Note:  Because tightly_coupled_allocation performs checks on the
 445   // out-edges of the dest, we need to avoid making derived pointers
 446   // from it until we have checked its uses.)
 447   if (ReduceBulkZeroing
 448       && !(UseTLAB && ZeroTLAB) // pointless if already zeroed
 449       && basic_elem_type != T_CONFLICT // avoid corner case
 450       && !src->eqv_uncast(dest)
 451       && alloc != nullptr
 452       && _igvn.find_int_con(alloc->in(AllocateNode::ALength), 1) > 0) {
 453     assert(ac->is_alloc_tightly_coupled(), "sanity");
 454     // acopy to uninitialized tightly coupled allocations
 455     // needs zeroing outside the copy range
 456     // and the acopy itself will be to uninitialized memory
 457     acopy_to_uninitialized = true;
 458     if (alloc->maybe_set_complete(&_igvn)) {
 459       // "You break it, you buy it."
 460       InitializeNode* init = alloc->initialization();
 461       assert(init->is_complete(), "we just did this");
 462       init->set_complete_with_arraycopy();
 463       assert(dest->is_CheckCastPP(), "sanity");
 464       assert(dest->in(0)->in(0) == init, "dest pinned");
 465       adr_type = TypeRawPtr::BOTTOM;  // all initializations are into raw memory
 466       // From this point on, every exit path is responsible for
 467       // initializing any non-copied parts of the object to zero.
 468       // Also, if this flag is set we make sure that arraycopy interacts properly
 469       // with G1, eliding pre-barriers. See CR 6627983.
 470       dest_needs_zeroing = true;
 471       init_value = alloc->in(AllocateNode::InitValue);
 472       raw_init_value = alloc->in(AllocateNode::RawInitValue);
 473     } else {
 474       // dest_need_zeroing = false;
 475     }
 476   } else {
 477     // No zeroing elimination needed here.
 478     alloc                  = nullptr;
 479     acopy_to_uninitialized = false;
 480     //original_dest        = dest;
 481     //dest_needs_zeroing   = false;
 482   }
 483 
 484   uint alias_idx = C->get_alias_index(adr_type);
 485 
 486   // Results are placed here:
 487   enum { fast_path        = 1,  // normal void-returning assembly stub
 488          checked_path     = 2,  // special assembly stub with cleanup
 489          slow_call_path   = 3,  // something went wrong; call the VM
 490          zero_path        = 4,  // bypass when length of copy is zero
 491          bcopy_path       = 5,  // copy primitive array by 64-bit blocks
 492          PATH_LIMIT       = 6
 493   };
 494   RegionNode* result_region = new RegionNode(PATH_LIMIT);
 495   PhiNode*    result_i_o    = new PhiNode(result_region, Type::ABIO);
 496   PhiNode*    result_memory = new PhiNode(result_region, Type::MEMORY, adr_type);
 497   assert(adr_type != TypePtr::BOTTOM, "must be RawMem or a T[] slice");
 498   transform_later(result_region);
 499   transform_later(result_i_o);
 500   transform_later(result_memory);
 501 
 502   // The slow_control path:
 503   Node* slow_control;
 504   Node* slow_i_o = *io;
 505   Node* slow_mem = mem->memory_at(alias_idx);
 506   DEBUG_ONLY(slow_control = (Node*) badAddress);
 507 
 508   // Checked control path:
 509   Node* checked_control = top();
 510   Node* checked_mem     = nullptr;
 511   Node* checked_i_o     = nullptr;
 512   Node* checked_value   = nullptr;
 513 
 514   if (basic_elem_type == T_CONFLICT) {
 515     assert(!dest_needs_zeroing, "");
 516     Node* cv = generate_generic_arraycopy(ctrl, &mem,
 517                                           adr_type,
 518                                           src, src_offset, dest, dest_offset,
 519                                           copy_length, acopy_to_uninitialized);
 520     if (cv == nullptr)  cv = intcon(-1);  // failure (no stub available)
 521     checked_control = *ctrl;
 522     checked_i_o     = *io;
 523     checked_mem     = mem->memory_at(alias_idx);
 524     checked_value   = cv;
 525     *ctrl = top();
 526   }
 527 
 528   Node* not_pos = generate_nonpositive_guard(ctrl, copy_length, length_never_negative);
 529   if (not_pos != nullptr) {
 530     Node* local_ctrl = not_pos, *local_io = *io;
 531     MergeMemNode* local_mem = MergeMemNode::make(mem);
 532     transform_later(local_mem);
 533 
 534     // (6) length must not be negative.
 535     if (!length_never_negative) {
 536       generate_negative_guard(&local_ctrl, copy_length, slow_region);
 537     }
 538 
 539     // copy_length is 0.
 540     if (dest_needs_zeroing) {
 541       assert(!local_ctrl->is_top(), "no ctrl?");
 542       if (copy_length->eqv_uncast(dest_length)
 543           || _igvn.find_int_con(dest_length, 1) <= 0) {
 544         // There is no zeroing to do. No need for a secondary raw memory barrier.
 545       } else {
 546         // Clear the whole thing since there are no source elements to copy.
 547         generate_clear_array(local_ctrl, local_mem,
 548                              adr_type, dest,
 549                              init_value, raw_init_value,
 550                              basic_elem_type,
 551                              intcon(0), nullptr,
 552                              alloc->in(AllocateNode::AllocSize));
 553         // Use a secondary InitializeNode as raw memory barrier.
 554         // Currently it is needed only on this path since other
 555         // paths have stub or runtime calls as raw memory barriers.
 556         MemBarNode* mb = MemBarNode::make(C, Op_Initialize,
 557                                           Compile::AliasIdxRaw,
 558                                           top());
 559         transform_later(mb);
 560         mb->set_req(TypeFunc::Control,local_ctrl);
 561         mb->set_req(TypeFunc::Memory, local_mem->memory_at(Compile::AliasIdxRaw));
 562         local_ctrl = transform_later(new ProjNode(mb, TypeFunc::Control));
 563         local_mem->set_memory_at(Compile::AliasIdxRaw, transform_later(new ProjNode(mb, TypeFunc::Memory)));
 564 
 565         InitializeNode* init = mb->as_Initialize();
 566         init->set_complete(&_igvn);  // (there is no corresponding AllocateNode)
 567       }
 568     }
 569 
 570     // Present the results of the fast call.
 571     result_region->init_req(zero_path, local_ctrl);
 572     result_i_o   ->init_req(zero_path, local_io);
 573     result_memory->init_req(zero_path, local_mem->memory_at(alias_idx));
 574   }
 575 
 576   if (!(*ctrl)->is_top() && dest_needs_zeroing) {
 577     // We have to initialize the *uncopied* part of the array to zero.
 578     // The copy destination is the slice dest[off..off+len].  The other slices
 579     // are dest_head = dest[0..off] and dest_tail = dest[off+len..dest.length].
 580     Node* dest_size   = alloc->in(AllocateNode::AllocSize);
 581     Node* dest_tail   = transform_later( new AddINode(dest_offset, copy_length));
 582 
 583     // If there is a head section that needs zeroing, do it now.
 584     if (_igvn.find_int_con(dest_offset, -1) != 0) {
 585       generate_clear_array(*ctrl, mem,
 586                            adr_type, dest,
 587                            init_value, raw_init_value,
 588                            basic_elem_type,
 589                            intcon(0), dest_offset,
 590                            nullptr);
 591     }
 592 
 593     // Next, perform a dynamic check on the tail length.
 594     // It is often zero, and we can win big if we prove this.
 595     // There are two wins:  Avoid generating the ClearArray
 596     // with its attendant messy index arithmetic, and upgrade
 597     // the copy to a more hardware-friendly word size of 64 bits.
 598     Node* tail_ctl = nullptr;
 599     if (!(*ctrl)->is_top() && !dest_tail->eqv_uncast(dest_length)) {
 600       Node* cmp_lt   = transform_later( new CmpINode(dest_tail, dest_length) );
 601       Node* bol_lt   = transform_later( new BoolNode(cmp_lt, BoolTest::lt) );
 602       tail_ctl = generate_slow_guard(ctrl, bol_lt, nullptr);
 603       assert(tail_ctl != nullptr || !(*ctrl)->is_top(), "must be an outcome");
 604     }
 605 
 606     // At this point, let's assume there is no tail.
 607     if (!(*ctrl)->is_top() && alloc != nullptr && basic_elem_type != T_OBJECT) {
 608       // There is no tail.  Try an upgrade to a 64-bit copy.
 609       bool didit = false;
 610       {
 611         Node* local_ctrl = *ctrl, *local_io = *io;
 612         MergeMemNode* local_mem = MergeMemNode::make(mem);
 613         transform_later(local_mem);
 614 
 615         didit = generate_block_arraycopy(&local_ctrl, &local_mem, local_io,
 616                                          adr_type, basic_elem_type, alloc,
 617                                          src, src_offset, dest, dest_offset,
 618                                          dest_size, acopy_to_uninitialized);
 619         if (didit) {
 620           // Present the results of the block-copying fast call.
 621           result_region->init_req(bcopy_path, local_ctrl);
 622           result_i_o   ->init_req(bcopy_path, local_io);
 623           result_memory->init_req(bcopy_path, local_mem->memory_at(alias_idx));
 624         }
 625       }
 626       if (didit) {
 627         *ctrl = top();     // no regular fast path
 628       }
 629     }
 630 
 631     // Clear the tail, if any.
 632     if (tail_ctl != nullptr) {
 633       Node* notail_ctl = (*ctrl)->is_top() ? nullptr : *ctrl;
 634       *ctrl = tail_ctl;
 635       if (notail_ctl == nullptr) {
 636         generate_clear_array(*ctrl, mem,
 637                              adr_type, dest,
 638                              init_value, raw_init_value,
 639                              basic_elem_type,
 640                              dest_tail, nullptr,
 641                              dest_size);
 642       } else {
 643         // Make a local merge.
 644         Node* done_ctl = transform_later(new RegionNode(3));
 645         Node* done_mem = transform_later(new PhiNode(done_ctl, Type::MEMORY, adr_type));
 646         done_ctl->init_req(1, notail_ctl);
 647         done_mem->init_req(1, mem->memory_at(alias_idx));
 648         generate_clear_array(*ctrl, mem,
 649                              adr_type, dest,
 650                              init_value, raw_init_value,
 651                              basic_elem_type,
 652                              dest_tail, nullptr,
 653                              dest_size);
 654         done_ctl->init_req(2, *ctrl);
 655         done_mem->init_req(2, mem->memory_at(alias_idx));
 656         *ctrl = done_ctl;
 657         mem->set_memory_at(alias_idx, done_mem);
 658       }
 659     }
 660   }
 661 
 662   BasicType copy_type = basic_elem_type;
 663   assert(basic_elem_type != T_ARRAY, "caller must fix this");
 664   if (!(*ctrl)->is_top() && copy_type == T_OBJECT) {
 665     // If src and dest have compatible element types, we can copy bits.
 666     // Types S[] and D[] are compatible if D is a supertype of S.
 667     //
 668     // If they are not, we will use checked_oop_disjoint_arraycopy,
 669     // which performs a fast optimistic per-oop check, and backs off
 670     // further to JVM_ArrayCopy on the first per-oop check that fails.
 671     // (Actually, we don't move raw bits only; the GC requires card marks.)
 672 
 673     // We don't need a subtype check for validated copies and Object[].clone()
 674     bool skip_subtype_check = ac->is_arraycopy_validated() || ac->is_copyof_validated() ||
 675                               ac->is_copyofrange_validated() || ac->is_clone_oop_array();
 676     if (!skip_subtype_check) {
 677       // Get the klass* for both src and dest
 678       Node* src_klass  = ac->in(ArrayCopyNode::SrcKlass);
 679       Node* dest_klass = ac->in(ArrayCopyNode::DestKlass);
 680 
 681       assert(src_klass != nullptr && dest_klass != nullptr, "should have klasses");
 682 
 683       // Generate the subtype check.
 684       // This might fold up statically, or then again it might not.
 685       //
 686       // Non-static example:  Copying List<String>.elements to a new String[].
 687       // The backing store for a List<String> is always an Object[],
 688       // but its elements are always type String, if the generic types
 689       // are correct at the source level.
 690       //
 691       // Test S[] against D[], not S against D, because (probably)
 692       // the secondary supertype cache is less busy for S[] than S.
 693       // This usually only matters when D is an interface.
 694       Node* not_subtype_ctrl = Phase::gen_subtype_check(src_klass, dest_klass, ctrl, mem, _igvn, nullptr, -1);
 695       // Plug failing path into checked_oop_disjoint_arraycopy
 696       if (not_subtype_ctrl != top()) {
 697         Node* local_ctrl = not_subtype_ctrl;
 698         MergeMemNode* local_mem = MergeMemNode::make(mem);
 699         transform_later(local_mem);
 700 
 701         // (At this point we can assume disjoint_bases, since types differ.)
 702         int ek_offset = in_bytes(ObjArrayKlass::element_klass_offset());
 703         Node* p1 = basic_plus_adr(dest_klass, ek_offset);
 704         Node* n1 = LoadKlassNode::make(_igvn, C->immutable_memory(), p1, TypeRawPtr::BOTTOM);
 705         Node* dest_elem_klass = transform_later(n1);
 706         Node* cv = generate_checkcast_arraycopy(&local_ctrl, &local_mem,
 707                                                 adr_type,
 708                                                 dest_elem_klass,
 709                                                 src, src_offset, dest, dest_offset,
 710                                                 ConvI2X(copy_length), acopy_to_uninitialized);
 711         if (cv == nullptr)  cv = intcon(-1);  // failure (no stub available)
 712         checked_control = local_ctrl;
 713         checked_i_o     = *io;
 714         checked_mem     = local_mem->memory_at(alias_idx);
 715         checked_value   = cv;
 716       }
 717     }
 718     // At this point we know we do not need type checks on oop stores.
 719 
 720     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 721     if (!bs->array_copy_requires_gc_barriers(alloc != nullptr, copy_type, false, false, BarrierSetC2::Expansion)) {
 722       // If we do not need gc barriers, copy using the jint or jlong stub.
 723       copy_type = LP64_ONLY(UseCompressedOops ? T_INT : T_LONG) NOT_LP64(T_INT);
 724       assert(type2aelembytes(basic_elem_type) == type2aelembytes(copy_type),
 725              "sizes agree");
 726     }
 727   }
 728 
 729   bool is_partial_array_copy = false;
 730   if (!(*ctrl)->is_top()) {
 731     // Generate the fast path, if possible.
 732     Node* local_ctrl = *ctrl;
 733     MergeMemNode* local_mem = MergeMemNode::make(mem);
 734     transform_later(local_mem);
 735     is_partial_array_copy = generate_unchecked_arraycopy(&local_ctrl, &local_mem,
 736                                                          adr_type, copy_type, disjoint_bases,
 737                                                          src, src_offset, dest, dest_offset,
 738                                                          ConvI2X(copy_length), acopy_to_uninitialized);
 739 
 740     // Present the results of the fast call.
 741     result_region->init_req(fast_path, local_ctrl);
 742     result_i_o   ->init_req(fast_path, *io);
 743     result_memory->init_req(fast_path, local_mem->memory_at(alias_idx));
 744   }
 745 
 746   // Here are all the slow paths up to this point, in one bundle:
 747   assert(slow_region != nullptr, "allocated on entry");
 748   slow_control = slow_region;
 749   DEBUG_ONLY(slow_region = (RegionNode*)badAddress);
 750 
 751   *ctrl = checked_control;
 752   if (!(*ctrl)->is_top()) {
 753     // Clean up after the checked call.
 754     // The returned value is either 0 or -1^K,
 755     // where K = number of partially transferred array elements.
 756     Node* cmp = new CmpINode(checked_value, intcon(0));
 757     transform_later(cmp);
 758     Node* bol = new BoolNode(cmp, BoolTest::eq);
 759     transform_later(bol);
 760     IfNode* iff = new IfNode(*ctrl, bol, PROB_MAX, COUNT_UNKNOWN);
 761     transform_later(iff);
 762 
 763     // If it is 0, we are done, so transfer to the end.
 764     Node* checks_done = new IfTrueNode(iff);
 765     transform_later(checks_done);
 766     result_region->init_req(checked_path, checks_done);
 767     result_i_o   ->init_req(checked_path, checked_i_o);
 768     result_memory->init_req(checked_path, checked_mem);
 769 
 770     // If it is not zero, merge into the slow call.
 771     *ctrl = new IfFalseNode(iff);
 772     transform_later(*ctrl);
 773     RegionNode* slow_reg2 = new RegionNode(3);
 774     PhiNode*    slow_i_o2 = new PhiNode(slow_reg2, Type::ABIO);
 775     PhiNode*    slow_mem2 = new PhiNode(slow_reg2, Type::MEMORY, adr_type);
 776     transform_later(slow_reg2);
 777     transform_later(slow_i_o2);
 778     transform_later(slow_mem2);
 779     slow_reg2  ->init_req(1, slow_control);
 780     slow_i_o2  ->init_req(1, slow_i_o);
 781     slow_mem2  ->init_req(1, slow_mem);
 782     slow_reg2  ->init_req(2, *ctrl);
 783     slow_i_o2  ->init_req(2, checked_i_o);
 784     slow_mem2  ->init_req(2, checked_mem);
 785 
 786     slow_control = slow_reg2;
 787     slow_i_o     = slow_i_o2;
 788     slow_mem     = slow_mem2;
 789 
 790     if (alloc != nullptr) {
 791       // We'll restart from the very beginning, after zeroing the whole thing.
 792       // This can cause double writes, but that's OK since dest is brand new.
 793       // So we ignore the low 31 bits of the value returned from the stub.
 794     } else {
 795       // We must continue the copy exactly where it failed, or else
 796       // another thread might see the wrong number of writes to dest.
 797       Node* checked_offset = new XorINode(checked_value, intcon(-1));
 798       Node* slow_offset    = new PhiNode(slow_reg2, TypeInt::INT);
 799       transform_later(checked_offset);
 800       transform_later(slow_offset);
 801       slow_offset->init_req(1, intcon(0));
 802       slow_offset->init_req(2, checked_offset);
 803 
 804       // Adjust the arguments by the conditionally incoming offset.
 805       Node* src_off_plus  = new AddINode(src_offset,  slow_offset);
 806       transform_later(src_off_plus);
 807       Node* dest_off_plus = new AddINode(dest_offset, slow_offset);
 808       transform_later(dest_off_plus);
 809       Node* length_minus  = new SubINode(copy_length, slow_offset);
 810       transform_later(length_minus);
 811 
 812       // Tweak the node variables to adjust the code produced below:
 813       src_offset  = src_off_plus;
 814       dest_offset = dest_off_plus;
 815       copy_length = length_minus;
 816     }
 817   }
 818   *ctrl = slow_control;
 819   if (!(*ctrl)->is_top()) {
 820     Node* local_ctrl = *ctrl, *local_io = slow_i_o;
 821     MergeMemNode* local_mem = MergeMemNode::make(mem);
 822     transform_later(local_mem);
 823 
 824     // Generate the slow path, if needed.
 825     local_mem->set_memory_at(alias_idx, slow_mem);
 826 
 827     if (dest_needs_zeroing) {
 828       generate_clear_array(local_ctrl, local_mem,
 829                            adr_type, dest,
 830                            init_value, raw_init_value,
 831                            basic_elem_type,
 832                            intcon(0), nullptr,
 833                            alloc->in(AllocateNode::AllocSize));
 834     }
 835 
 836     local_mem = generate_slow_arraycopy(ac,
 837                                         &local_ctrl, local_mem, &local_io,
 838                                         adr_type,
 839                                         src, src_offset, dest, dest_offset,
 840                                         copy_length, /*dest_uninitialized*/false);
 841 
 842     result_region->init_req(slow_call_path, local_ctrl);
 843     result_i_o   ->init_req(slow_call_path, local_io);
 844     result_memory->init_req(slow_call_path, local_mem->memory_at(alias_idx));
 845   } else {
 846     ShouldNotReachHere(); // no call to generate_slow_arraycopy:
 847                           // projections were not extracted
 848   }
 849 
 850   // Remove unused edges.
 851   for (uint i = 1; i < result_region->req(); i++) {
 852     if (result_region->in(i) == nullptr) {
 853       result_region->init_req(i, top());
 854     }
 855   }
 856 
 857   // Finished; return the combined state.
 858   *ctrl = result_region;
 859   *io = result_i_o;
 860   mem->set_memory_at(alias_idx, result_memory);
 861 
 862   // mem no longer guaranteed to stay a MergeMemNode
 863   Node* out_mem = mem;
 864   DEBUG_ONLY(mem = nullptr);
 865 
 866   // The memory edges above are precise in order to model effects around
 867   // array copies accurately to allow value numbering of field loads around
 868   // arraycopy.  Such field loads, both before and after, are common in Java
 869   // collections and similar classes involving header/array data structures.
 870   //
 871   // But with low number of register or when some registers are used or killed
 872   // by arraycopy calls it causes registers spilling on stack. See 6544710.
 873   // The next memory barrier is added to avoid it. If the arraycopy can be
 874   // optimized away (which it can, sometimes) then we can manually remove
 875   // the membar also.
 876   //
 877   // Do not let reads from the cloned object float above the arraycopy.
 878   if (alloc != nullptr && !alloc->initialization()->does_not_escape()) {
 879     // Do not let stores that initialize this object be reordered with
 880     // a subsequent store that would make this object accessible by
 881     // other threads.
 882     insert_mem_bar(ctrl, &out_mem, Op_MemBarStoreStore);
 883   } else {
 884     insert_mem_bar(ctrl, &out_mem, Op_MemBarCPUOrder);
 885   }
 886 
 887   if (is_partial_array_copy) {
 888     assert((*ctrl)->is_Proj(), "MemBar control projection");
 889     assert((*ctrl)->in(0)->isa_MemBar(), "MemBar node");
 890     (*ctrl)->in(0)->isa_MemBar()->set_trailing_partial_array_copy();
 891   }
 892 
 893   _igvn.replace_node(_callprojs->fallthrough_memproj, out_mem);
 894   if (_callprojs->fallthrough_ioproj != nullptr) {
 895     _igvn.replace_node(_callprojs->fallthrough_ioproj, *io);
 896   }
 897   _igvn.replace_node(_callprojs->fallthrough_catchproj, *ctrl);
 898 
 899 #ifdef ASSERT
 900   const TypeOopPtr* dest_t = _igvn.type(dest)->is_oopptr();
 901   if (dest_t->is_known_instance() && !is_partial_array_copy) {
 902     ArrayCopyNode* ac = nullptr;
 903     assert(ArrayCopyNode::may_modify(dest_t, (*ctrl)->in(0)->as_MemBar(), &_igvn, ac), "dependency on arraycopy lost");
 904     assert(ac == nullptr, "no arraycopy anymore");
 905   }
 906 #endif
 907 
 908   return out_mem;
 909 }
 910 
 911 // Helper for initialization of arrays, creating a ClearArray.
 912 // It writes zero bits in [start..end), within the body of an array object.
 913 // The memory effects are all chained onto the 'adr_type' alias category.
 914 //
 915 // Since the object is otherwise uninitialized, we are free
 916 // to put a little "slop" around the edges of the cleared area,
 917 // as long as it does not go back into the array's header,
 918 // or beyond the array end within the heap.
 919 //
 920 // The lower edge can be rounded down to the nearest jint and the
 921 // upper edge can be rounded up to the nearest MinObjAlignmentInBytes.
 922 //
 923 // Arguments:
 924 //   adr_type           memory slice where writes are generated
 925 //   dest               oop of the destination array
 926 //   basic_elem_type    element type of the destination
 927 //   slice_idx          array index of first element to store
 928 //   slice_len          number of elements to store (or null)
 929 //   dest_size          total size in bytes of the array object
 930 //
 931 // Exactly one of slice_len or dest_size must be non-null.
 932 // If dest_size is non-null, zeroing extends to the end of the object.
 933 // If slice_len is non-null, the slice_idx value must be a constant.
 934 void PhaseMacroExpand::generate_clear_array(Node* ctrl, MergeMemNode* merge_mem,
 935                                             const TypePtr* adr_type,
 936                                             Node* dest,
 937                                             Node* val,
 938                                             Node* raw_val,
 939                                             BasicType basic_elem_type,
 940                                             Node* slice_idx,
 941                                             Node* slice_len,
 942                                             Node* dest_size) {
 943   // one or the other but not both of slice_len and dest_size:
 944   assert((slice_len != nullptr? 1: 0) + (dest_size != nullptr? 1: 0) == 1, "");
 945   if (slice_len == nullptr)  slice_len = top();
 946   if (dest_size == nullptr)  dest_size = top();
 947 
 948   uint alias_idx = C->get_alias_index(adr_type);
 949 
 950   // operate on this memory slice:
 951   Node* mem = merge_mem->memory_at(alias_idx); // memory slice to operate on
 952 
 953   // scaling and rounding of indexes:
 954   int scale = exact_log2(type2aelembytes(basic_elem_type));
 955   int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
 956   int clear_low = (-1 << scale) & (BytesPerInt  - 1);
 957   int bump_bit  = (-1 << scale) & BytesPerInt;
 958 
 959   // determine constant starts and ends
 960   const intptr_t BIG_NEG = -128;
 961   assert(BIG_NEG + 2*abase < 0, "neg enough");
 962   intptr_t slice_idx_con = (intptr_t) _igvn.find_int_con(slice_idx, BIG_NEG);
 963   intptr_t slice_len_con = (intptr_t) _igvn.find_int_con(slice_len, BIG_NEG);
 964   if (slice_len_con == 0) {
 965     return;                     // nothing to do here
 966   }
 967   intptr_t start_con = (abase + (slice_idx_con << scale)) & ~clear_low;
 968   intptr_t end_con   = _igvn.find_intptr_t_con(dest_size, -1);
 969   if (slice_idx_con >= 0 && slice_len_con >= 0) {
 970     assert(end_con < 0, "not two cons");
 971     end_con = align_up(abase + ((slice_idx_con + slice_len_con) << scale),
 972                        BytesPerLong);
 973   }
 974 
 975   if (start_con >= 0 && end_con >= 0) {
 976     // Constant start and end.  Simple.
 977     mem = ClearArrayNode::clear_memory(ctrl, mem, dest, val, raw_val,
 978                                        start_con, end_con, &_igvn);
 979   } else if (start_con >= 0 && dest_size != top()) {
 980     // Constant start, pre-rounded end after the tail of the array.
 981     Node* end = dest_size;
 982     mem = ClearArrayNode::clear_memory(ctrl, mem, dest, val, raw_val,
 983                                        start_con, end, &_igvn);
 984   } else if (start_con >= 0 && slice_len != top()) {
 985     // Constant start, non-constant end.  End needs rounding up.
 986     // End offset = round_up(abase + ((slice_idx_con + slice_len) << scale), 8)
 987     intptr_t end_base  = abase + (slice_idx_con << scale);
 988     int      end_round = (-1 << scale) & (BytesPerLong  - 1);
 989     Node*    end       = ConvI2X(slice_len);
 990     if (scale != 0)
 991       end = transform_later(new LShiftXNode(end, intcon(scale) ));
 992     end_base += end_round;
 993     end = transform_later(new AddXNode(end, MakeConX(end_base)) );
 994     end = transform_later(new AndXNode(end, MakeConX(~end_round)) );
 995     mem = ClearArrayNode::clear_memory(ctrl, mem, dest, val, raw_val,
 996                                        start_con, end, &_igvn);
 997   } else if (start_con < 0 && dest_size != top()) {
 998     // Non-constant start, pre-rounded end after the tail of the array.
 999     // This is almost certainly a "round-to-end" operation.
1000     Node* start = slice_idx;
1001     start = ConvI2X(start);
1002     if (scale != 0)
1003       start = transform_later(new LShiftXNode( start, intcon(scale) ));
1004     start = transform_later(new AddXNode(start, MakeConX(abase)) );
1005     if ((bump_bit | clear_low) != 0) {
1006       int to_clear = (bump_bit | clear_low);
1007       // Align up mod 8, then store a jint zero unconditionally
1008       // just before the mod-8 boundary.
1009       if (((abase + bump_bit) & ~to_clear) - bump_bit
1010           < arrayOopDesc::length_offset_in_bytes() + BytesPerInt) {
1011         bump_bit = 0;
1012         assert((abase & to_clear) == 0, "array base must be long-aligned");
1013       } else {
1014         // Bump 'start' up to (or past) the next jint boundary:
1015         start = transform_later( new AddXNode(start, MakeConX(bump_bit)) );
1016         assert((abase & clear_low) == 0, "array base must be int-aligned");
1017       }
1018       // Round bumped 'start' down to jlong boundary in body of array.
1019       start = transform_later(new AndXNode(start, MakeConX(~to_clear)) );
1020       if (bump_bit != 0) {
1021         // Store a zero to the immediately preceding jint:
1022         Node* x1 = transform_later(new AddXNode(start, MakeConX(-bump_bit)) );
1023         Node* p1 = basic_plus_adr(dest, x1);
1024         if (val == nullptr) {
1025           assert(raw_val == nullptr, "val may not be null");
1026           mem = StoreNode::make(_igvn, ctrl, mem, p1, adr_type, intcon(0), T_INT, MemNode::unordered);
1027         } else {
1028           assert(_igvn.type(val)->isa_narrowoop(), "should be narrow oop");
1029           mem = new StoreNNode(ctrl, mem, p1, adr_type, val, MemNode::unordered);
1030         }
1031         mem = transform_later(mem);
1032       }
1033     }
1034     Node* end = dest_size; // pre-rounded
1035     mem = ClearArrayNode::clear_memory(ctrl, mem, dest, raw_val,
1036                                        start, end, &_igvn);
1037   } else {
1038     // Non-constant start, unrounded non-constant end.
1039     // (Nobody zeroes a random midsection of an array using this routine.)
1040     ShouldNotReachHere();       // fix caller
1041   }
1042 
1043   // Done.
1044   merge_mem->set_memory_at(alias_idx, mem);
1045 }
1046 
1047 bool PhaseMacroExpand::generate_block_arraycopy(Node** ctrl, MergeMemNode** mem, Node* io,
1048                                                 const TypePtr* adr_type,
1049                                                 BasicType basic_elem_type,
1050                                                 AllocateNode* alloc,
1051                                                 Node* src,  Node* src_offset,
1052                                                 Node* dest, Node* dest_offset,
1053                                                 Node* dest_size, bool dest_uninitialized) {
1054   // See if there is an advantage from block transfer.
1055   int scale = exact_log2(type2aelembytes(basic_elem_type));
1056   if (scale >= LogBytesPerLong)
1057     return false;               // it is already a block transfer
1058 
1059   // Look at the alignment of the starting offsets.
1060   int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
1061 
1062   intptr_t src_off_con  = (intptr_t) _igvn.find_int_con(src_offset, -1);
1063   intptr_t dest_off_con = (intptr_t) _igvn.find_int_con(dest_offset, -1);
1064   if (src_off_con < 0 || dest_off_con < 0) {
1065     // At present, we can only understand constants.
1066     return false;
1067   }
1068 
1069   intptr_t src_off  = abase + (src_off_con  << scale);
1070   intptr_t dest_off = abase + (dest_off_con << scale);
1071 
1072   if (((src_off | dest_off) & (BytesPerLong-1)) != 0) {
1073     // Non-aligned; too bad.
1074     // One more chance:  Pick off an initial 32-bit word.
1075     // This is a common case, since abase can be odd mod 8.
1076     if (((src_off | dest_off) & (BytesPerLong-1)) == BytesPerInt &&
1077         ((src_off ^ dest_off) & (BytesPerLong-1)) == 0) {
1078       Node* sptr = basic_plus_adr(src,  src_off);
1079       Node* dptr = basic_plus_adr(dest, dest_off);
1080       const TypePtr* s_adr_type = _igvn.type(sptr)->is_ptr();
1081       assert(s_adr_type->isa_aryptr(), "impossible slice");
1082       uint s_alias_idx = C->get_alias_index(s_adr_type);
1083       uint d_alias_idx = C->get_alias_index(adr_type);
1084       bool is_mismatched = (basic_elem_type != T_INT);
1085       Node* sval = transform_later(
1086           LoadNode::make(_igvn, *ctrl, (*mem)->memory_at(s_alias_idx), sptr, s_adr_type,
1087                          TypeInt::INT, T_INT, MemNode::unordered, LoadNode::DependsOnlyOnTest,
1088                          false /*require_atomic_access*/, false /*unaligned*/, is_mismatched));
1089       Node* st = transform_later(
1090           StoreNode::make(_igvn, *ctrl, (*mem)->memory_at(d_alias_idx), dptr, adr_type,
1091                           sval, T_INT, MemNode::unordered));
1092       if (is_mismatched) {
1093         st->as_Store()->set_mismatched_access();
1094       }
1095       (*mem)->set_memory_at(d_alias_idx, st);
1096       src_off += BytesPerInt;
1097       dest_off += BytesPerInt;
1098     } else {
1099       return false;
1100     }
1101   }
1102   assert(src_off % BytesPerLong == 0, "");
1103   assert(dest_off % BytesPerLong == 0, "");
1104 
1105   // Do this copy by giant steps.
1106   Node* sptr  = basic_plus_adr(src,  src_off);
1107   Node* dptr  = basic_plus_adr(dest, dest_off);
1108   Node* countx = dest_size;
1109   countx = transform_later(new SubXNode(countx, MakeConX(dest_off)));
1110   countx = transform_later(new URShiftXNode(countx, intcon(LogBytesPerLong)));
1111 
1112   bool disjoint_bases = true;   // since alloc isn't null
1113   generate_unchecked_arraycopy(ctrl, mem,
1114                                adr_type, T_LONG, disjoint_bases,
1115                                sptr, nullptr, dptr, nullptr, countx, dest_uninitialized);
1116 
1117   return true;
1118 }
1119 
1120 // Helper function; generates code for the slow case.
1121 // We make a call to a runtime method which emulates the native method,
1122 // but without the native wrapper overhead.
1123 MergeMemNode* PhaseMacroExpand::generate_slow_arraycopy(ArrayCopyNode *ac,
1124                                                         Node** ctrl, Node* mem, Node** io,
1125                                                         const TypePtr* adr_type,
1126                                                         Node* src,  Node* src_offset,
1127                                                         Node* dest, Node* dest_offset,
1128                                                         Node* copy_length, bool dest_uninitialized) {
1129   assert(!dest_uninitialized, "Invariant");
1130 
1131   const TypeFunc* call_type = OptoRuntime::slow_arraycopy_Type();
1132   CallNode* call = new CallStaticJavaNode(call_type, OptoRuntime::slow_arraycopy_Java(),
1133                                           "slow_arraycopy", TypePtr::BOTTOM);
1134 
1135   call->init_req(TypeFunc::Control, *ctrl);
1136   call->init_req(TypeFunc::I_O    , *io);
1137   call->init_req(TypeFunc::Memory , mem);
1138   call->init_req(TypeFunc::ReturnAdr, top());
1139   call->init_req(TypeFunc::FramePtr, top());
1140   call->init_req(TypeFunc::Parms+0, src);
1141   call->init_req(TypeFunc::Parms+1, src_offset);
1142   call->init_req(TypeFunc::Parms+2, dest);
1143   call->init_req(TypeFunc::Parms+3, dest_offset);
1144   call->init_req(TypeFunc::Parms+4, copy_length);
1145   call->copy_call_debug_info(&_igvn, ac);
1146 
1147   call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
1148   _igvn.replace_node(ac, call);
1149   transform_later(call);
1150 
1151   _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1152   *ctrl = _callprojs->fallthrough_catchproj->clone();
1153   transform_later(*ctrl);
1154 
1155   Node* m = _callprojs->fallthrough_memproj->clone();
1156   transform_later(m);
1157 
1158   uint alias_idx = C->get_alias_index(adr_type);
1159   MergeMemNode* out_mem;
1160   if (alias_idx != Compile::AliasIdxBot) {
1161     out_mem = MergeMemNode::make(mem);
1162     out_mem->set_memory_at(alias_idx, m);
1163   } else {
1164     out_mem = MergeMemNode::make(m);
1165   }
1166   transform_later(out_mem);
1167 
1168   // When src is negative and arraycopy is before an infinite loop,_callprojs.fallthrough_ioproj
1169   // could be nullptr. Skip clone and update nullptr fallthrough_ioproj.
1170   if (_callprojs->fallthrough_ioproj != nullptr) {
1171     *io = _callprojs->fallthrough_ioproj->clone();
1172     transform_later(*io);
1173   } else {
1174     *io = nullptr;
1175   }
1176 
1177   return out_mem;
1178 }
1179 
1180 // Helper function; generates code for cases requiring runtime checks.
1181 Node* PhaseMacroExpand::generate_checkcast_arraycopy(Node** ctrl, MergeMemNode** mem,
1182                                                      const TypePtr* adr_type,
1183                                                      Node* dest_elem_klass,
1184                                                      Node* src,  Node* src_offset,
1185                                                      Node* dest, Node* dest_offset,
1186                                                      Node* copy_length, bool dest_uninitialized) {
1187   if ((*ctrl)->is_top())  return nullptr;
1188 
1189   address copyfunc_addr = StubRoutines::checkcast_arraycopy(dest_uninitialized);
1190   if (copyfunc_addr == nullptr) { // Stub was not generated, go slow path.
1191     return nullptr;
1192   }
1193 
1194   // Pick out the parameters required to perform a store-check
1195   // for the target array.  This is an optimistic check.  It will
1196   // look in each non-null element's class, at the desired klass's
1197   // super_check_offset, for the desired klass.
1198   int sco_offset = in_bytes(Klass::super_check_offset_offset());
1199   Node* p3 = basic_plus_adr(dest_elem_klass, sco_offset);
1200   Node* n3 = new LoadINode(nullptr, *mem /*memory(p3)*/, p3, _igvn.type(p3)->is_ptr(), TypeInt::INT, MemNode::unordered);
1201   Node* check_offset = ConvI2X(transform_later(n3));
1202   Node* check_value  = dest_elem_klass;
1203 
1204   Node* src_start  = array_element_address(src,  src_offset,  T_OBJECT);
1205   Node* dest_start = array_element_address(dest, dest_offset, T_OBJECT);
1206 
1207   const TypeFunc* call_type = OptoRuntime::checkcast_arraycopy_Type();
1208   Node* call = make_leaf_call(*ctrl, *mem, call_type, copyfunc_addr, "checkcast_arraycopy", adr_type,
1209                               src_start, dest_start, copy_length XTOP, check_offset XTOP, check_value);
1210 
1211   finish_arraycopy_call(call, ctrl, mem, adr_type);
1212 
1213   Node* proj =  new ProjNode(call, TypeFunc::Parms);
1214   transform_later(proj);
1215 
1216   return proj;
1217 }
1218 
1219 // Helper function; generates code for cases requiring runtime checks.
1220 Node* PhaseMacroExpand::generate_generic_arraycopy(Node** ctrl, MergeMemNode** mem,
1221                                                    const TypePtr* adr_type,
1222                                                    Node* src,  Node* src_offset,
1223                                                    Node* dest, Node* dest_offset,
1224                                                    Node* copy_length, bool dest_uninitialized) {
1225   if ((*ctrl)->is_top()) return nullptr;
1226   assert(!dest_uninitialized, "Invariant");
1227 
1228   address copyfunc_addr = StubRoutines::generic_arraycopy();
1229   if (copyfunc_addr == nullptr) { // Stub was not generated, go slow path.
1230     return nullptr;
1231   }
1232 
1233   const TypeFunc* call_type = OptoRuntime::generic_arraycopy_Type();
1234   Node* call = make_leaf_call(*ctrl, *mem, call_type, copyfunc_addr, "generic_arraycopy", adr_type,
1235                               src, src_offset, dest, dest_offset, copy_length);
1236 
1237   finish_arraycopy_call(call, ctrl, mem, adr_type);
1238 
1239   Node* proj =  new ProjNode(call, TypeFunc::Parms);
1240   transform_later(proj);
1241 
1242   return proj;
1243 }
1244 
1245 // Helper function; generates the fast out-of-line call to an arraycopy stub.
1246 bool PhaseMacroExpand::generate_unchecked_arraycopy(Node** ctrl, MergeMemNode** mem,
1247                                                     const TypePtr* adr_type,
1248                                                     BasicType basic_elem_type,
1249                                                     bool disjoint_bases,
1250                                                     Node* src,  Node* src_offset,
1251                                                     Node* dest, Node* dest_offset,
1252                                                     Node* copy_length, bool dest_uninitialized) {
1253   if ((*ctrl)->is_top()) return false;
1254 
1255   Node* src_start  = src;
1256   Node* dest_start = dest;
1257   if (src_offset != nullptr || dest_offset != nullptr) {
1258     src_start =  array_element_address(src, src_offset, basic_elem_type);
1259     dest_start = array_element_address(dest, dest_offset, basic_elem_type);
1260   }
1261 
1262   // Figure out which arraycopy runtime method to call.
1263   const char* copyfunc_name = "arraycopy";
1264   address     copyfunc_addr =
1265       basictype2arraycopy(basic_elem_type, src_offset, dest_offset,
1266                           disjoint_bases, copyfunc_name, dest_uninitialized);
1267 
1268   Node* result_memory = nullptr;
1269   RegionNode* exit_block = nullptr;
1270   if (ArrayOperationPartialInlineSize > 0 && is_subword_type(basic_elem_type) &&
1271     Matcher::vector_width_in_bytes(basic_elem_type) >= 16) {
1272     generate_partial_inlining_block(ctrl, mem, adr_type, &exit_block, &result_memory,
1273                                     copy_length, src_start, dest_start, basic_elem_type);
1274   }
1275 
1276   const TypeFunc* call_type = OptoRuntime::fast_arraycopy_Type();
1277   Node* call = make_leaf_call(*ctrl, *mem, call_type, copyfunc_addr, copyfunc_name, adr_type,
1278                               src_start, dest_start, copy_length XTOP);
1279 
1280   finish_arraycopy_call(call, ctrl, mem, adr_type);
1281 
1282   // Connecting remaining edges for exit_block coming from stub_block.
1283   if (exit_block) {
1284     exit_block->init_req(2, *ctrl);
1285 
1286     // Memory edge corresponding to stub_region.
1287     result_memory->init_req(2, *mem);
1288 
1289     uint alias_idx = C->get_alias_index(adr_type);
1290     if (alias_idx != Compile::AliasIdxBot) {
1291       *mem = MergeMemNode::make(*mem);
1292       (*mem)->set_memory_at(alias_idx, result_memory);
1293     } else {
1294       *mem = MergeMemNode::make(result_memory);
1295     }
1296     transform_later(*mem);
1297     *ctrl = exit_block;
1298     return true;
1299   }
1300   return false;
1301 }
1302 
1303 const TypePtr* PhaseMacroExpand::adjust_for_flat_array(const TypeAryPtr* top_dest, Node*& src_offset,
1304                                                        Node*& dest_offset, Node*& length, BasicType& dest_elem,
1305                                                        Node*& dest_length) {
1306 #ifdef ASSERT
1307   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1308   bool needs_barriers = top_dest->elem()->inline_klass()->contains_oops() &&
1309     bs->array_copy_requires_gc_barriers(dest_length != nullptr, T_OBJECT, false, false, BarrierSetC2::Optimization);
1310   assert(!needs_barriers || StressReflectiveCode, "Flat arracopy would require GC barriers");
1311 #endif
1312   int elem_size = top_dest->flat_elem_size();
1313   if (elem_size >= 8) {
1314     if (elem_size > 8) {
1315       // treat as array of long but scale length, src offset and dest offset
1316       assert((elem_size % 8) == 0, "not a power of 2?");
1317       int factor = elem_size / 8;
1318       length = transform_later(new MulINode(length, intcon(factor)));
1319       src_offset = transform_later(new MulINode(src_offset, intcon(factor)));
1320       dest_offset = transform_later(new MulINode(dest_offset, intcon(factor)));
1321       if (dest_length != nullptr) {
1322         dest_length = transform_later(new MulINode(dest_length, intcon(factor)));
1323       }
1324       elem_size = 8;
1325     }
1326     dest_elem = T_LONG;
1327   } else if (elem_size == 4) {
1328     dest_elem = T_INT;
1329   } else if (elem_size == 2) {
1330     dest_elem = T_CHAR;
1331   } else if (elem_size == 1) {
1332     dest_elem = T_BYTE;
1333   } else {
1334     ShouldNotReachHere();
1335   }
1336   return TypeRawPtr::BOTTOM;
1337 }
1338 
1339 #undef XTOP
1340 
1341 void PhaseMacroExpand::expand_arraycopy_node(ArrayCopyNode *ac) {
1342   Node* ctrl = ac->in(TypeFunc::Control);
1343   Node* io = ac->in(TypeFunc::I_O);
1344   Node* src = ac->in(ArrayCopyNode::Src);
1345   Node* src_offset = ac->in(ArrayCopyNode::SrcPos);
1346   Node* dest = ac->in(ArrayCopyNode::Dest);
1347   Node* dest_offset = ac->in(ArrayCopyNode::DestPos);
1348   Node* length = ac->in(ArrayCopyNode::Length);
1349   MergeMemNode* merge_mem = nullptr;
1350 
1351   if (ac->is_clonebasic()) {
1352     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1353     bs->clone_at_expansion(this, ac);
1354     return;
1355   } else if (ac->is_copyof() || ac->is_copyofrange() || ac->is_clone_oop_array()) {
1356     const Type* src_type = _igvn.type(src);
1357     const Type* dest_type = _igvn.type(dest);
1358     const TypeAryPtr* top_src = src_type->isa_aryptr();
1359     // Note: The destination could have type Object (i.e. non-array) when directly invoking the protected method
1360     //       Object::clone() with reflection on a declared Object that is an array at runtime. top_dest is then null.
1361     const TypeAryPtr* top_dest = dest_type->isa_aryptr();
1362     BasicType dest_elem = T_OBJECT;
1363     if (top_dest != nullptr && top_dest->elem() != Type::BOTTOM) {
1364       dest_elem = top_dest->elem()->array_element_basic_type();
1365     }
1366     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
1367 
1368     if (top_src != nullptr && top_src->is_flat()) {
1369       // If src is flat, dest is guaranteed to be flat as well
1370       top_dest = top_src;
1371     }
1372 
1373     AllocateArrayNode* alloc = nullptr;
1374     Node* dest_length = nullptr;
1375     if (ac->is_alloc_tightly_coupled()) {
1376       alloc = AllocateArrayNode::Ideal_array_allocation(dest);
1377       assert(alloc != nullptr, "expect alloc");
1378       dest_length = alloc->in(AllocateNode::ALength);
1379     }
1380 
1381     Node* mem = ac->in(TypeFunc::Memory);
1382     const TypePtr* adr_type = nullptr;
1383     if (top_dest != nullptr && top_dest->is_flat()) {
1384       assert(dest_length != nullptr || StressReflectiveCode, "must be tightly coupled");
1385       // Copy to a flat array modifies multiple memory slices. Conservatively insert a barrier
1386       // on all slices to prevent writes into the source from floating below the arraycopy.
1387       insert_mem_bar(&ctrl, &mem, Op_MemBarCPUOrder);
1388       adr_type = adjust_for_flat_array(top_dest, src_offset, dest_offset, length, dest_elem, dest_length);
1389     } else {
1390       adr_type = dest_type->is_oopptr()->add_offset(Type::OffsetBot);
1391       if (ac->_dest_type != TypeOopPtr::BOTTOM) {
1392         adr_type = ac->_dest_type->add_offset(Type::OffsetBot)->is_ptr();
1393       }
1394       if (ac->_src_type != ac->_dest_type) {
1395         adr_type = TypeRawPtr::BOTTOM;
1396       }
1397     }
1398     merge_mem = MergeMemNode::make(mem);
1399     transform_later(merge_mem);
1400 
1401     generate_arraycopy(ac, alloc, &ctrl, merge_mem, &io,
1402                        adr_type, dest_elem,
1403                        src, src_offset, dest, dest_offset, length,
1404                        dest_length,
1405                        true, ac->has_negative_length_guard());
1406 
1407     return;
1408   }
1409 
1410   AllocateArrayNode* alloc = nullptr;
1411   if (ac->is_alloc_tightly_coupled()) {
1412     alloc = AllocateArrayNode::Ideal_array_allocation(dest);
1413     assert(alloc != nullptr, "expect alloc");
1414   }
1415 
1416   assert(ac->is_arraycopy() || ac->is_arraycopy_validated(), "should be an arraycopy");
1417 
1418   // Compile time checks.  If any of these checks cannot be verified at compile time,
1419   // we do not make a fast path for this call.  Instead, we let the call remain as it
1420   // is.  The checks we choose to mandate at compile time are:
1421   //
1422   // (1) src and dest are arrays.
1423   const Type* src_type = src->Value(&_igvn);
1424   const Type* dest_type = dest->Value(&_igvn);
1425   const TypeAryPtr* top_src = src_type->isa_aryptr();
1426   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
1427 
1428   BasicType src_elem = T_CONFLICT;
1429   BasicType dest_elem = T_CONFLICT;
1430 
1431   if (top_src != nullptr && top_src->elem() != Type::BOTTOM) {
1432     src_elem = top_src->elem()->array_element_basic_type();
1433   }
1434   if (top_dest != nullptr && top_dest->elem() != Type::BOTTOM) {
1435     dest_elem = top_dest->elem()->array_element_basic_type();
1436   }
1437   if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
1438   if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
1439 
1440   if (ac->is_arraycopy_validated() && dest_elem != T_CONFLICT && src_elem == T_CONFLICT) {
1441     src_elem = dest_elem;
1442   }
1443 
1444   if (src_elem == T_CONFLICT || dest_elem == T_CONFLICT) {
1445     // Conservatively insert a memory barrier on all memory slices.
1446     // Do not let writes into the source float below the arraycopy.
1447     {
1448       Node* mem = ac->in(TypeFunc::Memory);
1449       insert_mem_bar(&ctrl, &mem, Op_MemBarCPUOrder);
1450 
1451       merge_mem = MergeMemNode::make(mem);
1452       transform_later(merge_mem);
1453     }
1454 
1455     // Call StubRoutines::generic_arraycopy stub.
1456     generate_arraycopy(ac, nullptr, &ctrl, merge_mem, &io,
1457                        TypeRawPtr::BOTTOM, T_CONFLICT,
1458                        src, src_offset, dest, dest_offset, length,
1459                        nullptr,
1460                        // If a  negative length guard was generated for the ArrayCopyNode,
1461                        // the length of the array can never be negative.
1462                        false, ac->has_negative_length_guard());
1463     return;
1464   }
1465 
1466   assert(!ac->is_arraycopy_validated() || (src_elem == dest_elem && dest_elem != T_VOID), "validated but different basic types");
1467 
1468   // (2) src and dest arrays must have elements of the same BasicType
1469   // Figure out the size and type of the elements we will be copying.
1470   //
1471   // We have no stub to copy flat inline type arrays with oop
1472   // fields if we need to emit write barriers.
1473   //
1474   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1475   if (src_elem != dest_elem || top_src->is_flat() != top_dest->is_flat() || dest_elem == T_VOID ||
1476       (top_src->is_flat() && top_dest->elem()->inline_klass()->contains_oops() &&
1477        bs->array_copy_requires_gc_barriers(alloc != nullptr, T_OBJECT, false, false, BarrierSetC2::Optimization))) {
1478     // The component types are not the same or are not recognized.  Punt.
1479     // (But, avoid the native method wrapper to JVM_ArrayCopy.)
1480     {
1481       Node* mem = ac->in(TypeFunc::Memory);
1482       merge_mem = generate_slow_arraycopy(ac, &ctrl, mem, &io, TypePtr::BOTTOM, src, src_offset, dest, dest_offset, length, false);
1483     }
1484 
1485     _igvn.replace_node(_callprojs->fallthrough_memproj, merge_mem);
1486     if (_callprojs->fallthrough_ioproj != nullptr) {
1487       _igvn.replace_node(_callprojs->fallthrough_ioproj, io);
1488     }
1489     _igvn.replace_node(_callprojs->fallthrough_catchproj, ctrl);
1490     return;
1491   }
1492 
1493   //---------------------------------------------------------------------------
1494   // We will make a fast path for this call to arraycopy.
1495 
1496   // We have the following tests left to perform:
1497   //
1498   // (3) src and dest must not be null.
1499   // (4) src_offset must not be negative.
1500   // (5) dest_offset must not be negative.
1501   // (6) length must not be negative.
1502   // (7) src_offset + length must not exceed length of src.
1503   // (8) dest_offset + length must not exceed length of dest.
1504   // (9) each element of an oop array must be assignable
1505 
1506   Node* mem = ac->in(TypeFunc::Memory);
1507   if (top_dest->is_flat()) {
1508     // Copy to a flat array modifies multiple memory slices. Conservatively insert a barrier
1509     // on all slices to prevent writes into the source from floating below the arraycopy.
1510     insert_mem_bar(&ctrl, &mem, Op_MemBarCPUOrder);
1511   }
1512   merge_mem = MergeMemNode::make(mem);
1513   transform_later(merge_mem);
1514 
1515   RegionNode* slow_region = new RegionNode(1);
1516   transform_later(slow_region);
1517 
1518   if (!ac->is_arraycopy_validated()) {
1519     // (3) operands must not be null
1520     // We currently perform our null checks with the null_check routine.
1521     // This means that the null exceptions will be reported in the caller
1522     // rather than (correctly) reported inside of the native arraycopy call.
1523     // This should be corrected, given time.  We do our null check with the
1524     // stack pointer restored.
1525     // null checks done library_call.cpp
1526 
1527     // (4) src_offset must not be negative.
1528     generate_negative_guard(&ctrl, src_offset, slow_region);
1529 
1530     // (5) dest_offset must not be negative.
1531     generate_negative_guard(&ctrl, dest_offset, slow_region);
1532 
1533     // (6) length must not be negative (moved to generate_arraycopy()).
1534     // generate_negative_guard(length, slow_region);
1535 
1536     // (7) src_offset + length must not exceed length of src.
1537     Node* alen = ac->in(ArrayCopyNode::SrcLen);
1538     assert(alen != nullptr, "need src len");
1539     generate_limit_guard(&ctrl,
1540                          src_offset, length,
1541                          alen,
1542                          slow_region);
1543 
1544     // (8) dest_offset + length must not exceed length of dest.
1545     alen = ac->in(ArrayCopyNode::DestLen);
1546     assert(alen != nullptr, "need dest len");
1547     generate_limit_guard(&ctrl,
1548                          dest_offset, length,
1549                          alen,
1550                          slow_region);
1551 
1552     // (9) each element of an oop array must be assignable
1553     // The generate_arraycopy subroutine checks this.
1554 
1555     // TODO 8350865 Fix below logic. Also handle atomicity.
1556     // We need to be careful here because 'adjust_for_flat_array' will adjust offsets/length etc. which then does not work anymore for the slow call to SharedRuntime::slow_arraycopy_C.
1557     if (!(top_src->is_flat() && top_dest->is_flat())) {
1558       generate_flat_array_guard(&ctrl, src, merge_mem, slow_region);
1559       generate_flat_array_guard(&ctrl, dest, merge_mem, slow_region);
1560     }
1561 
1562     // Handle inline type arrays
1563     if (!top_src->is_flat()) {
1564       if (UseArrayFlattening && !top_src->is_not_flat()) {
1565         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
1566         generate_flat_array_guard(&ctrl, src, merge_mem, slow_region);
1567       }
1568       if (EnableValhalla) {
1569         // No validation. The subtype check emitted at macro expansion time will not go to the slow
1570         // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
1571         generate_null_free_array_guard(&ctrl, dest, merge_mem, slow_region);
1572       }
1573     } else {
1574       assert(top_dest->is_flat(), "dest array must be flat");
1575     }
1576   }
1577 
1578   // This is where the memory effects are placed:
1579   const TypePtr* adr_type = nullptr;
1580   Node* dest_length = (alloc != nullptr) ? alloc->in(AllocateNode::ALength) : nullptr;
1581 
1582   if (top_src->is_flat() && top_dest->is_flat()) {
1583     adr_type = adjust_for_flat_array(top_dest, src_offset, dest_offset, length, dest_elem, dest_length);
1584   } else if (ac->_dest_type != TypeOopPtr::BOTTOM) {
1585     adr_type = ac->_dest_type->add_offset(Type::OffsetBot)->is_ptr();
1586   } else {
1587     adr_type = TypeAryPtr::get_array_body_type(dest_elem);
1588   }
1589 
1590   generate_arraycopy(ac, alloc, &ctrl, merge_mem, &io,
1591                      adr_type, dest_elem,
1592                      src, src_offset, dest, dest_offset, length,
1593                      dest_length,
1594                      // If a  negative length guard was generated for the ArrayCopyNode,
1595                      // the length of the array can never be negative.
1596                      false, ac->has_negative_length_guard(),
1597                      slow_region);
1598 }