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