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   rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
1710   int header_size = alloc->minimum_header_size();  // conservatively small
1711 
1712   // Array length
1713   if (length != nullptr) {         // Arrays need length field
1714     rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1715     // conservatively small header size:
1716     header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1717     if (_igvn.type(klass_node)->isa_aryklassptr()) {   // we know the exact header size in most cases:
1718       BasicType elem = _igvn.type(klass_node)->is_klassptr()->as_instance_type()->isa_aryptr()->elem()->array_element_basic_type();
1719       if (is_reference_type(elem, true)) {
1720         elem = T_OBJECT;
1721       }
1722       header_size = Klass::layout_helper_header_size(Klass::array_layout_helper(elem));
1723     }
1724   }
1725 
1726   // Clear the object body, if necessary.
1727   if (init == nullptr) {
1728     // The init has somehow disappeared; be cautious and clear everything.
1729     //
1730     // This can happen if a node is allocated but an uncommon trap occurs
1731     // immediately.  In this case, the Initialize gets associated with the
1732     // trap, and may be placed in a different (outer) loop, if the Allocate
1733     // is in a loop.  If (this is rare) the inner loop gets unrolled, then
1734     // there can be two Allocates to one Initialize.  The answer in all these
1735     // edge cases is safety first.  It is always safe to clear immediately
1736     // within an Allocate, and then (maybe or maybe not) clear some more later.
1737     if (!(UseTLAB && ZeroTLAB)) {
1738       rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
1739                                             header_size, size_in_bytes,
1740                                             &_igvn);
1741     }
1742   } else {
1743     if (!init->is_complete()) {
1744       // Try to win by zeroing only what the init does not store.
1745       // We can also try to do some peephole optimizations,
1746       // such as combining some adjacent subword stores.
1747       rawmem = init->complete_stores(control, rawmem, object,
1748                                      header_size, size_in_bytes, &_igvn);
1749     }
1750     // We have no more use for this link, since the AllocateNode goes away:
1751     init->set_req(InitializeNode::RawAddress, top());
1752     // (If we keep the link, it just confuses the register allocator,
1753     // who thinks he sees a real use of the address by the membar.)
1754   }
1755 
1756   return rawmem;
1757 }
1758 
1759 // Generate prefetch instructions for next allocations.
1760 Node* PhaseMacroExpand::prefetch_allocation(Node* i_o, Node*& needgc_false,
1761                                         Node*& contended_phi_rawmem,
1762                                         Node* old_eden_top, Node* new_eden_top,
1763                                         intx lines) {
1764    enum { fall_in_path = 1, pf_path = 2 };
1765    if( UseTLAB && AllocatePrefetchStyle == 2 ) {
1766       // Generate prefetch allocation with watermark check.
1767       // As an allocation hits the watermark, we will prefetch starting
1768       // at a "distance" away from watermark.
1769 
1770       Node *pf_region = new RegionNode(3);
1771       Node *pf_phi_rawmem = new PhiNode( pf_region, Type::MEMORY,
1772                                                 TypeRawPtr::BOTTOM );
1773       // I/O is used for Prefetch
1774       Node *pf_phi_abio = new PhiNode( pf_region, Type::ABIO );
1775 
1776       Node *thread = new ThreadLocalNode();
1777       transform_later(thread);
1778 
1779       Node *eden_pf_adr = new AddPNode( top()/*not oop*/, thread,
1780                    _igvn.MakeConX(in_bytes(JavaThread::tlab_pf_top_offset())) );
1781       transform_later(eden_pf_adr);
1782 
1783       Node *old_pf_wm = new LoadPNode(needgc_false,
1784                                    contended_phi_rawmem, eden_pf_adr,
1785                                    TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM,
1786                                    MemNode::unordered);
1787       transform_later(old_pf_wm);
1788 
1789       // check against new_eden_top
1790       Node *need_pf_cmp = new CmpPNode( new_eden_top, old_pf_wm );
1791       transform_later(need_pf_cmp);
1792       Node *need_pf_bol = new BoolNode( need_pf_cmp, BoolTest::ge );
1793       transform_later(need_pf_bol);
1794       IfNode *need_pf_iff = new IfNode( needgc_false, need_pf_bol,
1795                                        PROB_UNLIKELY_MAG(4), COUNT_UNKNOWN );
1796       transform_later(need_pf_iff);
1797 
1798       // true node, add prefetchdistance
1799       Node *need_pf_true = new IfTrueNode( need_pf_iff );
1800       transform_later(need_pf_true);
1801 
1802       Node *need_pf_false = new IfFalseNode( need_pf_iff );
1803       transform_later(need_pf_false);
1804 
1805       Node *new_pf_wmt = new AddPNode( top(), old_pf_wm,
1806                                     _igvn.MakeConX(AllocatePrefetchDistance) );
1807       transform_later(new_pf_wmt );
1808       new_pf_wmt->set_req(0, need_pf_true);
1809 
1810       Node *store_new_wmt = new StorePNode(need_pf_true,
1811                                        contended_phi_rawmem, eden_pf_adr,
1812                                        TypeRawPtr::BOTTOM, new_pf_wmt,
1813                                        MemNode::unordered);
1814       transform_later(store_new_wmt);
1815 
1816       // adding prefetches
1817       pf_phi_abio->init_req( fall_in_path, i_o );
1818 
1819       Node *prefetch_adr;
1820       Node *prefetch;
1821       uint step_size = AllocatePrefetchStepSize;
1822       uint distance = 0;
1823 
1824       for ( intx i = 0; i < lines; i++ ) {
1825         prefetch_adr = new AddPNode( old_pf_wm, new_pf_wmt,
1826                                             _igvn.MakeConX(distance) );
1827         transform_later(prefetch_adr);
1828         prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
1829         transform_later(prefetch);
1830         distance += step_size;
1831         i_o = prefetch;
1832       }
1833       pf_phi_abio->set_req( pf_path, i_o );
1834 
1835       pf_region->init_req( fall_in_path, need_pf_false );
1836       pf_region->init_req( pf_path, need_pf_true );
1837 
1838       pf_phi_rawmem->init_req( fall_in_path, contended_phi_rawmem );
1839       pf_phi_rawmem->init_req( pf_path, store_new_wmt );
1840 
1841       transform_later(pf_region);
1842       transform_later(pf_phi_rawmem);
1843       transform_later(pf_phi_abio);
1844 
1845       needgc_false = pf_region;
1846       contended_phi_rawmem = pf_phi_rawmem;
1847       i_o = pf_phi_abio;
1848    } else if( UseTLAB && AllocatePrefetchStyle == 3 ) {
1849       // Insert a prefetch instruction for each allocation.
1850       // This code is used to generate 1 prefetch instruction per cache line.
1851 
1852       // Generate several prefetch instructions.
1853       uint step_size = AllocatePrefetchStepSize;
1854       uint distance = AllocatePrefetchDistance;
1855 
1856       // Next cache address.
1857       Node *cache_adr = new AddPNode(old_eden_top, old_eden_top,
1858                                      _igvn.MakeConX(step_size + distance));
1859       transform_later(cache_adr);
1860       cache_adr = new CastP2XNode(needgc_false, cache_adr);
1861       transform_later(cache_adr);
1862       // Address is aligned to execute prefetch to the beginning of cache line size
1863       // (it is important when BIS instruction is used on SPARC as prefetch).
1864       Node* mask = _igvn.MakeConX(~(intptr_t)(step_size-1));
1865       cache_adr = new AndXNode(cache_adr, mask);
1866       transform_later(cache_adr);
1867       cache_adr = new CastX2PNode(cache_adr);
1868       transform_later(cache_adr);
1869 
1870       // Prefetch
1871       Node *prefetch = new PrefetchAllocationNode( contended_phi_rawmem, cache_adr );
1872       prefetch->set_req(0, needgc_false);
1873       transform_later(prefetch);
1874       contended_phi_rawmem = prefetch;
1875       Node *prefetch_adr;
1876       distance = step_size;
1877       for ( intx i = 1; i < lines; i++ ) {
1878         prefetch_adr = new AddPNode( cache_adr, cache_adr,
1879                                             _igvn.MakeConX(distance) );
1880         transform_later(prefetch_adr);
1881         prefetch = new PrefetchAllocationNode( contended_phi_rawmem, prefetch_adr );
1882         transform_later(prefetch);
1883         distance += step_size;
1884         contended_phi_rawmem = prefetch;
1885       }
1886    } else if( AllocatePrefetchStyle > 0 ) {
1887       // Insert a prefetch for each allocation only on the fast-path
1888       Node *prefetch_adr;
1889       Node *prefetch;
1890       // Generate several prefetch instructions.
1891       uint step_size = AllocatePrefetchStepSize;
1892       uint distance = AllocatePrefetchDistance;
1893       for ( intx i = 0; i < lines; i++ ) {
1894         prefetch_adr = new AddPNode( old_eden_top, new_eden_top,
1895                                             _igvn.MakeConX(distance) );
1896         transform_later(prefetch_adr);
1897         prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
1898         // Do not let it float too high, since if eden_top == eden_end,
1899         // both might be null.
1900         if( i == 0 ) { // Set control for first prefetch, next follows it
1901           prefetch->init_req(0, needgc_false);
1902         }
1903         transform_later(prefetch);
1904         distance += step_size;
1905         i_o = prefetch;
1906       }
1907    }
1908    return i_o;
1909 }
1910 
1911 
1912 void PhaseMacroExpand::expand_allocate(AllocateNode *alloc) {
1913   expand_allocate_common(alloc, nullptr,
1914                          OptoRuntime::new_instance_Type(),
1915                          OptoRuntime::new_instance_Java(), nullptr);
1916 }
1917 
1918 void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) {
1919   Node* length = alloc->in(AllocateNode::ALength);
1920   Node* valid_length_test = alloc->in(AllocateNode::ValidLengthTest);
1921   InitializeNode* init = alloc->initialization();
1922   Node* klass_node = alloc->in(AllocateNode::KlassNode);
1923   const TypeAryKlassPtr* ary_klass_t = _igvn.type(klass_node)->isa_aryklassptr();
1924   address slow_call_address;  // Address of slow call
1925   if (init != nullptr && init->is_complete_with_arraycopy() &&
1926       ary_klass_t && ary_klass_t->elem()->isa_klassptr() == nullptr) {
1927     // Don't zero type array during slow allocation in VM since
1928     // it will be initialized later by arraycopy in compiled code.
1929     slow_call_address = OptoRuntime::new_array_nozero_Java();
1930   } else {
1931     slow_call_address = OptoRuntime::new_array_Java();
1932   }
1933   expand_allocate_common(alloc, length,
1934                          OptoRuntime::new_array_Type(),
1935                          slow_call_address, valid_length_test);
1936 }
1937 
1938 //-------------------mark_eliminated_box----------------------------------
1939 //
1940 // During EA obj may point to several objects but after few ideal graph
1941 // transformations (CCP) it may point to only one non escaping object
1942 // (but still using phi), corresponding locks and unlocks will be marked
1943 // for elimination. Later obj could be replaced with a new node (new phi)
1944 // and which does not have escape information. And later after some graph
1945 // reshape other locks and unlocks (which were not marked for elimination
1946 // before) are connected to this new obj (phi) but they still will not be
1947 // marked for elimination since new obj has no escape information.
1948 // Mark all associated (same box and obj) lock and unlock nodes for
1949 // elimination if some of them marked already.
1950 void PhaseMacroExpand::mark_eliminated_box(Node* box, Node* obj) {
1951   BoxLockNode* oldbox = box->as_BoxLock();
1952   if (oldbox->is_eliminated()) {
1953     return; // This BoxLock node was processed already.
1954   }
1955   assert(!oldbox->is_unbalanced(), "this should not be called for unbalanced region");
1956   // New implementation (EliminateNestedLocks) has separate BoxLock
1957   // node for each locked region so mark all associated locks/unlocks as
1958   // eliminated even if different objects are referenced in one locked region
1959   // (for example, OSR compilation of nested loop inside locked scope).
1960   if (EliminateNestedLocks ||
1961       oldbox->as_BoxLock()->is_simple_lock_region(nullptr, obj, nullptr)) {
1962     // Box is used only in one lock region. Mark this box as eliminated.
1963     oldbox->set_local();      // This verifies correct state of BoxLock
1964     _igvn.hash_delete(oldbox);
1965     oldbox->set_eliminated(); // This changes box's hash value
1966      _igvn.hash_insert(oldbox);
1967 
1968     for (uint i = 0; i < oldbox->outcnt(); i++) {
1969       Node* u = oldbox->raw_out(i);
1970       if (u->is_AbstractLock() && !u->as_AbstractLock()->is_non_esc_obj()) {
1971         AbstractLockNode* alock = u->as_AbstractLock();
1972         // Check lock's box since box could be referenced by Lock's debug info.
1973         if (alock->box_node() == oldbox) {
1974           // Mark eliminated all related locks and unlocks.
1975 #ifdef ASSERT
1976           alock->log_lock_optimization(C, "eliminate_lock_set_non_esc4");
1977 #endif
1978           alock->set_non_esc_obj();
1979         }
1980       }
1981     }
1982     return;
1983   }
1984 
1985   // Create new "eliminated" BoxLock node and use it in monitor debug info
1986   // instead of oldbox for the same object.
1987   BoxLockNode* newbox = oldbox->clone()->as_BoxLock();
1988 
1989   // Note: BoxLock node is marked eliminated only here and it is used
1990   // to indicate that all associated lock and unlock nodes are marked
1991   // for elimination.
1992   newbox->set_local(); // This verifies correct state of BoxLock
1993   newbox->set_eliminated();
1994   transform_later(newbox);
1995 
1996   // Replace old box node with new box for all users of the same object.
1997   for (uint i = 0; i < oldbox->outcnt();) {
1998     bool next_edge = true;
1999 
2000     Node* u = oldbox->raw_out(i);
2001     if (u->is_AbstractLock()) {
2002       AbstractLockNode* alock = u->as_AbstractLock();
2003       if (alock->box_node() == oldbox && alock->obj_node()->eqv_uncast(obj)) {
2004         // Replace Box and mark eliminated all related locks and unlocks.
2005 #ifdef ASSERT
2006         alock->log_lock_optimization(C, "eliminate_lock_set_non_esc5");
2007 #endif
2008         alock->set_non_esc_obj();
2009         _igvn.rehash_node_delayed(alock);
2010         alock->set_box_node(newbox);
2011         next_edge = false;
2012       }
2013     }
2014     if (u->is_FastLock() && u->as_FastLock()->obj_node()->eqv_uncast(obj)) {
2015       FastLockNode* flock = u->as_FastLock();
2016       assert(flock->box_node() == oldbox, "sanity");
2017       _igvn.rehash_node_delayed(flock);
2018       flock->set_box_node(newbox);
2019       next_edge = false;
2020     }
2021 
2022     // Replace old box in monitor debug info.
2023     if (u->is_SafePoint() && u->as_SafePoint()->jvms()) {
2024       SafePointNode* sfn = u->as_SafePoint();
2025       JVMState* youngest_jvms = sfn->jvms();
2026       int max_depth = youngest_jvms->depth();
2027       for (int depth = 1; depth <= max_depth; depth++) {
2028         JVMState* jvms = youngest_jvms->of_depth(depth);
2029         int num_mon  = jvms->nof_monitors();
2030         // Loop over monitors
2031         for (int idx = 0; idx < num_mon; idx++) {
2032           Node* obj_node = sfn->monitor_obj(jvms, idx);
2033           Node* box_node = sfn->monitor_box(jvms, idx);
2034           if (box_node == oldbox && obj_node->eqv_uncast(obj)) {
2035             int j = jvms->monitor_box_offset(idx);
2036             _igvn.replace_input_of(u, j, newbox);
2037             next_edge = false;
2038           }
2039         }
2040       }
2041     }
2042     if (next_edge) i++;
2043   }
2044 }
2045 
2046 //-----------------------mark_eliminated_locking_nodes-----------------------
2047 void PhaseMacroExpand::mark_eliminated_locking_nodes(AbstractLockNode *alock) {
2048   if (alock->box_node()->as_BoxLock()->is_unbalanced()) {
2049     return; // Can't do any more elimination for this locking region
2050   }
2051   if (EliminateNestedLocks) {
2052     if (alock->is_nested()) {
2053        assert(alock->box_node()->as_BoxLock()->is_eliminated(), "sanity");
2054        return;
2055     } else if (!alock->is_non_esc_obj()) { // Not eliminated or coarsened
2056       // Only Lock node has JVMState needed here.
2057       // Not that preceding claim is documented anywhere else.
2058       if (alock->jvms() != nullptr) {
2059         if (alock->as_Lock()->is_nested_lock_region()) {
2060           // Mark eliminated related nested locks and unlocks.
2061           Node* obj = alock->obj_node();
2062           BoxLockNode* box_node = alock->box_node()->as_BoxLock();
2063           assert(!box_node->is_eliminated(), "should not be marked yet");
2064           // Note: BoxLock node is marked eliminated only here
2065           // and it is used to indicate that all associated lock
2066           // and unlock nodes are marked for elimination.
2067           box_node->set_eliminated(); // Box's hash is always NO_HASH here
2068           for (uint i = 0; i < box_node->outcnt(); i++) {
2069             Node* u = box_node->raw_out(i);
2070             if (u->is_AbstractLock()) {
2071               alock = u->as_AbstractLock();
2072               if (alock->box_node() == box_node) {
2073                 // Verify that this Box is referenced only by related locks.
2074                 assert(alock->obj_node()->eqv_uncast(obj), "");
2075                 // Mark all related locks and unlocks.
2076 #ifdef ASSERT
2077                 alock->log_lock_optimization(C, "eliminate_lock_set_nested");
2078 #endif
2079                 alock->set_nested();
2080               }
2081             }
2082           }
2083         } else {
2084 #ifdef ASSERT
2085           alock->log_lock_optimization(C, "eliminate_lock_NOT_nested_lock_region");
2086           if (C->log() != nullptr)
2087             alock->as_Lock()->is_nested_lock_region(C); // rerun for debugging output
2088 #endif
2089         }
2090       }
2091       return;
2092     }
2093     // Process locks for non escaping object
2094     assert(alock->is_non_esc_obj(), "");
2095   } // EliminateNestedLocks
2096 
2097   if (alock->is_non_esc_obj()) { // Lock is used for non escaping object
2098     // Look for all locks of this object and mark them and
2099     // corresponding BoxLock nodes as eliminated.
2100     Node* obj = alock->obj_node();
2101     for (uint j = 0; j < obj->outcnt(); j++) {
2102       Node* o = obj->raw_out(j);
2103       if (o->is_AbstractLock() &&
2104           o->as_AbstractLock()->obj_node()->eqv_uncast(obj)) {
2105         alock = o->as_AbstractLock();
2106         Node* box = alock->box_node();
2107         // Replace old box node with new eliminated box for all users
2108         // of the same object and mark related locks as eliminated.
2109         mark_eliminated_box(box, obj);
2110       }
2111     }
2112   }
2113 }
2114 
2115 // we have determined that this lock/unlock can be eliminated, we simply
2116 // eliminate the node without expanding it.
2117 //
2118 // Note:  The membar's associated with the lock/unlock are currently not
2119 //        eliminated.  This should be investigated as a future enhancement.
2120 //
2121 bool PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) {
2122 
2123   if (!alock->is_eliminated()) {
2124     return false;
2125   }
2126 #ifdef ASSERT
2127   if (!alock->is_coarsened()) {
2128     // Check that new "eliminated" BoxLock node is created.
2129     BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2130     assert(oldbox->is_eliminated(), "should be done already");
2131   }
2132 #endif
2133 
2134   alock->log_lock_optimization(C, "eliminate_lock");
2135 
2136 #ifndef PRODUCT
2137   if (PrintEliminateLocks) {
2138     tty->print_cr("++++ Eliminated: %d %s '%s'", alock->_idx, (alock->is_Lock() ? "Lock" : "Unlock"), alock->kind_as_string());
2139   }
2140 #endif
2141 
2142   Node* mem  = alock->in(TypeFunc::Memory);
2143   Node* ctrl = alock->in(TypeFunc::Control);
2144   guarantee(ctrl != nullptr, "missing control projection, cannot replace_node() with null");
2145 
2146   alock->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2147   // There are 2 projections from the lock.  The lock node will
2148   // be deleted when its last use is subsumed below.
2149   assert(alock->outcnt() == 2 &&
2150          _callprojs.fallthrough_proj != nullptr &&
2151          _callprojs.fallthrough_memproj != nullptr,
2152          "Unexpected projections from Lock/Unlock");
2153 
2154   Node* fallthroughproj = _callprojs.fallthrough_proj;
2155   Node* memproj_fallthrough = _callprojs.fallthrough_memproj;
2156 
2157   // The memory projection from a lock/unlock is RawMem
2158   // The input to a Lock is merged memory, so extract its RawMem input
2159   // (unless the MergeMem has been optimized away.)
2160   if (alock->is_Lock()) {
2161     // Search for MemBarAcquireLock node and delete it also.
2162     MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
2163     assert(membar != nullptr && membar->Opcode() == Op_MemBarAcquireLock, "");
2164     Node* ctrlproj = membar->proj_out(TypeFunc::Control);
2165     Node* memproj = membar->proj_out(TypeFunc::Memory);
2166     _igvn.replace_node(ctrlproj, fallthroughproj);
2167     _igvn.replace_node(memproj, memproj_fallthrough);
2168 
2169     // Delete FastLock node also if this Lock node is unique user
2170     // (a loop peeling may clone a Lock node).
2171     Node* flock = alock->as_Lock()->fastlock_node();
2172     if (flock->outcnt() == 1) {
2173       assert(flock->unique_out() == alock, "sanity");
2174       _igvn.replace_node(flock, top());
2175     }
2176   }
2177 
2178   // Search for MemBarReleaseLock node and delete it also.
2179   if (alock->is_Unlock() && ctrl->is_Proj() && ctrl->in(0)->is_MemBar()) {
2180     MemBarNode* membar = ctrl->in(0)->as_MemBar();
2181     assert(membar->Opcode() == Op_MemBarReleaseLock &&
2182            mem->is_Proj() && membar == mem->in(0), "");
2183     _igvn.replace_node(fallthroughproj, ctrl);
2184     _igvn.replace_node(memproj_fallthrough, mem);
2185     fallthroughproj = ctrl;
2186     memproj_fallthrough = mem;
2187     ctrl = membar->in(TypeFunc::Control);
2188     mem  = membar->in(TypeFunc::Memory);
2189   }
2190 
2191   _igvn.replace_node(fallthroughproj, ctrl);
2192   _igvn.replace_node(memproj_fallthrough, mem);
2193   return true;
2194 }
2195 
2196 
2197 //------------------------------expand_lock_node----------------------
2198 void PhaseMacroExpand::expand_lock_node(LockNode *lock) {
2199 
2200   Node* ctrl = lock->in(TypeFunc::Control);
2201   Node* mem = lock->in(TypeFunc::Memory);
2202   Node* obj = lock->obj_node();
2203   Node* box = lock->box_node();
2204   Node* flock = lock->fastlock_node();
2205 
2206   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2207 
2208   // Make the merge point
2209   Node *region;
2210   Node *mem_phi;
2211   Node *slow_path;
2212 
2213   region  = new RegionNode(3);
2214   // create a Phi for the memory state
2215   mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2216 
2217   // Optimize test; set region slot 2
2218   slow_path = opt_bits_test(ctrl, region, 2, flock, 0, 0);
2219   mem_phi->init_req(2, mem);
2220 
2221   // Make slow path call
2222   CallNode *call = make_slow_call((CallNode *) lock, OptoRuntime::complete_monitor_enter_Type(),
2223                                   OptoRuntime::complete_monitor_locking_Java(), nullptr, slow_path,
2224                                   obj, box, nullptr);
2225 
2226   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2227 
2228   // Slow path can only throw asynchronous exceptions, which are always
2229   // de-opted.  So the compiler thinks the slow-call can never throw an
2230   // exception.  If it DOES throw an exception we would need the debug
2231   // info removed first (since if it throws there is no monitor).
2232   assert(_callprojs.fallthrough_ioproj == nullptr && _callprojs.catchall_ioproj == nullptr &&
2233          _callprojs.catchall_memproj == nullptr && _callprojs.catchall_catchproj == nullptr, "Unexpected projection from Lock");
2234 
2235   // Capture slow path
2236   // disconnect fall-through projection from call and create a new one
2237   // hook up users of fall-through projection to region
2238   Node *slow_ctrl = _callprojs.fallthrough_proj->clone();
2239   transform_later(slow_ctrl);
2240   _igvn.hash_delete(_callprojs.fallthrough_proj);
2241   _callprojs.fallthrough_proj->disconnect_inputs(C);
2242   region->init_req(1, slow_ctrl);
2243   // region inputs are now complete
2244   transform_later(region);
2245   _igvn.replace_node(_callprojs.fallthrough_proj, region);
2246 
2247   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2248 
2249   mem_phi->init_req(1, memproj);
2250 
2251   transform_later(mem_phi);
2252 
2253   _igvn.replace_node(_callprojs.fallthrough_memproj, mem_phi);
2254 }
2255 
2256 //------------------------------expand_unlock_node----------------------
2257 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
2258 
2259   Node* ctrl = unlock->in(TypeFunc::Control);
2260   Node* mem = unlock->in(TypeFunc::Memory);
2261   Node* obj = unlock->obj_node();
2262   Node* box = unlock->box_node();
2263 
2264   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2265 
2266   // No need for a null check on unlock
2267 
2268   // Make the merge point
2269   Node *region;
2270   Node *mem_phi;
2271 
2272   region  = new RegionNode(3);
2273   // create a Phi for the memory state
2274   mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2275 
2276   FastUnlockNode *funlock = new FastUnlockNode( ctrl, obj, box );
2277   funlock = transform_later( funlock )->as_FastUnlock();
2278   // Optimize test; set region slot 2
2279   Node *slow_path = opt_bits_test(ctrl, region, 2, funlock, 0, 0);
2280   Node *thread = transform_later(new ThreadLocalNode());
2281 
2282   CallNode *call = make_slow_call((CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(),
2283                                   CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C),
2284                                   "complete_monitor_unlocking_C", slow_path, obj, box, thread);
2285 
2286   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2287   assert(_callprojs.fallthrough_ioproj == nullptr && _callprojs.catchall_ioproj == nullptr &&
2288          _callprojs.catchall_memproj == nullptr && _callprojs.catchall_catchproj == nullptr, "Unexpected projection from Lock");
2289 
2290   // No exceptions for unlocking
2291   // Capture slow path
2292   // disconnect fall-through projection from call and create a new one
2293   // hook up users of fall-through projection to region
2294   Node *slow_ctrl = _callprojs.fallthrough_proj->clone();
2295   transform_later(slow_ctrl);
2296   _igvn.hash_delete(_callprojs.fallthrough_proj);
2297   _callprojs.fallthrough_proj->disconnect_inputs(C);
2298   region->init_req(1, slow_ctrl);
2299   // region inputs are now complete
2300   transform_later(region);
2301   _igvn.replace_node(_callprojs.fallthrough_proj, region);
2302 
2303   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory) );
2304   mem_phi->init_req(1, memproj );
2305   mem_phi->init_req(2, mem);
2306   transform_later(mem_phi);
2307 
2308   _igvn.replace_node(_callprojs.fallthrough_memproj, mem_phi);
2309 }
2310 
2311 void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) {
2312   assert(check->in(SubTypeCheckNode::Control) == nullptr, "should be pinned");
2313   Node* bol = check->unique_out();
2314   Node* obj_or_subklass = check->in(SubTypeCheckNode::ObjOrSubKlass);
2315   Node* superklass = check->in(SubTypeCheckNode::SuperKlass);
2316   assert(bol->is_Bool() && bol->as_Bool()->_test._test == BoolTest::ne, "unexpected bool node");
2317 
2318   for (DUIterator_Last imin, i = bol->last_outs(imin); i >= imin; --i) {
2319     Node* iff = bol->last_out(i);
2320     assert(iff->is_If(), "where's the if?");
2321 
2322     if (iff->in(0)->is_top()) {
2323       _igvn.replace_input_of(iff, 1, C->top());
2324       continue;
2325     }
2326 
2327     Node* iftrue = iff->as_If()->proj_out(1);
2328     Node* iffalse = iff->as_If()->proj_out(0);
2329     Node* ctrl = iff->in(0);
2330 
2331     Node* subklass = nullptr;
2332     if (_igvn.type(obj_or_subklass)->isa_klassptr()) {
2333       subklass = obj_or_subklass;
2334     } else {
2335       Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes());
2336       subklass = _igvn.transform(LoadKlassNode::make(_igvn, nullptr, C->immutable_memory(), k_adr, TypeInstPtr::KLASS));
2337     }
2338 
2339     Node* not_subtype_ctrl = Phase::gen_subtype_check(subklass, superklass, &ctrl, nullptr, _igvn, check->method(), check->bci());
2340 
2341     _igvn.replace_input_of(iff, 0, C->top());
2342     _igvn.replace_node(iftrue, not_subtype_ctrl);
2343     _igvn.replace_node(iffalse, ctrl);
2344   }
2345   _igvn.replace_node(check, C->top());
2346 }
2347 
2348 //---------------------------eliminate_macro_nodes----------------------
2349 // Eliminate scalar replaced allocations and associated locks.
2350 void PhaseMacroExpand::eliminate_macro_nodes() {
2351   if (C->macro_count() == 0)
2352     return;
2353   NOT_PRODUCT(int membar_before = count_MemBar(C);)
2354 
2355   // Before elimination may re-mark (change to Nested or NonEscObj)
2356   // all associated (same box and obj) lock and unlock nodes.
2357   int cnt = C->macro_count();
2358   for (int i=0; i < cnt; i++) {
2359     Node *n = C->macro_node(i);
2360     if (n->is_AbstractLock()) { // Lock and Unlock nodes
2361       mark_eliminated_locking_nodes(n->as_AbstractLock());
2362     }
2363   }
2364   // Re-marking may break consistency of Coarsened locks.
2365   if (!C->coarsened_locks_consistent()) {
2366     return; // recompile without Coarsened locks if broken
2367   } else {
2368     // After coarsened locks are eliminated locking regions
2369     // become unbalanced. We should not execute any more
2370     // locks elimination optimizations on them.
2371     C->mark_unbalanced_boxes();
2372   }
2373 
2374   // First, attempt to eliminate locks
2375   bool progress = true;
2376   while (progress) {
2377     progress = false;
2378     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
2379       Node* n = C->macro_node(i - 1);
2380       bool success = false;
2381       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2382       if (n->is_AbstractLock()) {
2383         success = eliminate_locking_node(n->as_AbstractLock());
2384 #ifndef PRODUCT
2385         if (success && PrintOptoStatistics) {
2386           Atomic::inc(&PhaseMacroExpand::_monitor_objects_removed_counter);
2387         }
2388 #endif
2389       }
2390       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2391       progress = progress || success;
2392     }
2393   }
2394   // Next, attempt to eliminate allocations
2395   _has_locks = false;
2396   progress = true;
2397   while (progress) {
2398     progress = false;
2399     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
2400       Node* n = C->macro_node(i - 1);
2401       bool success = false;
2402       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2403       switch (n->class_id()) {
2404       case Node::Class_Allocate:
2405       case Node::Class_AllocateArray:
2406         success = eliminate_allocate_node(n->as_Allocate());
2407 #ifndef PRODUCT
2408         if (success && PrintOptoStatistics) {
2409           Atomic::inc(&PhaseMacroExpand::_objs_scalar_replaced_counter);
2410         }
2411 #endif
2412         break;
2413       case Node::Class_CallStaticJava:
2414         success = eliminate_boxing_node(n->as_CallStaticJava());
2415         break;
2416       case Node::Class_Lock:
2417       case Node::Class_Unlock:
2418         assert(!n->as_AbstractLock()->is_eliminated(), "sanity");
2419         _has_locks = true;
2420         break;
2421       case Node::Class_ArrayCopy:
2422         break;
2423       case Node::Class_OuterStripMinedLoop:
2424         break;
2425       case Node::Class_SubTypeCheck:
2426         break;
2427       case Node::Class_Opaque1:
2428         break;
2429       default:
2430         assert(n->Opcode() == Op_LoopLimit ||
2431                n->is_Opaque4()             ||
2432                n->is_OpaqueInitializedAssertionPredicate() ||
2433                n->Opcode() == Op_MaxL      ||
2434                n->Opcode() == Op_MinL      ||
2435                BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
2436                "unknown node type in macro list");
2437       }
2438       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2439       progress = progress || success;
2440     }
2441   }
2442 #ifndef PRODUCT
2443   if (PrintOptoStatistics) {
2444     int membar_after = count_MemBar(C);
2445     Atomic::add(&PhaseMacroExpand::_memory_barriers_removed_counter, membar_before - membar_after);
2446   }
2447 #endif
2448 }
2449 
2450 //------------------------------expand_macro_nodes----------------------
2451 //  Returns true if a failure occurred.
2452 bool PhaseMacroExpand::expand_macro_nodes() {
2453   // Do not allow new macro nodes once we started to expand
2454   C->reset_allow_macro_nodes();
2455   if (StressMacroExpansion) {
2456     C->shuffle_macro_nodes();
2457   }
2458   // Last attempt to eliminate macro nodes.
2459   eliminate_macro_nodes();
2460   if (C->failing())  return true;
2461 
2462   // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
2463   bool progress = true;
2464   while (progress) {
2465     progress = false;
2466     for (int i = C->macro_count(); i > 0; i--) {
2467       Node* n = C->macro_node(i-1);
2468       bool success = false;
2469       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2470       if (n->Opcode() == Op_LoopLimit) {
2471         // Remove it from macro list and put on IGVN worklist to optimize.
2472         C->remove_macro_node(n);
2473         _igvn._worklist.push(n);
2474         success = true;
2475       } else if (n->Opcode() == Op_CallStaticJava) {
2476         // Remove it from macro list and put on IGVN worklist to optimize.
2477         C->remove_macro_node(n);
2478         _igvn._worklist.push(n);
2479         success = true;
2480       } else if (n->is_Opaque1()) {
2481         _igvn.replace_node(n, n->in(1));
2482         success = true;
2483       } else if (n->is_Opaque4()) {
2484         // With Opaque4 nodes, the expectation is that the test of input 1
2485         // is always equal to the constant value of input 2. So we can
2486         // remove the Opaque4 and replace it by input 2. In debug builds,
2487         // leave the non constant test in instead to sanity check that it
2488         // never fails (if it does, that subgraph was constructed so, at
2489         // runtime, a Halt node is executed).
2490 #ifdef ASSERT
2491         _igvn.replace_node(n, n->in(1));
2492 #else
2493         _igvn.replace_node(n, n->in(2));
2494 #endif
2495         success = true;
2496       } else if (n->is_OpaqueInitializedAssertionPredicate()) {
2497           // Initialized Assertion Predicates must always evaluate to true. Therefore, we get rid of them in product
2498           // builds as they are useless. In debug builds we keep them as additional verification code. Even though
2499           // loop opts are already over, we want to keep Initialized Assertion Predicates alive as long as possible to
2500           // enable folding of dead control paths within which cast nodes become top after due to impossible types -
2501           // even after loop opts are over. Therefore, we delay the removal of these opaque nodes until now.
2502 #ifdef ASSERT
2503         _igvn.replace_node(n, n->in(1));
2504 #else
2505         _igvn.replace_node(n, _igvn.intcon(1));
2506 #endif // ASSERT
2507       } else if (n->Opcode() == Op_OuterStripMinedLoop) {
2508         n->as_OuterStripMinedLoop()->adjust_strip_mined_loop(&_igvn);
2509         C->remove_macro_node(n);
2510         success = true;
2511       } else if (n->Opcode() == Op_MaxL) {
2512         // Since MaxL and MinL are not implemented in the backend, we expand them to
2513         // a CMoveL construct now. At least until here, the type could be computed
2514         // precisely. CMoveL is not so smart, but we can give it at least the best
2515         // type we know abouot n now.
2516         Node* repl = MaxNode::signed_max(n->in(1), n->in(2), _igvn.type(n), _igvn);
2517         _igvn.replace_node(n, repl);
2518         success = true;
2519       } else if (n->Opcode() == Op_MinL) {
2520         Node* repl = MaxNode::signed_min(n->in(1), n->in(2), _igvn.type(n), _igvn);
2521         _igvn.replace_node(n, repl);
2522         success = true;
2523       }
2524       assert(!success || (C->macro_count() == (old_macro_count - 1)), "elimination must have deleted one node from macro list");
2525       progress = progress || success;
2526       if (success) {
2527         C->print_method(PHASE_AFTER_MACRO_EXPANSION_STEP, 5, n);
2528       }
2529     }
2530   }
2531 
2532   // Clean up the graph so we're less likely to hit the maximum node
2533   // limit
2534   _igvn.set_delay_transform(false);
2535   _igvn.optimize();
2536   if (C->failing())  return true;
2537   _igvn.set_delay_transform(true);
2538 
2539 
2540   // Because we run IGVN after each expansion, some macro nodes may go
2541   // dead and be removed from the list as we iterate over it. Move
2542   // Allocate nodes (processed in a second pass) at the beginning of
2543   // the list and then iterate from the last element of the list until
2544   // an Allocate node is seen. This is robust to random deletion in
2545   // the list due to nodes going dead.
2546   C->sort_macro_nodes();
2547 
2548   // expand arraycopy "macro" nodes first
2549   // For ReduceBulkZeroing, we must first process all arraycopy nodes
2550   // before the allocate nodes are expanded.
2551   while (C->macro_count() > 0) {
2552     int macro_count = C->macro_count();
2553     Node * n = C->macro_node(macro_count-1);
2554     assert(n->is_macro(), "only macro nodes expected here");
2555     if (_igvn.type(n) == Type::TOP || (n->in(0) != nullptr && n->in(0)->is_top())) {
2556       // node is unreachable, so don't try to expand it
2557       C->remove_macro_node(n);
2558       continue;
2559     }
2560     if (n->is_Allocate()) {
2561       break;
2562     }
2563     // Make sure expansion will not cause node limit to be exceeded.
2564     // Worst case is a macro node gets expanded into about 200 nodes.
2565     // Allow 50% more for optimization.
2566     if (C->check_node_count(300, "out of nodes before macro expansion")) {
2567       return true;
2568     }
2569 
2570     DEBUG_ONLY(int old_macro_count = C->macro_count();)
2571     switch (n->class_id()) {
2572     case Node::Class_Lock:
2573       expand_lock_node(n->as_Lock());
2574       break;
2575     case Node::Class_Unlock:
2576       expand_unlock_node(n->as_Unlock());
2577       break;
2578     case Node::Class_ArrayCopy:
2579       expand_arraycopy_node(n->as_ArrayCopy());
2580       break;
2581     case Node::Class_SubTypeCheck:
2582       expand_subtypecheck_node(n->as_SubTypeCheck());
2583       break;
2584     default:
2585       assert(false, "unknown node type in macro list");
2586     }
2587     assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2588     if (C->failing())  return true;
2589     C->print_method(PHASE_AFTER_MACRO_EXPANSION_STEP, 5, n);
2590 
2591     // Clean up the graph so we're less likely to hit the maximum node
2592     // limit
2593     _igvn.set_delay_transform(false);
2594     _igvn.optimize();
2595     if (C->failing())  return true;
2596     _igvn.set_delay_transform(true);
2597   }
2598 
2599   // All nodes except Allocate nodes are expanded now. There could be
2600   // new optimization opportunities (such as folding newly created
2601   // load from a just allocated object). Run IGVN.
2602 
2603   // expand "macro" nodes
2604   // nodes are removed from the macro list as they are processed
2605   while (C->macro_count() > 0) {
2606     int macro_count = C->macro_count();
2607     Node * n = C->macro_node(macro_count-1);
2608     assert(n->is_macro(), "only macro nodes expected here");
2609     if (_igvn.type(n) == Type::TOP || (n->in(0) != nullptr && n->in(0)->is_top())) {
2610       // node is unreachable, so don't try to expand it
2611       C->remove_macro_node(n);
2612       continue;
2613     }
2614     // Make sure expansion will not cause node limit to be exceeded.
2615     // Worst case is a macro node gets expanded into about 200 nodes.
2616     // Allow 50% more for optimization.
2617     if (C->check_node_count(300, "out of nodes before macro expansion")) {
2618       return true;
2619     }
2620     switch (n->class_id()) {
2621     case Node::Class_Allocate:
2622       expand_allocate(n->as_Allocate());
2623       break;
2624     case Node::Class_AllocateArray:
2625       expand_allocate_array(n->as_AllocateArray());
2626       break;
2627     default:
2628       assert(false, "unknown node type in macro list");
2629     }
2630     assert(C->macro_count() < macro_count, "must have deleted a node from macro list");
2631     if (C->failing())  return true;
2632     C->print_method(PHASE_AFTER_MACRO_EXPANSION_STEP, 5, n);
2633 
2634     // Clean up the graph so we're less likely to hit the maximum node
2635     // limit
2636     _igvn.set_delay_transform(false);
2637     _igvn.optimize();
2638     if (C->failing())  return true;
2639     _igvn.set_delay_transform(true);
2640   }
2641 
2642   _igvn.set_delay_transform(false);
2643   return false;
2644 }
2645 
2646 #ifndef PRODUCT
2647 int PhaseMacroExpand::_objs_scalar_replaced_counter = 0;
2648 int PhaseMacroExpand::_monitor_objects_removed_counter = 0;
2649 int PhaseMacroExpand::_GC_barriers_removed_counter = 0;
2650 int PhaseMacroExpand::_memory_barriers_removed_counter = 0;
2651 
2652 void PhaseMacroExpand::print_statistics() {
2653   tty->print("Objects scalar replaced = %d, ", Atomic::load(&_objs_scalar_replaced_counter));
2654   tty->print("Monitor objects removed = %d, ", Atomic::load(&_monitor_objects_removed_counter));
2655   tty->print("GC barriers removed = %d, ", Atomic::load(&_GC_barriers_removed_counter));
2656   tty->print_cr("Memory barriers removed = %d", Atomic::load(&_memory_barriers_removed_counter));
2657 }
2658 
2659 int PhaseMacroExpand::count_MemBar(Compile *C) {
2660   if (!PrintOptoStatistics) {
2661     return 0;
2662   }
2663   Unique_Node_List ideal_nodes;
2664   int total = 0;
2665   ideal_nodes.map(C->live_nodes(), nullptr);
2666   ideal_nodes.push(C->root());
2667   for (uint next = 0; next < ideal_nodes.size(); ++next) {
2668     Node* n = ideal_nodes.at(next);
2669     if (n->is_MemBar()) {
2670       total++;
2671     }
2672     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2673       Node* m = n->fast_out(i);
2674       ideal_nodes.push(m);
2675     }
2676   }
2677   return total;
2678 }
2679 #endif