1 /*
   2  * Copyright (c) 2012, 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 "precompiled.hpp"
  26 #include "opto/arraycopynode.hpp"
  27 #include "oops/objArrayKlass.hpp"
  28 #include "opto/convertnode.hpp"
  29 #include "opto/graphKit.hpp"
  30 #include "opto/macro.hpp"
  31 #include "opto/runtime.hpp"
  32 
  33 
  34 void PhaseMacroExpand::insert_mem_bar(Node** ctrl, Node** mem, int opcode, Node* precedent) {
  35   MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);
  36   mb->init_req(TypeFunc::Control, *ctrl);
  37   mb->init_req(TypeFunc::Memory, *mem);
  38   transform_later(mb);
  39   *ctrl = new ProjNode(mb,TypeFunc::Control);
  40   transform_later(*ctrl);
  41   Node* mem_proj = new ProjNode(mb,TypeFunc::Memory);
  42   transform_later(mem_proj);
  43   *mem = mem_proj;
  44 }
  45 
  46 Node* PhaseMacroExpand::array_element_address(Node* ary, Node* idx, BasicType elembt) {
  47   uint shift  = exact_log2(type2aelembytes(elembt));
  48   uint header = arrayOopDesc::base_offset_in_bytes(elembt);
  49   Node* base =  basic_plus_adr(ary, header);
  50 #ifdef _LP64
  51   // see comment in GraphKit::array_element_address
  52   int index_max = max_jint - 1;  // array size is max_jint, index is one less
  53   const TypeLong* lidxtype = TypeLong::make(CONST64(0), index_max, Type::WidenMax);
  54   idx = transform_later( new ConvI2LNode(idx, lidxtype) );
  55 #endif
  56   Node* scale = new LShiftXNode(idx, intcon(shift));
  57   transform_later(scale);
  58   return basic_plus_adr(ary, base, scale);
  59 }
  60 
  61 Node* PhaseMacroExpand::ConvI2L(Node* offset) {
  62   return transform_later(new ConvI2LNode(offset));
  63 }
  64 
  65 Node* PhaseMacroExpand::make_leaf_call(Node* ctrl, Node* mem,
  66                                        const TypeFunc* call_type, address call_addr,
  67                                        const char* call_name,
  68                                        const TypePtr* adr_type,
  69                                        Node* parm0, Node* parm1,
  70                                        Node* parm2, Node* parm3,
  71                                        Node* parm4, Node* parm5,
  72                                        Node* parm6, Node* parm7) {
  73   int size = call_type->domain()->cnt();
  74   Node* call = new CallLeafNoFPNode(call_type, call_addr, call_name, adr_type);
  75   call->init_req(TypeFunc::Control, ctrl);
  76   call->init_req(TypeFunc::I_O    , top());
  77   call->init_req(TypeFunc::Memory , mem);
  78   call->init_req(TypeFunc::ReturnAdr, top());
  79   call->init_req(TypeFunc::FramePtr, top());
  80 
  81   // Hook each parm in order.  Stop looking at the first NULL.
  82   if (parm0 != NULL) { call->init_req(TypeFunc::Parms+0, parm0);
  83   if (parm1 != NULL) { call->init_req(TypeFunc::Parms+1, parm1);
  84   if (parm2 != NULL) { call->init_req(TypeFunc::Parms+2, parm2);
  85   if (parm3 != NULL) { call->init_req(TypeFunc::Parms+3, parm3);
  86   if (parm4 != NULL) { call->init_req(TypeFunc::Parms+4, parm4);
  87   if (parm5 != NULL) { call->init_req(TypeFunc::Parms+5, parm5);
  88   if (parm6 != NULL) { call->init_req(TypeFunc::Parms+6, parm6);
  89   if (parm7 != NULL) { call->init_req(TypeFunc::Parms+7, parm7);
  90     /* close each nested if ===> */  } } } } } } } }
  91   assert(call->in(call->req()-1) != NULL, "must initialize all parms");
  92 
  93   return call;
  94 }
  95 
  96 
  97 //------------------------------generate_guard---------------------------
  98 // Helper function for generating guarded fast-slow graph structures.
  99 // The given 'test', if true, guards a slow path.  If the test fails
 100 // then a fast path can be taken.  (We generally hope it fails.)
 101 // In all cases, GraphKit::control() is updated to the fast path.
 102 // The returned value represents the control for the slow path.
 103 // The return value is never 'top'; it is either a valid control
 104 // or NULL if it is obvious that the slow path can never be taken.
 105 // Also, if region and the slow control are not NULL, the slow edge
 106 // is appended to the region.
 107 Node* PhaseMacroExpand::generate_guard(Node** ctrl, Node* test, RegionNode* region, float true_prob) {
 108   if ((*ctrl)->is_top()) {
 109     // Already short circuited.
 110     return NULL;
 111   }
 112   // Build an if node and its projections.
 113   // If test is true we take the slow path, which we assume is uncommon.
 114   if (_igvn.type(test) == TypeInt::ZERO) {
 115     // The slow branch is never taken.  No need to build this guard.
 116     return NULL;
 117   }
 118 
 119   IfNode* iff = new IfNode(*ctrl, test, true_prob, COUNT_UNKNOWN);
 120   transform_later(iff);
 121 
 122   Node* if_slow = new IfTrueNode(iff);
 123   transform_later(if_slow);
 124 
 125   if (region != NULL) {
 126     region->add_req(if_slow);
 127   }
 128 
 129   Node* if_fast = new IfFalseNode(iff);
 130   transform_later(if_fast);
 131 
 132   *ctrl = if_fast;
 133 
 134   return if_slow;
 135 }
 136 
 137 inline Node* PhaseMacroExpand::generate_slow_guard(Node** ctrl, Node* test, RegionNode* region) {
 138   return generate_guard(ctrl, test, region, PROB_UNLIKELY_MAG(3));
 139 }
 140 
 141 void PhaseMacroExpand::generate_negative_guard(Node** ctrl, Node* index, RegionNode* region) {
 142   if ((*ctrl)->is_top())
 143     return;                // already stopped
 144   if (_igvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 145     return;                // index is already adequately typed
 146   Node* cmp_lt = new CmpINode(index, intcon(0));
 147   transform_later(cmp_lt);
 148   Node* bol_lt = new BoolNode(cmp_lt, BoolTest::lt);
 149   transform_later(bol_lt);
 150   generate_guard(ctrl, bol_lt, region, PROB_MIN);
 151 }
 152 
 153 void PhaseMacroExpand::generate_limit_guard(Node** ctrl, Node* offset, Node* subseq_length, Node* array_length, RegionNode* region) {
 154   if ((*ctrl)->is_top())
 155     return;                // already stopped
 156   bool zero_offset = _igvn.type(offset) == TypeInt::ZERO;
 157   if (zero_offset && subseq_length->eqv_uncast(array_length))
 158     return;                // common case of whole-array copy
 159   Node* last = subseq_length;
 160   if (!zero_offset) {            // last += offset
 161     last = new AddINode(last, offset);
 162     transform_later(last);
 163   }
 164   Node* cmp_lt = new CmpUNode(array_length, last);
 165   transform_later(cmp_lt);
 166   Node* bol_lt = new BoolNode(cmp_lt, BoolTest::lt);
 167   transform_later(bol_lt);
 168   generate_guard(ctrl, bol_lt, region, PROB_MIN);
 169 }
 170 
 171 Node* PhaseMacroExpand::generate_nonpositive_guard(Node** ctrl, Node* index, bool never_negative) {
 172   if ((*ctrl)->is_top())  return NULL;
 173 
 174   if (_igvn.type(index)->higher_equal(TypeInt::POS1)) // [1,maxint]
 175     return NULL;                // index is already adequately typed
 176   Node* cmp_le = new CmpINode(index, intcon(0));
 177   transform_later(cmp_le);
 178   BoolTest::mask le_or_eq = (never_negative ? BoolTest::eq : BoolTest::le);
 179   Node* bol_le = new BoolNode(cmp_le, le_or_eq);
 180   transform_later(bol_le);
 181   Node* is_notp = generate_guard(ctrl, bol_le, NULL, PROB_MIN);
 182 
 183   return is_notp;
 184 }
 185 
 186 void PhaseMacroExpand::finish_arraycopy_call(Node* call, Node** ctrl, MergeMemNode** mem, const TypePtr* adr_type) {
 187   transform_later(call);
 188 
 189   *ctrl = new ProjNode(call,TypeFunc::Control);
 190   transform_later(*ctrl);
 191   Node* newmem = new ProjNode(call, TypeFunc::Memory);
 192   transform_later(newmem);
 193 
 194   uint alias_idx = C->get_alias_index(adr_type);
 195   if (alias_idx != Compile::AliasIdxBot) {
 196     *mem = MergeMemNode::make(*mem);
 197     (*mem)->set_memory_at(alias_idx, newmem);
 198   } else {
 199     *mem = MergeMemNode::make(newmem);
 200   }
 201   transform_later(*mem);
 202 }
 203 
 204 address PhaseMacroExpand::basictype2arraycopy(BasicType t,
 205                                               Node* src_offset,
 206                                               Node* dest_offset,
 207                                               bool disjoint_bases,
 208                                               const char* &name,
 209                                               bool dest_uninitialized) {
 210   const TypeInt* src_offset_inttype  = _igvn.find_int_type(src_offset);;
 211   const TypeInt* dest_offset_inttype = _igvn.find_int_type(dest_offset);;
 212 
 213   bool aligned = false;
 214   bool disjoint = disjoint_bases;
 215 
 216   // if the offsets are the same, we can treat the memory regions as
 217   // disjoint, because either the memory regions are in different arrays,
 218   // or they are identical (which we can treat as disjoint.)  We can also
 219   // treat a copy with a destination index  less that the source index
 220   // as disjoint since a low->high copy will work correctly in this case.
 221   if (src_offset_inttype != NULL && src_offset_inttype->is_con() &&
 222       dest_offset_inttype != NULL && dest_offset_inttype->is_con()) {
 223     // both indices are constants
 224     int s_offs = src_offset_inttype->get_con();
 225     int d_offs = dest_offset_inttype->get_con();
 226     int element_size = type2aelembytes(t);
 227     aligned = ((arrayOopDesc::base_offset_in_bytes(t) + s_offs * element_size) % HeapWordSize == 0) &&
 228               ((arrayOopDesc::base_offset_in_bytes(t) + d_offs * element_size) % HeapWordSize == 0);
 229     if (s_offs >= d_offs)  disjoint = true;
 230   } else if (src_offset == dest_offset && src_offset != NULL) {
 231     // This can occur if the offsets are identical non-constants.
 232     disjoint = true;
 233   }
 234 
 235   return StubRoutines::select_arraycopy_function(t, aligned, disjoint, name, dest_uninitialized);
 236 }
 237 
 238 #define COMMA ,
 239 #define XTOP LP64_ONLY(COMMA top())
 240 
 241 // Generate an optimized call to arraycopy.
 242 // Caller must guard against non-arrays.
 243 // Caller must determine a common array basic-type for both arrays.
 244 // Caller must validate offsets against array bounds.
 245 // The slow_region has already collected guard failure paths
 246 // (such as out of bounds length or non-conformable array types).
 247 // The generated code has this shape, in general:
 248 //
 249 //     if (length == 0)  return   // via zero_path
 250 //     slowval = -1
 251 //     if (types unknown) {
 252 //       slowval = call generic copy loop
 253 //       if (slowval == 0)  return  // via checked_path
 254 //     } else if (indexes in bounds) {
 255 //       if ((is object array) && !(array type check)) {
 256 //         slowval = call checked copy loop
 257 //         if (slowval == 0)  return  // via checked_path
 258 //       } else {
 259 //         call bulk copy loop
 260 //         return  // via fast_path
 261 //       }
 262 //     }
 263 //     // adjust params for remaining work:
 264 //     if (slowval != -1) {
 265 //       n = -1^slowval; src_offset += n; dest_offset += n; length -= n
 266 //     }
 267 //   slow_region:
 268 //     call slow arraycopy(src, src_offset, dest, dest_offset, length)
 269 //     return  // via slow_call_path
 270 //
 271 // This routine is used from several intrinsics:  System.arraycopy,
 272 // Object.clone (the array subcase), and Arrays.copyOf[Range].
 273 //
 274 Node* PhaseMacroExpand::generate_arraycopy(ArrayCopyNode *ac, AllocateArrayNode* alloc,
 275                                            Node** ctrl, MergeMemNode* mem, Node** io,
 276                                            const TypePtr* adr_type,
 277                                            BasicType basic_elem_type,
 278                                            Node* src,  Node* src_offset,
 279                                            Node* dest, Node* dest_offset,
 280                                            Node* copy_length,
 281                                            bool disjoint_bases,
 282                                            bool length_never_negative,
 283                                            RegionNode* slow_region) {
 284   if (slow_region == NULL) {
 285     slow_region = new RegionNode(1);
 286     transform_later(slow_region);
 287   }
 288 
 289   Node* original_dest      = dest;
 290   bool  dest_uninitialized = false;
 291 
 292   // See if this is the initialization of a newly-allocated array.
 293   // If so, we will take responsibility here for initializing it to zero.
 294   // (Note:  Because tightly_coupled_allocation performs checks on the
 295   // out-edges of the dest, we need to avoid making derived pointers
 296   // from it until we have checked its uses.)
 297   if (ReduceBulkZeroing
 298       && !ZeroTLAB              // pointless if already zeroed
 299       && basic_elem_type != T_CONFLICT // avoid corner case
 300       && !src->eqv_uncast(dest)
 301       && alloc != NULL
 302       && _igvn.find_int_con(alloc->in(AllocateNode::ALength), 1) > 0
 303       && alloc->maybe_set_complete(&_igvn)) {
 304     // "You break it, you buy it."
 305     InitializeNode* init = alloc->initialization();
 306     assert(init->is_complete(), "we just did this");
 307     init->set_complete_with_arraycopy();
 308     assert(dest->is_CheckCastPP(), "sanity");
 309     assert(dest->in(0)->in(0) == init, "dest pinned");
 310     adr_type = TypeRawPtr::BOTTOM;  // all initializations are into raw memory
 311     // From this point on, every exit path is responsible for
 312     // initializing any non-copied parts of the object to zero.
 313     // Also, if this flag is set we make sure that arraycopy interacts properly
 314     // with G1, eliding pre-barriers. See CR 6627983.
 315     dest_uninitialized = true;
 316   } else {
 317     // No zeroing elimination here.
 318     alloc             = NULL;
 319     //original_dest   = dest;
 320     //dest_uninitialized = false;
 321   }
 322 
 323   uint alias_idx = C->get_alias_index(adr_type);
 324 
 325   // Results are placed here:
 326   enum { fast_path        = 1,  // normal void-returning assembly stub
 327          checked_path     = 2,  // special assembly stub with cleanup
 328          slow_call_path   = 3,  // something went wrong; call the VM
 329          zero_path        = 4,  // bypass when length of copy is zero
 330          bcopy_path       = 5,  // copy primitive array by 64-bit blocks
 331          PATH_LIMIT       = 6
 332   };
 333   RegionNode* result_region = new RegionNode(PATH_LIMIT);
 334   PhiNode*    result_i_o    = new PhiNode(result_region, Type::ABIO);
 335   PhiNode*    result_memory = new PhiNode(result_region, Type::MEMORY, adr_type);
 336   assert(adr_type != TypePtr::BOTTOM, "must be RawMem or a T[] slice");
 337   transform_later(result_region);
 338   transform_later(result_i_o);
 339   transform_later(result_memory);
 340 
 341   // The slow_control path:
 342   Node* slow_control;
 343   Node* slow_i_o = *io;
 344   Node* slow_mem = mem->memory_at(alias_idx);
 345   DEBUG_ONLY(slow_control = (Node*) badAddress);
 346 
 347   // Checked control path:
 348   Node* checked_control = top();
 349   Node* checked_mem     = NULL;
 350   Node* checked_i_o     = NULL;
 351   Node* checked_value   = NULL;
 352 
 353   if (basic_elem_type == T_CONFLICT) {
 354     assert(!dest_uninitialized, "");
 355     Node* cv = generate_generic_arraycopy(ctrl, &mem,
 356                                           adr_type,
 357                                           src, src_offset, dest, dest_offset,
 358                                           copy_length, dest_uninitialized);
 359     if (cv == NULL)  cv = intcon(-1);  // failure (no stub available)
 360     checked_control = *ctrl;
 361     checked_i_o     = *io;
 362     checked_mem     = mem->memory_at(alias_idx);
 363     checked_value   = cv;
 364     *ctrl = top();
 365   }
 366 
 367   Node* not_pos = generate_nonpositive_guard(ctrl, copy_length, length_never_negative);
 368   if (not_pos != NULL) {
 369     Node* local_ctrl = not_pos, *local_io = *io;
 370     MergeMemNode* local_mem = MergeMemNode::make(mem);
 371     transform_later(local_mem);
 372 
 373     // (6) length must not be negative.
 374     if (!length_never_negative) {
 375       generate_negative_guard(&local_ctrl, copy_length, slow_region);
 376     }
 377 
 378     // copy_length is 0.
 379     if (dest_uninitialized) {
 380       assert(!local_ctrl->is_top(), "no ctrl?");
 381       Node* dest_length = alloc->in(AllocateNode::ALength);
 382       if (copy_length->eqv_uncast(dest_length)
 383           || _igvn.find_int_con(dest_length, 1) <= 0) {
 384         // There is no zeroing to do. No need for a secondary raw memory barrier.
 385       } else {
 386         // Clear the whole thing since there are no source elements to copy.
 387         generate_clear_array(local_ctrl, local_mem,
 388                              adr_type, dest, basic_elem_type,
 389                              intcon(0), NULL,
 390                              alloc->in(AllocateNode::AllocSize));
 391         // Use a secondary InitializeNode as raw memory barrier.
 392         // Currently it is needed only on this path since other
 393         // paths have stub or runtime calls as raw memory barriers.
 394         MemBarNode* mb = MemBarNode::make(C, Op_Initialize,
 395                                           Compile::AliasIdxRaw,
 396                                           top());
 397         transform_later(mb);
 398         mb->set_req(TypeFunc::Control,local_ctrl);
 399         mb->set_req(TypeFunc::Memory, local_mem->memory_at(Compile::AliasIdxRaw));
 400         local_ctrl = transform_later(new ProjNode(mb, TypeFunc::Control));
 401         local_mem->set_memory_at(Compile::AliasIdxRaw, transform_later(new ProjNode(mb, TypeFunc::Memory)));
 402 
 403         InitializeNode* init = mb->as_Initialize();
 404         init->set_complete(&_igvn);  // (there is no corresponding AllocateNode)
 405       }
 406     }
 407 
 408     // Present the results of the fast call.
 409     result_region->init_req(zero_path, local_ctrl);
 410     result_i_o   ->init_req(zero_path, local_io);
 411     result_memory->init_req(zero_path, local_mem->memory_at(alias_idx));
 412   }
 413 
 414   if (!(*ctrl)->is_top() && dest_uninitialized) {
 415     // We have to initialize the *uncopied* part of the array to zero.
 416     // The copy destination is the slice dest[off..off+len].  The other slices
 417     // are dest_head = dest[0..off] and dest_tail = dest[off+len..dest.length].
 418     Node* dest_size   = alloc->in(AllocateNode::AllocSize);
 419     Node* dest_length = alloc->in(AllocateNode::ALength);
 420     Node* dest_tail   = transform_later( new AddINode(dest_offset, copy_length));
 421 
 422     // If there is a head section that needs zeroing, do it now.
 423     if (_igvn.find_int_con(dest_offset, -1) != 0) {
 424       generate_clear_array(*ctrl, mem,
 425                            adr_type, dest, basic_elem_type,
 426                            intcon(0), dest_offset,
 427                            NULL);
 428     }
 429 
 430     // Next, perform a dynamic check on the tail length.
 431     // It is often zero, and we can win big if we prove this.
 432     // There are two wins:  Avoid generating the ClearArray
 433     // with its attendant messy index arithmetic, and upgrade
 434     // the copy to a more hardware-friendly word size of 64 bits.
 435     Node* tail_ctl = NULL;
 436     if (!(*ctrl)->is_top() && !dest_tail->eqv_uncast(dest_length)) {
 437       Node* cmp_lt   = transform_later( new CmpINode(dest_tail, dest_length) );
 438       Node* bol_lt   = transform_later( new BoolNode(cmp_lt, BoolTest::lt) );
 439       tail_ctl = generate_slow_guard(ctrl, bol_lt, NULL);
 440       assert(tail_ctl != NULL || !(*ctrl)->is_top(), "must be an outcome");
 441     }
 442 
 443     // At this point, let's assume there is no tail.
 444     if (!(*ctrl)->is_top() && alloc != NULL && basic_elem_type != T_OBJECT) {
 445       // There is no tail.  Try an upgrade to a 64-bit copy.
 446       bool didit = false;
 447       {
 448         Node* local_ctrl = *ctrl, *local_io = *io;
 449         MergeMemNode* local_mem = MergeMemNode::make(mem);
 450         transform_later(local_mem);
 451 
 452         didit = generate_block_arraycopy(&local_ctrl, &local_mem, local_io,
 453                                          adr_type, basic_elem_type, alloc,
 454                                          src, src_offset, dest, dest_offset,
 455                                          dest_size, dest_uninitialized);
 456         if (didit) {
 457           // Present the results of the block-copying fast call.
 458           result_region->init_req(bcopy_path, local_ctrl);
 459           result_i_o   ->init_req(bcopy_path, local_io);
 460           result_memory->init_req(bcopy_path, local_mem->memory_at(alias_idx));
 461         }
 462       }
 463       if (didit) {
 464         *ctrl = top();     // no regular fast path
 465       }
 466     }
 467 
 468     // Clear the tail, if any.
 469     if (tail_ctl != NULL) {
 470       Node* notail_ctl = (*ctrl)->is_top() ? NULL : *ctrl;
 471       *ctrl = tail_ctl;
 472       if (notail_ctl == NULL) {
 473         generate_clear_array(*ctrl, mem,
 474                              adr_type, dest, basic_elem_type,
 475                              dest_tail, NULL,
 476                              dest_size);
 477       } else {
 478         // Make a local merge.
 479         Node* done_ctl = transform_later(new RegionNode(3));
 480         Node* done_mem = transform_later(new PhiNode(done_ctl, Type::MEMORY, adr_type));
 481         done_ctl->init_req(1, notail_ctl);
 482         done_mem->init_req(1, mem->memory_at(alias_idx));
 483         generate_clear_array(*ctrl, mem,
 484                              adr_type, dest, basic_elem_type,
 485                              dest_tail, NULL,
 486                              dest_size);
 487         done_ctl->init_req(2, *ctrl);
 488         done_mem->init_req(2, mem->memory_at(alias_idx));
 489         *ctrl = done_ctl;
 490         mem->set_memory_at(alias_idx, done_mem);
 491       }
 492     }
 493   }
 494 
 495   BasicType copy_type = basic_elem_type;
 496   assert(basic_elem_type != T_ARRAY, "caller must fix this");
 497   if (!(*ctrl)->is_top() && copy_type == T_OBJECT) {
 498     // If src and dest have compatible element types, we can copy bits.
 499     // Types S[] and D[] are compatible if D is a supertype of S.
 500     //
 501     // If they are not, we will use checked_oop_disjoint_arraycopy,
 502     // which performs a fast optimistic per-oop check, and backs off
 503     // further to JVM_ArrayCopy on the first per-oop check that fails.
 504     // (Actually, we don't move raw bits only; the GC requires card marks.)
 505 
 506     // Get the klass* for both src and dest
 507     Node* src_klass  = ac->in(ArrayCopyNode::SrcKlass);
 508     Node* dest_klass = ac->in(ArrayCopyNode::DestKlass);
 509 
 510     assert(src_klass != NULL && dest_klass != NULL, "should have klasses");
 511 
 512     // Generate the subtype check.
 513     // This might fold up statically, or then again it might not.
 514     //
 515     // Non-static example:  Copying List<String>.elements to a new String[].
 516     // The backing store for a List<String> is always an Object[],
 517     // but its elements are always type String, if the generic types
 518     // are correct at the source level.
 519     //
 520     // Test S[] against D[], not S against D, because (probably)
 521     // the secondary supertype cache is less busy for S[] than S.
 522     // This usually only matters when D is an interface.
 523     Node* not_subtype_ctrl = (ac->is_arraycopy_validated() || ac->is_copyof_validated() || ac->is_copyofrange_validated()) ? top() :
 524       Phase::gen_subtype_check(src_klass, dest_klass, ctrl, mem, &_igvn);
 525     // Plug failing path into checked_oop_disjoint_arraycopy
 526     if (not_subtype_ctrl != top()) {
 527       Node* local_ctrl = not_subtype_ctrl;
 528       MergeMemNode* local_mem = MergeMemNode::make(mem);
 529       transform_later(local_mem);
 530 
 531       // (At this point we can assume disjoint_bases, since types differ.)
 532       int ek_offset = in_bytes(ObjArrayKlass::element_klass_offset());
 533       Node* p1 = basic_plus_adr(dest_klass, ek_offset);
 534       Node* n1 = LoadKlassNode::make(_igvn, NULL, C->immutable_memory(), p1, TypeRawPtr::BOTTOM);
 535       Node* dest_elem_klass = transform_later(n1);
 536       Node* cv = generate_checkcast_arraycopy(&local_ctrl, &local_mem,
 537                                               adr_type,
 538                                               dest_elem_klass,
 539                                               src, src_offset, dest, dest_offset,
 540                                               ConvI2X(copy_length), dest_uninitialized);
 541       if (cv == NULL)  cv = intcon(-1);  // failure (no stub available)
 542       checked_control = local_ctrl;
 543       checked_i_o     = *io;
 544       checked_mem     = local_mem->memory_at(alias_idx);
 545       checked_value   = cv;
 546     }
 547     // At this point we know we do not need type checks on oop stores.
 548 
 549     // Let's see if we need card marks:
 550     if (alloc != NULL && GraphKit::use_ReduceInitialCardMarks()) {
 551       // If we do not need card marks, copy using the jint or jlong stub.
 552       copy_type = LP64_ONLY(UseCompressedOops ? T_INT : T_LONG) NOT_LP64(T_INT);
 553       assert(type2aelembytes(basic_elem_type) == type2aelembytes(copy_type),
 554              "sizes agree");
 555     }
 556   }
 557 
 558   if (!(*ctrl)->is_top()) {
 559     // Generate the fast path, if possible.
 560     Node* local_ctrl = *ctrl;
 561     MergeMemNode* local_mem = MergeMemNode::make(mem);
 562     transform_later(local_mem);
 563 
 564     generate_unchecked_arraycopy(&local_ctrl, &local_mem,
 565                                  adr_type, copy_type, disjoint_bases,
 566                                  src, src_offset, dest, dest_offset,
 567                                  ConvI2X(copy_length), dest_uninitialized);
 568 
 569     // Present the results of the fast call.
 570     result_region->init_req(fast_path, local_ctrl);
 571     result_i_o   ->init_req(fast_path, *io);
 572     result_memory->init_req(fast_path, local_mem->memory_at(alias_idx));
 573   }
 574 
 575   // Here are all the slow paths up to this point, in one bundle:
 576   assert(slow_region != NULL, "allocated on entry");
 577   slow_control = slow_region;
 578   DEBUG_ONLY(slow_region = (RegionNode*)badAddress);
 579 
 580   *ctrl = checked_control;
 581   if (!(*ctrl)->is_top()) {
 582     // Clean up after the checked call.
 583     // The returned value is either 0 or -1^K,
 584     // where K = number of partially transferred array elements.
 585     Node* cmp = new CmpINode(checked_value, intcon(0));
 586     transform_later(cmp);
 587     Node* bol = new BoolNode(cmp, BoolTest::eq);
 588     transform_later(bol);
 589     IfNode* iff = new IfNode(*ctrl, bol, PROB_MAX, COUNT_UNKNOWN);
 590     transform_later(iff);
 591 
 592     // If it is 0, we are done, so transfer to the end.
 593     Node* checks_done = new IfTrueNode(iff);
 594     transform_later(checks_done);
 595     result_region->init_req(checked_path, checks_done);
 596     result_i_o   ->init_req(checked_path, checked_i_o);
 597     result_memory->init_req(checked_path, checked_mem);
 598 
 599     // If it is not zero, merge into the slow call.
 600     *ctrl = new IfFalseNode(iff);
 601     transform_later(*ctrl);
 602     RegionNode* slow_reg2 = new RegionNode(3);
 603     PhiNode*    slow_i_o2 = new PhiNode(slow_reg2, Type::ABIO);
 604     PhiNode*    slow_mem2 = new PhiNode(slow_reg2, Type::MEMORY, adr_type);
 605     transform_later(slow_reg2);
 606     transform_later(slow_i_o2);
 607     transform_later(slow_mem2);
 608     slow_reg2  ->init_req(1, slow_control);
 609     slow_i_o2  ->init_req(1, slow_i_o);
 610     slow_mem2  ->init_req(1, slow_mem);
 611     slow_reg2  ->init_req(2, *ctrl);
 612     slow_i_o2  ->init_req(2, checked_i_o);
 613     slow_mem2  ->init_req(2, checked_mem);
 614 
 615     slow_control = slow_reg2;
 616     slow_i_o     = slow_i_o2;
 617     slow_mem     = slow_mem2;
 618 
 619     if (alloc != NULL) {
 620       // We'll restart from the very beginning, after zeroing the whole thing.
 621       // This can cause double writes, but that's OK since dest is brand new.
 622       // So we ignore the low 31 bits of the value returned from the stub.
 623     } else {
 624       // We must continue the copy exactly where it failed, or else
 625       // another thread might see the wrong number of writes to dest.
 626       Node* checked_offset = new XorINode(checked_value, intcon(-1));
 627       Node* slow_offset    = new PhiNode(slow_reg2, TypeInt::INT);
 628       transform_later(checked_offset);
 629       transform_later(slow_offset);
 630       slow_offset->init_req(1, intcon(0));
 631       slow_offset->init_req(2, checked_offset);
 632 
 633       // Adjust the arguments by the conditionally incoming offset.
 634       Node* src_off_plus  = new AddINode(src_offset,  slow_offset);
 635       transform_later(src_off_plus);
 636       Node* dest_off_plus = new AddINode(dest_offset, slow_offset);
 637       transform_later(dest_off_plus);
 638       Node* length_minus  = new SubINode(copy_length, slow_offset);
 639       transform_later(length_minus);
 640 
 641       // Tweak the node variables to adjust the code produced below:
 642       src_offset  = src_off_plus;
 643       dest_offset = dest_off_plus;
 644       copy_length = length_minus;
 645     }
 646   }
 647   *ctrl = slow_control;
 648   if (!(*ctrl)->is_top()) {
 649     Node* local_ctrl = *ctrl, *local_io = slow_i_o;
 650     MergeMemNode* local_mem = MergeMemNode::make(mem);
 651     transform_later(local_mem);
 652 
 653     // Generate the slow path, if needed.
 654     local_mem->set_memory_at(alias_idx, slow_mem);
 655 
 656     if (dest_uninitialized) {
 657       generate_clear_array(local_ctrl, local_mem,
 658                            adr_type, dest, basic_elem_type,
 659                            intcon(0), NULL,
 660                            alloc->in(AllocateNode::AllocSize));
 661     }
 662 
 663     local_mem = generate_slow_arraycopy(ac,
 664                                         &local_ctrl, local_mem, &local_io,
 665                                         adr_type,
 666                                         src, src_offset, dest, dest_offset,
 667                                         copy_length, /*dest_uninitialized*/false);
 668 
 669     result_region->init_req(slow_call_path, local_ctrl);
 670     result_i_o   ->init_req(slow_call_path, local_io);
 671     result_memory->init_req(slow_call_path, local_mem->memory_at(alias_idx));
 672   } else {
 673     ShouldNotReachHere(); // no call to generate_slow_arraycopy:
 674                           // projections were not extracted
 675   }
 676 
 677   // Remove unused edges.
 678   for (uint i = 1; i < result_region->req(); i++) {
 679     if (result_region->in(i) == NULL) {
 680       result_region->init_req(i, top());
 681     }
 682   }
 683 
 684   // Finished; return the combined state.
 685   *ctrl = result_region;
 686   *io = result_i_o;
 687   mem->set_memory_at(alias_idx, result_memory);
 688 
 689   // mem no longer guaranteed to stay a MergeMemNode
 690   Node* out_mem = mem;
 691   DEBUG_ONLY(mem = NULL);
 692 
 693   // The memory edges above are precise in order to model effects around
 694   // array copies accurately to allow value numbering of field loads around
 695   // arraycopy.  Such field loads, both before and after, are common in Java
 696   // collections and similar classes involving header/array data structures.
 697   //
 698   // But with low number of register or when some registers are used or killed
 699   // by arraycopy calls it causes registers spilling on stack. See 6544710.
 700   // The next memory barrier is added to avoid it. If the arraycopy can be
 701   // optimized away (which it can, sometimes) then we can manually remove
 702   // the membar also.
 703   //
 704   // Do not let reads from the cloned object float above the arraycopy.
 705   if (alloc != NULL && !alloc->initialization()->does_not_escape()) {
 706     // Do not let stores that initialize this object be reordered with
 707     // a subsequent store that would make this object accessible by
 708     // other threads.
 709     insert_mem_bar(ctrl, &out_mem, Op_MemBarStoreStore);
 710   } else if (InsertMemBarAfterArraycopy) {
 711     insert_mem_bar(ctrl, &out_mem, Op_MemBarCPUOrder);
 712   }
 713 
 714   _igvn.replace_node(_memproj_fallthrough, out_mem);
 715   _igvn.replace_node(_ioproj_fallthrough, *io);
 716   _igvn.replace_node(_fallthroughcatchproj, *ctrl);
 717 
 718   return out_mem;
 719 }
 720 
 721 // Helper for initialization of arrays, creating a ClearArray.
 722 // It writes zero bits in [start..end), within the body of an array object.
 723 // The memory effects are all chained onto the 'adr_type' alias category.
 724 //
 725 // Since the object is otherwise uninitialized, we are free
 726 // to put a little "slop" around the edges of the cleared area,
 727 // as long as it does not go back into the array's header,
 728 // or beyond the array end within the heap.
 729 //
 730 // The lower edge can be rounded down to the nearest jint and the
 731 // upper edge can be rounded up to the nearest MinObjAlignmentInBytes.
 732 //
 733 // Arguments:
 734 //   adr_type           memory slice where writes are generated
 735 //   dest               oop of the destination array
 736 //   basic_elem_type    element type of the destination
 737 //   slice_idx          array index of first element to store
 738 //   slice_len          number of elements to store (or NULL)
 739 //   dest_size          total size in bytes of the array object
 740 //
 741 // Exactly one of slice_len or dest_size must be non-NULL.
 742 // If dest_size is non-NULL, zeroing extends to the end of the object.
 743 // If slice_len is non-NULL, the slice_idx value must be a constant.
 744 void PhaseMacroExpand::generate_clear_array(Node* ctrl, MergeMemNode* merge_mem,
 745                                             const TypePtr* adr_type,
 746                                             Node* dest,
 747                                             BasicType basic_elem_type,
 748                                             Node* slice_idx,
 749                                             Node* slice_len,
 750                                             Node* dest_size) {
 751   // one or the other but not both of slice_len and dest_size:
 752   assert((slice_len != NULL? 1: 0) + (dest_size != NULL? 1: 0) == 1, "");
 753   if (slice_len == NULL)  slice_len = top();
 754   if (dest_size == NULL)  dest_size = top();
 755 
 756   uint alias_idx = C->get_alias_index(adr_type);
 757 
 758   // operate on this memory slice:
 759   Node* mem = merge_mem->memory_at(alias_idx); // memory slice to operate on
 760 
 761   // scaling and rounding of indexes:
 762   int scale = exact_log2(type2aelembytes(basic_elem_type));
 763   int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
 764   int clear_low = (-1 << scale) & (BytesPerInt  - 1);
 765   int bump_bit  = (-1 << scale) & BytesPerInt;
 766 
 767   // determine constant starts and ends
 768   const intptr_t BIG_NEG = -128;
 769   assert(BIG_NEG + 2*abase < 0, "neg enough");
 770   intptr_t slice_idx_con = (intptr_t) _igvn.find_int_con(slice_idx, BIG_NEG);
 771   intptr_t slice_len_con = (intptr_t) _igvn.find_int_con(slice_len, BIG_NEG);
 772   if (slice_len_con == 0) {
 773     return;                     // nothing to do here
 774   }
 775   intptr_t start_con = (abase + (slice_idx_con << scale)) & ~clear_low;
 776   intptr_t end_con   = _igvn.find_intptr_t_con(dest_size, -1);
 777   if (slice_idx_con >= 0 && slice_len_con >= 0) {
 778     assert(end_con < 0, "not two cons");
 779     end_con = round_to(abase + ((slice_idx_con + slice_len_con) << scale),
 780                        BytesPerLong);
 781   }
 782 
 783   if (start_con >= 0 && end_con >= 0) {
 784     // Constant start and end.  Simple.
 785     mem = ClearArrayNode::clear_memory(ctrl, mem, dest,
 786                                        start_con, end_con, &_igvn);
 787   } else if (start_con >= 0 && dest_size != top()) {
 788     // Constant start, pre-rounded end after the tail of the array.
 789     Node* end = dest_size;
 790     mem = ClearArrayNode::clear_memory(ctrl, mem, dest,
 791                                        start_con, end, &_igvn);
 792   } else if (start_con >= 0 && slice_len != top()) {
 793     // Constant start, non-constant end.  End needs rounding up.
 794     // End offset = round_up(abase + ((slice_idx_con + slice_len) << scale), 8)
 795     intptr_t end_base  = abase + (slice_idx_con << scale);
 796     int      end_round = (-1 << scale) & (BytesPerLong  - 1);
 797     Node*    end       = ConvI2X(slice_len);
 798     if (scale != 0)
 799       end = transform_later(new LShiftXNode(end, intcon(scale) ));
 800     end_base += end_round;
 801     end = transform_later(new AddXNode(end, MakeConX(end_base)) );
 802     end = transform_later(new AndXNode(end, MakeConX(~end_round)) );
 803     mem = ClearArrayNode::clear_memory(ctrl, mem, dest,
 804                                        start_con, end, &_igvn);
 805   } else if (start_con < 0 && dest_size != top()) {
 806     // Non-constant start, pre-rounded end after the tail of the array.
 807     // This is almost certainly a "round-to-end" operation.
 808     Node* start = slice_idx;
 809     start = ConvI2X(start);
 810     if (scale != 0)
 811       start = transform_later(new LShiftXNode( start, intcon(scale) ));
 812     start = transform_later(new AddXNode(start, MakeConX(abase)) );
 813     if ((bump_bit | clear_low) != 0) {
 814       int to_clear = (bump_bit | clear_low);
 815       // Align up mod 8, then store a jint zero unconditionally
 816       // just before the mod-8 boundary.
 817       if (((abase + bump_bit) & ~to_clear) - bump_bit
 818           < arrayOopDesc::length_offset_in_bytes() + BytesPerInt) {
 819         bump_bit = 0;
 820         assert((abase & to_clear) == 0, "array base must be long-aligned");
 821       } else {
 822         // Bump 'start' up to (or past) the next jint boundary:
 823         start = transform_later( new AddXNode(start, MakeConX(bump_bit)) );
 824         assert((abase & clear_low) == 0, "array base must be int-aligned");
 825       }
 826       // Round bumped 'start' down to jlong boundary in body of array.
 827       start = transform_later(new AndXNode(start, MakeConX(~to_clear)) );
 828       if (bump_bit != 0) {
 829         // Store a zero to the immediately preceding jint:
 830         Node* x1 = transform_later(new AddXNode(start, MakeConX(-bump_bit)) );
 831         Node* p1 = basic_plus_adr(dest, x1);
 832         mem = StoreNode::make(_igvn, ctrl, mem, p1, adr_type, intcon(0), T_INT, MemNode::unordered);
 833         mem = transform_later(mem);
 834       }
 835     }
 836     Node* end = dest_size; // pre-rounded
 837     mem = ClearArrayNode::clear_memory(ctrl, mem, dest,
 838                                        start, end, &_igvn);
 839   } else {
 840     // Non-constant start, unrounded non-constant end.
 841     // (Nobody zeroes a random midsection of an array using this routine.)
 842     ShouldNotReachHere();       // fix caller
 843   }
 844 
 845   // Done.
 846   merge_mem->set_memory_at(alias_idx, mem);
 847 }
 848 
 849 bool PhaseMacroExpand::generate_block_arraycopy(Node** ctrl, MergeMemNode** mem, Node* io,
 850                                                 const TypePtr* adr_type,
 851                                                 BasicType basic_elem_type,
 852                                                 AllocateNode* alloc,
 853                                                 Node* src,  Node* src_offset,
 854                                                 Node* dest, Node* dest_offset,
 855                                                 Node* dest_size, bool dest_uninitialized) {
 856   // See if there is an advantage from block transfer.
 857   int scale = exact_log2(type2aelembytes(basic_elem_type));
 858   if (scale >= LogBytesPerLong)
 859     return false;               // it is already a block transfer
 860 
 861   // Look at the alignment of the starting offsets.
 862   int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
 863 
 864   intptr_t src_off_con  = (intptr_t) _igvn.find_int_con(src_offset, -1);
 865   intptr_t dest_off_con = (intptr_t) _igvn.find_int_con(dest_offset, -1);
 866   if (src_off_con < 0 || dest_off_con < 0) {
 867     // At present, we can only understand constants.
 868     return false;
 869   }
 870 
 871   intptr_t src_off  = abase + (src_off_con  << scale);
 872   intptr_t dest_off = abase + (dest_off_con << scale);
 873 
 874   if (((src_off | dest_off) & (BytesPerLong-1)) != 0) {
 875     // Non-aligned; too bad.
 876     // One more chance:  Pick off an initial 32-bit word.
 877     // This is a common case, since abase can be odd mod 8.
 878     if (((src_off | dest_off) & (BytesPerLong-1)) == BytesPerInt &&
 879         ((src_off ^ dest_off) & (BytesPerLong-1)) == 0) {
 880       Node* sptr = basic_plus_adr(src,  src_off);
 881       Node* dptr = basic_plus_adr(dest, dest_off);
 882       uint alias_idx = C->get_alias_index(adr_type);
 883       Node* sval = transform_later(LoadNode::make(_igvn, *ctrl, (*mem)->memory_at(alias_idx), sptr, adr_type, TypeInt::INT, T_INT, MemNode::unordered));
 884       Node* st = transform_later(StoreNode::make(_igvn, *ctrl, (*mem)->memory_at(alias_idx), dptr, adr_type, sval, T_INT, MemNode::unordered));
 885       (*mem)->set_memory_at(alias_idx, st);
 886       src_off += BytesPerInt;
 887       dest_off += BytesPerInt;
 888     } else {
 889       return false;
 890     }
 891   }
 892   assert(src_off % BytesPerLong == 0, "");
 893   assert(dest_off % BytesPerLong == 0, "");
 894 
 895   // Do this copy by giant steps.
 896   Node* sptr  = basic_plus_adr(src,  src_off);
 897   Node* dptr  = basic_plus_adr(dest, dest_off);
 898   Node* countx = dest_size;
 899   countx = transform_later(new SubXNode(countx, MakeConX(dest_off)));
 900   countx = transform_later(new URShiftXNode(countx, intcon(LogBytesPerLong)));
 901 
 902   bool disjoint_bases = true;   // since alloc != NULL
 903   generate_unchecked_arraycopy(ctrl, mem,
 904                                adr_type, T_LONG, disjoint_bases,
 905                                sptr, NULL, dptr, NULL, countx, dest_uninitialized);
 906 
 907   return true;
 908 }
 909 
 910 // Helper function; generates code for the slow case.
 911 // We make a call to a runtime method which emulates the native method,
 912 // but without the native wrapper overhead.
 913 MergeMemNode* PhaseMacroExpand::generate_slow_arraycopy(ArrayCopyNode *ac,
 914                                                         Node** ctrl, Node* mem, Node** io,
 915                                                         const TypePtr* adr_type,
 916                                                         Node* src,  Node* src_offset,
 917                                                         Node* dest, Node* dest_offset,
 918                                                         Node* copy_length, bool dest_uninitialized) {
 919   assert(!dest_uninitialized, "Invariant");
 920 
 921   const TypeFunc* call_type = OptoRuntime::slow_arraycopy_Type();
 922   CallNode* call = new CallStaticJavaNode(call_type, OptoRuntime::slow_arraycopy_Java(),
 923                                           "slow_arraycopy",
 924                                           ac->jvms()->bci(), TypePtr::BOTTOM);
 925 
 926   call->init_req(TypeFunc::Control, *ctrl);
 927   call->init_req(TypeFunc::I_O    , *io);
 928   call->init_req(TypeFunc::Memory , mem);
 929   call->init_req(TypeFunc::ReturnAdr, top());
 930   call->init_req(TypeFunc::FramePtr, top());
 931   call->init_req(TypeFunc::Parms+0, src);
 932   call->init_req(TypeFunc::Parms+1, src_offset);
 933   call->init_req(TypeFunc::Parms+2, dest);
 934   call->init_req(TypeFunc::Parms+3, dest_offset);
 935   call->init_req(TypeFunc::Parms+4, copy_length);
 936   copy_call_debug_info(ac, call);
 937 
 938   call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
 939   _igvn.replace_node(ac, call);
 940   transform_later(call);
 941 
 942   extract_call_projections(call);
 943   *ctrl = _fallthroughcatchproj->clone();
 944   transform_later(*ctrl);
 945 
 946   Node* m = _memproj_fallthrough->clone();
 947   transform_later(m);
 948 
 949   uint alias_idx = C->get_alias_index(adr_type);
 950   MergeMemNode* out_mem;
 951   if (alias_idx != Compile::AliasIdxBot) {
 952     out_mem = MergeMemNode::make(mem);
 953     out_mem->set_memory_at(alias_idx, m);
 954   } else {
 955     out_mem = MergeMemNode::make(m);
 956   }
 957   transform_later(out_mem);
 958 
 959   *io = _ioproj_fallthrough->clone();
 960   transform_later(*io);
 961 
 962   return out_mem;
 963 }
 964 
 965 // Helper function; generates code for cases requiring runtime checks.
 966 Node* PhaseMacroExpand::generate_checkcast_arraycopy(Node** ctrl, MergeMemNode** mem,
 967                                                      const TypePtr* adr_type,
 968                                                      Node* dest_elem_klass,
 969                                                      Node* src,  Node* src_offset,
 970                                                      Node* dest, Node* dest_offset,
 971                                                      Node* copy_length, bool dest_uninitialized) {
 972   if ((*ctrl)->is_top())  return NULL;
 973 
 974   address copyfunc_addr = StubRoutines::checkcast_arraycopy(dest_uninitialized);
 975   if (copyfunc_addr == NULL) { // Stub was not generated, go slow path.
 976     return NULL;
 977   }
 978 
 979   // Pick out the parameters required to perform a store-check
 980   // for the target array.  This is an optimistic check.  It will
 981   // look in each non-null element's class, at the desired klass's
 982   // super_check_offset, for the desired klass.
 983   int sco_offset = in_bytes(Klass::super_check_offset_offset());
 984   Node* p3 = basic_plus_adr(dest_elem_klass, sco_offset);
 985   Node* n3 = new LoadINode(NULL, *mem /*memory(p3)*/, p3, _igvn.type(p3)->is_ptr(), TypeInt::INT, MemNode::unordered);
 986   Node* check_offset = ConvI2X(transform_later(n3));
 987   Node* check_value  = dest_elem_klass;
 988 
 989   Node* src_start  = array_element_address(src,  src_offset,  T_OBJECT);
 990   Node* dest_start = array_element_address(dest, dest_offset, T_OBJECT);
 991 
 992   const TypeFunc* call_type = OptoRuntime::checkcast_arraycopy_Type();
 993   Node* call = make_leaf_call(*ctrl, *mem, call_type, copyfunc_addr, "checkcast_arraycopy", adr_type,
 994                               src_start, dest_start, copy_length XTOP, check_offset XTOP, check_value);
 995 
 996   finish_arraycopy_call(call, ctrl, mem, adr_type);
 997 
 998   Node* proj =  new ProjNode(call, TypeFunc::Parms);
 999   transform_later(proj);
1000 
1001   return proj;
1002 }
1003 
1004 // Helper function; generates code for cases requiring runtime checks.
1005 Node* PhaseMacroExpand::generate_generic_arraycopy(Node** ctrl, MergeMemNode** mem,
1006                                                    const TypePtr* adr_type,
1007                                                    Node* src,  Node* src_offset,
1008                                                    Node* dest, Node* dest_offset,
1009                                                    Node* copy_length, bool dest_uninitialized) {
1010   if ((*ctrl)->is_top()) return NULL;
1011   assert(!dest_uninitialized, "Invariant");
1012 
1013   address copyfunc_addr = StubRoutines::generic_arraycopy();
1014   if (copyfunc_addr == NULL) { // Stub was not generated, go slow path.
1015     return NULL;
1016   }
1017 
1018   const TypeFunc* call_type = OptoRuntime::generic_arraycopy_Type();
1019   Node* call = make_leaf_call(*ctrl, *mem, call_type, copyfunc_addr, "generic_arraycopy", adr_type,
1020                               src, src_offset, dest, dest_offset, copy_length);
1021 
1022   finish_arraycopy_call(call, ctrl, mem, adr_type);
1023 
1024   Node* proj =  new ProjNode(call, TypeFunc::Parms);
1025   transform_later(proj);
1026 
1027   return proj;
1028 }
1029 
1030 // Helper function; generates the fast out-of-line call to an arraycopy stub.
1031 void PhaseMacroExpand::generate_unchecked_arraycopy(Node** ctrl, MergeMemNode** mem,
1032                                                     const TypePtr* adr_type,
1033                                                     BasicType basic_elem_type,
1034                                                     bool disjoint_bases,
1035                                                     Node* src,  Node* src_offset,
1036                                                     Node* dest, Node* dest_offset,
1037                                                     Node* copy_length, bool dest_uninitialized) {
1038   if ((*ctrl)->is_top()) return;
1039 
1040   Node* src_start  = src;
1041   Node* dest_start = dest;
1042   if (src_offset != NULL || dest_offset != NULL) {
1043     src_start =  array_element_address(src, src_offset, basic_elem_type);
1044     dest_start = array_element_address(dest, dest_offset, basic_elem_type);
1045   }
1046 
1047   // Figure out which arraycopy runtime method to call.
1048   const char* copyfunc_name = "arraycopy";
1049   address     copyfunc_addr =
1050       basictype2arraycopy(basic_elem_type, src_offset, dest_offset,
1051                           disjoint_bases, copyfunc_name, dest_uninitialized);
1052 
1053   const TypeFunc* call_type = OptoRuntime::fast_arraycopy_Type();
1054   Node* call = make_leaf_call(*ctrl, *mem, call_type, copyfunc_addr, copyfunc_name, adr_type,
1055                               src_start, dest_start, copy_length XTOP);
1056 
1057   finish_arraycopy_call(call, ctrl, mem, adr_type);
1058 }
1059 
1060 void PhaseMacroExpand::expand_arraycopy_node(ArrayCopyNode *ac) {
1061   Node* ctrl = ac->in(TypeFunc::Control);
1062   Node* io = ac->in(TypeFunc::I_O);
1063   Node* src = ac->in(ArrayCopyNode::Src);
1064   Node* src_offset = ac->in(ArrayCopyNode::SrcPos);
1065   Node* dest = ac->in(ArrayCopyNode::Dest);
1066   Node* dest_offset = ac->in(ArrayCopyNode::DestPos);
1067   Node* length = ac->in(ArrayCopyNode::Length);
1068   MergeMemNode* merge_mem = NULL;
1069 
1070   if (ac->is_clonebasic()) {
1071     assert (src_offset == NULL && dest_offset == NULL, "for clone offsets should be null");
1072     Node* mem = ac->in(TypeFunc::Memory);
1073     const char* copyfunc_name = "arraycopy";
1074     address     copyfunc_addr =
1075       basictype2arraycopy(T_LONG, NULL, NULL,
1076                           true, copyfunc_name, true);
1077 
1078     const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
1079     const TypeFunc* call_type = OptoRuntime::fast_arraycopy_Type();
1080 
1081     Node* call = make_leaf_call(ctrl, mem, call_type, copyfunc_addr, copyfunc_name, raw_adr_type, src, dest, length XTOP);
1082     transform_later(call);
1083 
1084     _igvn.replace_node(ac, call);
1085     return;
1086   } else if (ac->is_copyof() || ac->is_copyofrange() || ac->is_cloneoop()) {
1087     Node* mem = ac->in(TypeFunc::Memory);
1088     merge_mem = MergeMemNode::make(mem);
1089     transform_later(merge_mem);
1090 
1091     RegionNode* slow_region = new RegionNode(1);
1092     transform_later(slow_region);
1093 
1094     AllocateArrayNode* alloc = NULL;
1095     if (ac->is_alloc_tightly_coupled()) {
1096       alloc = AllocateArrayNode::Ideal_array_allocation(dest, &_igvn);
1097       assert(alloc != NULL, "expect alloc");
1098     }
1099 
1100     generate_arraycopy(ac, alloc, &ctrl, merge_mem, &io,
1101                        TypeAryPtr::OOPS, T_OBJECT,
1102                        src, src_offset, dest, dest_offset, length,
1103                        true, !ac->is_copyofrange());
1104 
1105     return;
1106   }
1107 
1108   AllocateArrayNode* alloc = NULL;
1109   if (ac->is_alloc_tightly_coupled()) {
1110     alloc = AllocateArrayNode::Ideal_array_allocation(dest, &_igvn);
1111     assert(alloc != NULL, "expect alloc");
1112   }
1113 
1114   assert(ac->is_arraycopy() || ac->is_arraycopy_validated(), "should be an arraycopy");
1115 
1116   // Compile time checks.  If any of these checks cannot be verified at compile time,
1117   // we do not make a fast path for this call.  Instead, we let the call remain as it
1118   // is.  The checks we choose to mandate at compile time are:
1119   //
1120   // (1) src and dest are arrays.
1121   const Type* src_type = src->Value(&_igvn);
1122   const Type* dest_type = dest->Value(&_igvn);
1123   const TypeAryPtr* top_src = src_type->isa_aryptr();
1124   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
1125 
1126   if (top_src  == NULL || top_src->klass()  == NULL ||
1127       top_dest == NULL || top_dest->klass() == NULL) {
1128     // Conservatively insert a memory barrier on all memory slices.
1129     // Do not let writes into the source float below the arraycopy.
1130     {
1131       Node* mem = ac->in(TypeFunc::Memory);
1132       insert_mem_bar(&ctrl, &mem, Op_MemBarCPUOrder);
1133 
1134       merge_mem = MergeMemNode::make(mem);
1135       transform_later(merge_mem);
1136     }
1137 
1138     // Call StubRoutines::generic_arraycopy stub.
1139     Node* mem = generate_arraycopy(ac, NULL, &ctrl, merge_mem, &io,
1140                                    TypeRawPtr::BOTTOM, T_CONFLICT,
1141                                    src, src_offset, dest, dest_offset, length);
1142 
1143     // Do not let reads from the destination float above the arraycopy.
1144     // Since we cannot type the arrays, we don't know which slices
1145     // might be affected.  We could restrict this barrier only to those
1146     // memory slices which pertain to array elements--but don't bother.
1147     if (!InsertMemBarAfterArraycopy) {
1148       // (If InsertMemBarAfterArraycopy, there is already one in place.)
1149       insert_mem_bar(&ctrl, &mem, Op_MemBarCPUOrder);
1150     }
1151     return;
1152   }
1153   // (2) src and dest arrays must have elements of the same BasicType
1154   // Figure out the size and type of the elements we will be copying.
1155   BasicType src_elem  =  top_src->klass()->as_array_klass()->element_type()->basic_type();
1156   BasicType dest_elem = top_dest->klass()->as_array_klass()->element_type()->basic_type();
1157   if (src_elem  == T_ARRAY)  src_elem  = T_OBJECT;
1158   if (dest_elem == T_ARRAY)  dest_elem = T_OBJECT;
1159 
1160   if (src_elem != dest_elem || dest_elem == T_VOID) {
1161     // The component types are not the same or are not recognized.  Punt.
1162     // (But, avoid the native method wrapper to JVM_ArrayCopy.)
1163     {
1164       Node* mem = ac->in(TypeFunc::Memory);
1165       merge_mem = generate_slow_arraycopy(ac, &ctrl, mem, &io, TypePtr::BOTTOM, src, src_offset, dest, dest_offset, length, false);
1166     }
1167 
1168     _igvn.replace_node(_memproj_fallthrough, merge_mem);
1169     _igvn.replace_node(_ioproj_fallthrough, io);
1170     _igvn.replace_node(_fallthroughcatchproj, ctrl);
1171     return;
1172   }
1173 
1174   //---------------------------------------------------------------------------
1175   // We will make a fast path for this call to arraycopy.
1176 
1177   // We have the following tests left to perform:
1178   //
1179   // (3) src and dest must not be null.
1180   // (4) src_offset must not be negative.
1181   // (5) dest_offset must not be negative.
1182   // (6) length must not be negative.
1183   // (7) src_offset + length must not exceed length of src.
1184   // (8) dest_offset + length must not exceed length of dest.
1185   // (9) each element of an oop array must be assignable
1186 
1187   {
1188     Node* mem = ac->in(TypeFunc::Memory);
1189     merge_mem = MergeMemNode::make(mem);
1190     transform_later(merge_mem);
1191   }
1192 
1193   RegionNode* slow_region = new RegionNode(1);
1194   transform_later(slow_region);
1195 
1196   if (!ac->is_arraycopy_validated()) {
1197     // (3) operands must not be null
1198     // We currently perform our null checks with the null_check routine.
1199     // This means that the null exceptions will be reported in the caller
1200     // rather than (correctly) reported inside of the native arraycopy call.
1201     // This should be corrected, given time.  We do our null check with the
1202     // stack pointer restored.
1203     // null checks done library_call.cpp
1204 
1205     // (4) src_offset must not be negative.
1206     generate_negative_guard(&ctrl, src_offset, slow_region);
1207 
1208     // (5) dest_offset must not be negative.
1209     generate_negative_guard(&ctrl, dest_offset, slow_region);
1210 
1211     // (6) length must not be negative (moved to generate_arraycopy()).
1212     // generate_negative_guard(length, slow_region);
1213 
1214     // (7) src_offset + length must not exceed length of src.
1215     Node* alen = ac->in(ArrayCopyNode::SrcLen);
1216     assert(alen != NULL, "need src len");
1217     generate_limit_guard(&ctrl,
1218                          src_offset, length,
1219                          alen,
1220                          slow_region);
1221 
1222     // (8) dest_offset + length must not exceed length of dest.
1223     alen = ac->in(ArrayCopyNode::DestLen);
1224     assert(alen != NULL, "need dest len");
1225     generate_limit_guard(&ctrl,
1226                          dest_offset, length,
1227                          alen,
1228                          slow_region);
1229 
1230     // (9) each element of an oop array must be assignable
1231     // The generate_arraycopy subroutine checks this.
1232   }
1233   // This is where the memory effects are placed:
1234   const TypePtr* adr_type = TypeAryPtr::get_array_body_type(dest_elem);
1235   generate_arraycopy(ac, alloc, &ctrl, merge_mem, &io,
1236                      adr_type, dest_elem,
1237                      src, src_offset, dest, dest_offset, length,
1238                      false, false, slow_region);
1239 }