1 /*
   2  * Copyright (c) 2005, 2021, 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 "ci/ciFlatArrayKlass.hpp"
  27 #include "compiler/compileLog.hpp"
  28 #include "gc/shared/collectedHeap.inline.hpp"
  29 #include "gc/shared/tlab_globals.hpp"
  30 #include "libadt/vectset.hpp"
  31 #include "memory/universe.hpp"
  32 #include "opto/addnode.hpp"
  33 #include "opto/arraycopynode.hpp"
  34 #include "opto/callnode.hpp"
  35 #include "opto/castnode.hpp"
  36 #include "opto/cfgnode.hpp"
  37 #include "opto/compile.hpp"
  38 #include "opto/convertnode.hpp"
  39 #include "opto/graphKit.hpp"
  40 #include "opto/inlinetypenode.hpp"
  41 #include "opto/intrinsicnode.hpp"
  42 #include "opto/locknode.hpp"
  43 #include "opto/loopnode.hpp"
  44 #include "opto/macro.hpp"
  45 #include "opto/memnode.hpp"
  46 #include "opto/narrowptrnode.hpp"
  47 #include "opto/node.hpp"
  48 #include "opto/opaquenode.hpp"
  49 #include "opto/phaseX.hpp"
  50 #include "opto/rootnode.hpp"
  51 #include "opto/runtime.hpp"
  52 #include "opto/subnode.hpp"
  53 #include "opto/subtypenode.hpp"
  54 #include "opto/type.hpp"
  55 #include "prims/jvmtiExport.hpp"
  56 #include "runtime/sharedRuntime.hpp"
  57 #include "runtime/stubRoutines.hpp"
  58 #include "utilities/macros.hpp"
  59 #include "utilities/powerOfTwo.hpp"
  60 #if INCLUDE_G1GC
  61 #include "gc/g1/g1ThreadLocalData.hpp"
  62 #endif // INCLUDE_G1GC
  63 #if INCLUDE_SHENANDOAHGC
  64 #include "gc/shenandoah/c2/shenandoahBarrierSetC2.hpp"
  65 #endif
  66 
  67 
  68 //
  69 // Replace any references to "oldref" in inputs to "use" with "newref".
  70 // Returns the number of replacements made.
  71 //
  72 int PhaseMacroExpand::replace_input(Node *use, Node *oldref, Node *newref) {
  73   int nreplacements = 0;
  74   uint req = use->req();
  75   for (uint j = 0; j < use->len(); j++) {
  76     Node *uin = use->in(j);
  77     if (uin == oldref) {
  78       if (j < req)
  79         use->set_req(j, newref);
  80       else
  81         use->set_prec(j, newref);
  82       nreplacements++;
  83     } else if (j >= req && uin == NULL) {
  84       break;
  85     }
  86   }
  87   return nreplacements;
  88 }
  89 
  90 Node* PhaseMacroExpand::opt_bits_test(Node* ctrl, Node* region, int edge, Node* word, int mask, int bits, bool return_fast_path) {
  91   Node* cmp;
  92   if (mask != 0) {
  93     Node* and_node = transform_later(new AndXNode(word, MakeConX(mask)));
  94     cmp = transform_later(new CmpXNode(and_node, MakeConX(bits)));
  95   } else {
  96     cmp = word;
  97   }
  98   Node* bol = transform_later(new BoolNode(cmp, BoolTest::ne));
  99   IfNode* iff = new IfNode( ctrl, bol, PROB_MIN, COUNT_UNKNOWN );
 100   transform_later(iff);
 101 
 102   // Fast path taken.
 103   Node *fast_taken = transform_later(new IfFalseNode(iff));
 104 
 105   // Fast path not-taken, i.e. slow path
 106   Node *slow_taken = transform_later(new IfTrueNode(iff));
 107 
 108   if (return_fast_path) {
 109     region->init_req(edge, slow_taken); // Capture slow-control
 110     return fast_taken;
 111   } else {
 112     region->init_req(edge, fast_taken); // Capture fast-control
 113     return slow_taken;
 114   }
 115 }
 116 
 117 //--------------------copy_predefined_input_for_runtime_call--------------------
 118 void PhaseMacroExpand::copy_predefined_input_for_runtime_call(Node * ctrl, CallNode* oldcall, CallNode* call) {
 119   // Set fixed predefined input arguments
 120   call->init_req( TypeFunc::Control, ctrl );
 121   call->init_req( TypeFunc::I_O    , oldcall->in( TypeFunc::I_O) );
 122   call->init_req( TypeFunc::Memory , oldcall->in( TypeFunc::Memory ) ); // ?????
 123   call->init_req( TypeFunc::ReturnAdr, oldcall->in( TypeFunc::ReturnAdr ) );
 124   call->init_req( TypeFunc::FramePtr, oldcall->in( TypeFunc::FramePtr ) );
 125 }
 126 
 127 //------------------------------make_slow_call---------------------------------
 128 CallNode* PhaseMacroExpand::make_slow_call(CallNode *oldcall, const TypeFunc* slow_call_type,
 129                                            address slow_call, const char* leaf_name, Node* slow_path,
 130                                            Node* parm0, Node* parm1, Node* parm2) {
 131 
 132   // Slow-path call
 133  CallNode *call = leaf_name
 134    ? (CallNode*)new CallLeafNode      ( slow_call_type, slow_call, leaf_name, TypeRawPtr::BOTTOM )
 135    : (CallNode*)new CallStaticJavaNode( slow_call_type, slow_call, OptoRuntime::stub_name(slow_call), TypeRawPtr::BOTTOM );
 136 
 137   // Slow path call has no side-effects, uses few values
 138   copy_predefined_input_for_runtime_call(slow_path, oldcall, call );
 139   if (parm0 != NULL)  call->init_req(TypeFunc::Parms+0, parm0);
 140   if (parm1 != NULL)  call->init_req(TypeFunc::Parms+1, parm1);
 141   if (parm2 != NULL)  call->init_req(TypeFunc::Parms+2, parm2);
 142   call->copy_call_debug_info(&_igvn, oldcall);
 143   call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
 144   _igvn.replace_node(oldcall, call);
 145   transform_later(call);
 146 
 147   return call;
 148 }
 149 
 150 void PhaseMacroExpand::eliminate_gc_barrier(Node* p2x) {
 151   BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
 152   bs->eliminate_gc_barrier(&_igvn, p2x);
 153 }
 154 
 155 // Search for a memory operation for the specified memory slice.
 156 static Node *scan_mem_chain(Node *mem, int alias_idx, int offset, Node *start_mem, Node *alloc, PhaseGVN *phase) {
 157   Node *orig_mem = mem;
 158   Node *alloc_mem = alloc->in(TypeFunc::Memory);
 159   const TypeOopPtr *tinst = phase->C->get_adr_type(alias_idx)->isa_oopptr();
 160   while (true) {
 161     if (mem == alloc_mem || mem == start_mem ) {
 162       return mem;  // hit one of our sentinels
 163     } else if (mem->is_MergeMem()) {
 164       mem = mem->as_MergeMem()->memory_at(alias_idx);
 165     } else if (mem->is_Proj() && mem->as_Proj()->_con == TypeFunc::Memory) {
 166       Node *in = mem->in(0);
 167       // we can safely skip over safepoints, calls, locks and membars because we
 168       // already know that the object is safe to eliminate.
 169       if (in->is_Initialize() && in->as_Initialize()->allocation() == alloc) {
 170         return in;
 171       } else if (in->is_Call()) {
 172         CallNode *call = in->as_Call();
 173         if (call->may_modify(tinst, phase)) {
 174           assert(call->is_ArrayCopy(), "ArrayCopy is the only call node that doesn't make allocation escape");
 175           if (call->as_ArrayCopy()->modifies(offset, offset, phase, false)) {
 176             return in;
 177           }
 178         }
 179         mem = in->in(TypeFunc::Memory);
 180       } else if (in->is_MemBar()) {
 181         ArrayCopyNode* ac = NULL;
 182         if (ArrayCopyNode::may_modify(tinst, in->as_MemBar(), phase, ac)) {
 183           if (ac != NULL) {
 184             assert(ac->is_clonebasic(), "Only basic clone is a non escaping clone");
 185             return ac;
 186           }
 187         }
 188         mem = in->in(TypeFunc::Memory);
 189       } else {
 190 #ifdef ASSERT
 191         in->dump();
 192         mem->dump();
 193         assert(false, "unexpected projection");
 194 #endif
 195       }
 196     } else if (mem->is_Store()) {
 197       const TypePtr* atype = mem->as_Store()->adr_type();
 198       int adr_idx = phase->C->get_alias_index(atype);
 199       if (adr_idx == alias_idx) {
 200         assert(atype->isa_oopptr(), "address type must be oopptr");
 201         int adr_offset = atype->flattened_offset();
 202         uint adr_iid = atype->is_oopptr()->instance_id();
 203         // Array elements references have the same alias_idx
 204         // but different offset and different instance_id.
 205         if (adr_offset == offset && adr_iid == alloc->_idx) {
 206           return mem;
 207         }
 208       } else {
 209         assert(adr_idx == Compile::AliasIdxRaw, "address must match or be raw");
 210       }
 211       mem = mem->in(MemNode::Memory);
 212     } else if (mem->is_ClearArray()) {
 213       if (!ClearArrayNode::step_through(&mem, alloc->_idx, phase)) {
 214         // Can not bypass initialization of the instance
 215         // we are looking.
 216         debug_only(intptr_t offset;)
 217         assert(alloc == AllocateNode::Ideal_allocation(mem->in(3), phase, offset), "sanity");
 218         InitializeNode* init = alloc->as_Allocate()->initialization();
 219         // We are looking for stored value, return Initialize node
 220         // or memory edge from Allocate node.
 221         if (init != NULL) {
 222           return init;
 223         } else {
 224           return alloc->in(TypeFunc::Memory); // It will produce zero value (see callers).
 225         }
 226       }
 227       // Otherwise skip it (the call updated 'mem' value).
 228     } else if (mem->Opcode() == Op_SCMemProj) {
 229       mem = mem->in(0);
 230       Node* adr = NULL;
 231       if (mem->is_LoadStore()) {
 232         adr = mem->in(MemNode::Address);
 233       } else {
 234         assert(mem->Opcode() == Op_EncodeISOArray ||
 235                mem->Opcode() == Op_StrCompressedCopy, "sanity");
 236         adr = mem->in(3); // Destination array
 237       }
 238       const TypePtr* atype = adr->bottom_type()->is_ptr();
 239       int adr_idx = phase->C->get_alias_index(atype);
 240       if (adr_idx == alias_idx) {
 241         DEBUG_ONLY(mem->dump();)
 242         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
 243         return NULL;
 244       }
 245       mem = mem->in(MemNode::Memory);
 246     } else if (mem->Opcode() == Op_StrInflatedCopy) {
 247       Node* adr = mem->in(3); // Destination array
 248       const TypePtr* atype = adr->bottom_type()->is_ptr();
 249       int adr_idx = phase->C->get_alias_index(atype);
 250       if (adr_idx == alias_idx) {
 251         DEBUG_ONLY(mem->dump();)
 252         assert(false, "Object is not scalar replaceable if a StrInflatedCopy node accesses its field");
 253         return NULL;
 254       }
 255       mem = mem->in(MemNode::Memory);
 256     } else {
 257       return mem;
 258     }
 259     assert(mem != orig_mem, "dead memory loop");
 260   }
 261 }
 262 
 263 // Generate loads from source of the arraycopy for fields of
 264 // destination needed at a deoptimization point
 265 Node* PhaseMacroExpand::make_arraycopy_load(ArrayCopyNode* ac, intptr_t offset, Node* ctl, Node* mem, BasicType ft, const Type *ftype, AllocateNode *alloc) {
 266   BasicType bt = ft;
 267   const Type *type = ftype;
 268   if (ft == T_NARROWOOP) {
 269     bt = T_OBJECT;
 270     type = ftype->make_oopptr();
 271   }
 272   Node* res = NULL;
 273   if (ac->is_clonebasic()) {
 274     assert(ac->in(ArrayCopyNode::Src) != ac->in(ArrayCopyNode::Dest), "clone source equals destination");
 275     Node* base = ac->in(ArrayCopyNode::Src);
 276     Node* adr = _igvn.transform(new AddPNode(base, base, MakeConX(offset)));
 277     const TypePtr* adr_type = _igvn.type(base)->is_ptr()->add_offset(offset);
 278     MergeMemNode* mergemen = _igvn.transform(MergeMemNode::make(mem))->as_MergeMem();
 279     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 280     res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
 281   } else {
 282     if (ac->modifies(offset, offset, &_igvn, true)) {
 283       assert(ac->in(ArrayCopyNode::Dest) == alloc->result_cast(), "arraycopy destination should be allocation's result");
 284       uint shift = exact_log2(type2aelembytes(bt));
 285       Node* src_pos = ac->in(ArrayCopyNode::SrcPos);
 286       Node* dest_pos = ac->in(ArrayCopyNode::DestPos);
 287       const TypeInt* src_pos_t = _igvn.type(src_pos)->is_int();
 288       const TypeInt* dest_pos_t = _igvn.type(dest_pos)->is_int();
 289 
 290       Node* adr = NULL;
 291       Node* base = ac->in(ArrayCopyNode::Src);
 292       const TypePtr* adr_type = _igvn.type(base)->is_ptr();
 293       assert(adr_type->isa_aryptr(), "only arrays here");
 294       if (adr_type->is_aryptr()->is_flat()) {
 295         ciFlatArrayKlass* vak = adr_type->is_aryptr()->klass()->as_flat_array_klass();
 296         shift = vak->log2_element_size();
 297       }
 298       if (src_pos_t->is_con() && dest_pos_t->is_con()) {
 299         intptr_t off = ((src_pos_t->get_con() - dest_pos_t->get_con()) << shift) + offset;
 300         adr = _igvn.transform(new AddPNode(base, base, MakeConX(off)));
 301         adr_type = _igvn.type(adr)->is_ptr();
 302         assert(adr_type == _igvn.type(base)->is_aryptr()->add_field_offset_and_offset(off), "incorrect address type");
 303         if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 304           // Don't emit a new load from src if src == dst but try to get the value from memory instead
 305           return value_from_mem(ac->in(TypeFunc::Memory), ctl, ft, ftype, adr_type->isa_oopptr(), alloc);
 306         }
 307       } else {
 308         if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 309           // Non constant offset in the array: we can't statically
 310           // determine the value
 311           return NULL;
 312         }
 313         Node* diff = _igvn.transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
 314 #ifdef _LP64
 315         diff = _igvn.transform(new ConvI2LNode(diff));
 316 #endif
 317         diff = _igvn.transform(new LShiftXNode(diff, intcon(shift)));
 318 
 319         Node* off = _igvn.transform(new AddXNode(MakeConX(offset), diff));
 320         adr = _igvn.transform(new AddPNode(base, base, off));
 321         // In the case of a flattened inline type array, each field has its
 322         // own slice so we need to extract the field being accessed from
 323         // the address computation
 324         adr_type = adr_type->is_aryptr()->add_field_offset_and_offset(offset)->add_offset(Type::OffsetBot);
 325         adr = _igvn.transform(new CastPPNode(adr, adr_type));
 326       }
 327       MergeMemNode* mergemen = _igvn.transform(MergeMemNode::make(mem))->as_MergeMem();
 328       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 329       res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
 330     }
 331   }
 332   if (res != NULL) {
 333     if (ftype->isa_narrowoop()) {
 334       // PhaseMacroExpand::scalar_replacement adds DecodeN nodes
 335       assert(res->isa_DecodeN(), "should be narrow oop");
 336       res = _igvn.transform(new EncodePNode(res, ftype));
 337     }
 338     return res;
 339   }
 340   return NULL;
 341 }
 342 
 343 //
 344 // Given a Memory Phi, compute a value Phi containing the values from stores
 345 // on the input paths.
 346 // Note: this function is recursive, its depth is limited by the "level" argument
 347 // Returns the computed Phi, or NULL if it cannot compute it.
 348 Node *PhaseMacroExpand::value_from_mem_phi(Node *mem, BasicType ft, const Type *phi_type, const TypeOopPtr *adr_t, AllocateNode *alloc, Node_Stack *value_phis, int level) {
 349   assert(mem->is_Phi(), "sanity");
 350   int alias_idx = C->get_alias_index(adr_t);
 351   int offset = adr_t->flattened_offset();
 352   int instance_id = adr_t->instance_id();
 353 
 354   // Check if an appropriate value phi already exists.
 355   Node* region = mem->in(0);
 356   for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) {
 357     Node* phi = region->fast_out(k);
 358     if (phi->is_Phi() && phi != mem &&
 359         phi->as_Phi()->is_same_inst_field(phi_type, (int)mem->_idx, instance_id, alias_idx, offset)) {
 360       return phi;
 361     }
 362   }
 363   // Check if an appropriate new value phi already exists.
 364   Node* new_phi = value_phis->find(mem->_idx);
 365   if (new_phi != NULL)
 366     return new_phi;
 367 
 368   if (level <= 0) {
 369     return NULL; // Give up: phi tree too deep
 370   }
 371   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
 372   Node *alloc_mem = alloc->in(TypeFunc::Memory);
 373 
 374   uint length = mem->req();
 375   GrowableArray <Node *> values(length, length, NULL);
 376 
 377   // create a new Phi for the value
 378   PhiNode *phi = new PhiNode(mem->in(0), phi_type, NULL, mem->_idx, instance_id, alias_idx, offset);
 379   transform_later(phi);
 380   value_phis->push(phi, mem->_idx);
 381 
 382   for (uint j = 1; j < length; j++) {
 383     Node *in = mem->in(j);
 384     if (in == NULL || in->is_top()) {
 385       values.at_put(j, in);
 386     } else  {
 387       Node *val = scan_mem_chain(in, alias_idx, offset, start_mem, alloc, &_igvn);
 388       if (val == start_mem || val == alloc_mem) {
 389         // hit a sentinel, return appropriate 0 value
 390         Node* default_value = alloc->in(AllocateNode::DefaultValue);
 391         if (default_value != NULL) {
 392           values.at_put(j, default_value);
 393         } else {
 394           assert(alloc->in(AllocateNode::RawDefaultValue) == NULL, "default value may not be null");
 395           values.at_put(j, _igvn.zerocon(ft));
 396         }
 397         continue;
 398       }
 399       if (val->is_Initialize()) {
 400         val = val->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 401       }
 402       if (val == NULL) {
 403         return NULL;  // can't find a value on this path
 404       }
 405       if (val == mem) {
 406         values.at_put(j, mem);
 407       } else if (val->is_Store()) {
 408         Node* n = val->in(MemNode::ValueIn);
 409         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 410         n = bs->step_over_gc_barrier(n);
 411         if (is_subword_type(ft)) {
 412           n = Compile::narrow_value(ft, n, phi_type, &_igvn, true);
 413         }
 414         values.at_put(j, n);
 415       } else if(val->is_Proj() && val->in(0) == alloc) {
 416         Node* default_value = alloc->in(AllocateNode::DefaultValue);
 417         if (default_value != NULL) {
 418           values.at_put(j, default_value);
 419         } else {
 420           assert(alloc->in(AllocateNode::RawDefaultValue) == NULL, "default value may not be null");
 421           values.at_put(j, _igvn.zerocon(ft));
 422         }
 423       } else if (val->is_Phi()) {
 424         val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, value_phis, level-1);
 425         if (val == NULL) {
 426           return NULL;
 427         }
 428         values.at_put(j, val);
 429       } else if (val->Opcode() == Op_SCMemProj) {
 430         assert(val->in(0)->is_LoadStore() ||
 431                val->in(0)->Opcode() == Op_EncodeISOArray ||
 432                val->in(0)->Opcode() == Op_StrCompressedCopy, "sanity");
 433         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
 434         return NULL;
 435       } else if (val->is_ArrayCopy()) {
 436         Node* res = make_arraycopy_load(val->as_ArrayCopy(), offset, val->in(0), val->in(TypeFunc::Memory), ft, phi_type, alloc);
 437         if (res == NULL) {
 438           return NULL;
 439         }
 440         values.at_put(j, res);
 441       } else {
 442         DEBUG_ONLY( val->dump(); )
 443         assert(false, "unknown node on this path");
 444         return NULL;  // unknown node on this path
 445       }
 446     }
 447   }
 448   // Set Phi's inputs
 449   for (uint j = 1; j < length; j++) {
 450     if (values.at(j) == mem) {
 451       phi->init_req(j, phi);
 452     } else {
 453       phi->init_req(j, values.at(j));
 454     }
 455   }
 456   return phi;
 457 }
 458 
 459 // Search the last value stored into the object's field.
 460 Node *PhaseMacroExpand::value_from_mem(Node *sfpt_mem, Node *sfpt_ctl, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, AllocateNode *alloc) {
 461   assert(adr_t->is_known_instance_field(), "instance required");
 462   int instance_id = adr_t->instance_id();
 463   assert((uint)instance_id == alloc->_idx, "wrong allocation");
 464 
 465   int alias_idx = C->get_alias_index(adr_t);
 466   int offset = adr_t->flattened_offset();
 467   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
 468   Node *alloc_mem = alloc->in(TypeFunc::Memory);
 469   VectorSet visited;
 470 
 471   bool done = sfpt_mem == alloc_mem;
 472   Node *mem = sfpt_mem;
 473   while (!done) {
 474     if (visited.test_set(mem->_idx)) {
 475       return NULL;  // found a loop, give up
 476     }
 477     mem = scan_mem_chain(mem, alias_idx, offset, start_mem, alloc, &_igvn);
 478     if (mem == start_mem || mem == alloc_mem) {
 479       done = true;  // hit a sentinel, return appropriate 0 value
 480     } else if (mem->is_Initialize()) {
 481       mem = mem->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 482       if (mem == NULL) {
 483         done = true; // Something went wrong.
 484       } else if (mem->is_Store()) {
 485         const TypePtr* atype = mem->as_Store()->adr_type();
 486         assert(C->get_alias_index(atype) == Compile::AliasIdxRaw, "store is correct memory slice");
 487         done = true;
 488       }
 489     } else if (mem->is_Store()) {
 490       const TypeOopPtr* atype = mem->as_Store()->adr_type()->isa_oopptr();
 491       assert(atype != NULL, "address type must be oopptr");
 492       assert(C->get_alias_index(atype) == alias_idx &&
 493              atype->is_known_instance_field() && atype->flattened_offset() == offset &&
 494              atype->instance_id() == instance_id, "store is correct memory slice");
 495       done = true;
 496     } else if (mem->is_Phi()) {
 497       // try to find a phi's unique input
 498       Node *unique_input = NULL;
 499       Node *top = C->top();
 500       for (uint i = 1; i < mem->req(); i++) {
 501         Node *n = scan_mem_chain(mem->in(i), alias_idx, offset, start_mem, alloc, &_igvn);
 502         if (n == NULL || n == top || n == mem) {
 503           continue;
 504         } else if (unique_input == NULL) {
 505           unique_input = n;
 506         } else if (unique_input != n) {
 507           unique_input = top;
 508           break;
 509         }
 510       }
 511       if (unique_input != NULL && unique_input != top) {
 512         mem = unique_input;
 513       } else {
 514         done = true;
 515       }
 516     } else if (mem->is_ArrayCopy()) {
 517       done = true;
 518     } else {
 519       DEBUG_ONLY( mem->dump(); )
 520       assert(false, "unexpected node");
 521     }
 522   }
 523   if (mem != NULL) {
 524     if (mem == start_mem || mem == alloc_mem) {
 525       // hit a sentinel, return appropriate 0 value
 526       Node* default_value = alloc->in(AllocateNode::DefaultValue);
 527       if (default_value != NULL) {
 528         return default_value;
 529       }
 530       assert(alloc->in(AllocateNode::RawDefaultValue) == NULL, "default value may not be null");
 531       return _igvn.zerocon(ft);
 532     } else if (mem->is_Store()) {
 533       Node* n = mem->in(MemNode::ValueIn);
 534       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 535       n = bs->step_over_gc_barrier(n);
 536       return n;
 537     } else if (mem->is_Phi()) {
 538       // attempt to produce a Phi reflecting the values on the input paths of the Phi
 539       Node_Stack value_phis(8);
 540       Node* phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, &value_phis, ValueSearchLimit);
 541       if (phi != NULL) {
 542         return phi;
 543       } else {
 544         // Kill all new Phis
 545         while(value_phis.is_nonempty()) {
 546           Node* n = value_phis.node();
 547           _igvn.replace_node(n, C->top());
 548           value_phis.pop();
 549         }
 550       }
 551     } else if (mem->is_ArrayCopy()) {
 552       Node* ctl = mem->in(0);
 553       Node* m = mem->in(TypeFunc::Memory);
 554       if (sfpt_ctl->is_Proj() && sfpt_ctl->as_Proj()->is_uncommon_trap_proj(Deoptimization::Reason_none)) {
 555         // pin the loads in the uncommon trap path
 556         ctl = sfpt_ctl;
 557         m = sfpt_mem;
 558       }
 559       return make_arraycopy_load(mem->as_ArrayCopy(), offset, ctl, m, ft, ftype, alloc);
 560     }
 561   }
 562   // Something went wrong.
 563   return NULL;
 564 }
 565 
 566 // Search the last value stored into the inline type's fields.
 567 Node* PhaseMacroExpand::inline_type_from_mem(Node* mem, Node* ctl, ciInlineKlass* vk, const TypeAryPtr* adr_type, int offset, AllocateNode* alloc) {
 568   // Subtract the offset of the first field to account for the missing oop header
 569   offset -= vk->first_field_offset();
 570   // Create a new InlineTypeNode and retrieve the field values from memory
 571   InlineTypeNode* vt = InlineTypeNode::make_uninitialized(_igvn, vk)->as_InlineType();
 572   transform_later(vt);
 573   for (int i = 0; i < vk->nof_declared_nonstatic_fields(); ++i) {
 574     ciType* field_type = vt->field_type(i);
 575     int field_offset = offset + vt->field_offset(i);
 576     Node* value = NULL;
 577     if (vt->field_is_flattened(i)) {
 578       value = inline_type_from_mem(mem, ctl, field_type->as_inline_klass(), adr_type, field_offset, alloc);
 579     } else {
 580       const Type* ft = Type::get_const_type(field_type);
 581       BasicType bt = type2field[field_type->basic_type()];
 582       if (UseCompressedOops && !is_java_primitive(bt)) {
 583         ft = ft->make_narrowoop();
 584         bt = T_NARROWOOP;
 585       }
 586       // Each inline type field has its own memory slice
 587       adr_type = adr_type->with_field_offset(field_offset);
 588       value = value_from_mem(mem, ctl, bt, ft, adr_type, alloc);
 589       if (value != NULL && ft->isa_narrowoop()) {
 590         assert(UseCompressedOops, "unexpected narrow oop");
 591         if (value->is_EncodeP()) {
 592           value = value->in(1);
 593         } else {
 594           value = transform_later(new DecodeNNode(value, value->get_ptr_type()));
 595         }
 596       }
 597     }
 598     if (value != NULL) {
 599       vt->set_field_value(i, value);
 600     } else {
 601       // We might have reached the TrackedInitializationLimit
 602       return NULL;
 603     }
 604   }
 605   return vt;
 606 }
 607 
 608 // Check the possibility of scalar replacement.
 609 bool PhaseMacroExpand::can_eliminate_allocation(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
 610   //  Scan the uses of the allocation to check for anything that would
 611   //  prevent us from eliminating it.
 612   NOT_PRODUCT( const char* fail_eliminate = NULL; )
 613   DEBUG_ONLY( Node* disq_node = NULL; )
 614   bool  can_eliminate = true;
 615 
 616   Unique_Node_List worklist;
 617   Node* res = alloc->result_cast();
 618   const TypeOopPtr* res_type = NULL;
 619   if (res == NULL) {
 620     // All users were eliminated.
 621   } else if (!res->is_CheckCastPP()) {
 622     NOT_PRODUCT(fail_eliminate = "Allocation does not have unique CheckCastPP";)
 623     can_eliminate = false;
 624   } else {
 625     worklist.push(res);
 626     res_type = _igvn.type(res)->isa_oopptr();
 627     if (res_type == NULL) {
 628       NOT_PRODUCT(fail_eliminate = "Neither instance or array allocation";)
 629       can_eliminate = false;
 630     } else if (res_type->isa_aryptr()) {
 631       int length = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 632       if (length < 0) {
 633         NOT_PRODUCT(fail_eliminate = "Array's size is not constant";)
 634         can_eliminate = false;
 635       }
 636     }
 637   }
 638 
 639   while (can_eliminate && worklist.size() > 0) {
 640     res = worklist.pop();
 641     for (DUIterator_Fast jmax, j = res->fast_outs(jmax); j < jmax && can_eliminate; j++) {
 642       Node* use = res->fast_out(j);
 643 
 644       if (use->is_AddP()) {
 645         const TypePtr* addp_type = _igvn.type(use)->is_ptr();
 646         int offset = addp_type->offset();
 647 
 648         if (offset == Type::OffsetTop || offset == Type::OffsetBot) {
 649           NOT_PRODUCT(fail_eliminate = "Undefined field reference";)
 650           can_eliminate = false;
 651           break;
 652         }
 653         for (DUIterator_Fast kmax, k = use->fast_outs(kmax);
 654                                    k < kmax && can_eliminate; k++) {
 655           Node* n = use->fast_out(k);
 656           if (!n->is_Store() && n->Opcode() != Op_CastP2X
 657               SHENANDOAHGC_ONLY(&& (!UseShenandoahGC || !ShenandoahBarrierSetC2::is_shenandoah_wb_pre_call(n))) ) {
 658             DEBUG_ONLY(disq_node = n;)
 659             if (n->is_Load() || n->is_LoadStore()) {
 660               NOT_PRODUCT(fail_eliminate = "Field load";)
 661             } else {
 662               NOT_PRODUCT(fail_eliminate = "Not store field reference";)
 663             }
 664             can_eliminate = false;
 665           }
 666         }
 667       } else if (use->is_ArrayCopy() &&
 668                  (use->as_ArrayCopy()->is_clonebasic() ||
 669                   use->as_ArrayCopy()->is_arraycopy_validated() ||
 670                   use->as_ArrayCopy()->is_copyof_validated() ||
 671                   use->as_ArrayCopy()->is_copyofrange_validated()) &&
 672                  use->in(ArrayCopyNode::Dest) == res) {
 673         // ok to eliminate
 674       } else if (use->is_SafePoint()) {
 675         SafePointNode* sfpt = use->as_SafePoint();
 676         if (sfpt->is_Call() && sfpt->as_Call()->has_non_debug_use(res)) {
 677           // Object is passed as argument.
 678           DEBUG_ONLY(disq_node = use;)
 679           NOT_PRODUCT(fail_eliminate = "Object is passed as argument";)
 680           can_eliminate = false;
 681         }
 682         Node* sfptMem = sfpt->memory();
 683         if (sfptMem == NULL || sfptMem->is_top()) {
 684           DEBUG_ONLY(disq_node = use;)
 685           NOT_PRODUCT(fail_eliminate = "NULL or TOP memory";)
 686           can_eliminate = false;
 687         } else {
 688           safepoints.append_if_missing(sfpt);
 689         }
 690       } else if (use->is_InlineType() && use->isa_InlineType()->get_oop() == res) {
 691         // ok to eliminate
 692       } else if (use->is_InlineTypePtr() && use->isa_InlineTypePtr()->get_oop() == res) {
 693         // Process users
 694         worklist.push(use);
 695       } else if (use->Opcode() == Op_StoreX && use->in(MemNode::Address) == res) {
 696         // Store to mark word of inline type larval buffer
 697         assert(res_type->is_inlinetypeptr(), "Unexpected store to mark word");
 698       } else if (use->Opcode() != Op_CastP2X) { // CastP2X is used by card mark
 699         if (use->is_Phi()) {
 700           if (use->outcnt() == 1 && use->unique_out()->Opcode() == Op_Return) {
 701             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 702           } else {
 703             NOT_PRODUCT(fail_eliminate = "Object is referenced by Phi";)
 704           }
 705           DEBUG_ONLY(disq_node = use;)
 706         } else {
 707           if (use->Opcode() == Op_Return) {
 708             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 709           } else {
 710             NOT_PRODUCT(fail_eliminate = "Object is referenced by node";)
 711           }
 712           DEBUG_ONLY(disq_node = use;)
 713         }
 714         can_eliminate = false;
 715       } else {
 716         assert(use->Opcode() == Op_CastP2X, "should be");
 717         assert(!use->has_out_with(Op_OrL), "should have been removed because oop is never null");
 718       }
 719     }
 720   }
 721 
 722 #ifndef PRODUCT
 723   if (PrintEliminateAllocations) {
 724     if (can_eliminate) {
 725       tty->print("Scalar ");
 726       if (res == NULL)
 727         alloc->dump();
 728       else
 729         res->dump();
 730     } else {
 731       tty->print("NotScalar (%s)", fail_eliminate);
 732       if (res == NULL)
 733         alloc->dump();
 734       else
 735         res->dump();
 736 #ifdef ASSERT
 737       if (disq_node != NULL) {
 738           tty->print("  >>>> ");
 739           disq_node->dump();
 740       }
 741 #endif /*ASSERT*/
 742     }
 743   }
 744 #endif
 745   return can_eliminate;
 746 }
 747 
 748 // Do scalar replacement.
 749 bool PhaseMacroExpand::scalar_replacement(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
 750   GrowableArray <SafePointNode *> safepoints_done;
 751 
 752   ciKlass* klass = NULL;
 753   ciInstanceKlass* iklass = NULL;
 754   int nfields = 0;
 755   int array_base = 0;
 756   int element_size = 0;
 757   BasicType basic_elem_type = T_ILLEGAL;
 758   ciType* elem_type = NULL;
 759 
 760   Node* res = alloc->result_cast();
 761   assert(res == NULL || res->is_CheckCastPP(), "unexpected AllocateNode result");
 762   const TypeOopPtr* res_type = NULL;
 763   if (res != NULL) { // Could be NULL when there are no users
 764     res_type = _igvn.type(res)->isa_oopptr();
 765   }
 766 
 767   if (res != NULL) {
 768     klass = res_type->klass();
 769     if (res_type->isa_instptr()) {
 770       // find the fields of the class which will be needed for safepoint debug information
 771       assert(klass->is_instance_klass(), "must be an instance klass.");
 772       iklass = klass->as_instance_klass();
 773       nfields = iklass->nof_nonstatic_fields();
 774     } else {
 775       // find the array's elements which will be needed for safepoint debug information
 776       nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 777       assert(klass->is_array_klass() && nfields >= 0, "must be an array klass.");
 778       elem_type = klass->as_array_klass()->element_type();
 779       basic_elem_type = elem_type->basic_type();
 780       if (elem_type->is_inlinetype() && !klass->is_flat_array_klass()) {
 781         assert(basic_elem_type == T_PRIMITIVE_OBJECT, "unexpected element basic type");
 782         basic_elem_type = T_OBJECT;
 783       }
 784       array_base = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
 785       element_size = type2aelembytes(basic_elem_type);
 786       if (klass->is_flat_array_klass()) {
 787         // Flattened inline type array
 788         element_size = klass->as_flat_array_klass()->element_byte_size();
 789       }
 790     }
 791   }
 792   //
 793   // Process the safepoint uses
 794   //
 795   assert(safepoints.length() == 0 || !res_type->is_inlinetypeptr(), "Inline type allocations should not have safepoint uses");
 796   Unique_Node_List value_worklist;
 797   while (safepoints.length() > 0) {
 798     SafePointNode* sfpt = safepoints.pop();
 799     Node* mem = sfpt->memory();
 800     Node* ctl = sfpt->control();
 801     assert(sfpt->jvms() != NULL, "missed JVMS");
 802     // Fields of scalar objs are referenced only at the end
 803     // of regular debuginfo at the last (youngest) JVMS.
 804     // Record relative start index.
 805     uint first_ind = (sfpt->req() - sfpt->jvms()->scloff());
 806     SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(res_type,
 807 #ifdef ASSERT
 808                                                  alloc,
 809 #endif
 810                                                  first_ind, nfields);
 811     sobj->init_req(0, C->root());
 812     transform_later(sobj);
 813 
 814     // Scan object's fields adding an input to the safepoint for each field.
 815     for (int j = 0; j < nfields; j++) {
 816       intptr_t offset;
 817       ciField* field = NULL;
 818       if (iklass != NULL) {
 819         field = iklass->nonstatic_field_at(j);
 820         offset = field->offset();
 821         elem_type = field->type();
 822         basic_elem_type = field->layout_type();
 823         assert(!field->is_flattened(), "flattened inline type fields should not have safepoint uses");
 824       } else {
 825         offset = array_base + j * (intptr_t)element_size;
 826       }
 827 
 828       const Type *field_type;
 829       // The next code is taken from Parse::do_get_xxx().
 830       if (is_reference_type(basic_elem_type)) {
 831         if (!elem_type->is_loaded()) {
 832           field_type = TypeInstPtr::BOTTOM;
 833         } else if (field != NULL && field->is_static_constant()) {
 834           // This can happen if the constant oop is non-perm.
 835           ciObject* con = field->constant_value().as_object();
 836           // Do not "join" in the previous type; it doesn't add value,
 837           // and may yield a vacuous result if the field is of interface type.
 838           field_type = TypeOopPtr::make_from_constant(con)->isa_oopptr();
 839           assert(field_type != NULL, "field singleton type must be consistent");
 840         } else {
 841           field_type = TypeOopPtr::make_from_klass(elem_type->as_klass());
 842         }
 843         if (UseCompressedOops) {
 844           field_type = field_type->make_narrowoop();
 845           basic_elem_type = T_NARROWOOP;
 846         }
 847       } else {
 848         field_type = Type::get_const_basic_type(basic_elem_type);
 849       }
 850 
 851       Node* field_val = NULL;
 852       const TypeOopPtr* field_addr_type = res_type->add_offset(offset)->isa_oopptr();
 853       if (klass->is_flat_array_klass()) {
 854         ciInlineKlass* vk = elem_type->as_inline_klass();
 855         assert(vk->flatten_array(), "must be flattened");
 856         field_val = inline_type_from_mem(mem, ctl, vk, field_addr_type->isa_aryptr(), 0, alloc);
 857       } else {
 858         field_val = value_from_mem(mem, ctl, basic_elem_type, field_type, field_addr_type, alloc);
 859       }
 860       if (field_val == NULL) {
 861         // We weren't able to find a value for this field,
 862         // give up on eliminating this allocation.
 863 
 864         // Remove any extra entries we added to the safepoint.
 865         uint last = sfpt->req() - 1;
 866         for (int k = 0;  k < j; k++) {
 867           sfpt->del_req(last--);
 868         }
 869         _igvn._worklist.push(sfpt);
 870         // rollback processed safepoints
 871         while (safepoints_done.length() > 0) {
 872           SafePointNode* sfpt_done = safepoints_done.pop();
 873           // remove any extra entries we added to the safepoint
 874           last = sfpt_done->req() - 1;
 875           for (int k = 0;  k < nfields; k++) {
 876             sfpt_done->del_req(last--);
 877           }
 878           JVMState *jvms = sfpt_done->jvms();
 879           jvms->set_endoff(sfpt_done->req());
 880           // Now make a pass over the debug information replacing any references
 881           // to SafePointScalarObjectNode with the allocated object.
 882           int start = jvms->debug_start();
 883           int end   = jvms->debug_end();
 884           for (int i = start; i < end; i++) {
 885             if (sfpt_done->in(i)->is_SafePointScalarObject()) {
 886               SafePointScalarObjectNode* scobj = sfpt_done->in(i)->as_SafePointScalarObject();
 887               if (scobj->first_index(jvms) == sfpt_done->req() &&
 888                   scobj->n_fields() == (uint)nfields) {
 889                 assert(scobj->alloc() == alloc, "sanity");
 890                 sfpt_done->set_req(i, res);
 891               }
 892             }
 893           }
 894           _igvn._worklist.push(sfpt_done);
 895         }
 896 #ifndef PRODUCT
 897         if (PrintEliminateAllocations) {
 898           if (field != NULL) {
 899             tty->print("=== At SafePoint node %d can't find value of Field: ",
 900                        sfpt->_idx);
 901             field->print();
 902             int field_idx = C->get_alias_index(field_addr_type);
 903             tty->print(" (alias_idx=%d)", field_idx);
 904           } else { // Array's element
 905             tty->print("=== At SafePoint node %d can't find value of array element [%d]",
 906                        sfpt->_idx, j);
 907           }
 908           tty->print(", which prevents elimination of: ");
 909           if (res == NULL)
 910             alloc->dump();
 911           else
 912             res->dump();
 913         }
 914 #endif
 915         return false;
 916       }
 917       if (UseCompressedOops && field_type->isa_narrowoop()) {
 918         // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation
 919         // to be able scalar replace the allocation.
 920         if (field_val->is_EncodeP()) {
 921           field_val = field_val->in(1);
 922         } else if (!field_val->is_InlineTypeBase()) {
 923           field_val = transform_later(new DecodeNNode(field_val, field_val->get_ptr_type()));
 924         }
 925       }
 926       if (field_val->is_InlineTypeBase()) {
 927         // Keep track of inline types to scalarize them later
 928         value_worklist.push(field_val);
 929       }
 930       sfpt->add_req(field_val);
 931     }
 932     JVMState *jvms = sfpt->jvms();
 933     jvms->set_endoff(sfpt->req());
 934     // Now make a pass over the debug information replacing any references
 935     // to the allocated object with "sobj"
 936     int start = jvms->debug_start();
 937     int end   = jvms->debug_end();
 938     sfpt->replace_edges_in_range(res, sobj, start, end, &_igvn);
 939     _igvn._worklist.push(sfpt);
 940     safepoints_done.append_if_missing(sfpt); // keep it for rollback
 941   }
 942   // Scalarize inline types that were added to the safepoint.
 943   // Don't allow linking a constant oop (if available) for flat array elements
 944   // because Deoptimization::reassign_flat_array_elements needs field values.
 945   bool allow_oop = (klass == NULL) || !klass->is_flat_array_klass();
 946   for (uint i = 0; i < value_worklist.size(); ++i) {
 947     InlineTypeBaseNode* vt = value_worklist.at(i)->as_InlineTypeBase();
 948     vt->make_scalar_in_safepoints(&_igvn, allow_oop);
 949   }
 950   return true;
 951 }
 952 
 953 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) {
 954   Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control);
 955   Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory);
 956   if (ctl_proj != NULL) {
 957     igvn.replace_node(ctl_proj, n->in(0));
 958   }
 959   if (mem_proj != NULL) {
 960     igvn.replace_node(mem_proj, n->in(TypeFunc::Memory));
 961   }
 962 }
 963 
 964 // Process users of eliminated allocation.
 965 void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc, bool inline_alloc) {
 966   Unique_Node_List worklist;
 967   Node* res = alloc->result_cast();
 968   if (res != NULL) {
 969     worklist.push(res);
 970   }
 971   while (worklist.size() > 0) {
 972     res = worklist.pop();
 973     for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
 974       Node *use = res->last_out(j);
 975       uint oc1 = res->outcnt();
 976 
 977       if (use->is_AddP()) {
 978         for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
 979           Node *n = use->last_out(k);
 980           uint oc2 = use->outcnt();
 981           if (n->is_Store()) {
 982             for (DUIterator_Fast pmax, p = n->fast_outs(pmax); p < pmax; p++) {
 983               MemBarNode* mb = n->fast_out(p)->isa_MemBar();
 984               if (mb != NULL && mb->req() <= MemBarNode::Precedent && mb->in(MemBarNode::Precedent) == n) {
 985                 // MemBarVolatiles should have been removed by MemBarNode::Ideal() for non-inline allocations
 986                 assert(inline_alloc, "MemBarVolatile should be eliminated for non-escaping object");
 987                 mb->remove(&_igvn);
 988               }
 989             }
 990             _igvn.replace_node(n, n->in(MemNode::Memory));
 991           } else {
 992             eliminate_gc_barrier(n);
 993           }
 994           k -= (oc2 - use->outcnt());
 995         }
 996         _igvn.remove_dead_node(use);
 997       } else if (use->is_ArrayCopy()) {
 998         // Disconnect ArrayCopy node
 999         ArrayCopyNode* ac = use->as_ArrayCopy();
1000         if (ac->is_clonebasic()) {
1001           Node* membar_after = ac->proj_out(TypeFunc::Control)->unique_ctrl_out();
1002           disconnect_projections(ac, _igvn);
1003           assert(alloc->in(TypeFunc::Memory)->is_Proj() && alloc->in(TypeFunc::Memory)->in(0)->Opcode() == Op_MemBarCPUOrder, "mem barrier expected before allocation");
1004           Node* membar_before = alloc->in(TypeFunc::Memory)->in(0);
1005           disconnect_projections(membar_before->as_MemBar(), _igvn);
1006           if (membar_after->is_MemBar()) {
1007             disconnect_projections(membar_after->as_MemBar(), _igvn);
1008           }
1009         } else {
1010           assert(ac->is_arraycopy_validated() ||
1011                  ac->is_copyof_validated() ||
1012                  ac->is_copyofrange_validated(), "unsupported");
1013           CallProjections* callprojs = ac->extract_projections(true);
1014 
1015           _igvn.replace_node(callprojs->fallthrough_ioproj, ac->in(TypeFunc::I_O));
1016           _igvn.replace_node(callprojs->fallthrough_memproj, ac->in(TypeFunc::Memory));
1017           _igvn.replace_node(callprojs->fallthrough_catchproj, ac->in(TypeFunc::Control));
1018 
1019           // Set control to top. IGVN will remove the remaining projections
1020           ac->set_req(0, top());
1021           ac->replace_edge(res, top(), &_igvn);
1022 
1023           // Disconnect src right away: it can help find new
1024           // opportunities for allocation elimination
1025           Node* src = ac->in(ArrayCopyNode::Src);
1026           ac->replace_edge(src, top(), &_igvn);
1027           // src can be top at this point if src and dest of the
1028           // arraycopy were the same
1029           if (src->outcnt() == 0 && !src->is_top()) {
1030             _igvn.remove_dead_node(src);
1031           }
1032         }
1033         _igvn._worklist.push(ac);
1034       } else if (use->is_InlineType()) {
1035         assert(use->isa_InlineType()->get_oop() == res, "unexpected inline type use");
1036         _igvn.rehash_node_delayed(use);
1037         use->isa_InlineType()->set_oop(_igvn.zerocon(T_PRIMITIVE_OBJECT));
1038       } else if (use->is_InlineTypePtr()) {
1039         assert(use->isa_InlineTypePtr()->get_oop() == res, "unexpected inline type ptr use");
1040         _igvn.rehash_node_delayed(use);
1041         use->isa_InlineTypePtr()->set_oop(_igvn.zerocon(T_PRIMITIVE_OBJECT));
1042         // Process users
1043         worklist.push(use);
1044       } else if (use->Opcode() == Op_StoreX && use->in(MemNode::Address) == res) {
1045         // Store to mark word of inline type larval buffer
1046         assert(inline_alloc, "Unexpected store to mark word");
1047         _igvn.replace_node(use, use->in(MemNode::Memory));
1048       } else {
1049         eliminate_gc_barrier(use);
1050       }
1051       j -= (oc1 - res->outcnt());
1052     }
1053     assert(res->outcnt() == 0, "all uses of allocated objects must be deleted");
1054     _igvn.remove_dead_node(res);
1055   }
1056 
1057   //
1058   // Process other users of allocation's projections
1059   //
1060   if (_callprojs->resproj[0] != NULL && _callprojs->resproj[0]->outcnt() != 0) {
1061     // First disconnect stores captured by Initialize node.
1062     // If Initialize node is eliminated first in the following code,
1063     // it will kill such stores and DUIterator_Last will assert.
1064     for (DUIterator_Fast jmax, j = _callprojs->resproj[0]->fast_outs(jmax);  j < jmax; j++) {
1065       Node* use = _callprojs->resproj[0]->fast_out(j);
1066       if (use->is_AddP()) {
1067         // raw memory addresses used only by the initialization
1068         _igvn.replace_node(use, C->top());
1069         --j; --jmax;
1070       }
1071     }
1072     for (DUIterator_Last jmin, j = _callprojs->resproj[0]->last_outs(jmin); j >= jmin; ) {
1073       Node* use = _callprojs->resproj[0]->last_out(j);
1074       uint oc1 = _callprojs->resproj[0]->outcnt();
1075       if (use->is_Initialize()) {
1076         // Eliminate Initialize node.
1077         InitializeNode *init = use->as_Initialize();
1078         assert(init->outcnt() <= 2, "only a control and memory projection expected");
1079         Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
1080         if (ctrl_proj != NULL) {
1081           _igvn.replace_node(ctrl_proj, init->in(TypeFunc::Control));
1082 #ifdef ASSERT
1083           // If the InitializeNode has no memory out, it will die, and tmp will become NULL
1084           Node* tmp = init->in(TypeFunc::Control);
1085           assert(tmp == NULL || tmp == _callprojs->fallthrough_catchproj, "allocation control projection");
1086 #endif
1087         }
1088         Node *mem_proj = init->proj_out_or_null(TypeFunc::Memory);
1089         if (mem_proj != NULL) {
1090           Node *mem = init->in(TypeFunc::Memory);
1091 #ifdef ASSERT
1092           if (mem->is_MergeMem()) {
1093             assert(mem->in(TypeFunc::Memory) == _callprojs->fallthrough_memproj, "allocation memory projection");
1094           } else {
1095             assert(mem == _callprojs->fallthrough_memproj, "allocation memory projection");
1096           }
1097 #endif
1098           _igvn.replace_node(mem_proj, mem);
1099         }
1100       } else if (use->Opcode() == Op_MemBarStoreStore) {
1101         // Inline type buffer allocations are followed by a membar
1102         assert(inline_alloc, "Unexpected MemBarStoreStore");
1103         use->as_MemBar()->remove(&_igvn);
1104       } else  {
1105         assert(false, "only Initialize or AddP expected");
1106       }
1107       j -= (oc1 - _callprojs->resproj[0]->outcnt());
1108     }
1109   }
1110   if (_callprojs->fallthrough_catchproj != NULL) {
1111     _igvn.replace_node(_callprojs->fallthrough_catchproj, alloc->in(TypeFunc::Control));
1112   }
1113   if (_callprojs->fallthrough_memproj != NULL) {
1114     _igvn.replace_node(_callprojs->fallthrough_memproj, alloc->in(TypeFunc::Memory));
1115   }
1116   if (_callprojs->catchall_memproj != NULL) {
1117     _igvn.replace_node(_callprojs->catchall_memproj, C->top());
1118   }
1119   if (_callprojs->fallthrough_ioproj != NULL) {
1120     _igvn.replace_node(_callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
1121   }
1122   if (_callprojs->catchall_ioproj != NULL) {
1123     _igvn.replace_node(_callprojs->catchall_ioproj, C->top());
1124   }
1125   if (_callprojs->catchall_catchproj != NULL) {
1126     _igvn.replace_node(_callprojs->catchall_catchproj, C->top());
1127   }
1128 }
1129 
1130 bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) {
1131   // If reallocation fails during deoptimization we'll pop all
1132   // interpreter frames for this compiled frame and that won't play
1133   // nice with JVMTI popframe.
1134   // We avoid this issue by eager reallocation when the popframe request
1135   // is received.
1136   if (!EliminateAllocations) {
1137     return false;
1138   }
1139   Node* klass = alloc->in(AllocateNode::KlassNode);
1140   const TypeKlassPtr* tklass = _igvn.type(klass)->is_klassptr();
1141 
1142   // Attempt to eliminate inline type buffer allocations
1143   // regardless of usage and escape/replaceable status.
1144   bool inline_alloc = tklass->klass()->is_inlinetype();
1145   if (!alloc->_is_non_escaping && !inline_alloc) {
1146     return false;
1147   }
1148   // Eliminate boxing allocations which are not used
1149   // regardless of scalar replaceable status.
1150   Node* res = alloc->result_cast();
1151   bool boxing_alloc = (res == NULL) && C->eliminate_boxing() &&
1152                       tklass->klass()->is_instance_klass() &&
1153                       tklass->klass()->as_instance_klass()->is_box_klass();
1154   if (!alloc->_is_scalar_replaceable && !boxing_alloc && !inline_alloc) {
1155     return false;
1156   }
1157 
1158   _callprojs = alloc->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1159 
1160   GrowableArray <SafePointNode *> safepoints;
1161   if (!can_eliminate_allocation(alloc, safepoints)) {
1162     return false;
1163   }
1164 
1165   if (!alloc->_is_scalar_replaceable) {
1166     assert(res == NULL || inline_alloc, "sanity");
1167     // We can only eliminate allocation if all debug info references
1168     // are already replaced with SafePointScalarObject because
1169     // we can't search for a fields value without instance_id.
1170     if (safepoints.length() > 0) {
1171       assert(!inline_alloc, "Inline type allocations should not have safepoint uses");
1172       return false;
1173     }
1174   }
1175 
1176   if (!scalar_replacement(alloc, safepoints)) {
1177     return false;
1178   }
1179 
1180   CompileLog* log = C->log();
1181   if (log != NULL) {
1182     log->head("eliminate_allocation type='%d'",
1183               log->identify(tklass->klass()));
1184     JVMState* p = alloc->jvms();
1185     while (p != NULL) {
1186       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1187       p = p->caller();
1188     }
1189     log->tail("eliminate_allocation");
1190   }
1191 
1192   process_users_of_allocation(alloc, inline_alloc);
1193 
1194 #ifndef PRODUCT
1195   if (PrintEliminateAllocations) {
1196     if (alloc->is_AllocateArray())
1197       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1198     else
1199       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1200   }
1201 #endif
1202 
1203   return true;
1204 }
1205 
1206 bool PhaseMacroExpand::eliminate_boxing_node(CallStaticJavaNode *boxing) {
1207   // EA should remove all uses of non-escaping boxing node.
1208   if (!C->eliminate_boxing() || boxing->proj_out_or_null(TypeFunc::Parms) != NULL) {
1209     return false;
1210   }
1211 
1212   assert(boxing->result_cast() == NULL, "unexpected boxing node result");
1213 
1214   _callprojs = boxing->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1215 
1216   const TypeTuple* r = boxing->tf()->range_sig();
1217   assert(r->cnt() > TypeFunc::Parms, "sanity");
1218   const TypeInstPtr* t = r->field_at(TypeFunc::Parms)->isa_instptr();
1219   assert(t != NULL, "sanity");
1220 
1221   CompileLog* log = C->log();
1222   if (log != NULL) {
1223     log->head("eliminate_boxing type='%d'",
1224               log->identify(t->klass()));
1225     JVMState* p = boxing->jvms();
1226     while (p != NULL) {
1227       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1228       p = p->caller();
1229     }
1230     log->tail("eliminate_boxing");
1231   }
1232 
1233   process_users_of_allocation(boxing);
1234 
1235 #ifndef PRODUCT
1236   if (PrintEliminateAllocations) {
1237     tty->print("++++ Eliminated: %d ", boxing->_idx);
1238     boxing->method()->print_short_name(tty);
1239     tty->cr();
1240   }
1241 #endif
1242 
1243   return true;
1244 }
1245 
1246 //---------------------------set_eden_pointers-------------------------
1247 void PhaseMacroExpand::set_eden_pointers(Node* &eden_top_adr, Node* &eden_end_adr) {
1248   if (UseTLAB) {                // Private allocation: load from TLS
1249     Node* thread = transform_later(new ThreadLocalNode());
1250     int tlab_top_offset = in_bytes(JavaThread::tlab_top_offset());
1251     int tlab_end_offset = in_bytes(JavaThread::tlab_end_offset());
1252     eden_top_adr = basic_plus_adr(top()/*not oop*/, thread, tlab_top_offset);
1253     eden_end_adr = basic_plus_adr(top()/*not oop*/, thread, tlab_end_offset);
1254   } else {                      // Shared allocation: load from globals
1255     CollectedHeap* ch = Universe::heap();
1256     address top_adr = (address)ch->top_addr();
1257     address end_adr = (address)ch->end_addr();
1258     eden_top_adr = makecon(TypeRawPtr::make(top_adr));
1259     eden_end_adr = basic_plus_adr(eden_top_adr, end_adr - top_adr);
1260   }
1261 }
1262 
1263 
1264 Node* PhaseMacroExpand::make_load(Node* ctl, Node* mem, Node* base, int offset, const Type* value_type, BasicType bt) {
1265   Node* adr = basic_plus_adr(base, offset);
1266   const TypePtr* adr_type = adr->bottom_type()->is_ptr();
1267   Node* value = LoadNode::make(_igvn, ctl, mem, adr, adr_type, value_type, bt, MemNode::unordered);
1268   transform_later(value);
1269   return value;
1270 }
1271 
1272 
1273 Node* PhaseMacroExpand::make_store(Node* ctl, Node* mem, Node* base, int offset, Node* value, BasicType bt) {
1274   Node* adr = basic_plus_adr(base, offset);
1275   mem = StoreNode::make(_igvn, ctl, mem, adr, NULL, value, bt, MemNode::unordered);
1276   transform_later(mem);
1277   return mem;
1278 }
1279 
1280 //=============================================================================
1281 //
1282 //                              A L L O C A T I O N
1283 //
1284 // Allocation attempts to be fast in the case of frequent small objects.
1285 // It breaks down like this:
1286 //
1287 // 1) Size in doublewords is computed.  This is a constant for objects and
1288 // variable for most arrays.  Doubleword units are used to avoid size
1289 // overflow of huge doubleword arrays.  We need doublewords in the end for
1290 // rounding.
1291 //
1292 // 2) Size is checked for being 'too large'.  Too-large allocations will go
1293 // the slow path into the VM.  The slow path can throw any required
1294 // exceptions, and does all the special checks for very large arrays.  The
1295 // size test can constant-fold away for objects.  For objects with
1296 // finalizers it constant-folds the otherway: you always go slow with
1297 // finalizers.
1298 //
1299 // 3) If NOT using TLABs, this is the contended loop-back point.
1300 // Load-Locked the heap top.  If using TLABs normal-load the heap top.
1301 //
1302 // 4) Check that heap top + size*8 < max.  If we fail go the slow ` route.
1303 // NOTE: "top+size*8" cannot wrap the 4Gig line!  Here's why: for largish
1304 // "size*8" we always enter the VM, where "largish" is a constant picked small
1305 // enough that there's always space between the eden max and 4Gig (old space is
1306 // there so it's quite large) and large enough that the cost of entering the VM
1307 // is dwarfed by the cost to initialize the space.
1308 //
1309 // 5) If NOT using TLABs, Store-Conditional the adjusted heap top back
1310 // down.  If contended, repeat at step 3.  If using TLABs normal-store
1311 // adjusted heap top back down; there is no contention.
1312 //
1313 // 6) If !ZeroTLAB then Bulk-clear the object/array.  Fill in klass & mark
1314 // fields.
1315 //
1316 // 7) Merge with the slow-path; cast the raw memory pointer to the correct
1317 // oop flavor.
1318 //
1319 //=============================================================================
1320 // FastAllocateSizeLimit value is in DOUBLEWORDS.
1321 // Allocations bigger than this always go the slow route.
1322 // This value must be small enough that allocation attempts that need to
1323 // trigger exceptions go the slow route.  Also, it must be small enough so
1324 // that heap_top + size_in_bytes does not wrap around the 4Gig limit.
1325 //=============================================================================j//
1326 // %%% Here is an old comment from parseHelper.cpp; is it outdated?
1327 // The allocator will coalesce int->oop copies away.  See comment in
1328 // coalesce.cpp about how this works.  It depends critically on the exact
1329 // code shape produced here, so if you are changing this code shape
1330 // make sure the GC info for the heap-top is correct in and around the
1331 // slow-path call.
1332 //
1333 
1334 void PhaseMacroExpand::expand_allocate_common(
1335             AllocateNode* alloc, // allocation node to be expanded
1336             Node* length,  // array length for an array allocation
1337             const TypeFunc* slow_call_type, // Type of slow call
1338             address slow_call_address,  // Address of slow call
1339             Node* valid_length_test // whether length is valid or not
1340     )
1341 {
1342   Node* ctrl = alloc->in(TypeFunc::Control);
1343   Node* mem  = alloc->in(TypeFunc::Memory);
1344   Node* i_o  = alloc->in(TypeFunc::I_O);
1345   Node* size_in_bytes     = alloc->in(AllocateNode::AllocSize);
1346   Node* klass_node        = alloc->in(AllocateNode::KlassNode);
1347   Node* initial_slow_test = alloc->in(AllocateNode::InitialTest);
1348   assert(ctrl != NULL, "must have control");
1349 
1350   // We need a Region and corresponding Phi's to merge the slow-path and fast-path results.
1351   // they will not be used if "always_slow" is set
1352   enum { slow_result_path = 1, fast_result_path = 2 };
1353   Node *result_region = NULL;
1354   Node *result_phi_rawmem = NULL;
1355   Node *result_phi_rawoop = NULL;
1356   Node *result_phi_i_o = NULL;
1357 
1358   // The initial slow comparison is a size check, the comparison
1359   // we want to do is a BoolTest::gt
1360   bool expand_fast_path = true;
1361   int tv = _igvn.find_int_con(initial_slow_test, -1);
1362   if (tv >= 0) {
1363     // InitialTest has constant result
1364     //   0 - can fit in TLAB
1365     //   1 - always too big or negative
1366     assert(tv <= 1, "0 or 1 if a constant");
1367     expand_fast_path = (tv == 0);
1368     initial_slow_test = NULL;
1369   } else {
1370     initial_slow_test = BoolNode::make_predicate(initial_slow_test, &_igvn);
1371   }
1372 
1373   if (!UseTLAB && !Universe::heap()->supports_inline_contig_alloc()) {
1374     // Force slow-path allocation
1375     expand_fast_path = false;
1376     initial_slow_test = NULL;
1377   }
1378 
1379   bool allocation_has_use = (alloc->result_cast() != NULL);
1380   if (!allocation_has_use) {
1381     InitializeNode* init = alloc->initialization();
1382     if (init != NULL) {
1383       init->remove(&_igvn);
1384     }
1385     if (expand_fast_path && (initial_slow_test == NULL)) {
1386       // Remove allocation node and return.
1387       // Size is a non-negative constant -> no initial check needed -> directly to fast path.
1388       // Also, no usages -> empty fast path -> no fall out to slow path -> nothing left.
1389 #ifndef PRODUCT
1390       if (PrintEliminateAllocations) {
1391         tty->print("NotUsed ");
1392         Node* res = alloc->proj_out_or_null(TypeFunc::Parms);
1393         if (res != NULL) {
1394           res->dump();
1395         } else {
1396           alloc->dump();
1397         }
1398       }
1399 #endif
1400       yank_alloc_node(alloc);
1401       return;
1402     }
1403   }
1404 
1405   enum { too_big_or_final_path = 1, need_gc_path = 2 };
1406   Node *slow_region = NULL;
1407   Node *toobig_false = ctrl;
1408 
1409   // generate the initial test if necessary
1410   if (initial_slow_test != NULL ) {
1411     assert (expand_fast_path, "Only need test if there is a fast path");
1412     slow_region = new RegionNode(3);
1413 
1414     // Now make the initial failure test.  Usually a too-big test but
1415     // might be a TRUE for finalizers or a fancy class check for
1416     // newInstance0.
1417     IfNode* toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1418     transform_later(toobig_iff);
1419     // Plug the failing-too-big test into the slow-path region
1420     Node* toobig_true = new IfTrueNode(toobig_iff);
1421     transform_later(toobig_true);
1422     slow_region    ->init_req( too_big_or_final_path, toobig_true );
1423     toobig_false = new IfFalseNode(toobig_iff);
1424     transform_later(toobig_false);
1425   } else {
1426     // No initial test, just fall into next case
1427     assert(allocation_has_use || !expand_fast_path, "Should already have been handled");
1428     toobig_false = ctrl;
1429     debug_only(slow_region = NodeSentinel);
1430   }
1431 
1432   // If we are here there are several possibilities
1433   // - expand_fast_path is false - then only a slow path is expanded. That's it.
1434   // no_initial_check means a constant allocation.
1435   // - If check always evaluates to false -> expand_fast_path is false (see above)
1436   // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath)
1437   // if !allocation_has_use the fast path is empty
1438   // if !allocation_has_use && no_initial_check
1439   // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all.
1440   //   removed by yank_alloc_node above.
1441 
1442   Node *slow_mem = mem;  // save the current memory state for slow path
1443   // generate the fast allocation code unless we know that the initial test will always go slow
1444   if (expand_fast_path) {
1445     // Fast path modifies only raw memory.
1446     if (mem->is_MergeMem()) {
1447       mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1448     }
1449 
1450     // allocate the Region and Phi nodes for the result
1451     result_region = new RegionNode(3);
1452     result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1453     result_phi_i_o    = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1454 
1455     // Grab regular I/O before optional prefetch may change it.
1456     // Slow-path does no I/O so just set it to the original I/O.
1457     result_phi_i_o->init_req(slow_result_path, i_o);
1458 
1459     // Name successful fast-path variables
1460     Node* fast_oop_ctrl;
1461     Node* fast_oop_rawmem;
1462 
1463     if (allocation_has_use) {
1464       Node* needgc_ctrl = NULL;
1465       result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1466 
1467       intx prefetch_lines = length != NULL ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1468       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1469       Node* fast_oop = bs->obj_allocate(this, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1470                                         fast_oop_ctrl, fast_oop_rawmem,
1471                                         prefetch_lines);
1472 
1473       if (initial_slow_test != NULL) {
1474         // This completes all paths into the slow merge point
1475         slow_region->init_req(need_gc_path, needgc_ctrl);
1476         transform_later(slow_region);
1477       } else {
1478         // No initial slow path needed!
1479         // Just fall from the need-GC path straight into the VM call.
1480         slow_region = needgc_ctrl;
1481       }
1482 
1483       InitializeNode* init = alloc->initialization();
1484       fast_oop_rawmem = initialize_object(alloc,
1485                                           fast_oop_ctrl, fast_oop_rawmem, fast_oop,
1486                                           klass_node, length, size_in_bytes);
1487       expand_initialize_membar(alloc, init, fast_oop_ctrl, fast_oop_rawmem);
1488       expand_dtrace_alloc_probe(alloc, fast_oop, fast_oop_ctrl, fast_oop_rawmem);
1489 
1490       result_phi_rawoop->init_req(fast_result_path, fast_oop);
1491     } else {
1492       assert (initial_slow_test != NULL, "sanity");
1493       fast_oop_ctrl   = toobig_false;
1494       fast_oop_rawmem = mem;
1495       transform_later(slow_region);
1496     }
1497 
1498     // Plug in the successful fast-path into the result merge point
1499     result_region    ->init_req(fast_result_path, fast_oop_ctrl);
1500     result_phi_i_o   ->init_req(fast_result_path, i_o);
1501     result_phi_rawmem->init_req(fast_result_path, fast_oop_rawmem);
1502   } else {
1503     slow_region = ctrl;
1504     result_phi_i_o = i_o; // Rename it to use in the following code.
1505   }
1506 
1507   // Generate slow-path call
1508   CallNode *call = new CallStaticJavaNode(slow_call_type, slow_call_address,
1509                                OptoRuntime::stub_name(slow_call_address),
1510                                TypePtr::BOTTOM);
1511   call->init_req(TypeFunc::Control,   slow_region);
1512   call->init_req(TypeFunc::I_O,       top());    // does no i/o
1513   call->init_req(TypeFunc::Memory,    slow_mem); // may gc ptrs
1514   call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1515   call->init_req(TypeFunc::FramePtr,  alloc->in(TypeFunc::FramePtr));
1516 
1517   call->init_req(TypeFunc::Parms+0, klass_node);
1518   if (length != NULL) {
1519     call->init_req(TypeFunc::Parms+1, length);
1520   } else {
1521     // Let the runtime know if this is a larval allocation
1522     call->init_req(TypeFunc::Parms+1, _igvn.intcon(alloc->_larval));
1523   }
1524 
1525   // Copy debug information and adjust JVMState information, then replace
1526   // allocate node with the call
1527   call->copy_call_debug_info(&_igvn, alloc);
1528   // For array allocations, copy the valid length check to the call node so Compile::final_graph_reshaping() can verify
1529   // that the call has the expected number of CatchProj nodes (in case the allocation always fails and the fallthrough
1530   // path dies).
1531   if (valid_length_test != NULL) {
1532     call->add_req(valid_length_test);
1533   }
1534   if (expand_fast_path) {
1535     call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
1536   } else {
1537     // Hook i_o projection to avoid its elimination during allocation
1538     // replacement (when only a slow call is generated).
1539     call->set_req(TypeFunc::I_O, result_phi_i_o);
1540   }
1541   _igvn.replace_node(alloc, call);
1542   transform_later(call);
1543 
1544   // Identify the output projections from the allocate node and
1545   // adjust any references to them.
1546   // The control and io projections look like:
1547   //
1548   //        v---Proj(ctrl) <-----+   v---CatchProj(ctrl)
1549   //  Allocate                   Catch
1550   //        ^---Proj(io) <-------+   ^---CatchProj(io)
1551   //
1552   //  We are interested in the CatchProj nodes.
1553   //
1554   _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1555 
1556   // An allocate node has separate memory projections for the uses on
1557   // the control and i_o paths. Replace the control memory projection with
1558   // result_phi_rawmem (unless we are only generating a slow call when
1559   // both memory projections are combined)
1560   if (expand_fast_path && _callprojs->fallthrough_memproj != NULL) {
1561     _igvn.replace_in_uses(_callprojs->fallthrough_memproj, result_phi_rawmem);
1562   }
1563   // Now change uses of catchall_memproj to use fallthrough_memproj and delete
1564   // catchall_memproj so we end up with a call that has only 1 memory projection.
1565   if (_callprojs->catchall_memproj != NULL) {
1566     if (_callprojs->fallthrough_memproj == NULL) {
1567       _callprojs->fallthrough_memproj = new ProjNode(call, TypeFunc::Memory);
1568       transform_later(_callprojs->fallthrough_memproj);
1569     }
1570     _igvn.replace_in_uses(_callprojs->catchall_memproj, _callprojs->fallthrough_memproj);
1571     _igvn.remove_dead_node(_callprojs->catchall_memproj);
1572   }
1573 
1574   // An allocate node has separate i_o projections for the uses on the control
1575   // and i_o paths. Always replace the control i_o projection with result i_o
1576   // otherwise incoming i_o become dead when only a slow call is generated
1577   // (it is different from memory projections where both projections are
1578   // combined in such case).
1579   if (_callprojs->fallthrough_ioproj != NULL) {
1580     _igvn.replace_in_uses(_callprojs->fallthrough_ioproj, result_phi_i_o);
1581   }
1582   // Now change uses of catchall_ioproj to use fallthrough_ioproj and delete
1583   // catchall_ioproj so we end up with a call that has only 1 i_o projection.
1584   if (_callprojs->catchall_ioproj != NULL) {
1585     if (_callprojs->fallthrough_ioproj == NULL) {
1586       _callprojs->fallthrough_ioproj = new ProjNode(call, TypeFunc::I_O);
1587       transform_later(_callprojs->fallthrough_ioproj);
1588     }
1589     _igvn.replace_in_uses(_callprojs->catchall_ioproj, _callprojs->fallthrough_ioproj);
1590     _igvn.remove_dead_node(_callprojs->catchall_ioproj);
1591   }
1592 
1593   // if we generated only a slow call, we are done
1594   if (!expand_fast_path) {
1595     // Now we can unhook i_o.
1596     if (result_phi_i_o->outcnt() > 1) {
1597       call->set_req(TypeFunc::I_O, top());
1598     } else {
1599       assert(result_phi_i_o->unique_ctrl_out() == call, "sanity");
1600       // Case of new array with negative size known during compilation.
1601       // AllocateArrayNode::Ideal() optimization disconnect unreachable
1602       // following code since call to runtime will throw exception.
1603       // As result there will be no users of i_o after the call.
1604       // Leave i_o attached to this call to avoid problems in preceding graph.
1605     }
1606     return;
1607   }
1608 
1609   if (_callprojs->fallthrough_catchproj != NULL) {
1610     ctrl = _callprojs->fallthrough_catchproj->clone();
1611     transform_later(ctrl);
1612     _igvn.replace_node(_callprojs->fallthrough_catchproj, result_region);
1613   } else {
1614     ctrl = top();
1615   }
1616   Node *slow_result;
1617   if (_callprojs->resproj[0] == NULL) {
1618     // no uses of the allocation result
1619     slow_result = top();
1620   } else {
1621     slow_result = _callprojs->resproj[0]->clone();
1622     transform_later(slow_result);
1623     _igvn.replace_node(_callprojs->resproj[0], result_phi_rawoop);
1624   }
1625 
1626   // Plug slow-path into result merge point
1627   result_region->init_req( slow_result_path, ctrl);
1628   transform_later(result_region);
1629   if (allocation_has_use) {
1630     result_phi_rawoop->init_req(slow_result_path, slow_result);
1631     transform_later(result_phi_rawoop);
1632   }
1633   result_phi_rawmem->init_req(slow_result_path, _callprojs->fallthrough_memproj);
1634   transform_later(result_phi_rawmem);
1635   transform_later(result_phi_i_o);
1636   // This completes all paths into the result merge point
1637 }
1638 
1639 // Remove alloc node that has no uses.
1640 void PhaseMacroExpand::yank_alloc_node(AllocateNode* alloc) {
1641   Node* ctrl = alloc->in(TypeFunc::Control);
1642   Node* mem  = alloc->in(TypeFunc::Memory);
1643   Node* i_o  = alloc->in(TypeFunc::I_O);
1644 
1645   _callprojs = alloc->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1646   if (_callprojs->resproj[0] != NULL) {
1647     for (DUIterator_Fast imax, i = _callprojs->resproj[0]->fast_outs(imax); i < imax; i++) {
1648       Node* use = _callprojs->resproj[0]->fast_out(i);
1649       use->isa_MemBar()->remove(&_igvn);
1650       --imax;
1651       --i; // back up iterator
1652     }
1653     assert(_callprojs->resproj[0]->outcnt() == 0, "all uses must be deleted");
1654     _igvn.remove_dead_node(_callprojs->resproj[0]);
1655   }
1656   if (_callprojs->fallthrough_catchproj != NULL) {
1657     _igvn.replace_in_uses(_callprojs->fallthrough_catchproj, ctrl);
1658     _igvn.remove_dead_node(_callprojs->fallthrough_catchproj);
1659   }
1660   if (_callprojs->catchall_catchproj != NULL) {
1661     _igvn.rehash_node_delayed(_callprojs->catchall_catchproj);
1662     _callprojs->catchall_catchproj->set_req(0, top());
1663   }
1664   if (_callprojs->fallthrough_proj != NULL) {
1665     Node* catchnode = _callprojs->fallthrough_proj->unique_ctrl_out();
1666     _igvn.remove_dead_node(catchnode);
1667     _igvn.remove_dead_node(_callprojs->fallthrough_proj);
1668   }
1669   if (_callprojs->fallthrough_memproj != NULL) {
1670     _igvn.replace_in_uses(_callprojs->fallthrough_memproj, mem);
1671     _igvn.remove_dead_node(_callprojs->fallthrough_memproj);
1672   }
1673   if (_callprojs->fallthrough_ioproj != NULL) {
1674     _igvn.replace_in_uses(_callprojs->fallthrough_ioproj, i_o);
1675     _igvn.remove_dead_node(_callprojs->fallthrough_ioproj);
1676   }
1677   if (_callprojs->catchall_memproj != NULL) {
1678     _igvn.rehash_node_delayed(_callprojs->catchall_memproj);
1679     _callprojs->catchall_memproj->set_req(0, top());
1680   }
1681   if (_callprojs->catchall_ioproj != NULL) {
1682     _igvn.rehash_node_delayed(_callprojs->catchall_ioproj);
1683     _callprojs->catchall_ioproj->set_req(0, top());
1684   }
1685 #ifndef PRODUCT
1686   if (PrintEliminateAllocations) {
1687     if (alloc->is_AllocateArray()) {
1688       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1689     } else {
1690       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1691     }
1692   }
1693 #endif
1694   _igvn.remove_dead_node(alloc);
1695 }
1696 
1697 void PhaseMacroExpand::expand_initialize_membar(AllocateNode* alloc, InitializeNode* init,
1698                                                 Node*& fast_oop_ctrl, Node*& fast_oop_rawmem) {
1699   // If initialization is performed by an array copy, any required
1700   // MemBarStoreStore was already added. If the object does not
1701   // escape no need for a MemBarStoreStore. If the object does not
1702   // escape in its initializer and memory barrier (MemBarStoreStore or
1703   // stronger) is already added at exit of initializer, also no need
1704   // for a MemBarStoreStore. Otherwise we need a MemBarStoreStore
1705   // so that stores that initialize this object can't be reordered
1706   // with a subsequent store that makes this object accessible by
1707   // other threads.
1708   // Other threads include java threads and JVM internal threads
1709   // (for example concurrent GC threads). Current concurrent GC
1710   // implementation: G1 will not scan newly created object,
1711   // so it's safe to skip storestore barrier when allocation does
1712   // not escape.
1713   if (!alloc->does_not_escape_thread() &&
1714     !alloc->is_allocation_MemBar_redundant() &&
1715     (init == NULL || !init->is_complete_with_arraycopy())) {
1716     if (init == NULL || init->req() < InitializeNode::RawStores) {
1717       // No InitializeNode or no stores captured by zeroing
1718       // elimination. Simply add the MemBarStoreStore after object
1719       // initialization.
1720       MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
1721       transform_later(mb);
1722 
1723       mb->init_req(TypeFunc::Memory, fast_oop_rawmem);
1724       mb->init_req(TypeFunc::Control, fast_oop_ctrl);
1725       fast_oop_ctrl = new ProjNode(mb, TypeFunc::Control);
1726       transform_later(fast_oop_ctrl);
1727       fast_oop_rawmem = new ProjNode(mb, TypeFunc::Memory);
1728       transform_later(fast_oop_rawmem);
1729     } else {
1730       // Add the MemBarStoreStore after the InitializeNode so that
1731       // all stores performing the initialization that were moved
1732       // before the InitializeNode happen before the storestore
1733       // barrier.
1734 
1735       Node* init_ctrl = init->proj_out_or_null(TypeFunc::Control);
1736       Node* init_mem = init->proj_out_or_null(TypeFunc::Memory);
1737 
1738       MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
1739       transform_later(mb);
1740 
1741       Node* ctrl = new ProjNode(init, TypeFunc::Control);
1742       transform_later(ctrl);
1743       Node* mem = new ProjNode(init, TypeFunc::Memory);
1744       transform_later(mem);
1745 
1746       // The MemBarStoreStore depends on control and memory coming
1747       // from the InitializeNode
1748       mb->init_req(TypeFunc::Memory, mem);
1749       mb->init_req(TypeFunc::Control, ctrl);
1750 
1751       ctrl = new ProjNode(mb, TypeFunc::Control);
1752       transform_later(ctrl);
1753       mem = new ProjNode(mb, TypeFunc::Memory);
1754       transform_later(mem);
1755 
1756       // All nodes that depended on the InitializeNode for control
1757       // and memory must now depend on the MemBarNode that itself
1758       // depends on the InitializeNode
1759       if (init_ctrl != NULL) {
1760         _igvn.replace_node(init_ctrl, ctrl);
1761       }
1762       if (init_mem != NULL) {
1763         _igvn.replace_node(init_mem, mem);
1764       }
1765     }
1766   }
1767 }
1768 
1769 void PhaseMacroExpand::expand_dtrace_alloc_probe(AllocateNode* alloc, Node* oop,
1770                                                 Node*& ctrl, Node*& rawmem) {
1771   if (C->env()->dtrace_alloc_probes()) {
1772     // Slow-path call
1773     int size = TypeFunc::Parms + 2;
1774     CallLeafNode *call = new CallLeafNode(OptoRuntime::dtrace_object_alloc_Type(),
1775                                           CAST_FROM_FN_PTR(address,
1776                                           static_cast<int (*)(Thread*, oopDesc*)>(SharedRuntime::dtrace_object_alloc)),
1777                                           "dtrace_object_alloc",
1778                                           TypeRawPtr::BOTTOM);
1779 
1780     // Get base of thread-local storage area
1781     Node* thread = new ThreadLocalNode();
1782     transform_later(thread);
1783 
1784     call->init_req(TypeFunc::Parms + 0, thread);
1785     call->init_req(TypeFunc::Parms + 1, oop);
1786     call->init_req(TypeFunc::Control, ctrl);
1787     call->init_req(TypeFunc::I_O    , top()); // does no i/o
1788     call->init_req(TypeFunc::Memory , rawmem);
1789     call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1790     call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1791     transform_later(call);
1792     ctrl = new ProjNode(call, TypeFunc::Control);
1793     transform_later(ctrl);
1794     rawmem = new ProjNode(call, TypeFunc::Memory);
1795     transform_later(rawmem);
1796   }
1797 }
1798 
1799 // Helper for PhaseMacroExpand::expand_allocate_common.
1800 // Initializes the newly-allocated storage.
1801 Node* PhaseMacroExpand::initialize_object(AllocateNode* alloc,
1802                                           Node* control, Node* rawmem, Node* object,
1803                                           Node* klass_node, Node* length,
1804                                           Node* size_in_bytes) {
1805   InitializeNode* init = alloc->initialization();
1806   // Store the klass & mark bits
1807   Node* mark_node = alloc->make_ideal_mark(&_igvn, control, rawmem);
1808   if (!mark_node->is_Con()) {
1809     transform_later(mark_node);
1810   }
1811   rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
1812 
1813   rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
1814   int header_size = alloc->minimum_header_size();  // conservatively small
1815 
1816   // Array length
1817   if (length != NULL) {         // Arrays need length field
1818     rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1819     // conservatively small header size:
1820     header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1821     ciKlass* k = _igvn.type(klass_node)->is_klassptr()->klass();
1822     if (k->is_array_klass())    // we know the exact header size in most cases:
1823       header_size = Klass::layout_helper_header_size(k->layout_helper());
1824   }
1825 
1826   // Clear the object body, if necessary.
1827   if (init == NULL) {
1828     // The init has somehow disappeared; be cautious and clear everything.
1829     //
1830     // This can happen if a node is allocated but an uncommon trap occurs
1831     // immediately.  In this case, the Initialize gets associated with the
1832     // trap, and may be placed in a different (outer) loop, if the Allocate
1833     // is in a loop.  If (this is rare) the inner loop gets unrolled, then
1834     // there can be two Allocates to one Initialize.  The answer in all these
1835     // edge cases is safety first.  It is always safe to clear immediately
1836     // within an Allocate, and then (maybe or maybe not) clear some more later.
1837     if (!(UseTLAB && ZeroTLAB)) {
1838       rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
1839                                             alloc->in(AllocateNode::DefaultValue),
1840                                             alloc->in(AllocateNode::RawDefaultValue),
1841                                             header_size, size_in_bytes,
1842                                             &_igvn);
1843     }
1844   } else {
1845     if (!init->is_complete()) {
1846       // Try to win by zeroing only what the init does not store.
1847       // We can also try to do some peephole optimizations,
1848       // such as combining some adjacent subword stores.
1849       rawmem = init->complete_stores(control, rawmem, object,
1850                                      header_size, size_in_bytes, &_igvn);
1851     }
1852     // We have no more use for this link, since the AllocateNode goes away:
1853     init->set_req(InitializeNode::RawAddress, top());
1854     // (If we keep the link, it just confuses the register allocator,
1855     // who thinks he sees a real use of the address by the membar.)
1856   }
1857 
1858   return rawmem;
1859 }
1860 
1861 // Generate prefetch instructions for next allocations.
1862 Node* PhaseMacroExpand::prefetch_allocation(Node* i_o, Node*& needgc_false,
1863                                         Node*& contended_phi_rawmem,
1864                                         Node* old_eden_top, Node* new_eden_top,
1865                                         intx lines) {
1866    enum { fall_in_path = 1, pf_path = 2 };
1867    if( UseTLAB && AllocatePrefetchStyle == 2 ) {
1868       // Generate prefetch allocation with watermark check.
1869       // As an allocation hits the watermark, we will prefetch starting
1870       // at a "distance" away from watermark.
1871 
1872       Node *pf_region = new RegionNode(3);
1873       Node *pf_phi_rawmem = new PhiNode( pf_region, Type::MEMORY,
1874                                                 TypeRawPtr::BOTTOM );
1875       // I/O is used for Prefetch
1876       Node *pf_phi_abio = new PhiNode( pf_region, Type::ABIO );
1877 
1878       Node *thread = new ThreadLocalNode();
1879       transform_later(thread);
1880 
1881       Node *eden_pf_adr = new AddPNode( top()/*not oop*/, thread,
1882                    _igvn.MakeConX(in_bytes(JavaThread::tlab_pf_top_offset())) );
1883       transform_later(eden_pf_adr);
1884 
1885       Node *old_pf_wm = new LoadPNode(needgc_false,
1886                                    contended_phi_rawmem, eden_pf_adr,
1887                                    TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM,
1888                                    MemNode::unordered);
1889       transform_later(old_pf_wm);
1890 
1891       // check against new_eden_top
1892       Node *need_pf_cmp = new CmpPNode( new_eden_top, old_pf_wm );
1893       transform_later(need_pf_cmp);
1894       Node *need_pf_bol = new BoolNode( need_pf_cmp, BoolTest::ge );
1895       transform_later(need_pf_bol);
1896       IfNode *need_pf_iff = new IfNode( needgc_false, need_pf_bol,
1897                                        PROB_UNLIKELY_MAG(4), COUNT_UNKNOWN );
1898       transform_later(need_pf_iff);
1899 
1900       // true node, add prefetchdistance
1901       Node *need_pf_true = new IfTrueNode( need_pf_iff );
1902       transform_later(need_pf_true);
1903 
1904       Node *need_pf_false = new IfFalseNode( need_pf_iff );
1905       transform_later(need_pf_false);
1906 
1907       Node *new_pf_wmt = new AddPNode( top(), old_pf_wm,
1908                                     _igvn.MakeConX(AllocatePrefetchDistance) );
1909       transform_later(new_pf_wmt );
1910       new_pf_wmt->set_req(0, need_pf_true);
1911 
1912       Node *store_new_wmt = new StorePNode(need_pf_true,
1913                                        contended_phi_rawmem, eden_pf_adr,
1914                                        TypeRawPtr::BOTTOM, new_pf_wmt,
1915                                        MemNode::unordered);
1916       transform_later(store_new_wmt);
1917 
1918       // adding prefetches
1919       pf_phi_abio->init_req( fall_in_path, i_o );
1920 
1921       Node *prefetch_adr;
1922       Node *prefetch;
1923       uint step_size = AllocatePrefetchStepSize;
1924       uint distance = 0;
1925 
1926       for ( intx i = 0; i < lines; i++ ) {
1927         prefetch_adr = new AddPNode( old_pf_wm, new_pf_wmt,
1928                                             _igvn.MakeConX(distance) );
1929         transform_later(prefetch_adr);
1930         prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
1931         transform_later(prefetch);
1932         distance += step_size;
1933         i_o = prefetch;
1934       }
1935       pf_phi_abio->set_req( pf_path, i_o );
1936 
1937       pf_region->init_req( fall_in_path, need_pf_false );
1938       pf_region->init_req( pf_path, need_pf_true );
1939 
1940       pf_phi_rawmem->init_req( fall_in_path, contended_phi_rawmem );
1941       pf_phi_rawmem->init_req( pf_path, store_new_wmt );
1942 
1943       transform_later(pf_region);
1944       transform_later(pf_phi_rawmem);
1945       transform_later(pf_phi_abio);
1946 
1947       needgc_false = pf_region;
1948       contended_phi_rawmem = pf_phi_rawmem;
1949       i_o = pf_phi_abio;
1950    } else if( UseTLAB && AllocatePrefetchStyle == 3 ) {
1951       // Insert a prefetch instruction for each allocation.
1952       // This code is used to generate 1 prefetch instruction per cache line.
1953 
1954       // Generate several prefetch instructions.
1955       uint step_size = AllocatePrefetchStepSize;
1956       uint distance = AllocatePrefetchDistance;
1957 
1958       // Next cache address.
1959       Node *cache_adr = new AddPNode(old_eden_top, old_eden_top,
1960                                      _igvn.MakeConX(step_size + distance));
1961       transform_later(cache_adr);
1962       cache_adr = new CastP2XNode(needgc_false, cache_adr);
1963       transform_later(cache_adr);
1964       // Address is aligned to execute prefetch to the beginning of cache line size
1965       // (it is important when BIS instruction is used on SPARC as prefetch).
1966       Node* mask = _igvn.MakeConX(~(intptr_t)(step_size-1));
1967       cache_adr = new AndXNode(cache_adr, mask);
1968       transform_later(cache_adr);
1969       cache_adr = new CastX2PNode(cache_adr);
1970       transform_later(cache_adr);
1971 
1972       // Prefetch
1973       Node *prefetch = new PrefetchAllocationNode( contended_phi_rawmem, cache_adr );
1974       prefetch->set_req(0, needgc_false);
1975       transform_later(prefetch);
1976       contended_phi_rawmem = prefetch;
1977       Node *prefetch_adr;
1978       distance = step_size;
1979       for ( intx i = 1; i < lines; i++ ) {
1980         prefetch_adr = new AddPNode( cache_adr, cache_adr,
1981                                             _igvn.MakeConX(distance) );
1982         transform_later(prefetch_adr);
1983         prefetch = new PrefetchAllocationNode( contended_phi_rawmem, prefetch_adr );
1984         transform_later(prefetch);
1985         distance += step_size;
1986         contended_phi_rawmem = prefetch;
1987       }
1988    } else if( AllocatePrefetchStyle > 0 ) {
1989       // Insert a prefetch for each allocation only on the fast-path
1990       Node *prefetch_adr;
1991       Node *prefetch;
1992       // Generate several prefetch instructions.
1993       uint step_size = AllocatePrefetchStepSize;
1994       uint distance = AllocatePrefetchDistance;
1995       for ( intx i = 0; i < lines; i++ ) {
1996         prefetch_adr = new AddPNode( old_eden_top, new_eden_top,
1997                                             _igvn.MakeConX(distance) );
1998         transform_later(prefetch_adr);
1999         prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
2000         // Do not let it float too high, since if eden_top == eden_end,
2001         // both might be null.
2002         if( i == 0 ) { // Set control for first prefetch, next follows it
2003           prefetch->init_req(0, needgc_false);
2004         }
2005         transform_later(prefetch);
2006         distance += step_size;
2007         i_o = prefetch;
2008       }
2009    }
2010    return i_o;
2011 }
2012 
2013 
2014 void PhaseMacroExpand::expand_allocate(AllocateNode *alloc) {
2015   expand_allocate_common(alloc, NULL,
2016                          OptoRuntime::new_instance_Type(),
2017                          OptoRuntime::new_instance_Java(), NULL);
2018 }
2019 
2020 void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) {
2021   Node* length = alloc->in(AllocateNode::ALength);
2022   Node* valid_length_test = alloc->in(AllocateNode::ValidLengthTest);
2023   InitializeNode* init = alloc->initialization();
2024   Node* klass_node = alloc->in(AllocateNode::KlassNode);
2025   ciKlass* k = _igvn.type(klass_node)->is_klassptr()->klass();
2026   address slow_call_address;  // Address of slow call
2027   if (init != NULL && init->is_complete_with_arraycopy() &&
2028       k->is_type_array_klass()) {
2029     // Don't zero type array during slow allocation in VM since
2030     // it will be initialized later by arraycopy in compiled code.
2031     slow_call_address = OptoRuntime::new_array_nozero_Java();
2032   } else {
2033     slow_call_address = OptoRuntime::new_array_Java();
2034   }
2035   expand_allocate_common(alloc, length,
2036                          OptoRuntime::new_array_Type(),
2037                          slow_call_address, valid_length_test);
2038 }
2039 
2040 //-------------------mark_eliminated_box----------------------------------
2041 //
2042 // During EA obj may point to several objects but after few ideal graph
2043 // transformations (CCP) it may point to only one non escaping object
2044 // (but still using phi), corresponding locks and unlocks will be marked
2045 // for elimination. Later obj could be replaced with a new node (new phi)
2046 // and which does not have escape information. And later after some graph
2047 // reshape other locks and unlocks (which were not marked for elimination
2048 // before) are connected to this new obj (phi) but they still will not be
2049 // marked for elimination since new obj has no escape information.
2050 // Mark all associated (same box and obj) lock and unlock nodes for
2051 // elimination if some of them marked already.
2052 void PhaseMacroExpand::mark_eliminated_box(Node* oldbox, Node* obj) {
2053   if (oldbox->as_BoxLock()->is_eliminated()) {
2054     return; // This BoxLock node was processed already.
2055   }
2056   // New implementation (EliminateNestedLocks) has separate BoxLock
2057   // node for each locked region so mark all associated locks/unlocks as
2058   // eliminated even if different objects are referenced in one locked region
2059   // (for example, OSR compilation of nested loop inside locked scope).
2060   if (EliminateNestedLocks ||
2061       oldbox->as_BoxLock()->is_simple_lock_region(NULL, obj, NULL)) {
2062     // Box is used only in one lock region. Mark this box as eliminated.
2063     _igvn.hash_delete(oldbox);
2064     oldbox->as_BoxLock()->set_eliminated(); // This changes box's hash value
2065      _igvn.hash_insert(oldbox);
2066 
2067     for (uint i = 0; i < oldbox->outcnt(); i++) {
2068       Node* u = oldbox->raw_out(i);
2069       if (u->is_AbstractLock() && !u->as_AbstractLock()->is_non_esc_obj()) {
2070         AbstractLockNode* alock = u->as_AbstractLock();
2071         // Check lock's box since box could be referenced by Lock's debug info.
2072         if (alock->box_node() == oldbox) {
2073           // Mark eliminated all related locks and unlocks.
2074 #ifdef ASSERT
2075           alock->log_lock_optimization(C, "eliminate_lock_set_non_esc4");
2076 #endif
2077           alock->set_non_esc_obj();
2078         }
2079       }
2080     }
2081     return;
2082   }
2083 
2084   // Create new "eliminated" BoxLock node and use it in monitor debug info
2085   // instead of oldbox for the same object.
2086   BoxLockNode* newbox = oldbox->clone()->as_BoxLock();
2087 
2088   // Note: BoxLock node is marked eliminated only here and it is used
2089   // to indicate that all associated lock and unlock nodes are marked
2090   // for elimination.
2091   newbox->set_eliminated();
2092   transform_later(newbox);
2093 
2094   // Replace old box node with new box for all users of the same object.
2095   for (uint i = 0; i < oldbox->outcnt();) {
2096     bool next_edge = true;
2097 
2098     Node* u = oldbox->raw_out(i);
2099     if (u->is_AbstractLock()) {
2100       AbstractLockNode* alock = u->as_AbstractLock();
2101       if (alock->box_node() == oldbox && alock->obj_node()->eqv_uncast(obj)) {
2102         // Replace Box and mark eliminated all related locks and unlocks.
2103 #ifdef ASSERT
2104         alock->log_lock_optimization(C, "eliminate_lock_set_non_esc5");
2105 #endif
2106         alock->set_non_esc_obj();
2107         _igvn.rehash_node_delayed(alock);
2108         alock->set_box_node(newbox);
2109         next_edge = false;
2110       }
2111     }
2112     if (u->is_FastLock() && u->as_FastLock()->obj_node()->eqv_uncast(obj)) {
2113       FastLockNode* flock = u->as_FastLock();
2114       assert(flock->box_node() == oldbox, "sanity");
2115       _igvn.rehash_node_delayed(flock);
2116       flock->set_box_node(newbox);
2117       next_edge = false;
2118     }
2119 
2120     // Replace old box in monitor debug info.
2121     if (u->is_SafePoint() && u->as_SafePoint()->jvms()) {
2122       SafePointNode* sfn = u->as_SafePoint();
2123       JVMState* youngest_jvms = sfn->jvms();
2124       int max_depth = youngest_jvms->depth();
2125       for (int depth = 1; depth <= max_depth; depth++) {
2126         JVMState* jvms = youngest_jvms->of_depth(depth);
2127         int num_mon  = jvms->nof_monitors();
2128         // Loop over monitors
2129         for (int idx = 0; idx < num_mon; idx++) {
2130           Node* obj_node = sfn->monitor_obj(jvms, idx);
2131           Node* box_node = sfn->monitor_box(jvms, idx);
2132           if (box_node == oldbox && obj_node->eqv_uncast(obj)) {
2133             int j = jvms->monitor_box_offset(idx);
2134             _igvn.replace_input_of(u, j, newbox);
2135             next_edge = false;
2136           }
2137         }
2138       }
2139     }
2140     if (next_edge) i++;
2141   }
2142 }
2143 
2144 //-----------------------mark_eliminated_locking_nodes-----------------------
2145 void PhaseMacroExpand::mark_eliminated_locking_nodes(AbstractLockNode *alock) {
2146   if (EliminateNestedLocks) {
2147     if (alock->is_nested()) {
2148        assert(alock->box_node()->as_BoxLock()->is_eliminated(), "sanity");
2149        return;
2150     } else if (!alock->is_non_esc_obj()) { // Not eliminated or coarsened
2151       // Only Lock node has JVMState needed here.
2152       // Not that preceding claim is documented anywhere else.
2153       if (alock->jvms() != NULL) {
2154         if (alock->as_Lock()->is_nested_lock_region()) {
2155           // Mark eliminated related nested locks and unlocks.
2156           Node* obj = alock->obj_node();
2157           BoxLockNode* box_node = alock->box_node()->as_BoxLock();
2158           assert(!box_node->is_eliminated(), "should not be marked yet");
2159           // Note: BoxLock node is marked eliminated only here
2160           // and it is used to indicate that all associated lock
2161           // and unlock nodes are marked for elimination.
2162           box_node->set_eliminated(); // Box's hash is always NO_HASH here
2163           for (uint i = 0; i < box_node->outcnt(); i++) {
2164             Node* u = box_node->raw_out(i);
2165             if (u->is_AbstractLock()) {
2166               alock = u->as_AbstractLock();
2167               if (alock->box_node() == box_node) {
2168                 // Verify that this Box is referenced only by related locks.
2169                 assert(alock->obj_node()->eqv_uncast(obj), "");
2170                 // Mark all related locks and unlocks.
2171 #ifdef ASSERT
2172                 alock->log_lock_optimization(C, "eliminate_lock_set_nested");
2173 #endif
2174                 alock->set_nested();
2175               }
2176             }
2177           }
2178         } else {
2179 #ifdef ASSERT
2180           alock->log_lock_optimization(C, "eliminate_lock_NOT_nested_lock_region");
2181           if (C->log() != NULL)
2182             alock->as_Lock()->is_nested_lock_region(C); // rerun for debugging output
2183 #endif
2184         }
2185       }
2186       return;
2187     }
2188     // Process locks for non escaping object
2189     assert(alock->is_non_esc_obj(), "");
2190   } // EliminateNestedLocks
2191 
2192   if (alock->is_non_esc_obj()) { // Lock is used for non escaping object
2193     // Look for all locks of this object and mark them and
2194     // corresponding BoxLock nodes as eliminated.
2195     Node* obj = alock->obj_node();
2196     for (uint j = 0; j < obj->outcnt(); j++) {
2197       Node* o = obj->raw_out(j);
2198       if (o->is_AbstractLock() &&
2199           o->as_AbstractLock()->obj_node()->eqv_uncast(obj)) {
2200         alock = o->as_AbstractLock();
2201         Node* box = alock->box_node();
2202         // Replace old box node with new eliminated box for all users
2203         // of the same object and mark related locks as eliminated.
2204         mark_eliminated_box(box, obj);
2205       }
2206     }
2207   }
2208 }
2209 
2210 void PhaseMacroExpand::inline_type_guard(Node** ctrl, LockNode* lock) {
2211   Node* obj = lock->obj_node();
2212   const TypePtr* obj_type = _igvn.type(obj)->make_ptr();
2213   if (!obj_type->can_be_inline_type()) {
2214     return;
2215   }
2216   Node* mark = make_load(*ctrl, lock->memory(), obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
2217   Node* value_mask = _igvn.MakeConX(markWord::inline_type_pattern);
2218   Node* is_value = _igvn.transform(new AndXNode(mark, value_mask));
2219   Node* cmp = _igvn.transform(new CmpXNode(is_value, value_mask));
2220   Node* bol = _igvn.transform(new BoolNode(cmp, BoolTest::eq));
2221   Node* unc_ctrl = generate_slow_guard(ctrl, bol, NULL);
2222 
2223   int trap_request = Deoptimization::make_trap_request(Deoptimization::Reason_class_check, Deoptimization::Action_none);
2224   address call_addr = SharedRuntime::uncommon_trap_blob()->entry_point();
2225   const TypePtr* no_memory_effects = NULL;
2226   CallNode* unc = new CallStaticJavaNode(OptoRuntime::uncommon_trap_Type(), call_addr, "uncommon_trap",
2227                                          no_memory_effects);
2228   unc->init_req(TypeFunc::Control, unc_ctrl);
2229   unc->init_req(TypeFunc::I_O, lock->i_o());
2230   unc->init_req(TypeFunc::Memory, lock->memory());
2231   unc->init_req(TypeFunc::FramePtr,  lock->in(TypeFunc::FramePtr));
2232   unc->init_req(TypeFunc::ReturnAdr, lock->in(TypeFunc::ReturnAdr));
2233   unc->init_req(TypeFunc::Parms+0, _igvn.intcon(trap_request));
2234   unc->set_cnt(PROB_UNLIKELY_MAG(4));
2235   unc->copy_call_debug_info(&_igvn, lock);
2236 
2237   assert(unc->peek_monitor_box() == lock->box_node(), "wrong monitor");
2238   assert((obj_type->is_inlinetypeptr() && unc->peek_monitor_obj()->is_SafePointScalarObject()) ||
2239          (obj->is_InlineTypePtr() && obj->in(1) == unc->peek_monitor_obj()) ||
2240          (obj == unc->peek_monitor_obj()), "wrong monitor");
2241 
2242   // pop monitor and push obj back on stack: we trap before the monitorenter
2243   unc->pop_monitor();
2244   unc->grow_stack(unc->jvms(), 1);
2245   unc->set_stack(unc->jvms(), unc->jvms()->stk_size()-1, obj);
2246   _igvn.register_new_node_with_optimizer(unc);
2247 
2248   unc_ctrl = _igvn.transform(new ProjNode(unc, TypeFunc::Control));
2249   Node* halt = _igvn.transform(new HaltNode(unc_ctrl, lock->in(TypeFunc::FramePtr), "monitor enter on inline type"));
2250   C->root()->add_req(halt);
2251 }
2252 
2253 // we have determined that this lock/unlock can be eliminated, we simply
2254 // eliminate the node without expanding it.
2255 //
2256 // Note:  The membar's associated with the lock/unlock are currently not
2257 //        eliminated.  This should be investigated as a future enhancement.
2258 //
2259 bool PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) {
2260 
2261   if (!alock->is_eliminated()) {
2262     return false;
2263   }
2264 #ifdef ASSERT
2265   if (!alock->is_coarsened()) {
2266     // Check that new "eliminated" BoxLock node is created.
2267     BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2268     assert(oldbox->is_eliminated(), "should be done already");
2269   }
2270 #endif
2271 
2272   alock->log_lock_optimization(C, "eliminate_lock");
2273 
2274 #ifndef PRODUCT
2275   if (PrintEliminateLocks) {
2276     tty->print_cr("++++ Eliminated: %d %s '%s'", alock->_idx, (alock->is_Lock() ? "Lock" : "Unlock"), alock->kind_as_string());
2277   }
2278 #endif
2279 
2280   Node* mem  = alock->in(TypeFunc::Memory);
2281   Node* ctrl = alock->in(TypeFunc::Control);
2282   guarantee(ctrl != NULL, "missing control projection, cannot replace_node() with NULL");
2283 
2284   _callprojs = alock->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
2285   // There are 2 projections from the lock.  The lock node will
2286   // be deleted when its last use is subsumed below.
2287   assert(alock->outcnt() == 2 &&
2288          _callprojs->fallthrough_proj != NULL &&
2289          _callprojs->fallthrough_memproj != NULL,
2290          "Unexpected projections from Lock/Unlock");
2291 
2292   Node* fallthroughproj = _callprojs->fallthrough_proj;
2293   Node* memproj_fallthrough = _callprojs->fallthrough_memproj;
2294 
2295   // The memory projection from a lock/unlock is RawMem
2296   // The input to a Lock is merged memory, so extract its RawMem input
2297   // (unless the MergeMem has been optimized away.)
2298   if (alock->is_Lock()) {
2299     // Deoptimize and re-execute if object is an inline type
2300     inline_type_guard(&ctrl, alock->as_Lock());
2301 
2302     // Seach for MemBarAcquireLock node and delete it also.
2303     MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
2304     assert(membar != NULL && membar->Opcode() == Op_MemBarAcquireLock, "");
2305     Node* ctrlproj = membar->proj_out(TypeFunc::Control);
2306     Node* memproj = membar->proj_out(TypeFunc::Memory);
2307     _igvn.replace_node(ctrlproj, fallthroughproj);
2308     _igvn.replace_node(memproj, memproj_fallthrough);
2309 
2310     // Delete FastLock node also if this Lock node is unique user
2311     // (a loop peeling may clone a Lock node).
2312     Node* flock = alock->as_Lock()->fastlock_node();
2313     if (flock->outcnt() == 1) {
2314       assert(flock->unique_out() == alock, "sanity");
2315       _igvn.replace_node(flock, top());
2316     }
2317   }
2318 
2319   // Seach for MemBarReleaseLock node and delete it also.
2320   if (alock->is_Unlock() && ctrl->is_Proj() && ctrl->in(0)->is_MemBar()) {
2321     MemBarNode* membar = ctrl->in(0)->as_MemBar();
2322     assert(membar->Opcode() == Op_MemBarReleaseLock &&
2323            mem->is_Proj() && membar == mem->in(0), "");
2324     _igvn.replace_node(fallthroughproj, ctrl);
2325     _igvn.replace_node(memproj_fallthrough, mem);
2326     fallthroughproj = ctrl;
2327     memproj_fallthrough = mem;
2328     ctrl = membar->in(TypeFunc::Control);
2329     mem  = membar->in(TypeFunc::Memory);
2330   }
2331 
2332   _igvn.replace_node(fallthroughproj, ctrl);
2333   _igvn.replace_node(memproj_fallthrough, mem);
2334   return true;
2335 }
2336 
2337 
2338 //------------------------------expand_lock_node----------------------
2339 void PhaseMacroExpand::expand_lock_node(LockNode *lock) {
2340 
2341   Node* ctrl = lock->in(TypeFunc::Control);
2342   Node* mem = lock->in(TypeFunc::Memory);
2343   Node* obj = lock->obj_node();
2344   Node* box = lock->box_node();
2345   Node* flock = lock->fastlock_node();
2346 
2347   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2348 
2349   // Make the merge point
2350   Node *region;
2351   Node *mem_phi;
2352   Node *slow_path;
2353 
2354   region  = new RegionNode(3);
2355   // create a Phi for the memory state
2356   mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2357 
2358   // Optimize test; set region slot 2
2359   slow_path = opt_bits_test(ctrl, region, 2, flock, 0, 0);
2360   mem_phi->init_req(2, mem);
2361 
2362   // Deoptimize and re-execute if object is an inline type
2363   inline_type_guard(&slow_path, lock);
2364 
2365   // Make slow path call
2366   CallNode *call = make_slow_call((CallNode *) lock, OptoRuntime::complete_monitor_enter_Type(),
2367                                   OptoRuntime::complete_monitor_locking_Java(), NULL, slow_path,
2368                                   obj, box, NULL);
2369 
2370   _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
2371 
2372   // Slow path can only throw asynchronous exceptions, which are always
2373   // de-opted.  So the compiler thinks the slow-call can never throw an
2374   // exception.  If it DOES throw an exception we would need the debug
2375   // info removed first (since if it throws there is no monitor).
2376   assert(_callprojs->fallthrough_ioproj == NULL && _callprojs->catchall_ioproj == NULL &&
2377          _callprojs->catchall_memproj == NULL && _callprojs->catchall_catchproj == NULL, "Unexpected projection from Lock");
2378 
2379   // Capture slow path
2380   // disconnect fall-through projection from call and create a new one
2381   // hook up users of fall-through projection to region
2382   Node *slow_ctrl = _callprojs->fallthrough_proj->clone();
2383   transform_later(slow_ctrl);
2384   _igvn.hash_delete(_callprojs->fallthrough_proj);
2385   _callprojs->fallthrough_proj->disconnect_inputs(C);
2386   region->init_req(1, slow_ctrl);
2387   // region inputs are now complete
2388   transform_later(region);
2389   _igvn.replace_node(_callprojs->fallthrough_proj, region);
2390 
2391   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2392   mem_phi->init_req(1, memproj );
2393   transform_later(mem_phi);
2394   _igvn.replace_node(_callprojs->fallthrough_memproj, mem_phi);
2395 }
2396 
2397 //------------------------------expand_unlock_node----------------------
2398 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
2399 
2400   Node* ctrl = unlock->in(TypeFunc::Control);
2401   Node* mem = unlock->in(TypeFunc::Memory);
2402   Node* obj = unlock->obj_node();
2403   Node* box = unlock->box_node();
2404 
2405   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2406 
2407   // No need for a null check on unlock
2408 
2409   // Make the merge point
2410   Node *region;
2411   Node *mem_phi;
2412 
2413   region  = new RegionNode(3);
2414   // create a Phi for the memory state
2415   mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2416 
2417   FastUnlockNode *funlock = new FastUnlockNode( ctrl, obj, box );
2418   funlock = transform_later( funlock )->as_FastUnlock();
2419   // Optimize test; set region slot 2
2420   Node *slow_path = opt_bits_test(ctrl, region, 2, funlock, 0, 0);
2421   Node *thread = transform_later(new ThreadLocalNode());
2422 
2423   CallNode *call = make_slow_call((CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(),
2424                                   CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C),
2425                                   "complete_monitor_unlocking_C", slow_path, obj, box, thread);
2426 
2427   _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
2428   assert(_callprojs->fallthrough_ioproj == NULL && _callprojs->catchall_ioproj == NULL &&
2429          _callprojs->catchall_memproj == NULL && _callprojs->catchall_catchproj == NULL, "Unexpected projection from Lock");
2430 
2431   // No exceptions for unlocking
2432   // Capture slow path
2433   // disconnect fall-through projection from call and create a new one
2434   // hook up users of fall-through projection to region
2435   Node *slow_ctrl = _callprojs->fallthrough_proj->clone();
2436   transform_later(slow_ctrl);
2437   _igvn.hash_delete(_callprojs->fallthrough_proj);
2438   _callprojs->fallthrough_proj->disconnect_inputs(C);
2439   region->init_req(1, slow_ctrl);
2440   // region inputs are now complete
2441   transform_later(region);
2442   _igvn.replace_node(_callprojs->fallthrough_proj, region);
2443 
2444   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory) );
2445   mem_phi->init_req(1, memproj );
2446   mem_phi->init_req(2, mem);
2447   transform_later(mem_phi);
2448   _igvn.replace_node(_callprojs->fallthrough_memproj, mem_phi);
2449 }
2450 
2451 // An inline type might be returned from the call but we don't know its
2452 // type. Either we get a buffered inline type (and nothing needs to be done)
2453 // or one of the inlines being returned is the klass of the inline type
2454 // and we need to allocate an inline type instance of that type and
2455 // initialize it with other values being returned. In that case, we
2456 // first try a fast path allocation and initialize the value with the
2457 // inline klass's pack handler or we fall back to a runtime call.
2458 void PhaseMacroExpand::expand_mh_intrinsic_return(CallStaticJavaNode* call) {
2459   assert(call->method()->is_method_handle_intrinsic(), "must be a method handle intrinsic call");
2460   Node* ret = call->proj_out_or_null(TypeFunc::Parms);
2461   if (ret == NULL) {
2462     return;
2463   }
2464   const TypeFunc* tf = call->_tf;
2465   const TypeTuple* domain = OptoRuntime::store_inline_type_fields_Type()->domain_cc();
2466   const TypeFunc* new_tf = TypeFunc::make(tf->domain_sig(), tf->domain_cc(), tf->range_sig(), domain);
2467   call->_tf = new_tf;
2468   // Make sure the change of type is applied before projections are processed by igvn
2469   _igvn.set_type(call, call->Value(&_igvn));
2470   _igvn.set_type(ret, ret->Value(&_igvn));
2471 
2472   // Before any new projection is added:
2473   CallProjections* projs = call->extract_projections(true, true);
2474 
2475   // Create temporary hook nodes that will be replaced below.
2476   // Add an input to prevent hook nodes from being dead.
2477   Node* ctl = new Node(call);
2478   Node* mem = new Node(ctl);
2479   Node* io = new Node(ctl);
2480   Node* ex_ctl = new Node(ctl);
2481   Node* ex_mem = new Node(ctl);
2482   Node* ex_io = new Node(ctl);
2483   Node* res = new Node(ctl);
2484 
2485   // Allocate a new buffered inline type only if a new one is not returned
2486   Node* cast = transform_later(new CastP2XNode(ctl, res));
2487   Node* mask = MakeConX(0x1);
2488   Node* masked = transform_later(new AndXNode(cast, mask));
2489   Node* cmp = transform_later(new CmpXNode(masked, mask));
2490   Node* bol = transform_later(new BoolNode(cmp, BoolTest::eq));
2491   IfNode* allocation_iff = new IfNode(ctl, bol, PROB_MAX, COUNT_UNKNOWN);
2492   transform_later(allocation_iff);
2493   Node* allocation_ctl = transform_later(new IfTrueNode(allocation_iff));
2494   Node* no_allocation_ctl = transform_later(new IfFalseNode(allocation_iff));
2495   Node* no_allocation_res = transform_later(new CheckCastPPNode(no_allocation_ctl, res, TypeInstPtr::BOTTOM));
2496 
2497   // Try to allocate a new buffered inline instance either from TLAB or eden space
2498   Node* needgc_ctrl = NULL; // needgc means slowcase, i.e. allocation failed
2499   CallLeafNoFPNode* handler_call;
2500   const bool alloc_in_place = (UseTLAB || Universe::heap()->supports_inline_contig_alloc());
2501   if (alloc_in_place) {
2502     Node* fast_oop_ctrl = NULL;
2503     Node* fast_oop_rawmem = NULL;
2504     Node* mask2 = MakeConX(-2);
2505     Node* masked2 = transform_later(new AndXNode(cast, mask2));
2506     Node* rawklassptr = transform_later(new CastX2PNode(masked2));
2507     Node* klass_node = transform_later(new CheckCastPPNode(allocation_ctl, rawklassptr, TypeInstKlassPtr::OBJECT_OR_NULL));
2508     Node* layout_val = make_load(NULL, mem, klass_node, in_bytes(Klass::layout_helper_offset()), TypeInt::INT, T_INT);
2509     Node* size_in_bytes = ConvI2X(layout_val);
2510     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2511     Node* fast_oop = bs->obj_allocate(this, mem, allocation_ctl, size_in_bytes, io, needgc_ctrl,
2512                                       fast_oop_ctrl, fast_oop_rawmem,
2513                                       AllocateInstancePrefetchLines);
2514     // Allocation succeed, initialize buffered inline instance header firstly,
2515     // and then initialize its fields with an inline class specific handler
2516     Node* mark_node = makecon(TypeRawPtr::make((address)markWord::inline_type_prototype().value()));
2517     fast_oop_rawmem = make_store(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::mark_offset_in_bytes(), mark_node, T_ADDRESS);
2518     fast_oop_rawmem = make_store(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
2519     if (UseCompressedClassPointers) {
2520       fast_oop_rawmem = make_store(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::klass_gap_offset_in_bytes(), intcon(0), T_INT);
2521     }
2522     Node* fixed_block  = make_load(fast_oop_ctrl, fast_oop_rawmem, klass_node, in_bytes(InstanceKlass::adr_inlineklass_fixed_block_offset()), TypeRawPtr::BOTTOM, T_ADDRESS);
2523     Node* pack_handler = make_load(fast_oop_ctrl, fast_oop_rawmem, fixed_block, in_bytes(InlineKlass::pack_handler_offset()), TypeRawPtr::BOTTOM, T_ADDRESS);
2524     handler_call = new CallLeafNoFPNode(OptoRuntime::pack_inline_type_Type(),
2525                                         NULL,
2526                                         "pack handler",
2527                                         TypeRawPtr::BOTTOM);
2528     handler_call->init_req(TypeFunc::Control, fast_oop_ctrl);
2529     handler_call->init_req(TypeFunc::Memory, fast_oop_rawmem);
2530     handler_call->init_req(TypeFunc::I_O, top());
2531     handler_call->init_req(TypeFunc::FramePtr, call->in(TypeFunc::FramePtr));
2532     handler_call->init_req(TypeFunc::ReturnAdr, top());
2533     handler_call->init_req(TypeFunc::Parms, pack_handler);
2534     handler_call->init_req(TypeFunc::Parms+1, fast_oop);
2535   } else {
2536     needgc_ctrl = allocation_ctl;
2537   }
2538 
2539   // Allocation failed, fall back to a runtime call
2540   CallStaticJavaNode* slow_call = new CallStaticJavaNode(OptoRuntime::store_inline_type_fields_Type(),
2541                                                          StubRoutines::store_inline_type_fields_to_buf(),
2542                                                          "store_inline_type_fields",
2543                                                          TypePtr::BOTTOM);
2544   slow_call->init_req(TypeFunc::Control, needgc_ctrl);
2545   slow_call->init_req(TypeFunc::Memory, mem);
2546   slow_call->init_req(TypeFunc::I_O, io);
2547   slow_call->init_req(TypeFunc::FramePtr, call->in(TypeFunc::FramePtr));
2548   slow_call->init_req(TypeFunc::ReturnAdr, call->in(TypeFunc::ReturnAdr));
2549   slow_call->init_req(TypeFunc::Parms, res);
2550 
2551   Node* slow_ctl = transform_later(new ProjNode(slow_call, TypeFunc::Control));
2552   Node* slow_mem = transform_later(new ProjNode(slow_call, TypeFunc::Memory));
2553   Node* slow_io = transform_later(new ProjNode(slow_call, TypeFunc::I_O));
2554   Node* slow_res = transform_later(new ProjNode(slow_call, TypeFunc::Parms));
2555   Node* slow_catc = transform_later(new CatchNode(slow_ctl, slow_io, 2));
2556   Node* slow_norm = transform_later(new CatchProjNode(slow_catc, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci));
2557   Node* slow_excp = transform_later(new CatchProjNode(slow_catc, CatchProjNode::catch_all_index,    CatchProjNode::no_handler_bci));
2558 
2559   Node* ex_r = new RegionNode(3);
2560   Node* ex_mem_phi = new PhiNode(ex_r, Type::MEMORY, TypePtr::BOTTOM);
2561   Node* ex_io_phi = new PhiNode(ex_r, Type::ABIO);
2562   ex_r->init_req(1, slow_excp);
2563   ex_mem_phi->init_req(1, slow_mem);
2564   ex_io_phi->init_req(1, slow_io);
2565   ex_r->init_req(2, ex_ctl);
2566   ex_mem_phi->init_req(2, ex_mem);
2567   ex_io_phi->init_req(2, ex_io);
2568   transform_later(ex_r);
2569   transform_later(ex_mem_phi);
2570   transform_later(ex_io_phi);
2571 
2572   // We don't know how many values are returned. This assumes the
2573   // worst case, that all available registers are used.
2574   for (uint i = TypeFunc::Parms+1; i < domain->cnt(); i++) {
2575     if (domain->field_at(i) == Type::HALF) {
2576       slow_call->init_req(i, top());
2577       if (alloc_in_place) {
2578         handler_call->init_req(i+1, top());
2579       }
2580       continue;
2581     }
2582     Node* proj = transform_later(new ProjNode(call, i));
2583     slow_call->init_req(i, proj);
2584     if (alloc_in_place) {
2585       handler_call->init_req(i+1, proj);
2586     }
2587   }
2588   // We can safepoint at that new call
2589   slow_call->copy_call_debug_info(&_igvn, call);
2590   transform_later(slow_call);
2591   if (alloc_in_place) {
2592     transform_later(handler_call);
2593   }
2594 
2595   Node* fast_ctl = NULL;
2596   Node* fast_res = NULL;
2597   MergeMemNode* fast_mem = NULL;
2598   if (alloc_in_place) {
2599     fast_ctl = transform_later(new ProjNode(handler_call, TypeFunc::Control));
2600     Node* rawmem = transform_later(new ProjNode(handler_call, TypeFunc::Memory));
2601     fast_res = transform_later(new ProjNode(handler_call, TypeFunc::Parms));
2602     fast_mem = MergeMemNode::make(mem);
2603     fast_mem->set_memory_at(Compile::AliasIdxRaw, rawmem);
2604     transform_later(fast_mem);
2605   }
2606 
2607   Node* r = new RegionNode(alloc_in_place ? 4 : 3);
2608   Node* mem_phi = new PhiNode(r, Type::MEMORY, TypePtr::BOTTOM);
2609   Node* io_phi = new PhiNode(r, Type::ABIO);
2610   Node* res_phi = new PhiNode(r, TypeInstPtr::BOTTOM);
2611   r->init_req(1, no_allocation_ctl);
2612   mem_phi->init_req(1, mem);
2613   io_phi->init_req(1, io);
2614   res_phi->init_req(1, no_allocation_res);
2615   r->init_req(2, slow_norm);
2616   mem_phi->init_req(2, slow_mem);
2617   io_phi->init_req(2, slow_io);
2618   res_phi->init_req(2, slow_res);
2619   if (alloc_in_place) {
2620     r->init_req(3, fast_ctl);
2621     mem_phi->init_req(3, fast_mem);
2622     io_phi->init_req(3, io);
2623     res_phi->init_req(3, fast_res);
2624   }
2625   transform_later(r);
2626   transform_later(mem_phi);
2627   transform_later(io_phi);
2628   transform_later(res_phi);
2629 
2630   assert(projs->nb_resproj == 1, "unexpected number of results");
2631   _igvn.replace_in_uses(projs->fallthrough_catchproj, r);
2632   _igvn.replace_in_uses(projs->fallthrough_memproj, mem_phi);
2633   _igvn.replace_in_uses(projs->fallthrough_ioproj, io_phi);
2634   _igvn.replace_in_uses(projs->resproj[0], res_phi);
2635   _igvn.replace_in_uses(projs->catchall_catchproj, ex_r);
2636   _igvn.replace_in_uses(projs->catchall_memproj, ex_mem_phi);
2637   _igvn.replace_in_uses(projs->catchall_ioproj, ex_io_phi);
2638   // The CatchNode should not use the ex_io_phi. Re-connect it to the catchall_ioproj.
2639   Node* cn = projs->fallthrough_catchproj->in(0);
2640   _igvn.replace_input_of(cn, 1, projs->catchall_ioproj);
2641 
2642   _igvn.replace_node(ctl, projs->fallthrough_catchproj);
2643   _igvn.replace_node(mem, projs->fallthrough_memproj);
2644   _igvn.replace_node(io, projs->fallthrough_ioproj);
2645   _igvn.replace_node(res, projs->resproj[0]);
2646   _igvn.replace_node(ex_ctl, projs->catchall_catchproj);
2647   _igvn.replace_node(ex_mem, projs->catchall_memproj);
2648   _igvn.replace_node(ex_io, projs->catchall_ioproj);
2649  }
2650 
2651 void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) {
2652   assert(check->in(SubTypeCheckNode::Control) == NULL, "should be pinned");
2653   Node* bol = check->unique_out();
2654   Node* obj_or_subklass = check->in(SubTypeCheckNode::ObjOrSubKlass);
2655   Node* superklass = check->in(SubTypeCheckNode::SuperKlass);
2656   assert(bol->is_Bool() && bol->as_Bool()->_test._test == BoolTest::ne, "unexpected bool node");
2657 
2658   for (DUIterator_Last imin, i = bol->last_outs(imin); i >= imin; --i) {
2659     Node* iff = bol->last_out(i);
2660     assert(iff->is_If(), "where's the if?");
2661 
2662     if (iff->in(0)->is_top()) {
2663       _igvn.replace_input_of(iff, 1, C->top());
2664       continue;
2665     }
2666 
2667     Node* iftrue = iff->as_If()->proj_out(1);
2668     Node* iffalse = iff->as_If()->proj_out(0);
2669     Node* ctrl = iff->in(0);
2670 
2671     Node* subklass = NULL;
2672     if (_igvn.type(obj_or_subklass)->isa_klassptr()) {
2673       subklass = obj_or_subklass;
2674     } else {
2675       Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes());
2676       subklass = _igvn.transform(LoadKlassNode::make(_igvn, NULL, C->immutable_memory(), k_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
2677     }
2678 
2679     Node* not_subtype_ctrl = Phase::gen_subtype_check(subklass, superklass, &ctrl, NULL, _igvn);
2680 
2681     _igvn.replace_input_of(iff, 0, C->top());
2682     _igvn.replace_node(iftrue, not_subtype_ctrl);
2683     _igvn.replace_node(iffalse, ctrl);
2684   }
2685   _igvn.replace_node(check, C->top());
2686 }
2687 
2688 // FlatArrayCheckNode (array1 array2 ...) is expanded into:
2689 //
2690 // long mark = array1.mark | array2.mark | ...;
2691 // long locked_bit = markWord::unlocked_value & array1.mark & array2.mark & ...;
2692 // if (locked_bit == 0) {
2693 //   // One array is locked, load prototype header from the klass
2694 //   mark = array1.klass.proto | array2.klass.proto | ...
2695 // }
2696 // if ((mark & markWord::flat_array_bit_in_place) == 0) {
2697 //    ...
2698 // }
2699 void PhaseMacroExpand::expand_flatarraycheck_node(FlatArrayCheckNode* check) {
2700   bool array_inputs = _igvn.type(check->in(FlatArrayCheckNode::ArrayOrKlass))->isa_oopptr() != NULL;
2701   if (UseArrayMarkWordCheck && array_inputs) {
2702     Node* mark = MakeConX(0);
2703     Node* locked_bit = MakeConX(markWord::unlocked_value);
2704     Node* mem = check->in(FlatArrayCheckNode::Memory);
2705     for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) {
2706       Node* ary = check->in(i);
2707       const TypeOopPtr* t = _igvn.type(ary)->isa_oopptr();
2708       assert(t != NULL, "Mixing array and klass inputs");
2709       assert(!t->is_flat() && !t->is_not_flat(), "Should have been optimized out");
2710       Node* mark_adr = basic_plus_adr(ary, oopDesc::mark_offset_in_bytes());
2711       Node* mark_load = _igvn.transform(LoadNode::make(_igvn, NULL, mem, mark_adr, mark_adr->bottom_type()->is_ptr(), TypeX_X, TypeX_X->basic_type(), MemNode::unordered));
2712       mark = _igvn.transform(new OrXNode(mark, mark_load));
2713       locked_bit = _igvn.transform(new AndXNode(locked_bit, mark_load));
2714     }
2715     assert(!mark->is_Con(), "Should have been optimized out");
2716     Node* cmp = _igvn.transform(new CmpXNode(locked_bit, MakeConX(0)));
2717     Node* is_unlocked = _igvn.transform(new BoolNode(cmp, BoolTest::ne));
2718 
2719     // BoolNode might be shared, replace each if user
2720     Node* old_bol = check->unique_out();
2721     assert(old_bol->is_Bool() && old_bol->as_Bool()->_test._test == BoolTest::ne, "unexpected condition");
2722     for (DUIterator_Last imin, i = old_bol->last_outs(imin); i >= imin; --i) {
2723       IfNode* old_iff = old_bol->last_out(i)->as_If();
2724       Node* ctrl = old_iff->in(0);
2725       RegionNode* region = new RegionNode(3);
2726       Node* mark_phi = new PhiNode(region, TypeX_X);
2727 
2728       // Check if array is unlocked
2729       IfNode* iff = _igvn.transform(new IfNode(ctrl, is_unlocked, PROB_MAX, COUNT_UNKNOWN))->as_If();
2730 
2731       // Unlocked: Use bits from mark word
2732       region->init_req(1, _igvn.transform(new IfTrueNode(iff)));
2733       mark_phi->init_req(1, mark);
2734 
2735       // Locked: Load prototype header from klass
2736       ctrl = _igvn.transform(new IfFalseNode(iff));
2737       Node* proto = MakeConX(0);
2738       for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) {
2739         Node* ary = check->in(i);
2740         // Make loads control dependent to make sure they are only executed if array is locked
2741         Node* klass_adr = basic_plus_adr(ary, oopDesc::klass_offset_in_bytes());
2742         Node* klass = _igvn.transform(LoadKlassNode::make(_igvn, ctrl, C->immutable_memory(), klass_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
2743         Node* proto_adr = basic_plus_adr(klass, in_bytes(Klass::prototype_header_offset()));
2744         Node* proto_load = _igvn.transform(LoadNode::make(_igvn, ctrl, C->immutable_memory(), proto_adr, proto_adr->bottom_type()->is_ptr(), TypeX_X, TypeX_X->basic_type(), MemNode::unordered));
2745         proto = _igvn.transform(new OrXNode(proto, proto_load));
2746       }
2747       region->init_req(2, ctrl);
2748       mark_phi->init_req(2, proto);
2749 
2750       // Check if flat array bits are set
2751       Node* mask = MakeConX(markWord::flat_array_bit_in_place);
2752       Node* masked = _igvn.transform(new AndXNode(_igvn.transform(mark_phi), mask));
2753       cmp = _igvn.transform(new CmpXNode(masked, MakeConX(0)));
2754       Node* is_not_flat = _igvn.transform(new BoolNode(cmp, BoolTest::eq));
2755 
2756       ctrl = _igvn.transform(region);
2757       iff = _igvn.transform(new IfNode(ctrl, is_not_flat, PROB_MAX, COUNT_UNKNOWN))->as_If();
2758       _igvn.replace_node(old_iff, iff);
2759     }
2760     _igvn.replace_node(check, C->top());
2761   } else {
2762     // Fall back to layout helper check
2763     Node* lhs = intcon(0);
2764     for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) {
2765       Node* array_or_klass = check->in(i);
2766       Node* klass = NULL;
2767       const TypePtr* t = _igvn.type(array_or_klass)->is_ptr();
2768       assert(!t->is_flat() && !t->is_not_flat(), "Should have been optimized out");
2769       if (t->isa_oopptr() != NULL) {
2770         Node* klass_adr = basic_plus_adr(array_or_klass, oopDesc::klass_offset_in_bytes());
2771         klass = transform_later(LoadKlassNode::make(_igvn, NULL, C->immutable_memory(), klass_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
2772       } else {
2773         assert(t->isa_aryklassptr(), "Unexpected input type");
2774         klass = array_or_klass;
2775       }
2776       Node* lh_addr = basic_plus_adr(klass, in_bytes(Klass::layout_helper_offset()));
2777       Node* lh_val = _igvn.transform(LoadNode::make(_igvn, NULL, C->immutable_memory(), lh_addr, lh_addr->bottom_type()->is_ptr(), TypeInt::INT, T_INT, MemNode::unordered));
2778       lhs = _igvn.transform(new OrINode(lhs, lh_val));
2779     }
2780     Node* masked = transform_later(new AndINode(lhs, intcon(Klass::_lh_array_tag_flat_value_bit_inplace)));
2781     Node* cmp = transform_later(new CmpINode(masked, intcon(0)));
2782     Node* bol = transform_later(new BoolNode(cmp, BoolTest::eq));
2783     Node* old_bol = check->unique_out();
2784     _igvn.replace_node(old_bol, bol);
2785     _igvn.replace_node(check, C->top());
2786   }
2787 }
2788 
2789 //---------------------------eliminate_macro_nodes----------------------
2790 // Eliminate scalar replaced allocations and associated locks.
2791 void PhaseMacroExpand::eliminate_macro_nodes() {
2792   if (C->macro_count() == 0)
2793     return;
2794 
2795   // Before elimination may re-mark (change to Nested or NonEscObj)
2796   // all associated (same box and obj) lock and unlock nodes.
2797   int cnt = C->macro_count();
2798   for (int i=0; i < cnt; i++) {
2799     Node *n = C->macro_node(i);
2800     if (n->is_AbstractLock()) { // Lock and Unlock nodes
2801       mark_eliminated_locking_nodes(n->as_AbstractLock());
2802     }
2803   }
2804   // Re-marking may break consistency of Coarsened locks.
2805   if (!C->coarsened_locks_consistent()) {
2806     return; // recompile without Coarsened locks if broken
2807   }
2808 
2809   // First, attempt to eliminate locks
2810   bool progress = true;
2811   while (progress) {
2812     progress = false;
2813     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
2814       Node* n = C->macro_node(i - 1);
2815       bool success = false;
2816       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2817       if (n->is_AbstractLock()) {
2818         success = eliminate_locking_node(n->as_AbstractLock());
2819       }
2820       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2821       progress = progress || success;
2822     }
2823   }
2824   // Next, attempt to eliminate allocations
2825   _has_locks = false;
2826   progress = true;
2827   while (progress) {
2828     progress = false;
2829     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
2830       Node* n = C->macro_node(i - 1);
2831       bool success = false;
2832       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2833       switch (n->class_id()) {
2834       case Node::Class_Allocate:
2835       case Node::Class_AllocateArray:
2836         success = eliminate_allocate_node(n->as_Allocate());
2837         break;
2838       case Node::Class_CallStaticJava: {
2839         CallStaticJavaNode* call = n->as_CallStaticJava();
2840         if (!call->method()->is_method_handle_intrinsic()) {
2841           success = eliminate_boxing_node(n->as_CallStaticJava());
2842         }
2843         break;
2844       }
2845       case Node::Class_Lock:
2846       case Node::Class_Unlock:
2847         assert(!n->as_AbstractLock()->is_eliminated(), "sanity");
2848         _has_locks = true;
2849         break;
2850       case Node::Class_ArrayCopy:
2851         break;
2852       case Node::Class_OuterStripMinedLoop:
2853         break;
2854       case Node::Class_SubTypeCheck:
2855         break;
2856       case Node::Class_Opaque1:
2857         break;
2858       case Node::Class_FlatArrayCheck:
2859         break;
2860       default:
2861         assert(n->Opcode() == Op_LoopLimit ||
2862                n->Opcode() == Op_Opaque2   ||
2863                n->Opcode() == Op_Opaque3   ||
2864                n->Opcode() == Op_Opaque4   ||
2865                BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
2866                "unknown node type in macro list");
2867       }
2868       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2869       progress = progress || success;
2870     }
2871   }
2872 }
2873 
2874 //------------------------------expand_macro_nodes----------------------
2875 //  Returns true if a failure occurred.
2876 bool PhaseMacroExpand::expand_macro_nodes() {
2877   // Last attempt to eliminate macro nodes.
2878   eliminate_macro_nodes();
2879   if (C->failing())  return true;
2880 
2881   // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
2882   bool progress = true;
2883   while (progress) {
2884     progress = false;
2885     for (int i = C->macro_count(); i > 0; i--) {
2886       Node* n = C->macro_node(i-1);
2887       bool success = false;
2888       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2889       if (n->Opcode() == Op_LoopLimit) {
2890         // Remove it from macro list and put on IGVN worklist to optimize.
2891         C->remove_macro_node(n);
2892         _igvn._worklist.push(n);
2893         success = true;
2894       } else if (n->Opcode() == Op_CallStaticJava) {
2895         CallStaticJavaNode* call = n->as_CallStaticJava();
2896         if (!call->method()->is_method_handle_intrinsic()) {
2897           // Remove it from macro list and put on IGVN worklist to optimize.
2898           C->remove_macro_node(n);
2899           _igvn._worklist.push(n);
2900           success = true;
2901         }
2902       } else if (n->is_Opaque1() || n->Opcode() == Op_Opaque2) {
2903         _igvn.replace_node(n, n->in(1));
2904         success = true;
2905 #if INCLUDE_RTM_OPT
2906       } else if ((n->Opcode() == Op_Opaque3) && ((Opaque3Node*)n)->rtm_opt()) {
2907         assert(C->profile_rtm(), "should be used only in rtm deoptimization code");
2908         assert((n->outcnt() == 1) && n->unique_out()->is_Cmp(), "");
2909         Node* cmp = n->unique_out();
2910 #ifdef ASSERT
2911         // Validate graph.
2912         assert((cmp->outcnt() == 1) && cmp->unique_out()->is_Bool(), "");
2913         BoolNode* bol = cmp->unique_out()->as_Bool();
2914         assert((bol->outcnt() == 1) && bol->unique_out()->is_If() &&
2915                (bol->_test._test == BoolTest::ne), "");
2916         IfNode* ifn = bol->unique_out()->as_If();
2917         assert((ifn->outcnt() == 2) &&
2918                ifn->proj_out(1)->is_uncommon_trap_proj(Deoptimization::Reason_rtm_state_change) != NULL, "");
2919 #endif
2920         Node* repl = n->in(1);
2921         if (!_has_locks) {
2922           // Remove RTM state check if there are no locks in the code.
2923           // Replace input to compare the same value.
2924           repl = (cmp->in(1) == n) ? cmp->in(2) : cmp->in(1);
2925         }
2926         _igvn.replace_node(n, repl);
2927         success = true;
2928 #endif
2929       } else if (n->Opcode() == Op_Opaque4) {
2930         // With Opaque4 nodes, the expectation is that the test of input 1
2931         // is always equal to the constant value of input 2. So we can
2932         // remove the Opaque4 and replace it by input 2. In debug builds,
2933         // leave the non constant test in instead to sanity check that it
2934         // never fails (if it does, that subgraph was constructed so, at
2935         // runtime, a Halt node is executed).
2936 #ifdef ASSERT
2937         _igvn.replace_node(n, n->in(1));
2938 #else
2939         _igvn.replace_node(n, n->in(2));
2940 #endif
2941         success = true;
2942       } else if (n->Opcode() == Op_OuterStripMinedLoop) {
2943         n->as_OuterStripMinedLoop()->adjust_strip_mined_loop(&_igvn);
2944         C->remove_macro_node(n);
2945         success = true;
2946       }
2947       assert(!success || (C->macro_count() == (old_macro_count - 1)), "elimination must have deleted one node from macro list");
2948       progress = progress || success;
2949     }
2950   }
2951 
2952   // Clean up the graph so we're less likely to hit the maximum node
2953   // limit
2954   _igvn.set_delay_transform(false);
2955   _igvn.optimize();
2956   if (C->failing())  return true;
2957   _igvn.set_delay_transform(true);
2958 
2959 
2960   // Because we run IGVN after each expansion, some macro nodes may go
2961   // dead and be removed from the list as we iterate over it. Move
2962   // Allocate nodes (processed in a second pass) at the beginning of
2963   // the list and then iterate from the last element of the list until
2964   // an Allocate node is seen. This is robust to random deletion in
2965   // the list due to nodes going dead.
2966   C->sort_macro_nodes();
2967 
2968   // expand arraycopy "macro" nodes first
2969   // For ReduceBulkZeroing, we must first process all arraycopy nodes
2970   // before the allocate nodes are expanded.
2971   while (C->macro_count() > 0) {
2972     int macro_count = C->macro_count();
2973     Node * n = C->macro_node(macro_count-1);
2974     assert(n->is_macro(), "only macro nodes expected here");
2975     if (_igvn.type(n) == Type::TOP || (n->in(0) != NULL && n->in(0)->is_top())) {
2976       // node is unreachable, so don't try to expand it
2977       C->remove_macro_node(n);
2978       continue;
2979     }
2980     if (n->is_Allocate()) {
2981       break;
2982     }
2983     // Make sure expansion will not cause node limit to be exceeded.
2984     // Worst case is a macro node gets expanded into about 200 nodes.
2985     // Allow 50% more for optimization.
2986     if (C->check_node_count(300, "out of nodes before macro expansion")) {
2987       return true;
2988     }
2989 
2990     DEBUG_ONLY(int old_macro_count = C->macro_count();)
2991     switch (n->class_id()) {
2992     case Node::Class_Lock:
2993       expand_lock_node(n->as_Lock());
2994       break;
2995     case Node::Class_Unlock:
2996       expand_unlock_node(n->as_Unlock());
2997       break;
2998     case Node::Class_ArrayCopy:
2999       expand_arraycopy_node(n->as_ArrayCopy());
3000       break;
3001     case Node::Class_SubTypeCheck:
3002       expand_subtypecheck_node(n->as_SubTypeCheck());
3003       break;
3004     case Node::Class_CallStaticJava:
3005       expand_mh_intrinsic_return(n->as_CallStaticJava());
3006       C->remove_macro_node(n);
3007       break;
3008     case Node::Class_FlatArrayCheck:
3009       expand_flatarraycheck_node(n->as_FlatArrayCheck());
3010       break;
3011     default:
3012       assert(false, "unknown node type in macro list");
3013     }
3014     assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
3015     if (C->failing())  return true;
3016 
3017     // Clean up the graph so we're less likely to hit the maximum node
3018     // limit
3019     _igvn.set_delay_transform(false);
3020     _igvn.optimize();
3021     if (C->failing())  return true;
3022     _igvn.set_delay_transform(true);
3023   }
3024 
3025   // All nodes except Allocate nodes are expanded now. There could be
3026   // new optimization opportunities (such as folding newly created
3027   // load from a just allocated object). Run IGVN.
3028 
3029   // expand "macro" nodes
3030   // nodes are removed from the macro list as they are processed
3031   while (C->macro_count() > 0) {
3032     int macro_count = C->macro_count();
3033     Node * n = C->macro_node(macro_count-1);
3034     assert(n->is_macro(), "only macro nodes expected here");
3035     if (_igvn.type(n) == Type::TOP || (n->in(0) != NULL && n->in(0)->is_top())) {
3036       // node is unreachable, so don't try to expand it
3037       C->remove_macro_node(n);
3038       continue;
3039     }
3040     // Make sure expansion will not cause node limit to be exceeded.
3041     // Worst case is a macro node gets expanded into about 200 nodes.
3042     // Allow 50% more for optimization.
3043     if (C->check_node_count(300, "out of nodes before macro expansion")) {
3044       return true;
3045     }
3046     switch (n->class_id()) {
3047     case Node::Class_Allocate:
3048       expand_allocate(n->as_Allocate());
3049       break;
3050     case Node::Class_AllocateArray:
3051       expand_allocate_array(n->as_AllocateArray());
3052       break;
3053     default:
3054       assert(false, "unknown node type in macro list");
3055     }
3056     assert(C->macro_count() < macro_count, "must have deleted a node from macro list");
3057     if (C->failing())  return true;
3058 
3059     // Clean up the graph so we're less likely to hit the maximum node
3060     // limit
3061     _igvn.set_delay_transform(false);
3062     _igvn.optimize();
3063     if (C->failing())  return true;
3064     _igvn.set_delay_transform(true);
3065   }
3066 
3067   _igvn.set_delay_transform(false);
3068   return false;
3069 }