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 or a fancy class check for
1316     // newInstance0.
1317     IfNode *toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1318     transform_later(toobig_iff);
1319     // Plug the failing-too-big test into the slow-path region
1320     Node *toobig_true = new IfTrueNode( toobig_iff );
1321     transform_later(toobig_true);
1322     slow_region    ->init_req( too_big_or_final_path, toobig_true );
1323     toobig_false = new IfFalseNode( toobig_iff );
1324     transform_later(toobig_false);
1325   } else {
1326     // No initial test, just fall into next case
1327     assert(allocation_has_use || !expand_fast_path, "Should already have been handled");
1328     toobig_false = ctrl;
1329     debug_only(slow_region = NodeSentinel);
1330   }
1331 
1332   // If we are here there are several possibilities
1333   // - expand_fast_path is false - then only a slow path is expanded. That's it.
1334   // no_initial_check means a constant allocation.
1335   // - If check always evaluates to false -> expand_fast_path is false (see above)
1336   // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath)
1337   // if !allocation_has_use the fast path is empty
1338   // if !allocation_has_use && no_initial_check
1339   // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all.
1340   //   removed by yank_alloc_node above.
1341 
1342   Node *slow_mem = mem;  // save the current memory state for slow path
1343   // generate the fast allocation code unless we know that the initial test will always go slow
1344   if (expand_fast_path) {
1345     // Fast path modifies only raw memory.
1346     if (mem->is_MergeMem()) {
1347       mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1348     }
1349 
1350     // allocate the Region and Phi nodes for the result
1351     result_region = new RegionNode(3);
1352     result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1353     result_phi_i_o    = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1354 
1355     // Grab regular I/O before optional prefetch may change it.
1356     // Slow-path does no I/O so just set it to the original I/O.
1357     result_phi_i_o->init_req(slow_result_path, i_o);
1358 
1359     // Name successful fast-path variables
1360     Node* fast_oop_ctrl;
1361     Node* fast_oop_rawmem;
1362     if (allocation_has_use) {
1363       Node* needgc_ctrl = nullptr;
1364       result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1365 
1366       intx prefetch_lines = length != nullptr ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1367       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1368       Node* fast_oop = bs->obj_allocate(this, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1369                                         fast_oop_ctrl, fast_oop_rawmem,
1370                                         prefetch_lines);
1371 
1372       if (initial_slow_test != nullptr) {
1373         // This completes all paths into the slow merge point
1374         slow_region->init_req(need_gc_path, needgc_ctrl);
1375         transform_later(slow_region);
1376       } else {
1377         // No initial slow path needed!
1378         // Just fall from the need-GC path straight into the VM call.
1379         slow_region = needgc_ctrl;
1380       }
1381 
1382       InitializeNode* init = alloc->initialization();
1383       fast_oop_rawmem = initialize_object(alloc,
1384                                           fast_oop_ctrl, fast_oop_rawmem, fast_oop,
1385                                           klass_node, length, size_in_bytes);
1386       expand_initialize_membar(alloc, init, fast_oop_ctrl, fast_oop_rawmem);
1387       expand_dtrace_alloc_probe(alloc, fast_oop, fast_oop_ctrl, fast_oop_rawmem);
1388 
1389       result_phi_rawoop->init_req(fast_result_path, fast_oop);
1390     } else {
1391       assert (initial_slow_test != nullptr, "sanity");
1392       fast_oop_ctrl   = toobig_false;
1393       fast_oop_rawmem = mem;
1394       transform_later(slow_region);
1395     }
1396 
1397     // Plug in the successful fast-path into the result merge point
1398     result_region    ->init_req(fast_result_path, fast_oop_ctrl);
1399     result_phi_i_o   ->init_req(fast_result_path, i_o);
1400     result_phi_rawmem->init_req(fast_result_path, fast_oop_rawmem);
1401   } else {
1402     slow_region = ctrl;
1403     result_phi_i_o = i_o; // Rename it to use in the following code.
1404   }
1405 
1406   // Generate slow-path call
1407   CallNode *call = new CallStaticJavaNode(slow_call_type, slow_call_address,
1408                                OptoRuntime::stub_name(slow_call_address),
1409                                TypePtr::BOTTOM);
1410   call->init_req(TypeFunc::Control,   slow_region);
1411   call->init_req(TypeFunc::I_O,       top());    // does no i/o
1412   call->init_req(TypeFunc::Memory,    slow_mem); // may gc ptrs
1413   call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1414   call->init_req(TypeFunc::FramePtr,  alloc->in(TypeFunc::FramePtr));
1415 
1416   call->init_req(TypeFunc::Parms+0, klass_node);
1417   if (length != nullptr) {
1418     call->init_req(TypeFunc::Parms+1, length);
1419   }
1420 
1421   // Copy debug information and adjust JVMState information, then replace
1422   // allocate node with the call
1423   call->copy_call_debug_info(&_igvn, alloc);
1424   // For array allocations, copy the valid length check to the call node so Compile::final_graph_reshaping() can verify
1425   // that the call has the expected number of CatchProj nodes (in case the allocation always fails and the fallthrough
1426   // path dies).
1427   if (valid_length_test != nullptr) {
1428     call->add_req(valid_length_test);
1429   }
1430   if (expand_fast_path) {
1431     call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
1432   } else {
1433     // Hook i_o projection to avoid its elimination during allocation
1434     // replacement (when only a slow call is generated).
1435     call->set_req(TypeFunc::I_O, result_phi_i_o);
1436   }
1437   _igvn.replace_node(alloc, call);
1438   transform_later(call);
1439 
1440   // Identify the output projections from the allocate node and
1441   // adjust any references to them.
1442   // The control and io projections look like:
1443   //
1444   //        v---Proj(ctrl) <-----+   v---CatchProj(ctrl)
1445   //  Allocate                   Catch
1446   //        ^---Proj(io) <-------+   ^---CatchProj(io)
1447   //
1448   //  We are interested in the CatchProj nodes.
1449   //
1450   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1451 
1452   // An allocate node has separate memory projections for the uses on
1453   // the control and i_o paths. Replace the control memory projection with
1454   // result_phi_rawmem (unless we are only generating a slow call when
1455   // both memory projections are combined)
1456   if (expand_fast_path && _callprojs.fallthrough_memproj != nullptr) {
1457     migrate_outs(_callprojs.fallthrough_memproj, result_phi_rawmem);
1458   }
1459   // Now change uses of catchall_memproj to use fallthrough_memproj and delete
1460   // catchall_memproj so we end up with a call that has only 1 memory projection.
1461   if (_callprojs.catchall_memproj != nullptr ) {
1462     if (_callprojs.fallthrough_memproj == nullptr) {
1463       _callprojs.fallthrough_memproj = new ProjNode(call, TypeFunc::Memory);
1464       transform_later(_callprojs.fallthrough_memproj);
1465     }
1466     migrate_outs(_callprojs.catchall_memproj, _callprojs.fallthrough_memproj);
1467     _igvn.remove_dead_node(_callprojs.catchall_memproj);
1468   }
1469 
1470   // An allocate node has separate i_o projections for the uses on the control
1471   // and i_o paths. Always replace the control i_o projection with result i_o
1472   // otherwise incoming i_o become dead when only a slow call is generated
1473   // (it is different from memory projections where both projections are
1474   // combined in such case).
1475   if (_callprojs.fallthrough_ioproj != nullptr) {
1476     migrate_outs(_callprojs.fallthrough_ioproj, result_phi_i_o);
1477   }
1478   // Now change uses of catchall_ioproj to use fallthrough_ioproj and delete
1479   // catchall_ioproj so we end up with a call that has only 1 i_o projection.
1480   if (_callprojs.catchall_ioproj != nullptr ) {
1481     if (_callprojs.fallthrough_ioproj == nullptr) {
1482       _callprojs.fallthrough_ioproj = new ProjNode(call, TypeFunc::I_O);
1483       transform_later(_callprojs.fallthrough_ioproj);
1484     }
1485     migrate_outs(_callprojs.catchall_ioproj, _callprojs.fallthrough_ioproj);
1486     _igvn.remove_dead_node(_callprojs.catchall_ioproj);
1487   }
1488 
1489   // if we generated only a slow call, we are done
1490   if (!expand_fast_path) {
1491     // Now we can unhook i_o.
1492     if (result_phi_i_o->outcnt() > 1) {
1493       call->set_req(TypeFunc::I_O, top());
1494     } else {
1495       assert(result_phi_i_o->unique_ctrl_out() == call, "sanity");
1496       // Case of new array with negative size known during compilation.
1497       // AllocateArrayNode::Ideal() optimization disconnect unreachable
1498       // following code since call to runtime will throw exception.
1499       // As result there will be no users of i_o after the call.
1500       // Leave i_o attached to this call to avoid problems in preceding graph.
1501     }
1502     return;
1503   }
1504 
1505   if (_callprojs.fallthrough_catchproj != nullptr) {
1506     ctrl = _callprojs.fallthrough_catchproj->clone();
1507     transform_later(ctrl);
1508     _igvn.replace_node(_callprojs.fallthrough_catchproj, result_region);
1509   } else {
1510     ctrl = top();
1511   }
1512   Node *slow_result;
1513   if (_callprojs.resproj == nullptr) {
1514     // no uses of the allocation result
1515     slow_result = top();
1516   } else {
1517     slow_result = _callprojs.resproj->clone();
1518     transform_later(slow_result);
1519     _igvn.replace_node(_callprojs.resproj, result_phi_rawoop);
1520   }
1521 
1522   // Plug slow-path into result merge point
1523   result_region->init_req( slow_result_path, ctrl);
1524   transform_later(result_region);
1525   if (allocation_has_use) {
1526     result_phi_rawoop->init_req(slow_result_path, slow_result);
1527     transform_later(result_phi_rawoop);
1528   }
1529   result_phi_rawmem->init_req(slow_result_path, _callprojs.fallthrough_memproj);
1530   transform_later(result_phi_rawmem);
1531   transform_later(result_phi_i_o);
1532   // This completes all paths into the result merge point
1533 }
1534 
1535 // Remove alloc node that has no uses.
1536 void PhaseMacroExpand::yank_alloc_node(AllocateNode* alloc) {
1537   Node* ctrl = alloc->in(TypeFunc::Control);
1538   Node* mem  = alloc->in(TypeFunc::Memory);
1539   Node* i_o  = alloc->in(TypeFunc::I_O);
1540 
1541   alloc->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1542   if (_callprojs.resproj != nullptr) {
1543     for (DUIterator_Fast imax, i = _callprojs.resproj->fast_outs(imax); i < imax; i++) {
1544       Node* use = _callprojs.resproj->fast_out(i);
1545       use->isa_MemBar()->remove(&_igvn);
1546       --imax;
1547       --i; // back up iterator
1548     }
1549     assert(_callprojs.resproj->outcnt() == 0, "all uses must be deleted");
1550     _igvn.remove_dead_node(_callprojs.resproj);
1551   }
1552   if (_callprojs.fallthrough_catchproj != nullptr) {
1553     migrate_outs(_callprojs.fallthrough_catchproj, ctrl);
1554     _igvn.remove_dead_node(_callprojs.fallthrough_catchproj);
1555   }
1556   if (_callprojs.catchall_catchproj != nullptr) {
1557     _igvn.rehash_node_delayed(_callprojs.catchall_catchproj);
1558     _callprojs.catchall_catchproj->set_req(0, top());
1559   }
1560   if (_callprojs.fallthrough_proj != nullptr) {
1561     Node* catchnode = _callprojs.fallthrough_proj->unique_ctrl_out();
1562     _igvn.remove_dead_node(catchnode);
1563     _igvn.remove_dead_node(_callprojs.fallthrough_proj);
1564   }
1565   if (_callprojs.fallthrough_memproj != nullptr) {
1566     migrate_outs(_callprojs.fallthrough_memproj, mem);
1567     _igvn.remove_dead_node(_callprojs.fallthrough_memproj);
1568   }
1569   if (_callprojs.fallthrough_ioproj != nullptr) {
1570     migrate_outs(_callprojs.fallthrough_ioproj, i_o);
1571     _igvn.remove_dead_node(_callprojs.fallthrough_ioproj);
1572   }
1573   if (_callprojs.catchall_memproj != nullptr) {
1574     _igvn.rehash_node_delayed(_callprojs.catchall_memproj);
1575     _callprojs.catchall_memproj->set_req(0, top());
1576   }
1577   if (_callprojs.catchall_ioproj != nullptr) {
1578     _igvn.rehash_node_delayed(_callprojs.catchall_ioproj);
1579     _callprojs.catchall_ioproj->set_req(0, top());
1580   }
1581 #ifndef PRODUCT
1582   if (PrintEliminateAllocations) {
1583     if (alloc->is_AllocateArray()) {
1584       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1585     } else {
1586       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1587     }
1588   }
1589 #endif
1590   _igvn.remove_dead_node(alloc);
1591 }
1592 
1593 void PhaseMacroExpand::expand_initialize_membar(AllocateNode* alloc, InitializeNode* init,
1594                                                 Node*& fast_oop_ctrl, Node*& fast_oop_rawmem) {
1595   // If initialization is performed by an array copy, any required
1596   // MemBarStoreStore was already added. If the object does not
1597   // escape no need for a MemBarStoreStore. If the object does not
1598   // escape in its initializer and memory barrier (MemBarStoreStore or
1599   // stronger) is already added at exit of initializer, also no need
1600   // for a MemBarStoreStore. Otherwise we need a MemBarStoreStore
1601   // so that stores that initialize this object can't be reordered
1602   // with a subsequent store that makes this object accessible by
1603   // other threads.
1604   // Other threads include java threads and JVM internal threads
1605   // (for example concurrent GC threads). Current concurrent GC
1606   // implementation: G1 will not scan newly created object,
1607   // so it's safe to skip storestore barrier when allocation does
1608   // not escape.
1609   if (!alloc->does_not_escape_thread() &&
1610     !alloc->is_allocation_MemBar_redundant() &&
1611     (init == nullptr || !init->is_complete_with_arraycopy())) {
1612     if (init == nullptr || init->req() < InitializeNode::RawStores) {
1613       // No InitializeNode or no stores captured by zeroing
1614       // elimination. Simply add the MemBarStoreStore after object
1615       // initialization.
1616       MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
1617       transform_later(mb);
1618 
1619       mb->init_req(TypeFunc::Memory, fast_oop_rawmem);
1620       mb->init_req(TypeFunc::Control, fast_oop_ctrl);
1621       fast_oop_ctrl = new ProjNode(mb, TypeFunc::Control);
1622       transform_later(fast_oop_ctrl);
1623       fast_oop_rawmem = new ProjNode(mb, TypeFunc::Memory);
1624       transform_later(fast_oop_rawmem);
1625     } else {
1626       // Add the MemBarStoreStore after the InitializeNode so that
1627       // all stores performing the initialization that were moved
1628       // before the InitializeNode happen before the storestore
1629       // barrier.
1630 
1631       Node* init_ctrl = init->proj_out_or_null(TypeFunc::Control);
1632       Node* init_mem = init->proj_out_or_null(TypeFunc::Memory);
1633 
1634       MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
1635       transform_later(mb);
1636 
1637       Node* ctrl = new ProjNode(init, TypeFunc::Control);
1638       transform_later(ctrl);
1639       Node* mem = new ProjNode(init, TypeFunc::Memory);
1640       transform_later(mem);
1641 
1642       // The MemBarStoreStore depends on control and memory coming
1643       // from the InitializeNode
1644       mb->init_req(TypeFunc::Memory, mem);
1645       mb->init_req(TypeFunc::Control, ctrl);
1646 
1647       ctrl = new ProjNode(mb, TypeFunc::Control);
1648       transform_later(ctrl);
1649       mem = new ProjNode(mb, TypeFunc::Memory);
1650       transform_later(mem);
1651 
1652       // All nodes that depended on the InitializeNode for control
1653       // and memory must now depend on the MemBarNode that itself
1654       // depends on the InitializeNode
1655       if (init_ctrl != nullptr) {
1656         _igvn.replace_node(init_ctrl, ctrl);
1657       }
1658       if (init_mem != nullptr) {
1659         _igvn.replace_node(init_mem, mem);
1660       }
1661     }
1662   }
1663 }
1664 
1665 void PhaseMacroExpand::expand_dtrace_alloc_probe(AllocateNode* alloc, Node* oop,
1666                                                 Node*& ctrl, Node*& rawmem) {
1667   if (C->env()->dtrace_alloc_probes()) {
1668     // Slow-path call
1669     int size = TypeFunc::Parms + 2;
1670     CallLeafNode *call = new CallLeafNode(OptoRuntime::dtrace_object_alloc_Type(),
1671                                           CAST_FROM_FN_PTR(address,
1672                                           static_cast<int (*)(JavaThread*, oopDesc*)>(SharedRuntime::dtrace_object_alloc)),
1673                                           "dtrace_object_alloc",
1674                                           TypeRawPtr::BOTTOM);
1675 
1676     // Get base of thread-local storage area
1677     Node* thread = new ThreadLocalNode();
1678     transform_later(thread);
1679 
1680     call->init_req(TypeFunc::Parms + 0, thread);
1681     call->init_req(TypeFunc::Parms + 1, oop);
1682     call->init_req(TypeFunc::Control, ctrl);
1683     call->init_req(TypeFunc::I_O    , top()); // does no i/o
1684     call->init_req(TypeFunc::Memory , rawmem);
1685     call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1686     call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1687     transform_later(call);
1688     ctrl = new ProjNode(call, TypeFunc::Control);
1689     transform_later(ctrl);
1690     rawmem = new ProjNode(call, TypeFunc::Memory);
1691     transform_later(rawmem);
1692   }
1693 }
1694 
1695 // Helper for PhaseMacroExpand::expand_allocate_common.
1696 // Initializes the newly-allocated storage.
1697 Node*
1698 PhaseMacroExpand::initialize_object(AllocateNode* alloc,
1699                                     Node* control, Node* rawmem, Node* object,
1700                                     Node* klass_node, Node* length,
1701                                     Node* size_in_bytes) {
1702   InitializeNode* init = alloc->initialization();
1703   // Store the klass & mark bits
1704   Node* mark_node = alloc->make_ideal_mark(&_igvn, object, control, rawmem);
1705   if (!mark_node->is_Con()) {
1706     transform_later(mark_node);
1707   }
1708   rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
1709 
1710   rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
1711   int header_size = alloc->minimum_header_size();  // conservatively small
1712 
1713   // Array length
1714   if (length != nullptr) {         // Arrays need length field
1715     rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1716     // conservatively small header size:
1717     header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1718     if (_igvn.type(klass_node)->isa_aryklassptr()) {   // we know the exact header size in most cases:
1719       BasicType elem = _igvn.type(klass_node)->is_klassptr()->as_instance_type()->isa_aryptr()->elem()->array_element_basic_type();
1720       if (is_reference_type(elem, true)) {
1721         elem = T_OBJECT;
1722       }
1723       header_size = Klass::layout_helper_header_size(Klass::array_layout_helper(elem));
1724     }
1725   }
1726 
1727   // Clear the object body, if necessary.
1728   if (init == nullptr) {
1729     // The init has somehow disappeared; be cautious and clear everything.
1730     //
1731     // This can happen if a node is allocated but an uncommon trap occurs
1732     // immediately.  In this case, the Initialize gets associated with the
1733     // trap, and may be placed in a different (outer) loop, if the Allocate
1734     // is in a loop.  If (this is rare) the inner loop gets unrolled, then
1735     // there can be two Allocates to one Initialize.  The answer in all these
1736     // edge cases is safety first.  It is always safe to clear immediately
1737     // within an Allocate, and then (maybe or maybe not) clear some more later.
1738     if (!(UseTLAB && ZeroTLAB)) {
1739       rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
1740                                             header_size, size_in_bytes,
1741                                             &_igvn);
1742     }
1743   } else {
1744     if (!init->is_complete()) {
1745       // Try to win by zeroing only what the init does not store.
1746       // We can also try to do some peephole optimizations,
1747       // such as combining some adjacent subword stores.
1748       rawmem = init->complete_stores(control, rawmem, object,
1749                                      header_size, size_in_bytes, &_igvn);
1750     }
1751     // We have no more use for this link, since the AllocateNode goes away:
1752     init->set_req(InitializeNode::RawAddress, top());
1753     // (If we keep the link, it just confuses the register allocator,
1754     // who thinks he sees a real use of the address by the membar.)
1755   }
1756 
1757   return rawmem;
1758 }
1759 
1760 // Generate prefetch instructions for next allocations.
1761 Node* PhaseMacroExpand::prefetch_allocation(Node* i_o, Node*& needgc_false,
1762                                         Node*& contended_phi_rawmem,
1763                                         Node* old_eden_top, Node* new_eden_top,
1764                                         intx lines) {
1765    enum { fall_in_path = 1, pf_path = 2 };
1766    if( UseTLAB && AllocatePrefetchStyle == 2 ) {
1767       // Generate prefetch allocation with watermark check.
1768       // As an allocation hits the watermark, we will prefetch starting
1769       // at a "distance" away from watermark.
1770 
1771       Node *pf_region = new RegionNode(3);
1772       Node *pf_phi_rawmem = new PhiNode( pf_region, Type::MEMORY,
1773                                                 TypeRawPtr::BOTTOM );
1774       // I/O is used for Prefetch
1775       Node *pf_phi_abio = new PhiNode( pf_region, Type::ABIO );
1776 
1777       Node *thread = new ThreadLocalNode();
1778       transform_later(thread);
1779 
1780       Node *eden_pf_adr = new AddPNode( top()/*not oop*/, thread,
1781                    _igvn.MakeConX(in_bytes(JavaThread::tlab_pf_top_offset())) );
1782       transform_later(eden_pf_adr);
1783 
1784       Node *old_pf_wm = new LoadPNode(needgc_false,
1785                                    contended_phi_rawmem, eden_pf_adr,
1786                                    TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM,
1787                                    MemNode::unordered);
1788       transform_later(old_pf_wm);
1789 
1790       // check against new_eden_top
1791       Node *need_pf_cmp = new CmpPNode( new_eden_top, old_pf_wm );
1792       transform_later(need_pf_cmp);
1793       Node *need_pf_bol = new BoolNode( need_pf_cmp, BoolTest::ge );
1794       transform_later(need_pf_bol);
1795       IfNode *need_pf_iff = new IfNode( needgc_false, need_pf_bol,
1796                                        PROB_UNLIKELY_MAG(4), COUNT_UNKNOWN );
1797       transform_later(need_pf_iff);
1798 
1799       // true node, add prefetchdistance
1800       Node *need_pf_true = new IfTrueNode( need_pf_iff );
1801       transform_later(need_pf_true);
1802 
1803       Node *need_pf_false = new IfFalseNode( need_pf_iff );
1804       transform_later(need_pf_false);
1805 
1806       Node *new_pf_wmt = new AddPNode( top(), old_pf_wm,
1807                                     _igvn.MakeConX(AllocatePrefetchDistance) );
1808       transform_later(new_pf_wmt );
1809       new_pf_wmt->set_req(0, need_pf_true);
1810 
1811       Node *store_new_wmt = new StorePNode(need_pf_true,
1812                                        contended_phi_rawmem, eden_pf_adr,
1813                                        TypeRawPtr::BOTTOM, new_pf_wmt,
1814                                        MemNode::unordered);
1815       transform_later(store_new_wmt);
1816 
1817       // adding prefetches
1818       pf_phi_abio->init_req( fall_in_path, i_o );
1819 
1820       Node *prefetch_adr;
1821       Node *prefetch;
1822       uint step_size = AllocatePrefetchStepSize;
1823       uint distance = 0;
1824 
1825       for ( intx i = 0; i < lines; i++ ) {
1826         prefetch_adr = new AddPNode( old_pf_wm, new_pf_wmt,
1827                                             _igvn.MakeConX(distance) );
1828         transform_later(prefetch_adr);
1829         prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
1830         transform_later(prefetch);
1831         distance += step_size;
1832         i_o = prefetch;
1833       }
1834       pf_phi_abio->set_req( pf_path, i_o );
1835 
1836       pf_region->init_req( fall_in_path, need_pf_false );
1837       pf_region->init_req( pf_path, need_pf_true );
1838 
1839       pf_phi_rawmem->init_req( fall_in_path, contended_phi_rawmem );
1840       pf_phi_rawmem->init_req( pf_path, store_new_wmt );
1841 
1842       transform_later(pf_region);
1843       transform_later(pf_phi_rawmem);
1844       transform_later(pf_phi_abio);
1845 
1846       needgc_false = pf_region;
1847       contended_phi_rawmem = pf_phi_rawmem;
1848       i_o = pf_phi_abio;
1849    } else if( UseTLAB && AllocatePrefetchStyle == 3 ) {
1850       // Insert a prefetch instruction for each allocation.
1851       // This code is used to generate 1 prefetch instruction per cache line.
1852 
1853       // Generate several prefetch instructions.
1854       uint step_size = AllocatePrefetchStepSize;
1855       uint distance = AllocatePrefetchDistance;
1856 
1857       // Next cache address.
1858       Node *cache_adr = new AddPNode(old_eden_top, old_eden_top,
1859                                      _igvn.MakeConX(step_size + distance));
1860       transform_later(cache_adr);
1861       cache_adr = new CastP2XNode(needgc_false, cache_adr);
1862       transform_later(cache_adr);
1863       // Address is aligned to execute prefetch to the beginning of cache line size
1864       // (it is important when BIS instruction is used on SPARC as prefetch).
1865       Node* mask = _igvn.MakeConX(~(intptr_t)(step_size-1));
1866       cache_adr = new AndXNode(cache_adr, mask);
1867       transform_later(cache_adr);
1868       cache_adr = new CastX2PNode(cache_adr);
1869       transform_later(cache_adr);
1870 
1871       // Prefetch
1872       Node *prefetch = new PrefetchAllocationNode( contended_phi_rawmem, cache_adr );
1873       prefetch->set_req(0, needgc_false);
1874       transform_later(prefetch);
1875       contended_phi_rawmem = prefetch;
1876       Node *prefetch_adr;
1877       distance = step_size;
1878       for ( intx i = 1; i < lines; i++ ) {
1879         prefetch_adr = new AddPNode( cache_adr, cache_adr,
1880                                             _igvn.MakeConX(distance) );
1881         transform_later(prefetch_adr);
1882         prefetch = new PrefetchAllocationNode( contended_phi_rawmem, prefetch_adr );
1883         transform_later(prefetch);
1884         distance += step_size;
1885         contended_phi_rawmem = prefetch;
1886       }
1887    } else if( AllocatePrefetchStyle > 0 ) {
1888       // Insert a prefetch for each allocation only on the fast-path
1889       Node *prefetch_adr;
1890       Node *prefetch;
1891       // Generate several prefetch instructions.
1892       uint step_size = AllocatePrefetchStepSize;
1893       uint distance = AllocatePrefetchDistance;
1894       for ( intx i = 0; i < lines; i++ ) {
1895         prefetch_adr = new AddPNode( old_eden_top, new_eden_top,
1896                                             _igvn.MakeConX(distance) );
1897         transform_later(prefetch_adr);
1898         prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
1899         // Do not let it float too high, since if eden_top == eden_end,
1900         // both might be null.
1901         if( i == 0 ) { // Set control for first prefetch, next follows it
1902           prefetch->init_req(0, needgc_false);
1903         }
1904         transform_later(prefetch);
1905         distance += step_size;
1906         i_o = prefetch;
1907       }
1908    }
1909    return i_o;
1910 }
1911 
1912 
1913 void PhaseMacroExpand::expand_allocate(AllocateNode *alloc) {
1914   expand_allocate_common(alloc, nullptr,
1915                          OptoRuntime::new_instance_Type(),
1916                          OptoRuntime::new_instance_Java(), nullptr);
1917 }
1918 
1919 void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) {
1920   Node* length = alloc->in(AllocateNode::ALength);
1921   Node* valid_length_test = alloc->in(AllocateNode::ValidLengthTest);
1922   InitializeNode* init = alloc->initialization();
1923   Node* klass_node = alloc->in(AllocateNode::KlassNode);
1924   const TypeAryKlassPtr* ary_klass_t = _igvn.type(klass_node)->isa_aryklassptr();
1925   address slow_call_address;  // Address of slow call
1926   if (init != nullptr && init->is_complete_with_arraycopy() &&
1927       ary_klass_t && ary_klass_t->elem()->isa_klassptr() == nullptr) {
1928     // Don't zero type array during slow allocation in VM since
1929     // it will be initialized later by arraycopy in compiled code.
1930     slow_call_address = OptoRuntime::new_array_nozero_Java();
1931   } else {
1932     slow_call_address = OptoRuntime::new_array_Java();
1933   }
1934   expand_allocate_common(alloc, length,
1935                          OptoRuntime::new_array_Type(),
1936                          slow_call_address, valid_length_test);
1937 }
1938 
1939 //-------------------mark_eliminated_box----------------------------------
1940 //
1941 // During EA obj may point to several objects but after few ideal graph
1942 // transformations (CCP) it may point to only one non escaping object
1943 // (but still using phi), corresponding locks and unlocks will be marked
1944 // for elimination. Later obj could be replaced with a new node (new phi)
1945 // and which does not have escape information. And later after some graph
1946 // reshape other locks and unlocks (which were not marked for elimination
1947 // before) are connected to this new obj (phi) but they still will not be
1948 // marked for elimination since new obj has no escape information.
1949 // Mark all associated (same box and obj) lock and unlock nodes for
1950 // elimination if some of them marked already.
1951 void PhaseMacroExpand::mark_eliminated_box(Node* box, Node* obj) {
1952   BoxLockNode* oldbox = box->as_BoxLock();
1953   if (oldbox->is_eliminated()) {
1954     return; // This BoxLock node was processed already.
1955   }
1956   assert(!oldbox->is_unbalanced(), "this should not be called for unbalanced region");
1957   // New implementation (EliminateNestedLocks) has separate BoxLock
1958   // node for each locked region so mark all associated locks/unlocks as
1959   // eliminated even if different objects are referenced in one locked region
1960   // (for example, OSR compilation of nested loop inside locked scope).
1961   if (EliminateNestedLocks ||
1962       oldbox->as_BoxLock()->is_simple_lock_region(nullptr, obj, nullptr)) {
1963     // Box is used only in one lock region. Mark this box as eliminated.
1964     oldbox->set_local();      // This verifies correct state of BoxLock
1965     _igvn.hash_delete(oldbox);
1966     oldbox->set_eliminated(); // This changes box's hash value
1967      _igvn.hash_insert(oldbox);
1968 
1969     for (uint i = 0; i < oldbox->outcnt(); i++) {
1970       Node* u = oldbox->raw_out(i);
1971       if (u->is_AbstractLock() && !u->as_AbstractLock()->is_non_esc_obj()) {
1972         AbstractLockNode* alock = u->as_AbstractLock();
1973         // Check lock's box since box could be referenced by Lock's debug info.
1974         if (alock->box_node() == oldbox) {
1975           // Mark eliminated all related locks and unlocks.
1976 #ifdef ASSERT
1977           alock->log_lock_optimization(C, "eliminate_lock_set_non_esc4");
1978 #endif
1979           alock->set_non_esc_obj();
1980         }
1981       }
1982     }
1983     return;
1984   }
1985 
1986   // Create new "eliminated" BoxLock node and use it in monitor debug info
1987   // instead of oldbox for the same object.
1988   BoxLockNode* newbox = oldbox->clone()->as_BoxLock();
1989 
1990   // Note: BoxLock node is marked eliminated only here and it is used
1991   // to indicate that all associated lock and unlock nodes are marked
1992   // for elimination.
1993   newbox->set_local(); // This verifies correct state of BoxLock
1994   newbox->set_eliminated();
1995   transform_later(newbox);
1996 
1997   // Replace old box node with new box for all users of the same object.
1998   for (uint i = 0; i < oldbox->outcnt();) {
1999     bool next_edge = true;
2000 
2001     Node* u = oldbox->raw_out(i);
2002     if (u->is_AbstractLock()) {
2003       AbstractLockNode* alock = u->as_AbstractLock();
2004       if (alock->box_node() == oldbox && alock->obj_node()->eqv_uncast(obj)) {
2005         // Replace Box and mark eliminated all related locks and unlocks.
2006 #ifdef ASSERT
2007         alock->log_lock_optimization(C, "eliminate_lock_set_non_esc5");
2008 #endif
2009         alock->set_non_esc_obj();
2010         _igvn.rehash_node_delayed(alock);
2011         alock->set_box_node(newbox);
2012         next_edge = false;
2013       }
2014     }
2015     if (u->is_FastLock() && u->as_FastLock()->obj_node()->eqv_uncast(obj)) {
2016       FastLockNode* flock = u->as_FastLock();
2017       assert(flock->box_node() == oldbox, "sanity");
2018       _igvn.rehash_node_delayed(flock);
2019       flock->set_box_node(newbox);
2020       next_edge = false;
2021     }
2022 
2023     // Replace old box in monitor debug info.
2024     if (u->is_SafePoint() && u->as_SafePoint()->jvms()) {
2025       SafePointNode* sfn = u->as_SafePoint();
2026       JVMState* youngest_jvms = sfn->jvms();
2027       int max_depth = youngest_jvms->depth();
2028       for (int depth = 1; depth <= max_depth; depth++) {
2029         JVMState* jvms = youngest_jvms->of_depth(depth);
2030         int num_mon  = jvms->nof_monitors();
2031         // Loop over monitors
2032         for (int idx = 0; idx < num_mon; idx++) {
2033           Node* obj_node = sfn->monitor_obj(jvms, idx);
2034           Node* box_node = sfn->monitor_box(jvms, idx);
2035           if (box_node == oldbox && obj_node->eqv_uncast(obj)) {
2036             int j = jvms->monitor_box_offset(idx);
2037             _igvn.replace_input_of(u, j, newbox);
2038             next_edge = false;
2039           }
2040         }
2041       }
2042     }
2043     if (next_edge) i++;
2044   }
2045 }
2046 
2047 //-----------------------mark_eliminated_locking_nodes-----------------------
2048 void PhaseMacroExpand::mark_eliminated_locking_nodes(AbstractLockNode *alock) {
2049   if (alock->box_node()->as_BoxLock()->is_unbalanced()) {
2050     return; // Can't do any more elimination for this locking region
2051   }
2052   if (EliminateNestedLocks) {
2053     if (alock->is_nested()) {
2054        assert(alock->box_node()->as_BoxLock()->is_eliminated(), "sanity");
2055        return;
2056     } else if (!alock->is_non_esc_obj()) { // Not eliminated or coarsened
2057       // Only Lock node has JVMState needed here.
2058       // Not that preceding claim is documented anywhere else.
2059       if (alock->jvms() != nullptr) {
2060         if (alock->as_Lock()->is_nested_lock_region()) {
2061           // Mark eliminated related nested locks and unlocks.
2062           Node* obj = alock->obj_node();
2063           BoxLockNode* box_node = alock->box_node()->as_BoxLock();
2064           assert(!box_node->is_eliminated(), "should not be marked yet");
2065           // Note: BoxLock node is marked eliminated only here
2066           // and it is used to indicate that all associated lock
2067           // and unlock nodes are marked for elimination.
2068           box_node->set_eliminated(); // Box's hash is always NO_HASH here
2069           for (uint i = 0; i < box_node->outcnt(); i++) {
2070             Node* u = box_node->raw_out(i);
2071             if (u->is_AbstractLock()) {
2072               alock = u->as_AbstractLock();
2073               if (alock->box_node() == box_node) {
2074                 // Verify that this Box is referenced only by related locks.
2075                 assert(alock->obj_node()->eqv_uncast(obj), "");
2076                 // Mark all related locks and unlocks.
2077 #ifdef ASSERT
2078                 alock->log_lock_optimization(C, "eliminate_lock_set_nested");
2079 #endif
2080                 alock->set_nested();
2081               }
2082             }
2083           }
2084         } else {
2085 #ifdef ASSERT
2086           alock->log_lock_optimization(C, "eliminate_lock_NOT_nested_lock_region");
2087           if (C->log() != nullptr)
2088             alock->as_Lock()->is_nested_lock_region(C); // rerun for debugging output
2089 #endif
2090         }
2091       }
2092       return;
2093     }
2094     // Process locks for non escaping object
2095     assert(alock->is_non_esc_obj(), "");
2096   } // EliminateNestedLocks
2097 
2098   if (alock->is_non_esc_obj()) { // Lock is used for non escaping object
2099     // Look for all locks of this object and mark them and
2100     // corresponding BoxLock nodes as eliminated.
2101     Node* obj = alock->obj_node();
2102     for (uint j = 0; j < obj->outcnt(); j++) {
2103       Node* o = obj->raw_out(j);
2104       if (o->is_AbstractLock() &&
2105           o->as_AbstractLock()->obj_node()->eqv_uncast(obj)) {
2106         alock = o->as_AbstractLock();
2107         Node* box = alock->box_node();
2108         // Replace old box node with new eliminated box for all users
2109         // of the same object and mark related locks as eliminated.
2110         mark_eliminated_box(box, obj);
2111       }
2112     }
2113   }
2114 }
2115 
2116 // we have determined that this lock/unlock can be eliminated, we simply
2117 // eliminate the node without expanding it.
2118 //
2119 // Note:  The membar's associated with the lock/unlock are currently not
2120 //        eliminated.  This should be investigated as a future enhancement.
2121 //
2122 bool PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) {
2123 
2124   if (!alock->is_eliminated()) {
2125     return false;
2126   }
2127 #ifdef ASSERT
2128   if (!alock->is_coarsened()) {
2129     // Check that new "eliminated" BoxLock node is created.
2130     BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2131     assert(oldbox->is_eliminated(), "should be done already");
2132   }
2133 #endif
2134 
2135   alock->log_lock_optimization(C, "eliminate_lock");
2136 
2137 #ifndef PRODUCT
2138   if (PrintEliminateLocks) {
2139     tty->print_cr("++++ Eliminated: %d %s '%s'", alock->_idx, (alock->is_Lock() ? "Lock" : "Unlock"), alock->kind_as_string());
2140   }
2141 #endif
2142 
2143   Node* mem  = alock->in(TypeFunc::Memory);
2144   Node* ctrl = alock->in(TypeFunc::Control);
2145   guarantee(ctrl != nullptr, "missing control projection, cannot replace_node() with null");
2146 
2147   alock->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2148   // There are 2 projections from the lock.  The lock node will
2149   // be deleted when its last use is subsumed below.
2150   assert(alock->outcnt() == 2 &&
2151          _callprojs.fallthrough_proj != nullptr &&
2152          _callprojs.fallthrough_memproj != nullptr,
2153          "Unexpected projections from Lock/Unlock");
2154 
2155   Node* fallthroughproj = _callprojs.fallthrough_proj;
2156   Node* memproj_fallthrough = _callprojs.fallthrough_memproj;
2157 
2158   // The memory projection from a lock/unlock is RawMem
2159   // The input to a Lock is merged memory, so extract its RawMem input
2160   // (unless the MergeMem has been optimized away.)
2161   if (alock->is_Lock()) {
2162     // Search for MemBarAcquireLock node and delete it also.
2163     MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
2164     assert(membar != nullptr && membar->Opcode() == Op_MemBarAcquireLock, "");
2165     Node* ctrlproj = membar->proj_out(TypeFunc::Control);
2166     Node* memproj = membar->proj_out(TypeFunc::Memory);
2167     _igvn.replace_node(ctrlproj, fallthroughproj);
2168     _igvn.replace_node(memproj, memproj_fallthrough);
2169 
2170     // Delete FastLock node also if this Lock node is unique user
2171     // (a loop peeling may clone a Lock node).
2172     Node* flock = alock->as_Lock()->fastlock_node();
2173     if (flock->outcnt() == 1) {
2174       assert(flock->unique_out() == alock, "sanity");
2175       _igvn.replace_node(flock, top());
2176     }
2177   }
2178 
2179   // Search for MemBarReleaseLock node and delete it also.
2180   if (alock->is_Unlock() && ctrl->is_Proj() && ctrl->in(0)->is_MemBar()) {
2181     MemBarNode* membar = ctrl->in(0)->as_MemBar();
2182     assert(membar->Opcode() == Op_MemBarReleaseLock &&
2183            mem->is_Proj() && membar == mem->in(0), "");
2184     _igvn.replace_node(fallthroughproj, ctrl);
2185     _igvn.replace_node(memproj_fallthrough, mem);
2186     fallthroughproj = ctrl;
2187     memproj_fallthrough = mem;
2188     ctrl = membar->in(TypeFunc::Control);
2189     mem  = membar->in(TypeFunc::Memory);
2190   }
2191 
2192   _igvn.replace_node(fallthroughproj, ctrl);
2193   _igvn.replace_node(memproj_fallthrough, mem);
2194   return true;
2195 }
2196 
2197 
2198 //------------------------------expand_lock_node----------------------
2199 void PhaseMacroExpand::expand_lock_node(LockNode *lock) {
2200 
2201   Node* ctrl = lock->in(TypeFunc::Control);
2202   Node* mem = lock->in(TypeFunc::Memory);
2203   Node* obj = lock->obj_node();
2204   Node* box = lock->box_node();
2205   Node* flock = lock->fastlock_node();
2206 
2207   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2208 
2209   // Make the merge point
2210   Node *region;
2211   Node *mem_phi;
2212   Node *slow_path;
2213 
2214   region  = new RegionNode(3);
2215   // create a Phi for the memory state
2216   mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2217 
2218   // Optimize test; set region slot 2
2219   slow_path = opt_bits_test(ctrl, region, 2, flock, 0, 0);
2220   mem_phi->init_req(2, mem);
2221 
2222   // Make slow path call
2223   CallNode *call = make_slow_call((CallNode *) lock, OptoRuntime::complete_monitor_enter_Type(),
2224                                   OptoRuntime::complete_monitor_locking_Java(), nullptr, slow_path,
2225                                   obj, box, nullptr);
2226 
2227   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2228 
2229   // Slow path can only throw asynchronous exceptions, which are always
2230   // de-opted.  So the compiler thinks the slow-call can never throw an
2231   // exception.  If it DOES throw an exception we would need the debug
2232   // info removed first (since if it throws there is no monitor).
2233   assert(_callprojs.fallthrough_ioproj == nullptr && _callprojs.catchall_ioproj == nullptr &&
2234          _callprojs.catchall_memproj == nullptr && _callprojs.catchall_catchproj == nullptr, "Unexpected projection from Lock");
2235 
2236   // Capture slow path
2237   // disconnect fall-through projection from call and create a new one
2238   // hook up users of fall-through projection to region
2239   Node *slow_ctrl = _callprojs.fallthrough_proj->clone();
2240   transform_later(slow_ctrl);
2241   _igvn.hash_delete(_callprojs.fallthrough_proj);
2242   _callprojs.fallthrough_proj->disconnect_inputs(C);
2243   region->init_req(1, slow_ctrl);
2244   // region inputs are now complete
2245   transform_later(region);
2246   _igvn.replace_node(_callprojs.fallthrough_proj, region);
2247 
2248   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2249 
2250   mem_phi->init_req(1, memproj);
2251 
2252   transform_later(mem_phi);
2253 
2254   _igvn.replace_node(_callprojs.fallthrough_memproj, mem_phi);
2255 }
2256 
2257 //------------------------------expand_unlock_node----------------------
2258 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
2259 
2260   Node* ctrl = unlock->in(TypeFunc::Control);
2261   Node* mem = unlock->in(TypeFunc::Memory);
2262   Node* obj = unlock->obj_node();
2263   Node* box = unlock->box_node();
2264 
2265   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2266 
2267   // No need for a null check on unlock
2268 
2269   // Make the merge point
2270   Node *region;
2271   Node *mem_phi;
2272 
2273   region  = new RegionNode(3);
2274   // create a Phi for the memory state
2275   mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2276 
2277   FastUnlockNode *funlock = new FastUnlockNode( ctrl, obj, box );
2278   funlock = transform_later( funlock )->as_FastUnlock();
2279   // Optimize test; set region slot 2
2280   Node *slow_path = opt_bits_test(ctrl, region, 2, funlock, 0, 0);
2281   Node *thread = transform_later(new ThreadLocalNode());
2282 
2283   CallNode *call = make_slow_call((CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(),
2284                                   CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C),
2285                                   "complete_monitor_unlocking_C", slow_path, obj, box, thread);
2286 
2287   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2288   assert(_callprojs.fallthrough_ioproj == nullptr && _callprojs.catchall_ioproj == nullptr &&
2289          _callprojs.catchall_memproj == nullptr && _callprojs.catchall_catchproj == nullptr, "Unexpected projection from Lock");
2290 
2291   // No exceptions for unlocking
2292   // Capture slow path
2293   // disconnect fall-through projection from call and create a new one
2294   // hook up users of fall-through projection to region
2295   Node *slow_ctrl = _callprojs.fallthrough_proj->clone();
2296   transform_later(slow_ctrl);
2297   _igvn.hash_delete(_callprojs.fallthrough_proj);
2298   _callprojs.fallthrough_proj->disconnect_inputs(C);
2299   region->init_req(1, slow_ctrl);
2300   // region inputs are now complete
2301   transform_later(region);
2302   _igvn.replace_node(_callprojs.fallthrough_proj, region);
2303 
2304   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory) );
2305   mem_phi->init_req(1, memproj );
2306   mem_phi->init_req(2, mem);
2307   transform_later(mem_phi);
2308 
2309   _igvn.replace_node(_callprojs.fallthrough_memproj, mem_phi);
2310 }
2311 
2312 void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) {
2313   assert(check->in(SubTypeCheckNode::Control) == nullptr, "should be pinned");
2314   Node* bol = check->unique_out();
2315   Node* obj_or_subklass = check->in(SubTypeCheckNode::ObjOrSubKlass);
2316   Node* superklass = check->in(SubTypeCheckNode::SuperKlass);
2317   assert(bol->is_Bool() && bol->as_Bool()->_test._test == BoolTest::ne, "unexpected bool node");
2318 
2319   for (DUIterator_Last imin, i = bol->last_outs(imin); i >= imin; --i) {
2320     Node* iff = bol->last_out(i);
2321     assert(iff->is_If(), "where's the if?");
2322 
2323     if (iff->in(0)->is_top()) {
2324       _igvn.replace_input_of(iff, 1, C->top());
2325       continue;
2326     }
2327 
2328     Node* iftrue = iff->as_If()->proj_out(1);
2329     Node* iffalse = iff->as_If()->proj_out(0);
2330     Node* ctrl = iff->in(0);
2331 
2332     Node* subklass = nullptr;
2333     if (_igvn.type(obj_or_subklass)->isa_klassptr()) {
2334       subklass = obj_or_subklass;
2335     } else {
2336       Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes());
2337       subklass = _igvn.transform(LoadKlassNode::make(_igvn, nullptr, C->immutable_memory(), k_adr, TypeInstPtr::KLASS));
2338     }
2339 
2340     Node* not_subtype_ctrl = Phase::gen_subtype_check(subklass, superklass, &ctrl, nullptr, _igvn, check->method(), check->bci());
2341 
2342     _igvn.replace_input_of(iff, 0, C->top());
2343     _igvn.replace_node(iftrue, not_subtype_ctrl);
2344     _igvn.replace_node(iffalse, ctrl);
2345   }
2346   _igvn.replace_node(check, C->top());
2347 }
2348 
2349 //---------------------------eliminate_macro_nodes----------------------
2350 // Eliminate scalar replaced allocations and associated locks.
2351 void PhaseMacroExpand::eliminate_macro_nodes() {
2352   if (C->macro_count() == 0)
2353     return;
2354   NOT_PRODUCT(int membar_before = count_MemBar(C);)
2355 
2356   // Before elimination may re-mark (change to Nested or NonEscObj)
2357   // all associated (same box and obj) lock and unlock nodes.
2358   int cnt = C->macro_count();
2359   for (int i=0; i < cnt; i++) {
2360     Node *n = C->macro_node(i);
2361     if (n->is_AbstractLock()) { // Lock and Unlock nodes
2362       mark_eliminated_locking_nodes(n->as_AbstractLock());
2363     }
2364   }
2365   // Re-marking may break consistency of Coarsened locks.
2366   if (!C->coarsened_locks_consistent()) {
2367     return; // recompile without Coarsened locks if broken
2368   } else {
2369     // After coarsened locks are eliminated locking regions
2370     // become unbalanced. We should not execute any more
2371     // locks elimination optimizations on them.
2372     C->mark_unbalanced_boxes();
2373   }
2374 
2375   // First, attempt to eliminate locks
2376   bool progress = true;
2377   while (progress) {
2378     progress = false;
2379     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
2380       Node* n = C->macro_node(i - 1);
2381       bool success = false;
2382       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2383       if (n->is_AbstractLock()) {
2384         success = eliminate_locking_node(n->as_AbstractLock());
2385 #ifndef PRODUCT
2386         if (success && PrintOptoStatistics) {
2387           Atomic::inc(&PhaseMacroExpand::_monitor_objects_removed_counter);
2388         }
2389 #endif
2390       }
2391       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2392       progress = progress || success;
2393     }
2394   }
2395   // Next, attempt to eliminate allocations
2396   _has_locks = false;
2397   progress = true;
2398   while (progress) {
2399     progress = false;
2400     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
2401       Node* n = C->macro_node(i - 1);
2402       bool success = false;
2403       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2404       switch (n->class_id()) {
2405       case Node::Class_Allocate:
2406       case Node::Class_AllocateArray:
2407         success = eliminate_allocate_node(n->as_Allocate());
2408 #ifndef PRODUCT
2409         if (success && PrintOptoStatistics) {
2410           Atomic::inc(&PhaseMacroExpand::_objs_scalar_replaced_counter);
2411         }
2412 #endif
2413         break;
2414       case Node::Class_CallStaticJava:
2415         success = eliminate_boxing_node(n->as_CallStaticJava());
2416         break;
2417       case Node::Class_Lock:
2418       case Node::Class_Unlock:
2419         assert(!n->as_AbstractLock()->is_eliminated(), "sanity");
2420         _has_locks = true;
2421         break;
2422       case Node::Class_ArrayCopy:
2423         break;
2424       case Node::Class_OuterStripMinedLoop:
2425         break;
2426       case Node::Class_SubTypeCheck:
2427         break;
2428       case Node::Class_Opaque1:
2429         break;
2430       default:
2431         assert(n->Opcode() == Op_LoopLimit ||
2432                n->Opcode() == Op_Opaque3   ||
2433                n->Opcode() == Op_Opaque4   ||
2434                n->Opcode() == Op_MaxL      ||
2435                n->Opcode() == Op_MinL      ||
2436                BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
2437                "unknown node type in macro list");
2438       }
2439       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2440       progress = progress || success;
2441     }
2442   }
2443 #ifndef PRODUCT
2444   if (PrintOptoStatistics) {
2445     int membar_after = count_MemBar(C);
2446     Atomic::add(&PhaseMacroExpand::_memory_barriers_removed_counter, membar_before - membar_after);
2447   }
2448 #endif
2449 }
2450 
2451 //------------------------------expand_macro_nodes----------------------
2452 //  Returns true if a failure occurred.
2453 bool PhaseMacroExpand::expand_macro_nodes() {
2454   // Do not allow new macro nodes once we started to expand
2455   C->reset_allow_macro_nodes();
2456   if (StressMacroExpansion) {
2457     C->shuffle_macro_nodes();
2458   }
2459   // Last attempt to eliminate macro nodes.
2460   eliminate_macro_nodes();
2461   if (C->failing())  return true;
2462 
2463   // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
2464   bool progress = true;
2465   while (progress) {
2466     progress = false;
2467     for (int i = C->macro_count(); i > 0; i--) {
2468       Node* n = C->macro_node(i-1);
2469       bool success = false;
2470       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2471       if (n->Opcode() == Op_LoopLimit) {
2472         // Remove it from macro list and put on IGVN worklist to optimize.
2473         C->remove_macro_node(n);
2474         _igvn._worklist.push(n);
2475         success = true;
2476       } else if (n->Opcode() == Op_CallStaticJava) {
2477         // Remove it from macro list and put on IGVN worklist to optimize.
2478         C->remove_macro_node(n);
2479         _igvn._worklist.push(n);
2480         success = true;
2481       } else if (n->is_Opaque1()) {
2482         _igvn.replace_node(n, n->in(1));
2483         success = true;
2484 #if INCLUDE_RTM_OPT
2485       } else if ((n->Opcode() == Op_Opaque3) && ((Opaque3Node*)n)->rtm_opt()) {
2486         assert(C->profile_rtm(), "should be used only in rtm deoptimization code");
2487         assert((n->outcnt() == 1) && n->unique_out()->is_Cmp(), "");
2488         Node* cmp = n->unique_out();
2489 #ifdef ASSERT
2490         // Validate graph.
2491         assert((cmp->outcnt() == 1) && cmp->unique_out()->is_Bool(), "");
2492         BoolNode* bol = cmp->unique_out()->as_Bool();
2493         assert((bol->outcnt() == 1) && bol->unique_out()->is_If() &&
2494                (bol->_test._test == BoolTest::ne), "");
2495         IfNode* ifn = bol->unique_out()->as_If();
2496         assert((ifn->outcnt() == 2) &&
2497                ifn->proj_out(1)->is_uncommon_trap_proj(Deoptimization::Reason_rtm_state_change) != nullptr, "");
2498 #endif
2499         Node* repl = n->in(1);
2500         if (!_has_locks) {
2501           // Remove RTM state check if there are no locks in the code.
2502           // Replace input to compare the same value.
2503           repl = (cmp->in(1) == n) ? cmp->in(2) : cmp->in(1);
2504         }
2505         _igvn.replace_node(n, repl);
2506         success = true;
2507 #endif
2508       } else if (n->Opcode() == Op_Opaque4) {
2509         // With Opaque4 nodes, the expectation is that the test of input 1
2510         // is always equal to the constant value of input 2. So we can
2511         // remove the Opaque4 and replace it by input 2. In debug builds,
2512         // leave the non constant test in instead to sanity check that it
2513         // never fails (if it does, that subgraph was constructed so, at
2514         // runtime, a Halt node is executed).
2515 #ifdef ASSERT
2516         _igvn.replace_node(n, n->in(1));
2517 #else
2518         _igvn.replace_node(n, n->in(2));
2519 #endif
2520         success = true;
2521       } else if (n->Opcode() == Op_OuterStripMinedLoop) {
2522         n->as_OuterStripMinedLoop()->adjust_strip_mined_loop(&_igvn);
2523         C->remove_macro_node(n);
2524         success = true;
2525       } else if (n->Opcode() == Op_MaxL) {
2526         // Since MaxL and MinL are not implemented in the backend, we expand them to
2527         // a CMoveL construct now. At least until here, the type could be computed
2528         // precisely. CMoveL is not so smart, but we can give it at least the best
2529         // type we know abouot n now.
2530         Node* repl = MaxNode::signed_max(n->in(1), n->in(2), _igvn.type(n), _igvn);
2531         _igvn.replace_node(n, repl);
2532         success = true;
2533       } else if (n->Opcode() == Op_MinL) {
2534         Node* repl = MaxNode::signed_min(n->in(1), n->in(2), _igvn.type(n), _igvn);
2535         _igvn.replace_node(n, repl);
2536         success = true;
2537       }
2538       assert(!success || (C->macro_count() == (old_macro_count - 1)), "elimination must have deleted one node from macro list");
2539       progress = progress || success;
2540       if (success) {
2541         C->print_method(PHASE_AFTER_MACRO_EXPANSION_STEP, 5, n);
2542       }
2543     }
2544   }
2545 
2546   // Clean up the graph so we're less likely to hit the maximum node
2547   // limit
2548   _igvn.set_delay_transform(false);
2549   _igvn.optimize();
2550   if (C->failing())  return true;
2551   _igvn.set_delay_transform(true);
2552 
2553 
2554   // Because we run IGVN after each expansion, some macro nodes may go
2555   // dead and be removed from the list as we iterate over it. Move
2556   // Allocate nodes (processed in a second pass) at the beginning of
2557   // the list and then iterate from the last element of the list until
2558   // an Allocate node is seen. This is robust to random deletion in
2559   // the list due to nodes going dead.
2560   C->sort_macro_nodes();
2561 
2562   // expand arraycopy "macro" nodes first
2563   // For ReduceBulkZeroing, we must first process all arraycopy nodes
2564   // before the allocate nodes are expanded.
2565   while (C->macro_count() > 0) {
2566     int macro_count = C->macro_count();
2567     Node * n = C->macro_node(macro_count-1);
2568     assert(n->is_macro(), "only macro nodes expected here");
2569     if (_igvn.type(n) == Type::TOP || (n->in(0) != nullptr && n->in(0)->is_top())) {
2570       // node is unreachable, so don't try to expand it
2571       C->remove_macro_node(n);
2572       continue;
2573     }
2574     if (n->is_Allocate()) {
2575       break;
2576     }
2577     // Make sure expansion will not cause node limit to be exceeded.
2578     // Worst case is a macro node gets expanded into about 200 nodes.
2579     // Allow 50% more for optimization.
2580     if (C->check_node_count(300, "out of nodes before macro expansion")) {
2581       return true;
2582     }
2583 
2584     DEBUG_ONLY(int old_macro_count = C->macro_count();)
2585     switch (n->class_id()) {
2586     case Node::Class_Lock:
2587       expand_lock_node(n->as_Lock());
2588       break;
2589     case Node::Class_Unlock:
2590       expand_unlock_node(n->as_Unlock());
2591       break;
2592     case Node::Class_ArrayCopy:
2593       expand_arraycopy_node(n->as_ArrayCopy());
2594       break;
2595     case Node::Class_SubTypeCheck:
2596       expand_subtypecheck_node(n->as_SubTypeCheck());
2597       break;
2598     default:
2599       assert(false, "unknown node type in macro list");
2600     }
2601     assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2602     if (C->failing())  return true;
2603     C->print_method(PHASE_AFTER_MACRO_EXPANSION_STEP, 5, n);
2604 
2605     // Clean up the graph so we're less likely to hit the maximum node
2606     // limit
2607     _igvn.set_delay_transform(false);
2608     _igvn.optimize();
2609     if (C->failing())  return true;
2610     _igvn.set_delay_transform(true);
2611   }
2612 
2613   // All nodes except Allocate nodes are expanded now. There could be
2614   // new optimization opportunities (such as folding newly created
2615   // load from a just allocated object). Run IGVN.
2616 
2617   // expand "macro" nodes
2618   // nodes are removed from the macro list as they are processed
2619   while (C->macro_count() > 0) {
2620     int macro_count = C->macro_count();
2621     Node * n = C->macro_node(macro_count-1);
2622     assert(n->is_macro(), "only macro nodes expected here");
2623     if (_igvn.type(n) == Type::TOP || (n->in(0) != nullptr && n->in(0)->is_top())) {
2624       // node is unreachable, so don't try to expand it
2625       C->remove_macro_node(n);
2626       continue;
2627     }
2628     // Make sure expansion will not cause node limit to be exceeded.
2629     // Worst case is a macro node gets expanded into about 200 nodes.
2630     // Allow 50% more for optimization.
2631     if (C->check_node_count(300, "out of nodes before macro expansion")) {
2632       return true;
2633     }
2634     switch (n->class_id()) {
2635     case Node::Class_Allocate:
2636       expand_allocate(n->as_Allocate());
2637       break;
2638     case Node::Class_AllocateArray:
2639       expand_allocate_array(n->as_AllocateArray());
2640       break;
2641     default:
2642       assert(false, "unknown node type in macro list");
2643     }
2644     assert(C->macro_count() < macro_count, "must have deleted a node from macro list");
2645     if (C->failing())  return true;
2646     C->print_method(PHASE_AFTER_MACRO_EXPANSION_STEP, 5, n);
2647 
2648     // Clean up the graph so we're less likely to hit the maximum node
2649     // limit
2650     _igvn.set_delay_transform(false);
2651     _igvn.optimize();
2652     if (C->failing())  return true;
2653     _igvn.set_delay_transform(true);
2654   }
2655 
2656   _igvn.set_delay_transform(false);
2657   return false;
2658 }
2659 
2660 #ifndef PRODUCT
2661 int PhaseMacroExpand::_objs_scalar_replaced_counter = 0;
2662 int PhaseMacroExpand::_monitor_objects_removed_counter = 0;
2663 int PhaseMacroExpand::_GC_barriers_removed_counter = 0;
2664 int PhaseMacroExpand::_memory_barriers_removed_counter = 0;
2665 
2666 void PhaseMacroExpand::print_statistics() {
2667   tty->print("Objects scalar replaced = %d, ", Atomic::load(&_objs_scalar_replaced_counter));
2668   tty->print("Monitor objects removed = %d, ", Atomic::load(&_monitor_objects_removed_counter));
2669   tty->print("GC barriers removed = %d, ", Atomic::load(&_GC_barriers_removed_counter));
2670   tty->print_cr("Memory barriers removed = %d", Atomic::load(&_memory_barriers_removed_counter));
2671 }
2672 
2673 int PhaseMacroExpand::count_MemBar(Compile *C) {
2674   if (!PrintOptoStatistics) {
2675     return 0;
2676   }
2677   Unique_Node_List ideal_nodes;
2678   int total = 0;
2679   ideal_nodes.map(C->live_nodes(), nullptr);
2680   ideal_nodes.push(C->root());
2681   for (uint next = 0; next < ideal_nodes.size(); ++next) {
2682     Node* n = ideal_nodes.at(next);
2683     if (n->is_MemBar()) {
2684       total++;
2685     }
2686     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2687       Node* m = n->fast_out(i);
2688       ideal_nodes.push(m);
2689     }
2690   }
2691   return total;
2692 }
2693 #endif