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