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