< prev index next >

src/hotspot/share/opto/macro.cpp

Print this page

   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 "compiler/compileLog.hpp"
  26 #include "gc/shared/collectedHeap.inline.hpp"
  27 #include "gc/shared/tlab_globals.hpp"
  28 #include "libadt/vectset.hpp"
  29 #include "memory/universe.hpp"
  30 #include "opto/addnode.hpp"
  31 #include "opto/arraycopynode.hpp"
  32 #include "opto/callnode.hpp"
  33 #include "opto/castnode.hpp"
  34 #include "opto/cfgnode.hpp"
  35 #include "opto/compile.hpp"
  36 #include "opto/convertnode.hpp"
  37 #include "opto/graphKit.hpp"

  38 #include "opto/intrinsicnode.hpp"
  39 #include "opto/locknode.hpp"
  40 #include "opto/loopnode.hpp"
  41 #include "opto/macro.hpp"
  42 #include "opto/memnode.hpp"
  43 #include "opto/narrowptrnode.hpp"
  44 #include "opto/node.hpp"
  45 #include "opto/opaquenode.hpp"

  46 #include "opto/phaseX.hpp"
  47 #include "opto/rootnode.hpp"
  48 #include "opto/runtime.hpp"
  49 #include "opto/subnode.hpp"
  50 #include "opto/subtypenode.hpp"
  51 #include "opto/type.hpp"
  52 #include "prims/jvmtiExport.hpp"
  53 #include "runtime/continuation.hpp"
  54 #include "runtime/sharedRuntime.hpp"


  55 #include "utilities/macros.hpp"
  56 #include "utilities/powerOfTwo.hpp"
  57 #if INCLUDE_G1GC
  58 #include "gc/g1/g1ThreadLocalData.hpp"
  59 #endif // INCLUDE_G1GC
  60 
  61 
  62 //
  63 // Replace any references to "oldref" in inputs to "use" with "newref".
  64 // Returns the number of replacements made.
  65 //
  66 int PhaseMacroExpand::replace_input(Node *use, Node *oldref, Node *newref) {
  67   int nreplacements = 0;
  68   uint req = use->req();
  69   for (uint j = 0; j < use->len(); j++) {
  70     Node *uin = use->in(j);
  71     if (uin == oldref) {
  72       if (j < req)
  73         use->set_req(j, newref);
  74       else
  75         use->set_prec(j, newref);
  76       nreplacements++;
  77     } else if (j >= req && uin == nullptr) {
  78       break;
  79     }
  80   }
  81   return nreplacements;
  82 }
  83 
  84 void PhaseMacroExpand::migrate_outs(Node *old, Node *target) {
  85   assert(old != nullptr, "sanity");
  86   for (DUIterator_Fast imax, i = old->fast_outs(imax); i < imax; i++) {
  87     Node* use = old->fast_out(i);
  88     _igvn.rehash_node_delayed(use);
  89     imax -= replace_input(use, old, target);
  90     // back up iterator
  91     --i;
  92   }
  93   assert(old->outcnt() == 0, "all uses must be deleted");
  94 }
  95 
  96 Node* PhaseMacroExpand::opt_bits_test(Node* ctrl, Node* region, int edge, Node* word) {
  97   Node* cmp = word;
  98   Node* bol = transform_later(new BoolNode(cmp, BoolTest::ne));
  99   IfNode* iff = new IfNode( ctrl, bol, PROB_MIN, COUNT_UNKNOWN );
 100   transform_later(iff);
 101 
 102   // Fast path taken.
 103   Node *fast_taken = transform_later(new IfFalseNode(iff));
 104 
 105   // Fast path not-taken, i.e. slow path
 106   Node *slow_taken = transform_later(new IfTrueNode(iff));
 107 
 108     region->init_req(edge, fast_taken); // Capture fast-control
 109     return slow_taken;
 110 }
 111 
 112 //--------------------copy_predefined_input_for_runtime_call--------------------
 113 void PhaseMacroExpand::copy_predefined_input_for_runtime_call(Node * ctrl, CallNode* oldcall, CallNode* call) {
 114   // Set fixed predefined input arguments

 127   // Slow-path call
 128  CallNode *call = leaf_name
 129    ? (CallNode*)new CallLeafNode      ( slow_call_type, slow_call, leaf_name, TypeRawPtr::BOTTOM )
 130    : (CallNode*)new CallStaticJavaNode( slow_call_type, slow_call, OptoRuntime::stub_name(slow_call), TypeRawPtr::BOTTOM );
 131 
 132   // Slow path call has no side-effects, uses few values
 133   copy_predefined_input_for_runtime_call(slow_path, oldcall, call );
 134   if (parm0 != nullptr)  call->init_req(TypeFunc::Parms+0, parm0);
 135   if (parm1 != nullptr)  call->init_req(TypeFunc::Parms+1, parm1);
 136   if (parm2 != nullptr)  call->init_req(TypeFunc::Parms+2, parm2);
 137   call->copy_call_debug_info(&_igvn, oldcall);
 138   call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
 139   _igvn.replace_node(oldcall, call);
 140   transform_later(call);
 141 
 142   return call;
 143 }
 144 
 145 void PhaseMacroExpand::eliminate_gc_barrier(Node* p2x) {
 146   BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
 147   bs->eliminate_gc_barrier(this, p2x);
 148 #ifndef PRODUCT
 149   if (PrintOptoStatistics) {
 150     AtomicAccess::inc(&PhaseMacroExpand::_GC_barriers_removed_counter);
 151   }
 152 #endif
 153 }
 154 
 155 // Search for a memory operation for the specified memory slice.
 156 static Node *scan_mem_chain(Node *mem, int alias_idx, int offset, Node *start_mem, Node *alloc, PhaseGVN *phase) {
 157   Node *orig_mem = mem;
 158   Node *alloc_mem = alloc->as_Allocate()->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false);
 159   assert(alloc_mem != nullptr, "Allocation without a memory projection.");
 160   const TypeOopPtr *tinst = phase->C->get_adr_type(alias_idx)->isa_oopptr();
 161   while (true) {
 162     if (mem == alloc_mem || mem == start_mem ) {
 163       return mem;  // hit one of our sentinels
 164     } else if (mem->is_MergeMem()) {
 165       mem = mem->as_MergeMem()->memory_at(alias_idx);
 166     } else if (mem->is_Proj() && mem->as_Proj()->_con == TypeFunc::Memory) {
 167       Node *in = mem->in(0);

 170       if (in->is_Initialize() && in->as_Initialize()->allocation() == alloc) {
 171         return in;
 172       } else if (in->is_Call()) {
 173         CallNode *call = in->as_Call();
 174         if (call->may_modify(tinst, phase)) {
 175           assert(call->is_ArrayCopy(), "ArrayCopy is the only call node that doesn't make allocation escape");
 176           if (call->as_ArrayCopy()->modifies(offset, offset, phase, false)) {
 177             return in;
 178           }
 179         }
 180         mem = in->in(TypeFunc::Memory);
 181       } else if (in->is_MemBar()) {
 182         ArrayCopyNode* ac = nullptr;
 183         if (ArrayCopyNode::may_modify(tinst, in->as_MemBar(), phase, ac)) {
 184           if (ac != nullptr) {
 185             assert(ac->is_clonebasic(), "Only basic clone is a non escaping clone");
 186             return ac;
 187           }
 188         }
 189         mem = in->in(TypeFunc::Memory);


 190       } else {
 191 #ifdef ASSERT
 192         in->dump();
 193         mem->dump();
 194         assert(false, "unexpected projection");
 195 #endif
 196       }
 197     } else if (mem->is_Store()) {
 198       const TypePtr* atype = mem->as_Store()->adr_type();
 199       int adr_idx = phase->C->get_alias_index(atype);
 200       if (adr_idx == alias_idx) {
 201         assert(atype->isa_oopptr(), "address type must be oopptr");
 202         int adr_offset = atype->offset();
 203         uint adr_iid = atype->is_oopptr()->instance_id();
 204         // Array elements references have the same alias_idx
 205         // but different offset and different instance_id.
 206         if (adr_offset == offset && adr_iid == alloc->_idx) {
 207           return mem;
 208         }
 209       } else {
 210         assert(adr_idx == Compile::AliasIdxRaw, "address must match or be raw");
 211       }
 212       mem = mem->in(MemNode::Memory);
 213     } else if (mem->is_ClearArray()) {
 214       if (!ClearArrayNode::step_through(&mem, alloc->_idx, phase)) {
 215         // Can not bypass initialization of the instance
 216         // we are looking.
 217         DEBUG_ONLY(intptr_t offset;)
 218         assert(alloc == AllocateNode::Ideal_allocation(mem->in(3), phase, offset), "sanity");
 219         InitializeNode* init = alloc->as_Allocate()->initialization();
 220         // We are looking for stored value, return Initialize node
 221         // or memory edge from Allocate node.
 222         if (init != nullptr) {

 227       }
 228       // Otherwise skip it (the call updated 'mem' value).
 229     } else if (mem->Opcode() == Op_SCMemProj) {
 230       mem = mem->in(0);
 231       Node* adr = nullptr;
 232       if (mem->is_LoadStore()) {
 233         adr = mem->in(MemNode::Address);
 234       } else {
 235         assert(mem->Opcode() == Op_EncodeISOArray ||
 236                mem->Opcode() == Op_StrCompressedCopy, "sanity");
 237         adr = mem->in(3); // Destination array
 238       }
 239       const TypePtr* atype = adr->bottom_type()->is_ptr();
 240       int adr_idx = phase->C->get_alias_index(atype);
 241       if (adr_idx == alias_idx) {
 242         DEBUG_ONLY(mem->dump();)
 243         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
 244         return nullptr;
 245       }
 246       mem = mem->in(MemNode::Memory);
 247    } else if (mem->Opcode() == Op_StrInflatedCopy) {
 248       Node* adr = mem->in(3); // Destination array
 249       const TypePtr* atype = adr->bottom_type()->is_ptr();
 250       int adr_idx = phase->C->get_alias_index(atype);
 251       if (adr_idx == alias_idx) {
 252         DEBUG_ONLY(mem->dump();)
 253         assert(false, "Object is not scalar replaceable if a StrInflatedCopy node accesses its field");
 254         return nullptr;
 255       }
 256       mem = mem->in(MemNode::Memory);
 257     } else {
 258       return mem;
 259     }
 260     assert(mem != orig_mem, "dead memory loop");
 261   }
 262 }
 263 
 264 // Generate loads from source of the arraycopy for fields of
 265 // destination needed at a deoptimization point
 266 Node* PhaseMacroExpand::make_arraycopy_load(ArrayCopyNode* ac, intptr_t offset, Node* ctl, Node* mem, BasicType ft, const Type *ftype, AllocateNode *alloc) {
 267   BasicType bt = ft;

 272   }
 273   Node* res = nullptr;
 274   if (ac->is_clonebasic()) {
 275     assert(ac->in(ArrayCopyNode::Src) != ac->in(ArrayCopyNode::Dest), "clone source equals destination");
 276     Node* base = ac->in(ArrayCopyNode::Src);
 277     Node* adr = _igvn.transform(AddPNode::make_with_base(base, _igvn.MakeConX(offset)));
 278     const TypePtr* adr_type = _igvn.type(base)->is_ptr()->add_offset(offset);
 279     MergeMemNode* mergemen = _igvn.transform(MergeMemNode::make(mem))->as_MergeMem();
 280     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 281     res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
 282   } else {
 283     if (ac->modifies(offset, offset, &_igvn, true)) {
 284       assert(ac->in(ArrayCopyNode::Dest) == alloc->result_cast(), "arraycopy destination should be allocation's result");
 285       uint shift = exact_log2(type2aelembytes(bt));
 286       Node* src_pos = ac->in(ArrayCopyNode::SrcPos);
 287       Node* dest_pos = ac->in(ArrayCopyNode::DestPos);
 288       const TypeInt* src_pos_t = _igvn.type(src_pos)->is_int();
 289       const TypeInt* dest_pos_t = _igvn.type(dest_pos)->is_int();
 290 
 291       Node* adr = nullptr;
 292       const TypePtr* adr_type = nullptr;




 293       if (src_pos_t->is_con() && dest_pos_t->is_con()) {
 294         intptr_t off = ((src_pos_t->get_con() - dest_pos_t->get_con()) << shift) + offset;
 295         Node* base = ac->in(ArrayCopyNode::Src);
 296         adr = _igvn.transform(AddPNode::make_with_base(base, _igvn.MakeConX(off)));
 297         adr_type = _igvn.type(base)->is_ptr()->add_offset(off);
 298         if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 299           // Don't emit a new load from src if src == dst but try to get the value from memory instead
 300           return value_from_mem(ac->in(TypeFunc::Memory), ctl, ft, ftype, adr_type->isa_oopptr(), alloc);
 301         }
 302       } else {





 303         Node* diff = _igvn.transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
 304 #ifdef _LP64
 305         diff = _igvn.transform(new ConvI2LNode(diff));
 306 #endif
 307         diff = _igvn.transform(new LShiftXNode(diff, _igvn.intcon(shift)));
 308 
 309         Node* off = _igvn.transform(new AddXNode(_igvn.MakeConX(offset), diff));
 310         Node* base = ac->in(ArrayCopyNode::Src);
 311         adr = _igvn.transform(AddPNode::make_with_base(base, off));
 312         adr_type = _igvn.type(base)->is_ptr()->add_offset(Type::OffsetBot);
 313         if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 314           // Non constant offset in the array: we can't statically
 315           // determine the value
 316           return nullptr;
 317         }
 318       }
 319       MergeMemNode* mergemen = _igvn.transform(MergeMemNode::make(mem))->as_MergeMem();
 320       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 321       res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
 322     }
 323   }
 324   if (res != nullptr) {
 325     if (ftype->isa_narrowoop()) {
 326       // PhaseMacroExpand::scalar_replacement adds DecodeN nodes

 327       res = _igvn.transform(new EncodePNode(res, ftype));
 328     }
 329     return res;
 330   }
 331   return nullptr;
 332 }
 333 
 334 //
 335 // Given a Memory Phi, compute a value Phi containing the values from stores
 336 // on the input paths.
 337 // Note: this function is recursive, its depth is limited by the "level" argument
 338 // Returns the computed Phi, or null if it cannot compute it.
 339 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) {
 340   assert(mem->is_Phi(), "sanity");
 341   int alias_idx = C->get_alias_index(adr_t);
 342   int offset = adr_t->offset();
 343   int instance_id = adr_t->instance_id();
 344 
 345   // Check if an appropriate value phi already exists.
 346   Node* region = mem->in(0);
 347   for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) {
 348     Node* phi = region->fast_out(k);
 349     if (phi->is_Phi() && phi != mem &&
 350         phi->as_Phi()->is_same_inst_field(phi_type, (int)mem->_idx, instance_id, alias_idx, offset)) {
 351       return phi;
 352     }
 353   }
 354   // Check if an appropriate new value phi already exists.
 355   Node* new_phi = value_phis->find(mem->_idx);
 356   if (new_phi != nullptr)
 357     return new_phi;
 358 
 359   if (level <= 0) {
 360     return nullptr; // Give up: phi tree too deep
 361   }
 362   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
 363   Node *alloc_mem = alloc->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false);
 364   assert(alloc_mem != nullptr, "Allocation without a memory projection.");
 365 
 366   uint length = mem->req();
 367   GrowableArray <Node *> values(length, length, nullptr);
 368 
 369   // create a new Phi for the value
 370   PhiNode *phi = new PhiNode(mem->in(0), phi_type, nullptr, mem->_idx, instance_id, alias_idx, offset);
 371   transform_later(phi);
 372   value_phis->push(phi, mem->_idx);
 373 
 374   for (uint j = 1; j < length; j++) {
 375     Node *in = mem->in(j);
 376     if (in == nullptr || in->is_top()) {
 377       values.at_put(j, in);
 378     } else  {
 379       Node *val = scan_mem_chain(in, alias_idx, offset, start_mem, alloc, &_igvn);
 380       if (val == start_mem || val == alloc_mem) {
 381         // hit a sentinel, return appropriate 0 value
 382         values.at_put(j, _igvn.zerocon(ft));
 383         continue;





 384       }
 385       if (val->is_Initialize()) {
 386         val = val->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 387       }
 388       if (val == nullptr) {
 389         return nullptr;  // can't find a value on this path
 390       }
 391       if (val == mem) {
 392         values.at_put(j, mem);
 393       } else if (val->is_Store()) {
 394         Node* n = val->in(MemNode::ValueIn);
 395         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 396         n = bs->step_over_gc_barrier(n);
 397         if (is_subword_type(ft)) {
 398           n = Compile::narrow_value(ft, n, phi_type, &_igvn, true);
 399         }
 400         values.at_put(j, n);
 401       } else if(val->is_Proj() && val->in(0) == alloc) {
 402         values.at_put(j, _igvn.zerocon(ft));





 403       } else if (val->is_Phi()) {
 404         val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, value_phis, level-1);
 405         if (val == nullptr) {
 406           return nullptr;
 407         }
 408         values.at_put(j, val);
 409       } else if (val->Opcode() == Op_SCMemProj) {
 410         assert(val->in(0)->is_LoadStore() ||
 411                val->in(0)->Opcode() == Op_EncodeISOArray ||
 412                val->in(0)->Opcode() == Op_StrCompressedCopy, "sanity");
 413         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
 414         return nullptr;
 415       } else if (val->is_ArrayCopy()) {
 416         Node* res = make_arraycopy_load(val->as_ArrayCopy(), offset, val->in(0), val->in(TypeFunc::Memory), ft, phi_type, alloc);
 417         if (res == nullptr) {
 418           return nullptr;
 419         }
 420         values.at_put(j, res);
 421       } else if (val->is_top()) {
 422         // This indicates that this path into the phi is dead. Top will eventually also propagate into the Region.
 423         // IGVN will clean this up later.
 424         values.at_put(j, val);
 425       } else {
 426         DEBUG_ONLY( val->dump(); )
 427         assert(false, "unknown node on this path");
 428         return nullptr;  // unknown node on this path
 429       }
 430     }
 431   }
 432   // Set Phi's inputs
 433   for (uint j = 1; j < length; j++) {
 434     if (values.at(j) == mem) {
 435       phi->init_req(j, phi);
 436     } else {
 437       phi->init_req(j, values.at(j));
 438     }
 439   }
 440   return phi;
 441 }
 442 
























































 443 // Search the last value stored into the object's field.
 444 Node *PhaseMacroExpand::value_from_mem(Node *sfpt_mem, Node *sfpt_ctl, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, AllocateNode *alloc) {
 445   assert(adr_t->is_known_instance_field(), "instance required");
 446   int instance_id = adr_t->instance_id();
 447   assert((uint)instance_id == alloc->_idx, "wrong allocation");
 448 
 449   int alias_idx = C->get_alias_index(adr_t);
 450   int offset = adr_t->offset();
 451   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
 452   Node *alloc_ctrl = alloc->in(TypeFunc::Control);
 453   Node *alloc_mem = alloc->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false);
 454   assert(alloc_mem != nullptr, "Allocation without a memory projection.");
 455   VectorSet visited;
 456 
 457   bool done = sfpt_mem == alloc_mem;
 458   Node *mem = sfpt_mem;
 459   while (!done) {
 460     if (visited.test_set(mem->_idx)) {
 461       return nullptr;  // found a loop, give up
 462     }
 463     mem = scan_mem_chain(mem, alias_idx, offset, start_mem, alloc, &_igvn);
 464     if (mem == start_mem || mem == alloc_mem) {
 465       done = true;  // hit a sentinel, return appropriate 0 value
 466     } else if (mem->is_Initialize()) {
 467       mem = mem->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 468       if (mem == nullptr) {
 469         done = true; // Something go wrong.
 470       } else if (mem->is_Store()) {
 471         const TypePtr* atype = mem->as_Store()->adr_type();
 472         assert(C->get_alias_index(atype) == Compile::AliasIdxRaw, "store is correct memory slice");
 473         done = true;
 474       }
 475     } else if (mem->is_Store()) {
 476       const TypeOopPtr* atype = mem->as_Store()->adr_type()->isa_oopptr();
 477       assert(atype != nullptr, "address type must be oopptr");
 478       assert(C->get_alias_index(atype) == alias_idx &&
 479              atype->is_known_instance_field() && atype->offset() == offset &&
 480              atype->instance_id() == instance_id, "store is correct memory slice");
 481       done = true;
 482     } else if (mem->is_Phi()) {
 483       // try to find a phi's unique input
 484       Node *unique_input = nullptr;
 485       Node *top = C->top();
 486       for (uint i = 1; i < mem->req(); i++) {
 487         Node *n = scan_mem_chain(mem->in(i), alias_idx, offset, start_mem, alloc, &_igvn);
 488         if (n == nullptr || n == top || n == mem) {
 489           continue;
 490         } else if (unique_input == nullptr) {
 491           unique_input = n;
 492         } else if (unique_input != n) {
 493           unique_input = top;
 494           break;
 495         }
 496       }
 497       if (unique_input != nullptr && unique_input != top) {
 498         mem = unique_input;
 499       } else {
 500         done = true;
 501       }
 502     } else if (mem->is_ArrayCopy()) {
 503       done = true;
 504     } else if (mem->is_top()) {
 505       // The slice is on a dead path. Returning nullptr would lead to elimination
 506       // bailout, but we want to prevent that. Just forwarding the top is also legal,
 507       // and IGVN can just clean things up, and remove whatever receives top.
 508       return mem;
 509     } else {
 510       DEBUG_ONLY( mem->dump(); )
 511       assert(false, "unexpected node");
 512     }
 513   }
 514   if (mem != nullptr) {
 515     if (mem == start_mem || mem == alloc_mem) {
 516       // hit a sentinel, return appropriate 0 value
 517       return _igvn.zerocon(ft);
 518     } else if (mem->is_Store()) {
 519       Node* n = mem->in(MemNode::ValueIn);
 520       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 521       n = bs->step_over_gc_barrier(n);
 522       return n;
 523     } else if (mem->is_Phi()) {
 524       // attempt to produce a Phi reflecting the values on the input paths of the Phi
 525       Node_Stack value_phis(8);
 526       Node* phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, &value_phis, ValueSearchLimit);
 527       if (phi != nullptr) {
 528         return phi;
 529       } else {
 530         // Kill all new Phis
 531         while(value_phis.is_nonempty()) {
 532           Node* n = value_phis.node();
 533           _igvn.replace_node(n, C->top());
 534           value_phis.pop();
 535         }
 536       }
 537     } else if (mem->is_ArrayCopy()) {
 538       Node* ctl = mem->in(0);
 539       Node* m = mem->in(TypeFunc::Memory);
 540       if (sfpt_ctl->is_Proj() && sfpt_ctl->as_Proj()->is_uncommon_trap_proj()) {
 541         // pin the loads in the uncommon trap path
 542         ctl = sfpt_ctl;
 543         m = sfpt_mem;
 544       }
 545       return make_arraycopy_load(mem->as_ArrayCopy(), offset, ctl, m, ft, ftype, alloc);
 546     }
 547   }
 548   // Something go wrong.
 549   return nullptr;
 550 }
 551 







































































 552 // Check the possibility of scalar replacement.
 553 bool PhaseMacroExpand::can_eliminate_allocation(PhaseIterGVN* igvn, AllocateNode *alloc, GrowableArray <SafePointNode *>* safepoints) {
 554   //  Scan the uses of the allocation to check for anything that would
 555   //  prevent us from eliminating it.
 556   NOT_PRODUCT( const char* fail_eliminate = nullptr; )
 557   DEBUG_ONLY( Node* disq_node = nullptr; )
 558   bool can_eliminate = true;
 559   bool reduce_merge_precheck = (safepoints == nullptr);
 560 

 561   Node* res = alloc->result_cast();
 562   const TypeOopPtr* res_type = nullptr;
 563   if (res == nullptr) {
 564     // All users were eliminated.
 565   } else if (!res->is_CheckCastPP()) {
 566     NOT_PRODUCT(fail_eliminate = "Allocation does not have unique CheckCastPP";)
 567     can_eliminate = false;
 568   } else {

 569     res_type = igvn->type(res)->isa_oopptr();
 570     if (res_type == nullptr) {
 571       NOT_PRODUCT(fail_eliminate = "Neither instance or array allocation";)
 572       can_eliminate = false;
 573     } else if (!res_type->klass_is_exact()) {
 574       NOT_PRODUCT(fail_eliminate = "Not an exact type.";)
 575       can_eliminate = false;
 576     } else if (res_type->isa_aryptr()) {
 577       int length = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 578       if (length < 0) {
 579         NOT_PRODUCT(fail_eliminate = "Array's size is not constant";)
 580         can_eliminate = false;
 581       }
 582     }
 583   }
 584 
 585   if (can_eliminate && res != nullptr) {
 586     BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
 587     for (DUIterator_Fast jmax, j = res->fast_outs(jmax);
 588                                j < jmax && can_eliminate; j++) {
 589       Node* use = res->fast_out(j);
 590 
 591       if (use->is_AddP()) {
 592         const TypePtr* addp_type = igvn->type(use)->is_ptr();
 593         int offset = addp_type->offset();
 594 
 595         if (offset == Type::OffsetTop || offset == Type::OffsetBot) {
 596           NOT_PRODUCT(fail_eliminate = "Undefined field reference";)
 597           can_eliminate = false;
 598           break;
 599         }
 600         for (DUIterator_Fast kmax, k = use->fast_outs(kmax);
 601                                    k < kmax && can_eliminate; k++) {
 602           Node* n = use->fast_out(k);
 603           if (n->is_Mem() && n->as_Mem()->is_mismatched_access()) {
 604             DEBUG_ONLY(disq_node = n);
 605             NOT_PRODUCT(fail_eliminate = "Mismatched access");
 606             can_eliminate = false;
 607           }
 608           if (!n->is_Store() && n->Opcode() != Op_CastP2X && !bs->is_gc_pre_barrier_node(n) && !reduce_merge_precheck) {
 609             DEBUG_ONLY(disq_node = n;)
 610             if (n->is_Load() || n->is_LoadStore()) {
 611               NOT_PRODUCT(fail_eliminate = "Field load";)
 612             } else {
 613               NOT_PRODUCT(fail_eliminate = "Not store field reference";)
 614             }
 615             can_eliminate = false;
 616           }
 617         }
 618       } else if (use->is_ArrayCopy() &&
 619                  (use->as_ArrayCopy()->is_clonebasic() ||
 620                   use->as_ArrayCopy()->is_arraycopy_validated() ||
 621                   use->as_ArrayCopy()->is_copyof_validated() ||
 622                   use->as_ArrayCopy()->is_copyofrange_validated()) &&
 623                  use->in(ArrayCopyNode::Dest) == res) {
 624         // ok to eliminate
 625       } else if (use->is_SafePoint()) {
 626         SafePointNode* sfpt = use->as_SafePoint();
 627         if (sfpt->is_Call() && sfpt->as_Call()->has_non_debug_use(res)) {
 628           // Object is passed as argument.
 629           DEBUG_ONLY(disq_node = use;)
 630           NOT_PRODUCT(fail_eliminate = "Object is passed as argument";)
 631           can_eliminate = false;
 632         }
 633         Node* sfptMem = sfpt->memory();
 634         if (sfptMem == nullptr || sfptMem->is_top()) {
 635           DEBUG_ONLY(disq_node = use;)
 636           NOT_PRODUCT(fail_eliminate = "null or TOP memory";)
 637           can_eliminate = false;
 638         } else if (!reduce_merge_precheck) {

 639           safepoints->append_if_missing(sfpt);
 640         }























 641       } else if (reduce_merge_precheck &&
 642                  (use->is_Phi() || use->is_EncodeP() ||
 643                   use->Opcode() == Op_MemBarRelease ||
 644                   (UseStoreStoreForCtor && use->Opcode() == Op_MemBarStoreStore))) {
 645         // Nothing to do
 646       } else if (use->Opcode() != Op_CastP2X) { // CastP2X is used by card mark
 647         if (use->is_Phi()) {
 648           if (use->outcnt() == 1 && use->unique_out()->Opcode() == Op_Return) {
 649             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 650           } else {
 651             NOT_PRODUCT(fail_eliminate = "Object is referenced by Phi";)
 652           }
 653           DEBUG_ONLY(disq_node = use;)
 654         } else {
 655           if (use->Opcode() == Op_Return) {
 656             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 657           } else {
 658             NOT_PRODUCT(fail_eliminate = "Object is referenced by node";)
 659           }
 660           DEBUG_ONLY(disq_node = use;)
 661         }
 662         can_eliminate = false;



 663       }
 664     }
 665   }
 666 
 667 #ifndef PRODUCT
 668   if (PrintEliminateAllocations && safepoints != nullptr) {
 669     if (can_eliminate) {
 670       tty->print("Scalar ");
 671       if (res == nullptr)
 672         alloc->dump();
 673       else
 674         res->dump();
 675     } else if (alloc->_is_scalar_replaceable) {
 676       tty->print("NotScalar (%s)", fail_eliminate);
 677       if (res == nullptr)
 678         alloc->dump();
 679       else
 680         res->dump();
 681 #ifdef ASSERT
 682       if (disq_node != nullptr) {
 683           tty->print("  >>>> ");
 684           disq_node->dump();
 685       }
 686 #endif /*ASSERT*/
 687     }
 688   }
 689 
 690   if (TraceReduceAllocationMerges && !can_eliminate && reduce_merge_precheck) {
 691     tty->print_cr("\tCan't eliminate allocation because '%s': ", fail_eliminate != nullptr ? fail_eliminate : "");
 692     DEBUG_ONLY(if (disq_node != nullptr) disq_node->dump();)
 693   }
 694 #endif
 695   return can_eliminate;

 760     // CheckCastPP result was not updated in the stack slot, and so
 761     // we ended up using the CastPP. That means that the field knows
 762     // that it should get an oop from an interface, but the value lost
 763     // that information, and so it is not a subtype.
 764     // There may be other issues, feel free to investigate further!
 765     if (!is_java_primitive(value_bt)) { return; }
 766 
 767     tty->print_cr("value not compatible for field: %s vs %s",
 768                   type2name(value_bt),
 769                   type2name(field_bt));
 770     tty->print("value_type: ");
 771     value_type->dump();
 772     tty->cr();
 773     tty->print("field_type: ");
 774     field_type->dump();
 775     tty->cr();
 776     assert(false, "value_type does not fit field_type");
 777   }
 778 #endif
 779 
 780 SafePointScalarObjectNode* PhaseMacroExpand::create_scalarized_object_description(AllocateNode *alloc, SafePointNode* sfpt) {



















































































































































 781   // Fields of scalar objs are referenced only at the end
 782   // of regular debuginfo at the last (youngest) JVMS.
 783   // Record relative start index.
 784   ciInstanceKlass* iklass    = nullptr;
 785   BasicType basic_elem_type  = T_ILLEGAL;
 786   const Type* field_type     = nullptr;
 787   const TypeOopPtr* res_type = nullptr;
 788   int nfields                = 0;
 789   int array_base             = 0;
 790   int element_size           = 0;
 791   uint first_ind             = (sfpt->req() - sfpt->jvms()->scloff());
 792   Node* res                  = alloc->result_cast();
 793 
 794   assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");
 795   assert(sfpt->jvms() != nullptr, "missed JVMS");

 796 
 797   if (res != nullptr) { // Could be null when there are no users
 798     res_type = _igvn.type(res)->isa_oopptr();
 799 
 800     if (res_type->isa_instptr()) {
 801       // find the fields of the class which will be needed for safepoint debug information
 802       iklass = res_type->is_instptr()->instance_klass();
 803       nfields = iklass->nof_nonstatic_fields();
 804     } else {
 805       // find the array's elements which will be needed for safepoint debug information
 806       nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 807       assert(nfields >= 0, "must be an array klass.");
 808       basic_elem_type = res_type->is_aryptr()->elem()->array_element_basic_type();
 809       array_base = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
 810       element_size = type2aelembytes(basic_elem_type);
 811       field_type = res_type->is_aryptr()->elem();






 812     }
 813   }
 814 
 815   SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(res_type, alloc, first_ind, sfpt->jvms()->depth(), nfields);
 816   sobj->init_req(0, C->root());
 817   transform_later(sobj);
 818 
 819   // Scan object's fields adding an input to the safepoint for each field.
 820   for (int j = 0; j < nfields; j++) {
 821     intptr_t offset;
 822     ciField* field = nullptr;
 823     if (iklass != nullptr) {
 824       field = iklass->nonstatic_field_at(j);
 825       offset = field->offset_in_bytes();
 826       ciType* elem_type = field->type();
 827       basic_elem_type = field->layout_type();
 828 
 829       // The next code is taken from Parse::do_get_xxx().
 830       if (is_reference_type(basic_elem_type)) {
 831         if (!elem_type->is_loaded()) {
 832           field_type = TypeInstPtr::BOTTOM;
 833         } else if (field != nullptr && field->is_static_constant()) {
 834           ciObject* con = field->constant_value().as_object();
 835           // Do not "join" in the previous type; it doesn't add value,
 836           // and may yield a vacuous result if the field is of interface type.
 837           field_type = TypeOopPtr::make_from_constant(con)->isa_oopptr();
 838           assert(field_type != nullptr, "field singleton type must be consistent");
 839         } else {
 840           field_type = TypeOopPtr::make_from_klass(elem_type->as_klass());
 841         }
 842         if (UseCompressedOops) {
 843           field_type = field_type->make_narrowoop();
 844           basic_elem_type = T_NARROWOOP;
 845         }
 846       } else {
 847         field_type = Type::get_const_basic_type(basic_elem_type);
 848       }
 849     } else {
 850       offset = array_base + j * (intptr_t)element_size;
 851     }
 852 
 853     const TypeOopPtr *field_addr_type = res_type->add_offset(offset)->isa_oopptr();
 854 
 855     Node *field_val = value_from_mem(sfpt->memory(), sfpt->control(), basic_elem_type, field_type, field_addr_type, alloc);
 856 
 857     // We weren't able to find a value for this field,
 858     // give up on eliminating this allocation.
 859     if (field_val == nullptr) {
 860       uint last = sfpt->req() - 1;
 861       for (int k = 0;  k < j; k++) {
 862         sfpt->del_req(last--);
 863       }
 864       _igvn._worklist.push(sfpt);
 865 
 866 #ifndef PRODUCT
 867       if (PrintEliminateAllocations) {
 868         if (field != nullptr) {
 869           tty->print("=== At SafePoint node %d can't find value of field: ", sfpt->_idx);
 870           field->print();
 871           int field_idx = C->get_alias_index(field_addr_type);
 872           tty->print(" (alias_idx=%d)", field_idx);
 873         } else { // Array's element
 874           tty->print("=== At SafePoint node %d can't find value of array element [%d]", sfpt->_idx, j);
 875         }
 876         tty->print(", which prevents elimination of: ");
 877         if (res == nullptr)
 878           alloc->dump();
 879         else
 880           res->dump();
 881       }
 882 #endif
 883 
 884       return nullptr;
 885     }




 886 
 887     if (UseCompressedOops && field_type->isa_narrowoop()) {
 888       // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation
 889       // to be able scalar replace the allocation.
 890       if (field_val->is_EncodeP()) {
 891         field_val = field_val->in(1);
 892       } else {
 893         field_val = transform_later(new DecodeNNode(field_val, field_val->get_ptr_type()));
 894       }
 895     }
 896     DEBUG_ONLY(verify_type_compatability(field_val->bottom_type(), field_type);)
 897     sfpt->add_req(field_val);
 898   }
 899 
 900   sfpt->jvms()->set_endoff(sfpt->req());
 901 
 902   return sobj;
 903 }
 904 
 905 // Do scalar replacement.
 906 bool PhaseMacroExpand::scalar_replacement(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
 907   GrowableArray <SafePointNode *> safepoints_done;
 908   Node* res = alloc->result_cast();
 909   assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");




 910 
 911   // Process the safepoint uses

 912   while (safepoints.length() > 0) {
 913     SafePointNode* sfpt = safepoints.pop();
 914     SafePointScalarObjectNode* sobj = create_scalarized_object_description(alloc, sfpt);
 915 
 916     if (sobj == nullptr) {
 917       undo_previous_scalarizations(safepoints_done, alloc);
 918       return false;
 919     }
 920 
 921     // Now make a pass over the debug information replacing any references
 922     // to the allocated object with "sobj"
 923     JVMState *jvms = sfpt->jvms();
 924     sfpt->replace_edges_in_range(res, sobj, jvms->debug_start(), jvms->debug_end(), &_igvn);
 925     _igvn._worklist.push(sfpt);
 926 
 927     // keep it for rollback
 928     safepoints_done.append_if_missing(sfpt);
 929   }
 930 







 931   return true;
 932 }
 933 
 934 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) {
 935   Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control);
 936   Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory);
 937   if (ctl_proj != nullptr) {
 938     igvn.replace_node(ctl_proj, n->in(0));
 939   }
 940   if (mem_proj != nullptr) {
 941     igvn.replace_node(mem_proj, n->in(TypeFunc::Memory));
 942   }
 943 }
 944 
 945 // Process users of eliminated allocation.
 946 void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc) {

 947   Node* res = alloc->result_cast();
 948   if (res != nullptr) {




 949     for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
 950       Node *use = res->last_out(j);
 951       uint oc1 = res->outcnt();
 952 
 953       if (use->is_AddP()) {
 954         for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
 955           Node *n = use->last_out(k);
 956           uint oc2 = use->outcnt();
 957           if (n->is_Store()) {
 958 #ifdef ASSERT
 959             // Verify that there is no dependent MemBarVolatile nodes,
 960             // they should be removed during IGVN, see MemBarNode::Ideal().
 961             for (DUIterator_Fast pmax, p = n->fast_outs(pmax);
 962                                        p < pmax; p++) {
 963               Node* mb = n->fast_out(p);
 964               assert(mb->is_Initialize() || !mb->is_MemBar() ||
 965                      mb->req() <= MemBarNode::Precedent ||
 966                      mb->in(MemBarNode::Precedent) != n,
 967                      "MemBarVolatile should be eliminated for non-escaping object");
 968             }
 969 #endif
 970             _igvn.replace_node(n, n->in(MemNode::Memory));
 971           } else {
 972             eliminate_gc_barrier(n);
 973           }
 974           k -= (oc2 - use->outcnt());
 975         }
 976         _igvn.remove_dead_node(use);
 977       } else if (use->is_ArrayCopy()) {
 978         // Disconnect ArrayCopy node
 979         ArrayCopyNode* ac = use->as_ArrayCopy();
 980         if (ac->is_clonebasic()) {
 981           Node* membar_after = ac->proj_out(TypeFunc::Control)->unique_ctrl_out();
 982           disconnect_projections(ac, _igvn);
 983           assert(alloc->in(TypeFunc::Memory)->is_Proj() && alloc->in(TypeFunc::Memory)->in(0)->Opcode() == Op_MemBarCPUOrder, "mem barrier expected before allocation");
 984           Node* membar_before = alloc->in(TypeFunc::Memory)->in(0);
 985           disconnect_projections(membar_before->as_MemBar(), _igvn);
 986           if (membar_after->is_MemBar()) {
 987             disconnect_projections(membar_after->as_MemBar(), _igvn);
 988           }
 989         } else {
 990           assert(ac->is_arraycopy_validated() ||
 991                  ac->is_copyof_validated() ||
 992                  ac->is_copyofrange_validated(), "unsupported");
 993           CallProjections callprojs;
 994           ac->extract_projections(&callprojs, true);
 995 
 996           _igvn.replace_node(callprojs.fallthrough_ioproj, ac->in(TypeFunc::I_O));
 997           _igvn.replace_node(callprojs.fallthrough_memproj, ac->in(TypeFunc::Memory));
 998           _igvn.replace_node(callprojs.fallthrough_catchproj, ac->in(TypeFunc::Control));
 999 
1000           // Set control to top. IGVN will remove the remaining projections
1001           ac->set_req(0, top());
1002           ac->replace_edge(res, top(), &_igvn);
1003 
1004           // Disconnect src right away: it can help find new
1005           // opportunities for allocation elimination
1006           Node* src = ac->in(ArrayCopyNode::Src);
1007           ac->replace_edge(src, top(), &_igvn);
1008           // src can be top at this point if src and dest of the
1009           // arraycopy were the same
1010           if (src->outcnt() == 0 && !src->is_top()) {
1011             _igvn.remove_dead_node(src);
1012           }
1013         }
1014         _igvn._worklist.push(ac);
























1015       } else {
1016         eliminate_gc_barrier(use);
1017       }
1018       j -= (oc1 - res->outcnt());
1019     }
1020     assert(res->outcnt() == 0, "all uses of allocated objects must be deleted");
1021     _igvn.remove_dead_node(res);
1022   }
1023 
1024   //
1025   // Process other users of allocation's projections
1026   //
1027   if (_callprojs.resproj != nullptr && _callprojs.resproj->outcnt() != 0) {
1028     // First disconnect stores captured by Initialize node.
1029     // If Initialize node is eliminated first in the following code,
1030     // it will kill such stores and DUIterator_Last will assert.
1031     for (DUIterator_Fast jmax, j = _callprojs.resproj->fast_outs(jmax);  j < jmax; j++) {
1032       Node* use = _callprojs.resproj->fast_out(j);
1033       if (use->is_AddP()) {
1034         // raw memory addresses used only by the initialization
1035         _igvn.replace_node(use, C->top());
1036         --j; --jmax;
1037       }
1038     }
1039     for (DUIterator_Last jmin, j = _callprojs.resproj->last_outs(jmin); j >= jmin; ) {
1040       Node* use = _callprojs.resproj->last_out(j);
1041       uint oc1 = _callprojs.resproj->outcnt();
1042       if (use->is_Initialize()) {
1043         // Eliminate Initialize node.
1044         InitializeNode *init = use->as_Initialize();
1045         Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
1046         if (ctrl_proj != nullptr) {
1047           _igvn.replace_node(ctrl_proj, init->in(TypeFunc::Control));
1048 #ifdef ASSERT
1049           // If the InitializeNode has no memory out, it will die, and tmp will become null
1050           Node* tmp = init->in(TypeFunc::Control);
1051           assert(tmp == nullptr || tmp == _callprojs.fallthrough_catchproj, "allocation control projection");
1052 #endif
1053         }
1054         Node* mem = init->in(TypeFunc::Memory);
1055 #ifdef ASSERT
1056         if (init->number_of_projs(TypeFunc::Memory) > 0) {
1057           if (mem->is_MergeMem()) {
1058             assert(mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw) == _callprojs.fallthrough_memproj, "allocation memory projection");
1059           } else {
1060             assert(mem == _callprojs.fallthrough_memproj, "allocation memory projection");
1061           }
1062         }
1063 #endif
1064         init->replace_mem_projs_by(mem, &_igvn);
1065         assert(init->outcnt() == 0, "should only have had a control and some memory projections, and we removed them");




1066       } else  {
1067         assert(false, "only Initialize or AddP expected");
1068       }
1069       j -= (oc1 - _callprojs.resproj->outcnt());
1070     }
1071   }
1072   if (_callprojs.fallthrough_catchproj != nullptr) {
1073     _igvn.replace_node(_callprojs.fallthrough_catchproj, alloc->in(TypeFunc::Control));
1074   }
1075   if (_callprojs.fallthrough_memproj != nullptr) {
1076     _igvn.replace_node(_callprojs.fallthrough_memproj, alloc->in(TypeFunc::Memory));
1077   }
1078   if (_callprojs.catchall_memproj != nullptr) {
1079     _igvn.replace_node(_callprojs.catchall_memproj, C->top());
1080   }
1081   if (_callprojs.fallthrough_ioproj != nullptr) {
1082     _igvn.replace_node(_callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
1083   }
1084   if (_callprojs.catchall_ioproj != nullptr) {
1085     _igvn.replace_node(_callprojs.catchall_ioproj, C->top());
1086   }
1087   if (_callprojs.catchall_catchproj != nullptr) {
1088     _igvn.replace_node(_callprojs.catchall_catchproj, C->top());
1089   }
1090 }
1091 
1092 bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) {
1093   // If reallocation fails during deoptimization we'll pop all
1094   // interpreter frames for this compiled frame and that won't play
1095   // nice with JVMTI popframe.
1096   // We avoid this issue by eager reallocation when the popframe request
1097   // is received.
1098   if (!EliminateAllocations || !alloc->_is_non_escaping) {
1099     return false;
1100   }
1101   Node* klass = alloc->in(AllocateNode::KlassNode);
1102   const TypeKlassPtr* tklass = _igvn.type(klass)->is_klassptr();
1103   Node* res = alloc->result_cast();







1104   // Eliminate boxing allocations which are not used
1105   // regardless scalar replaceable status.
1106   bool boxing_alloc = C->eliminate_boxing() &&

1107                       tklass->isa_instklassptr() &&
1108                       tklass->is_instklassptr()->instance_klass()->is_box_klass();
1109   if (!alloc->_is_scalar_replaceable && (!boxing_alloc || (res != nullptr))) {
1110     return false;
1111   }
1112 
1113   alloc->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1114 
1115   GrowableArray <SafePointNode *> safepoints;
1116   if (!can_eliminate_allocation(&_igvn, alloc, &safepoints)) {
1117     return false;
1118   }
1119 
1120   if (!alloc->_is_scalar_replaceable) {
1121     assert(res == nullptr, "sanity");
1122     // We can only eliminate allocation if all debug info references
1123     // are already replaced with SafePointScalarObject because
1124     // we can't search for a fields value without instance_id.
1125     if (safepoints.length() > 0) {
1126       return false;
1127     }
1128   }
1129 
1130   if (!scalar_replacement(alloc, safepoints)) {
1131     return false;
1132   }
1133 
1134   CompileLog* log = C->log();
1135   if (log != nullptr) {
1136     log->head("eliminate_allocation type='%d'",
1137               log->identify(tklass->exact_klass()));
1138     JVMState* p = alloc->jvms();
1139     while (p != nullptr) {
1140       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1141       p = p->caller();
1142     }
1143     log->tail("eliminate_allocation");
1144   }
1145 
1146   process_users_of_allocation(alloc);
1147 
1148 #ifndef PRODUCT
1149   if (PrintEliminateAllocations) {
1150     if (alloc->is_AllocateArray())
1151       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1152     else
1153       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1154   }
1155 #endif
1156 
1157   return true;
1158 }
1159 
1160 bool PhaseMacroExpand::eliminate_boxing_node(CallStaticJavaNode *boxing) {
1161   // EA should remove all uses of non-escaping boxing node.
1162   if (!C->eliminate_boxing() || boxing->proj_out_or_null(TypeFunc::Parms) != nullptr) {
1163     return false;
1164   }
1165 
1166   assert(boxing->result_cast() == nullptr, "unexpected boxing node result");
1167 
1168   boxing->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1169 
1170   const TypeTuple* r = boxing->tf()->range();
1171   assert(r->cnt() > TypeFunc::Parms, "sanity");
1172   const TypeInstPtr* t = r->field_at(TypeFunc::Parms)->isa_instptr();
1173   assert(t != nullptr, "sanity");
1174 
1175   CompileLog* log = C->log();
1176   if (log != nullptr) {
1177     log->head("eliminate_boxing type='%d'",
1178               log->identify(t->instance_klass()));
1179     JVMState* p = boxing->jvms();
1180     while (p != nullptr) {
1181       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1182       p = p->caller();
1183     }
1184     log->tail("eliminate_boxing");
1185   }
1186 
1187   process_users_of_allocation(boxing);
1188 
1189 #ifndef PRODUCT
1190   if (PrintEliminateAllocations) {

1254 // oop flavor.
1255 //
1256 //=============================================================================
1257 // FastAllocateSizeLimit value is in DOUBLEWORDS.
1258 // Allocations bigger than this always go the slow route.
1259 // This value must be small enough that allocation attempts that need to
1260 // trigger exceptions go the slow route.  Also, it must be small enough so
1261 // that heap_top + size_in_bytes does not wrap around the 4Gig limit.
1262 //=============================================================================j//
1263 // %%% Here is an old comment from parseHelper.cpp; is it outdated?
1264 // The allocator will coalesce int->oop copies away.  See comment in
1265 // coalesce.cpp about how this works.  It depends critically on the exact
1266 // code shape produced here, so if you are changing this code shape
1267 // make sure the GC info for the heap-top is correct in and around the
1268 // slow-path call.
1269 //
1270 
1271 void PhaseMacroExpand::expand_allocate_common(
1272             AllocateNode* alloc, // allocation node to be expanded
1273             Node* length,  // array length for an array allocation

1274             const TypeFunc* slow_call_type, // Type of slow call
1275             address slow_call_address,  // Address of slow call
1276             Node* valid_length_test // whether length is valid or not
1277     )
1278 {
1279   Node* ctrl = alloc->in(TypeFunc::Control);
1280   Node* mem  = alloc->in(TypeFunc::Memory);
1281   Node* i_o  = alloc->in(TypeFunc::I_O);
1282   Node* size_in_bytes     = alloc->in(AllocateNode::AllocSize);
1283   Node* klass_node        = alloc->in(AllocateNode::KlassNode);
1284   Node* initial_slow_test = alloc->in(AllocateNode::InitialTest);
1285   assert(ctrl != nullptr, "must have control");
1286 
1287   // We need a Region and corresponding Phi's to merge the slow-path and fast-path results.
1288   // they will not be used if "always_slow" is set
1289   enum { slow_result_path = 1, fast_result_path = 2 };
1290   Node *result_region = nullptr;
1291   Node *result_phi_rawmem = nullptr;
1292   Node *result_phi_rawoop = nullptr;
1293   Node *result_phi_i_o = nullptr;

1338 #endif
1339       yank_alloc_node(alloc);
1340       return;
1341     }
1342   }
1343 
1344   enum { too_big_or_final_path = 1, need_gc_path = 2 };
1345   Node *slow_region = nullptr;
1346   Node *toobig_false = ctrl;
1347 
1348   // generate the initial test if necessary
1349   if (initial_slow_test != nullptr ) {
1350     assert (expand_fast_path, "Only need test if there is a fast path");
1351     slow_region = new RegionNode(3);
1352 
1353     // Now make the initial failure test.  Usually a too-big test but
1354     // might be a TRUE for finalizers.
1355     IfNode *toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1356     transform_later(toobig_iff);
1357     // Plug the failing-too-big test into the slow-path region
1358     Node *toobig_true = new IfTrueNode( toobig_iff );
1359     transform_later(toobig_true);
1360     slow_region    ->init_req( too_big_or_final_path, toobig_true );
1361     toobig_false = new IfFalseNode( toobig_iff );
1362     transform_later(toobig_false);
1363   } else {
1364     // No initial test, just fall into next case
1365     assert(allocation_has_use || !expand_fast_path, "Should already have been handled");
1366     toobig_false = ctrl;
1367     DEBUG_ONLY(slow_region = NodeSentinel);
1368   }
1369 
1370   // If we are here there are several possibilities
1371   // - expand_fast_path is false - then only a slow path is expanded. That's it.
1372   // no_initial_check means a constant allocation.
1373   // - If check always evaluates to false -> expand_fast_path is false (see above)
1374   // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath)
1375   // if !allocation_has_use the fast path is empty
1376   // if !allocation_has_use && no_initial_check
1377   // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all.
1378   //   removed by yank_alloc_node above.
1379 
1380   Node *slow_mem = mem;  // save the current memory state for slow path
1381   // generate the fast allocation code unless we know that the initial test will always go slow
1382   if (expand_fast_path) {
1383     // Fast path modifies only raw memory.
1384     if (mem->is_MergeMem()) {
1385       mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1386     }
1387 
1388     // allocate the Region and Phi nodes for the result
1389     result_region = new RegionNode(3);
1390     result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1391     result_phi_i_o    = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1392 
1393     // Grab regular I/O before optional prefetch may change it.
1394     // Slow-path does no I/O so just set it to the original I/O.
1395     result_phi_i_o->init_req(slow_result_path, i_o);
1396 
1397     // Name successful fast-path variables
1398     Node* fast_oop_ctrl;
1399     Node* fast_oop_rawmem;

1400     if (allocation_has_use) {
1401       Node* needgc_ctrl = nullptr;
1402       result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1403 
1404       intx prefetch_lines = length != nullptr ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1405       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1406       Node* fast_oop = bs->obj_allocate(this, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1407                                         fast_oop_ctrl, fast_oop_rawmem,
1408                                         prefetch_lines);
1409 
1410       if (initial_slow_test != nullptr) {
1411         // This completes all paths into the slow merge point
1412         slow_region->init_req(need_gc_path, needgc_ctrl);
1413         transform_later(slow_region);
1414       } else {
1415         // No initial slow path needed!
1416         // Just fall from the need-GC path straight into the VM call.
1417         slow_region = needgc_ctrl;
1418       }
1419 

1437     result_phi_i_o   ->init_req(fast_result_path, i_o);
1438     result_phi_rawmem->init_req(fast_result_path, fast_oop_rawmem);
1439   } else {
1440     slow_region = ctrl;
1441     result_phi_i_o = i_o; // Rename it to use in the following code.
1442   }
1443 
1444   // Generate slow-path call
1445   CallNode *call = new CallStaticJavaNode(slow_call_type, slow_call_address,
1446                                OptoRuntime::stub_name(slow_call_address),
1447                                TypePtr::BOTTOM);
1448   call->init_req(TypeFunc::Control,   slow_region);
1449   call->init_req(TypeFunc::I_O,       top());    // does no i/o
1450   call->init_req(TypeFunc::Memory,    slow_mem); // may gc ptrs
1451   call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1452   call->init_req(TypeFunc::FramePtr,  alloc->in(TypeFunc::FramePtr));
1453 
1454   call->init_req(TypeFunc::Parms+0, klass_node);
1455   if (length != nullptr) {
1456     call->init_req(TypeFunc::Parms+1, length);






1457   }
1458 
1459   // Copy debug information and adjust JVMState information, then replace
1460   // allocate node with the call
1461   call->copy_call_debug_info(&_igvn, alloc);
1462   // For array allocations, copy the valid length check to the call node so Compile::final_graph_reshaping() can verify
1463   // that the call has the expected number of CatchProj nodes (in case the allocation always fails and the fallthrough
1464   // path dies).
1465   if (valid_length_test != nullptr) {
1466     call->add_req(valid_length_test);
1467   }
1468   if (expand_fast_path) {
1469     call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
1470   } else {
1471     // Hook i_o projection to avoid its elimination during allocation
1472     // replacement (when only a slow call is generated).
1473     call->set_req(TypeFunc::I_O, result_phi_i_o);
1474   }
1475   _igvn.replace_node(alloc, call);
1476   transform_later(call);
1477 
1478   // Identify the output projections from the allocate node and
1479   // adjust any references to them.
1480   // The control and io projections look like:
1481   //
1482   //        v---Proj(ctrl) <-----+   v---CatchProj(ctrl)
1483   //  Allocate                   Catch
1484   //        ^---Proj(io) <-------+   ^---CatchProj(io)
1485   //
1486   //  We are interested in the CatchProj nodes.
1487   //
1488   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1489 
1490   // An allocate node has separate memory projections for the uses on
1491   // the control and i_o paths. Replace the control memory projection with
1492   // result_phi_rawmem (unless we are only generating a slow call when
1493   // both memory projections are combined)
1494   if (expand_fast_path && _callprojs.fallthrough_memproj != nullptr) {
1495     migrate_outs(_callprojs.fallthrough_memproj, result_phi_rawmem);
1496   }
1497   // Now change uses of catchall_memproj to use fallthrough_memproj and delete
1498   // catchall_memproj so we end up with a call that has only 1 memory projection.
1499   if (_callprojs.catchall_memproj != nullptr ) {
1500     if (_callprojs.fallthrough_memproj == nullptr) {
1501       _callprojs.fallthrough_memproj = new ProjNode(call, TypeFunc::Memory);
1502       transform_later(_callprojs.fallthrough_memproj);
1503     }
1504     migrate_outs(_callprojs.catchall_memproj, _callprojs.fallthrough_memproj);
1505     _igvn.remove_dead_node(_callprojs.catchall_memproj);
1506   }
1507 
1508   // An allocate node has separate i_o projections for the uses on the control
1509   // and i_o paths. Always replace the control i_o projection with result i_o
1510   // otherwise incoming i_o become dead when only a slow call is generated
1511   // (it is different from memory projections where both projections are
1512   // combined in such case).
1513   if (_callprojs.fallthrough_ioproj != nullptr) {
1514     migrate_outs(_callprojs.fallthrough_ioproj, result_phi_i_o);
1515   }
1516   // Now change uses of catchall_ioproj to use fallthrough_ioproj and delete
1517   // catchall_ioproj so we end up with a call that has only 1 i_o projection.
1518   if (_callprojs.catchall_ioproj != nullptr ) {
1519     if (_callprojs.fallthrough_ioproj == nullptr) {
1520       _callprojs.fallthrough_ioproj = new ProjNode(call, TypeFunc::I_O);
1521       transform_later(_callprojs.fallthrough_ioproj);
1522     }
1523     migrate_outs(_callprojs.catchall_ioproj, _callprojs.fallthrough_ioproj);
1524     _igvn.remove_dead_node(_callprojs.catchall_ioproj);
1525   }
1526 
1527   // if we generated only a slow call, we are done
1528   if (!expand_fast_path) {
1529     // Now we can unhook i_o.
1530     if (result_phi_i_o->outcnt() > 1) {
1531       call->set_req(TypeFunc::I_O, top());
1532     } else {
1533       assert(result_phi_i_o->unique_ctrl_out() == call, "sanity");
1534       // Case of new array with negative size known during compilation.
1535       // AllocateArrayNode::Ideal() optimization disconnect unreachable
1536       // following code since call to runtime will throw exception.
1537       // As result there will be no users of i_o after the call.
1538       // Leave i_o attached to this call to avoid problems in preceding graph.
1539     }
1540     return;
1541   }
1542 
1543   if (_callprojs.fallthrough_catchproj != nullptr) {
1544     ctrl = _callprojs.fallthrough_catchproj->clone();
1545     transform_later(ctrl);
1546     _igvn.replace_node(_callprojs.fallthrough_catchproj, result_region);
1547   } else {
1548     ctrl = top();
1549   }
1550   Node *slow_result;
1551   if (_callprojs.resproj == nullptr) {
1552     // no uses of the allocation result
1553     slow_result = top();
1554   } else {
1555     slow_result = _callprojs.resproj->clone();
1556     transform_later(slow_result);
1557     _igvn.replace_node(_callprojs.resproj, result_phi_rawoop);
1558   }
1559 
1560   // Plug slow-path into result merge point
1561   result_region->init_req( slow_result_path, ctrl);
1562   transform_later(result_region);
1563   if (allocation_has_use) {
1564     result_phi_rawoop->init_req(slow_result_path, slow_result);
1565     transform_later(result_phi_rawoop);
1566   }
1567   result_phi_rawmem->init_req(slow_result_path, _callprojs.fallthrough_memproj);
1568   transform_later(result_phi_rawmem);
1569   transform_later(result_phi_i_o);
1570   // This completes all paths into the result merge point
1571 }
1572 
1573 // Remove alloc node that has no uses.
1574 void PhaseMacroExpand::yank_alloc_node(AllocateNode* alloc) {
1575   Node* ctrl = alloc->in(TypeFunc::Control);
1576   Node* mem  = alloc->in(TypeFunc::Memory);
1577   Node* i_o  = alloc->in(TypeFunc::I_O);
1578 
1579   alloc->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1580   if (_callprojs.resproj != nullptr) {
1581     for (DUIterator_Fast imax, i = _callprojs.resproj->fast_outs(imax); i < imax; i++) {
1582       Node* use = _callprojs.resproj->fast_out(i);
1583       use->isa_MemBar()->remove(&_igvn);
1584       --imax;
1585       --i; // back up iterator
1586     }
1587     assert(_callprojs.resproj->outcnt() == 0, "all uses must be deleted");
1588     _igvn.remove_dead_node(_callprojs.resproj);
1589   }
1590   if (_callprojs.fallthrough_catchproj != nullptr) {
1591     migrate_outs(_callprojs.fallthrough_catchproj, ctrl);
1592     _igvn.remove_dead_node(_callprojs.fallthrough_catchproj);
1593   }
1594   if (_callprojs.catchall_catchproj != nullptr) {
1595     _igvn.rehash_node_delayed(_callprojs.catchall_catchproj);
1596     _callprojs.catchall_catchproj->set_req(0, top());
1597   }
1598   if (_callprojs.fallthrough_proj != nullptr) {
1599     Node* catchnode = _callprojs.fallthrough_proj->unique_ctrl_out();
1600     _igvn.remove_dead_node(catchnode);
1601     _igvn.remove_dead_node(_callprojs.fallthrough_proj);
1602   }
1603   if (_callprojs.fallthrough_memproj != nullptr) {
1604     migrate_outs(_callprojs.fallthrough_memproj, mem);
1605     _igvn.remove_dead_node(_callprojs.fallthrough_memproj);
1606   }
1607   if (_callprojs.fallthrough_ioproj != nullptr) {
1608     migrate_outs(_callprojs.fallthrough_ioproj, i_o);
1609     _igvn.remove_dead_node(_callprojs.fallthrough_ioproj);
1610   }
1611   if (_callprojs.catchall_memproj != nullptr) {
1612     _igvn.rehash_node_delayed(_callprojs.catchall_memproj);
1613     _callprojs.catchall_memproj->set_req(0, top());
1614   }
1615   if (_callprojs.catchall_ioproj != nullptr) {
1616     _igvn.rehash_node_delayed(_callprojs.catchall_ioproj);
1617     _callprojs.catchall_ioproj->set_req(0, top());
1618   }
1619 #ifndef PRODUCT
1620   if (PrintEliminateAllocations) {
1621     if (alloc->is_AllocateArray()) {
1622       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1623     } else {
1624       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1625     }
1626   }
1627 #endif
1628   _igvn.remove_dead_node(alloc);
1629 }
1630 
1631 void PhaseMacroExpand::expand_initialize_membar(AllocateNode* alloc, InitializeNode* init,
1632                                                 Node*& fast_oop_ctrl, Node*& fast_oop_rawmem) {
1633   // If initialization is performed by an array copy, any required
1634   // MemBarStoreStore was already added. If the object does not
1635   // escape no need for a MemBarStoreStore. If the object does not
1636   // escape in its initializer and memory barrier (MemBarStoreStore or
1637   // stronger) is already added at exit of initializer, also no need

1731     Node* thread = new ThreadLocalNode();
1732     transform_later(thread);
1733 
1734     call->init_req(TypeFunc::Parms + 0, thread);
1735     call->init_req(TypeFunc::Parms + 1, oop);
1736     call->init_req(TypeFunc::Control, ctrl);
1737     call->init_req(TypeFunc::I_O    , top()); // does no i/o
1738     call->init_req(TypeFunc::Memory , rawmem);
1739     call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1740     call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1741     transform_later(call);
1742     ctrl = new ProjNode(call, TypeFunc::Control);
1743     transform_later(ctrl);
1744     rawmem = new ProjNode(call, TypeFunc::Memory);
1745     transform_later(rawmem);
1746   }
1747 }
1748 
1749 // Helper for PhaseMacroExpand::expand_allocate_common.
1750 // Initializes the newly-allocated storage.
1751 Node*
1752 PhaseMacroExpand::initialize_object(AllocateNode* alloc,
1753                                     Node* control, Node* rawmem, Node* object,
1754                                     Node* klass_node, Node* length,
1755                                     Node* size_in_bytes) {
1756   InitializeNode* init = alloc->initialization();
1757   // Store the klass & mark bits
1758   Node* mark_node = alloc->make_ideal_mark(&_igvn, control, rawmem);
1759   if (!mark_node->is_Con()) {
1760     transform_later(mark_node);
1761   }
1762   rawmem = make_store_raw(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
1763 
1764   if (!UseCompactObjectHeaders) {
1765     rawmem = make_store_raw(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
1766   }
1767   int header_size = alloc->minimum_header_size();  // conservatively small
1768 
1769   // Array length
1770   if (length != nullptr) {         // Arrays need length field
1771     rawmem = make_store_raw(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1772     // conservatively small header size:
1773     header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1774     if (_igvn.type(klass_node)->isa_aryklassptr()) {   // we know the exact header size in most cases:
1775       BasicType elem = _igvn.type(klass_node)->is_klassptr()->as_instance_type()->isa_aryptr()->elem()->array_element_basic_type();
1776       if (is_reference_type(elem, true)) {
1777         elem = T_OBJECT;
1778       }
1779       header_size = Klass::layout_helper_header_size(Klass::array_layout_helper(elem));
1780     }
1781   }
1782 
1783   // Clear the object body, if necessary.
1784   if (init == nullptr) {
1785     // The init has somehow disappeared; be cautious and clear everything.
1786     //
1787     // This can happen if a node is allocated but an uncommon trap occurs
1788     // immediately.  In this case, the Initialize gets associated with the
1789     // trap, and may be placed in a different (outer) loop, if the Allocate
1790     // is in a loop.  If (this is rare) the inner loop gets unrolled, then
1791     // there can be two Allocates to one Initialize.  The answer in all these
1792     // edge cases is safety first.  It is always safe to clear immediately
1793     // within an Allocate, and then (maybe or maybe not) clear some more later.
1794     if (!(UseTLAB && ZeroTLAB)) {
1795       rawmem = ClearArrayNode::clear_memory(control, rawmem, object,


1796                                             header_size, size_in_bytes,
1797                                             true,
1798                                             &_igvn);
1799     }
1800   } else {
1801     if (!init->is_complete()) {
1802       // Try to win by zeroing only what the init does not store.
1803       // We can also try to do some peephole optimizations,
1804       // such as combining some adjacent subword stores.
1805       rawmem = init->complete_stores(control, rawmem, object,
1806                                      header_size, size_in_bytes, &_igvn);
1807     }
1808     // We have no more use for this link, since the AllocateNode goes away:
1809     init->set_req(InitializeNode::RawAddress, top());
1810     // (If we keep the link, it just confuses the register allocator,
1811     // who thinks he sees a real use of the address by the membar.)
1812   }
1813 
1814   return rawmem;
1815 }

1950       for (intx i = 0; i < lines; i++) {
1951         prefetch_adr = AddPNode::make_off_heap(new_eden_top,
1952                                                _igvn.MakeConX(distance));
1953         transform_later(prefetch_adr);
1954         prefetch = new PrefetchAllocationNode(i_o, prefetch_adr);
1955         // Do not let it float too high, since if eden_top == eden_end,
1956         // both might be null.
1957         if (i == 0) { // Set control for first prefetch, next follows it
1958           prefetch->init_req(0, needgc_false);
1959         }
1960         transform_later(prefetch);
1961         distance += step_size;
1962         i_o = prefetch;
1963       }
1964    }
1965    return i_o;
1966 }
1967 
1968 
1969 void PhaseMacroExpand::expand_allocate(AllocateNode *alloc) {
1970   expand_allocate_common(alloc, nullptr,
1971                          OptoRuntime::new_instance_Type(),
1972                          OptoRuntime::new_instance_Java(), nullptr);
1973 }
1974 
1975 void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) {
1976   Node* length = alloc->in(AllocateNode::ALength);
1977   Node* valid_length_test = alloc->in(AllocateNode::ValidLengthTest);
1978   InitializeNode* init = alloc->initialization();
1979   Node* klass_node = alloc->in(AllocateNode::KlassNode);

1980   const TypeAryKlassPtr* ary_klass_t = _igvn.type(klass_node)->isa_aryklassptr();



1981   address slow_call_address;  // Address of slow call
1982   if (init != nullptr && init->is_complete_with_arraycopy() &&
1983       ary_klass_t && ary_klass_t->elem()->isa_klassptr() == nullptr) {
1984     // Don't zero type array during slow allocation in VM since
1985     // it will be initialized later by arraycopy in compiled code.
1986     slow_call_address = OptoRuntime::new_array_nozero_Java();

1987   } else {
1988     slow_call_address = OptoRuntime::new_array_Java();







1989   }
1990   expand_allocate_common(alloc, length,
1991                          OptoRuntime::new_array_Type(),
1992                          slow_call_address, valid_length_test);
1993 }
1994 
1995 //-------------------mark_eliminated_box----------------------------------
1996 //
1997 // During EA obj may point to several objects but after few ideal graph
1998 // transformations (CCP) it may point to only one non escaping object
1999 // (but still using phi), corresponding locks and unlocks will be marked
2000 // for elimination. Later obj could be replaced with a new node (new phi)
2001 // and which does not have escape information. And later after some graph
2002 // reshape other locks and unlocks (which were not marked for elimination
2003 // before) are connected to this new obj (phi) but they still will not be
2004 // marked for elimination since new obj has no escape information.
2005 // Mark all associated (same box and obj) lock and unlock nodes for
2006 // elimination if some of them marked already.
2007 void PhaseMacroExpand::mark_eliminated_box(Node* box, Node* obj) {
2008   BoxLockNode* oldbox = box->as_BoxLock();
2009   if (oldbox->is_eliminated()) {
2010     return; // This BoxLock node was processed already.
2011   }

2183 #ifdef ASSERT
2184   if (!alock->is_coarsened()) {
2185     // Check that new "eliminated" BoxLock node is created.
2186     BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2187     assert(oldbox->is_eliminated(), "should be done already");
2188   }
2189 #endif
2190 
2191   alock->log_lock_optimization(C, "eliminate_lock");
2192 
2193 #ifndef PRODUCT
2194   if (PrintEliminateLocks) {
2195     tty->print_cr("++++ Eliminated: %d %s '%s'", alock->_idx, (alock->is_Lock() ? "Lock" : "Unlock"), alock->kind_as_string());
2196   }
2197 #endif
2198 
2199   Node* mem  = alock->in(TypeFunc::Memory);
2200   Node* ctrl = alock->in(TypeFunc::Control);
2201   guarantee(ctrl != nullptr, "missing control projection, cannot replace_node() with null");
2202 
2203   alock->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2204   // There are 2 projections from the lock.  The lock node will
2205   // be deleted when its last use is subsumed below.
2206   assert(alock->outcnt() == 2 &&
2207          _callprojs.fallthrough_proj != nullptr &&
2208          _callprojs.fallthrough_memproj != nullptr,
2209          "Unexpected projections from Lock/Unlock");
2210 
2211   Node* fallthroughproj = _callprojs.fallthrough_proj;
2212   Node* memproj_fallthrough = _callprojs.fallthrough_memproj;
2213 
2214   // The memory projection from a lock/unlock is RawMem
2215   // The input to a Lock is merged memory, so extract its RawMem input
2216   // (unless the MergeMem has been optimized away.)
2217   if (alock->is_Lock()) {
2218     // Search for MemBarAcquireLock node and delete it also.
2219     MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
2220     assert(membar != nullptr && membar->Opcode() == Op_MemBarAcquireLock, "");
2221     Node* ctrlproj = membar->proj_out(TypeFunc::Control);
2222     Node* memproj = membar->proj_out(TypeFunc::Memory);
2223     _igvn.replace_node(ctrlproj, fallthroughproj);
2224     _igvn.replace_node(memproj, memproj_fallthrough);
2225 
2226     // Delete FastLock node also if this Lock node is unique user
2227     // (a loop peeling may clone a Lock node).
2228     Node* flock = alock->as_Lock()->fastlock_node();
2229     if (flock->outcnt() == 1) {
2230       assert(flock->unique_out() == alock, "sanity");
2231       _igvn.replace_node(flock, top());
2232     }

2263   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2264 
2265   // Make the merge point
2266   Node *region;
2267   Node *mem_phi;
2268   Node *slow_path;
2269 
2270   region  = new RegionNode(3);
2271   // create a Phi for the memory state
2272   mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2273 
2274   // Optimize test; set region slot 2
2275   slow_path = opt_bits_test(ctrl, region, 2, flock);
2276   mem_phi->init_req(2, mem);
2277 
2278   // Make slow path call
2279   CallNode* call = make_slow_call(lock, OptoRuntime::complete_monitor_enter_Type(),
2280                                   OptoRuntime::complete_monitor_locking_Java(), nullptr, slow_path,
2281                                   obj, box, nullptr);
2282 
2283   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2284 
2285   // Slow path can only throw asynchronous exceptions, which are always
2286   // de-opted.  So the compiler thinks the slow-call can never throw an
2287   // exception.  If it DOES throw an exception we would need the debug
2288   // info removed first (since if it throws there is no monitor).
2289   assert(_callprojs.fallthrough_ioproj == nullptr && _callprojs.catchall_ioproj == nullptr &&
2290          _callprojs.catchall_memproj == nullptr && _callprojs.catchall_catchproj == nullptr, "Unexpected projection from Lock");
2291 
2292   // Capture slow path
2293   // disconnect fall-through projection from call and create a new one
2294   // hook up users of fall-through projection to region
2295   Node *slow_ctrl = _callprojs.fallthrough_proj->clone();
2296   transform_later(slow_ctrl);
2297   _igvn.hash_delete(_callprojs.fallthrough_proj);
2298   _callprojs.fallthrough_proj->disconnect_inputs(C);
2299   region->init_req(1, slow_ctrl);
2300   // region inputs are now complete
2301   transform_later(region);
2302   _igvn.replace_node(_callprojs.fallthrough_proj, region);
2303 
2304   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2305 
2306   mem_phi->init_req(1, memproj);
2307 
2308   transform_later(mem_phi);
2309 
2310   _igvn.replace_node(_callprojs.fallthrough_memproj, mem_phi);
2311 }
2312 
2313 //------------------------------expand_unlock_node----------------------
2314 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
2315 
2316   Node* ctrl = unlock->in(TypeFunc::Control);
2317   Node* mem = unlock->in(TypeFunc::Memory);
2318   Node* obj = unlock->obj_node();
2319   Node* box = unlock->box_node();
2320 
2321   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2322 
2323   // No need for a null check on unlock
2324 
2325   // Make the merge point
2326   Node* region = new RegionNode(3);
2327 
2328   FastUnlockNode *funlock = new FastUnlockNode( ctrl, obj, box );
2329   funlock = transform_later( funlock )->as_FastUnlock();
2330   // Optimize test; set region slot 2
2331   Node *slow_path = opt_bits_test(ctrl, region, 2, funlock);
2332   Node *thread = transform_later(new ThreadLocalNode());
2333 
2334   CallNode *call = make_slow_call((CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(),
2335                                   CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C),
2336                                   "complete_monitor_unlocking_C", slow_path, obj, box, thread);
2337 
2338   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2339   assert(_callprojs.fallthrough_ioproj == nullptr && _callprojs.catchall_ioproj == nullptr &&
2340          _callprojs.catchall_memproj == nullptr && _callprojs.catchall_catchproj == nullptr, "Unexpected projection from Lock");
2341 
2342   // No exceptions for unlocking
2343   // Capture slow path
2344   // disconnect fall-through projection from call and create a new one
2345   // hook up users of fall-through projection to region
2346   Node *slow_ctrl = _callprojs.fallthrough_proj->clone();
2347   transform_later(slow_ctrl);
2348   _igvn.hash_delete(_callprojs.fallthrough_proj);
2349   _callprojs.fallthrough_proj->disconnect_inputs(C);
2350   region->init_req(1, slow_ctrl);
2351   // region inputs are now complete
2352   transform_later(region);
2353   _igvn.replace_node(_callprojs.fallthrough_proj, region);
2354 
2355   if (_callprojs.fallthrough_memproj != nullptr) {
2356     // create a Phi for the memory state
2357     Node* mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2358     Node* memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2359     mem_phi->init_req(1, memproj);
2360     mem_phi->init_req(2, mem);
2361     transform_later(mem_phi);
2362     _igvn.replace_node(_callprojs.fallthrough_memproj, mem_phi);
2363   }
2364 }
2365 






























































































































































































































2366 void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) {
2367   assert(check->in(SubTypeCheckNode::Control) == nullptr, "should be pinned");
2368   Node* bol = check->unique_out();
2369   Node* obj_or_subklass = check->in(SubTypeCheckNode::ObjOrSubKlass);
2370   Node* superklass = check->in(SubTypeCheckNode::SuperKlass);
2371   assert(bol->is_Bool() && bol->as_Bool()->_test._test == BoolTest::ne, "unexpected bool node");
2372 
2373   for (DUIterator_Last imin, i = bol->last_outs(imin); i >= imin; --i) {
2374     Node* iff = bol->last_out(i);
2375     assert(iff->is_If(), "where's the if?");
2376 
2377     if (iff->in(0)->is_top()) {
2378       _igvn.replace_input_of(iff, 1, C->top());
2379       continue;
2380     }
2381 
2382     IfTrueNode* iftrue = iff->as_If()->true_proj();
2383     IfFalseNode* iffalse = iff->as_If()->false_proj();
2384     Node* ctrl = iff->in(0);
2385 
2386     Node* subklass = nullptr;
2387     if (_igvn.type(obj_or_subklass)->isa_klassptr()) {
2388       subklass = obj_or_subklass;
2389     } else {
2390       Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes());
2391       subklass = _igvn.transform(LoadKlassNode::make(_igvn, C->immutable_memory(), k_adr, TypeInstPtr::KLASS));
2392     }
2393 
2394     Node* not_subtype_ctrl = Phase::gen_subtype_check(subklass, superklass, &ctrl, nullptr, _igvn, check->method(), check->bci());
2395 
2396     _igvn.replace_input_of(iff, 0, C->top());
2397     _igvn.replace_node(iftrue, not_subtype_ctrl);
2398     _igvn.replace_node(iffalse, ctrl);
2399   }
2400   _igvn.replace_node(check, C->top());
2401 }
2402 

















































































































2403 // Perform refining of strip mined loop nodes in the macro nodes list.
2404 void PhaseMacroExpand::refine_strip_mined_loop_macro_nodes() {
2405    for (int i = C->macro_count(); i > 0; i--) {
2406     Node* n = C->macro_node(i - 1);
2407     if (n->is_OuterStripMinedLoop()) {
2408       n->as_OuterStripMinedLoop()->adjust_strip_mined_loop(&_igvn);
2409     }
2410   }
2411 }
2412 
2413 //---------------------------eliminate_macro_nodes----------------------
2414 // Eliminate scalar replaced allocations and associated locks.
2415 void PhaseMacroExpand::eliminate_macro_nodes() {
2416   if (C->macro_count() == 0)
2417     return;

2418 
2419   if (StressMacroElimination) {
2420     C->shuffle_macro_nodes();
2421   }
2422   NOT_PRODUCT(int membar_before = count_MemBar(C);)
2423 
2424   // Before elimination may re-mark (change to Nested or NonEscObj)
2425   // all associated (same box and obj) lock and unlock nodes.
2426   int cnt = C->macro_count();
2427   for (int i=0; i < cnt; i++) {
2428     Node *n = C->macro_node(i);
2429     if (n->is_AbstractLock()) { // Lock and Unlock nodes
2430       mark_eliminated_locking_nodes(n->as_AbstractLock());
2431     }
2432   }
2433   // Re-marking may break consistency of Coarsened locks.
2434   if (!C->coarsened_locks_consistent()) {
2435     return; // recompile without Coarsened locks if broken
2436   } else {
2437     // After coarsened locks are eliminated locking regions
2438     // become unbalanced. We should not execute any more
2439     // locks elimination optimizations on them.
2440     C->mark_unbalanced_boxes();
2441   }
2442 
2443   // First, attempt to eliminate locks
2444   bool progress = true;
2445   while (progress) {
2446     progress = false;
2447     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
2448       Node* n = C->macro_node(i - 1);
2449       bool success = false;
2450       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2451       if (n->is_AbstractLock()) {
2452         success = eliminate_locking_node(n->as_AbstractLock());
2453 #ifndef PRODUCT
2454         if (success && PrintOptoStatistics) {
2455           AtomicAccess::inc(&PhaseMacroExpand::_monitor_objects_removed_counter);
2456         }
2457 #endif
2458       }
2459       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2460       progress = progress || success;
2461       if (success) {
2462         C->print_method(PHASE_AFTER_MACRO_ELIMINATION_STEP, 5, n);




2463       }
2464     }
2465   }
2466   // Next, attempt to eliminate allocations
2467   progress = true;
2468   while (progress) {
2469     progress = false;
2470     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
2471       Node* n = C->macro_node(i - 1);
2472       bool success = false;
2473       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2474       switch (n->class_id()) {
2475       case Node::Class_Allocate:
2476       case Node::Class_AllocateArray:
2477         success = eliminate_allocate_node(n->as_Allocate());
2478 #ifndef PRODUCT
2479         if (success && PrintOptoStatistics) {
2480           AtomicAccess::inc(&PhaseMacroExpand::_objs_scalar_replaced_counter);
2481         }
2482 #endif
2483         break;
2484       case Node::Class_CallStaticJava:
2485         success = eliminate_boxing_node(n->as_CallStaticJava());



2486         break;

2487       case Node::Class_Lock:
2488       case Node::Class_Unlock:
2489         assert(!n->as_AbstractLock()->is_eliminated(), "sanity");







2490         break;
2491       case Node::Class_ArrayCopy:
2492         break;
2493       case Node::Class_OuterStripMinedLoop:
2494         break;
2495       case Node::Class_SubTypeCheck:
2496         break;
2497       case Node::Class_Opaque1:
2498         break;


2499       default:
2500         assert(n->Opcode() == Op_LoopLimit ||
2501                n->Opcode() == Op_ModD ||
2502                n->Opcode() == Op_ModF ||
2503                n->Opcode() == Op_PowD ||
2504                n->is_OpaqueConstantBool()    ||
2505                n->is_OpaqueInitializedAssertionPredicate() ||
2506                n->Opcode() == Op_MaxL      ||
2507                n->Opcode() == Op_MinL      ||
2508                BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
2509                "unknown node type in macro list");
2510       }
2511       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2512       progress = progress || success;
2513       if (success) {
2514         C->print_method(PHASE_AFTER_MACRO_ELIMINATION_STEP, 5, n);
2515       }
2516     }
















2517   }
2518 #ifndef PRODUCT
2519   if (PrintOptoStatistics) {
2520     int membar_after = count_MemBar(C);
2521     AtomicAccess::add(&PhaseMacroExpand::_memory_barriers_removed_counter, membar_before - membar_after);
2522   }
2523 #endif
2524 }
2525 
2526 void PhaseMacroExpand::eliminate_opaque_looplimit_macro_nodes() {
2527   if (C->macro_count() == 0) {
2528     return;
2529   }
2530   refine_strip_mined_loop_macro_nodes();
2531   // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
2532   bool progress = true;
2533   while (progress) {
2534     progress = false;
2535     for (int i = C->macro_count(); i > 0; i--) {
2536       Node* n = C->macro_node(i-1);
2537       bool success = false;
2538       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2539       if (n->Opcode() == Op_LoopLimit) {
2540         // Remove it from macro list and put on IGVN worklist to optimize.
2541         C->remove_macro_node(n);
2542         _igvn._worklist.push(n);
2543         success = true;
2544       } else if (n->Opcode() == Op_CallStaticJava) {
2545         // Remove it from macro list and put on IGVN worklist to optimize.
2546         C->remove_macro_node(n);
2547         _igvn._worklist.push(n);
2548         success = true;



2549       } else if (n->is_Opaque1()) {
2550         _igvn.replace_node(n, n->in(1));
2551         success = true;
2552       } else if (n->is_OpaqueConstantBool()) {
2553         // Tests with OpaqueConstantBool nodes are implicitly known. Replace the node with true/false. In debug builds,
2554         // we leave the test in the graph to have an additional sanity check at runtime. If the test fails (i.e. a bug),
2555         // we will execute a Halt node.
2556 #ifdef ASSERT
2557         _igvn.replace_node(n, n->in(1));
2558 #else
2559         _igvn.replace_node(n, _igvn.intcon(n->as_OpaqueConstantBool()->constant()));
2560 #endif
2561         success = true;
2562       } else if (n->is_OpaqueInitializedAssertionPredicate()) {
2563           // Initialized Assertion Predicates must always evaluate to true. Therefore, we get rid of them in product
2564           // builds as they are useless. In debug builds we keep them as additional verification code. Even though
2565           // loop opts are already over, we want to keep Initialized Assertion Predicates alive as long as possible to
2566           // enable folding of dead control paths within which cast nodes become top after due to impossible types -
2567           // even after loop opts are over. Therefore, we delay the removal of these opaque nodes until now.
2568 #ifdef ASSERT

2637     // Worst case is a macro node gets expanded into about 200 nodes.
2638     // Allow 50% more for optimization.
2639     if (C->check_node_count(300, "out of nodes before macro expansion")) {
2640       return true;
2641     }
2642 
2643     DEBUG_ONLY(int old_macro_count = C->macro_count();)
2644     switch (n->class_id()) {
2645     case Node::Class_Lock:
2646       expand_lock_node(n->as_Lock());
2647       break;
2648     case Node::Class_Unlock:
2649       expand_unlock_node(n->as_Unlock());
2650       break;
2651     case Node::Class_ArrayCopy:
2652       expand_arraycopy_node(n->as_ArrayCopy());
2653       break;
2654     case Node::Class_SubTypeCheck:
2655       expand_subtypecheck_node(n->as_SubTypeCheck());
2656       break;







2657     default:
2658       switch (n->Opcode()) {
2659       case Op_ModD:
2660       case Op_ModF:
2661       case Op_PowD: {
2662         CallLeafPureNode* call_macro = n->as_CallLeafPure();
2663         CallLeafPureNode* call = call_macro->inline_call_leaf_pure_node();
2664         _igvn.replace_node(call_macro, call);
2665         transform_later(call);
2666         break;
2667       }
2668       default:
2669         assert(false, "unknown node type in macro list");
2670       }
2671     }
2672     assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2673     if (C->failing())  return true;
2674     C->print_method(PHASE_AFTER_MACRO_EXPANSION_STEP, 5, n);
2675 
2676     // Clean up the graph so we're less likely to hit the maximum node

   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 "ci/ciInlineKlass.hpp"
  27 #include "ci/ciInstanceKlass.hpp"
  28 #include "compiler/compileLog.hpp"
  29 #include "gc/shared/collectedHeap.inline.hpp"
  30 #include "gc/shared/tlab_globals.hpp"
  31 #include "libadt/vectset.hpp"
  32 #include "memory/universe.hpp"
  33 #include "opto/addnode.hpp"
  34 #include "opto/arraycopynode.hpp"
  35 #include "opto/callnode.hpp"
  36 #include "opto/castnode.hpp"
  37 #include "opto/cfgnode.hpp"
  38 #include "opto/compile.hpp"
  39 #include "opto/convertnode.hpp"
  40 #include "opto/graphKit.hpp"
  41 #include "opto/inlinetypenode.hpp"
  42 #include "opto/intrinsicnode.hpp"
  43 #include "opto/locknode.hpp"
  44 #include "opto/loopnode.hpp"
  45 #include "opto/macro.hpp"
  46 #include "opto/memnode.hpp"
  47 #include "opto/narrowptrnode.hpp"
  48 #include "opto/node.hpp"
  49 #include "opto/opaquenode.hpp"
  50 #include "opto/opcodes.hpp"
  51 #include "opto/phaseX.hpp"
  52 #include "opto/rootnode.hpp"
  53 #include "opto/runtime.hpp"
  54 #include "opto/subnode.hpp"
  55 #include "opto/subtypenode.hpp"
  56 #include "opto/type.hpp"
  57 #include "prims/jvmtiExport.hpp"
  58 #include "runtime/continuation.hpp"
  59 #include "runtime/sharedRuntime.hpp"
  60 #include "runtime/stubRoutines.hpp"
  61 #include "utilities/globalDefinitions.hpp"
  62 #include "utilities/macros.hpp"
  63 #include "utilities/powerOfTwo.hpp"
  64 #if INCLUDE_G1GC
  65 #include "gc/g1/g1ThreadLocalData.hpp"
  66 #endif // INCLUDE_G1GC
  67 
  68 
  69 //
  70 // Replace any references to "oldref" in inputs to "use" with "newref".
  71 // Returns the number of replacements made.
  72 //
  73 int PhaseMacroExpand::replace_input(Node *use, Node *oldref, Node *newref) {
  74   int nreplacements = 0;
  75   uint req = use->req();
  76   for (uint j = 0; j < use->len(); j++) {
  77     Node *uin = use->in(j);
  78     if (uin == oldref) {
  79       if (j < req)
  80         use->set_req(j, newref);
  81       else
  82         use->set_prec(j, newref);
  83       nreplacements++;
  84     } else if (j >= req && uin == nullptr) {
  85       break;
  86     }
  87   }
  88   return nreplacements;
  89 }
  90 











  91 
  92 Node* PhaseMacroExpand::opt_bits_test(Node* ctrl, Node* region, int edge, Node* word) {
  93   Node* cmp = word;
  94   Node* bol = transform_later(new BoolNode(cmp, BoolTest::ne));
  95   IfNode* iff = new IfNode( ctrl, bol, PROB_MIN, COUNT_UNKNOWN );
  96   transform_later(iff);
  97 
  98   // Fast path taken.
  99   Node *fast_taken = transform_later(new IfFalseNode(iff));
 100 
 101   // Fast path not-taken, i.e. slow path
 102   Node *slow_taken = transform_later(new IfTrueNode(iff));
 103 
 104     region->init_req(edge, fast_taken); // Capture fast-control
 105     return slow_taken;
 106 }
 107 
 108 //--------------------copy_predefined_input_for_runtime_call--------------------
 109 void PhaseMacroExpand::copy_predefined_input_for_runtime_call(Node * ctrl, CallNode* oldcall, CallNode* call) {
 110   // Set fixed predefined input arguments

 123   // Slow-path call
 124  CallNode *call = leaf_name
 125    ? (CallNode*)new CallLeafNode      ( slow_call_type, slow_call, leaf_name, TypeRawPtr::BOTTOM )
 126    : (CallNode*)new CallStaticJavaNode( slow_call_type, slow_call, OptoRuntime::stub_name(slow_call), TypeRawPtr::BOTTOM );
 127 
 128   // Slow path call has no side-effects, uses few values
 129   copy_predefined_input_for_runtime_call(slow_path, oldcall, call );
 130   if (parm0 != nullptr)  call->init_req(TypeFunc::Parms+0, parm0);
 131   if (parm1 != nullptr)  call->init_req(TypeFunc::Parms+1, parm1);
 132   if (parm2 != nullptr)  call->init_req(TypeFunc::Parms+2, parm2);
 133   call->copy_call_debug_info(&_igvn, oldcall);
 134   call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
 135   _igvn.replace_node(oldcall, call);
 136   transform_later(call);
 137 
 138   return call;
 139 }
 140 
 141 void PhaseMacroExpand::eliminate_gc_barrier(Node* p2x) {
 142   BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
 143   bs->eliminate_gc_barrier(&_igvn, p2x);
 144 #ifndef PRODUCT
 145   if (PrintOptoStatistics) {
 146     AtomicAccess::inc(&PhaseMacroExpand::_GC_barriers_removed_counter);
 147   }
 148 #endif
 149 }
 150 
 151 // Search for a memory operation for the specified memory slice.
 152 static Node *scan_mem_chain(Node *mem, int alias_idx, int offset, Node *start_mem, Node *alloc, PhaseGVN *phase) {
 153   Node *orig_mem = mem;
 154   Node *alloc_mem = alloc->as_Allocate()->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false);
 155   assert(alloc_mem != nullptr, "Allocation without a memory projection.");
 156   const TypeOopPtr *tinst = phase->C->get_adr_type(alias_idx)->isa_oopptr();
 157   while (true) {
 158     if (mem == alloc_mem || mem == start_mem ) {
 159       return mem;  // hit one of our sentinels
 160     } else if (mem->is_MergeMem()) {
 161       mem = mem->as_MergeMem()->memory_at(alias_idx);
 162     } else if (mem->is_Proj() && mem->as_Proj()->_con == TypeFunc::Memory) {
 163       Node *in = mem->in(0);

 166       if (in->is_Initialize() && in->as_Initialize()->allocation() == alloc) {
 167         return in;
 168       } else if (in->is_Call()) {
 169         CallNode *call = in->as_Call();
 170         if (call->may_modify(tinst, phase)) {
 171           assert(call->is_ArrayCopy(), "ArrayCopy is the only call node that doesn't make allocation escape");
 172           if (call->as_ArrayCopy()->modifies(offset, offset, phase, false)) {
 173             return in;
 174           }
 175         }
 176         mem = in->in(TypeFunc::Memory);
 177       } else if (in->is_MemBar()) {
 178         ArrayCopyNode* ac = nullptr;
 179         if (ArrayCopyNode::may_modify(tinst, in->as_MemBar(), phase, ac)) {
 180           if (ac != nullptr) {
 181             assert(ac->is_clonebasic(), "Only basic clone is a non escaping clone");
 182             return ac;
 183           }
 184         }
 185         mem = in->in(TypeFunc::Memory);
 186       } else if (in->is_LoadFlat() || in->is_StoreFlat()) {
 187         mem = in->in(TypeFunc::Memory);
 188       } else {
 189 #ifdef ASSERT
 190         in->dump();
 191         mem->dump();
 192         assert(false, "unexpected projection");
 193 #endif
 194       }
 195     } else if (mem->is_Store()) {
 196       const TypePtr* atype = mem->as_Store()->adr_type();
 197       int adr_idx = phase->C->get_alias_index(atype);
 198       if (adr_idx == alias_idx) {
 199         assert(atype->isa_oopptr(), "address type must be oopptr");
 200         int adr_offset = atype->flat_offset();
 201         uint adr_iid = atype->is_oopptr()->instance_id();
 202         // Array elements references have the same alias_idx
 203         // but different offset and different instance_id.
 204         if (adr_offset == offset && adr_iid == alloc->_idx) {
 205           return mem;
 206         }
 207       } else {
 208         assert(adr_idx == Compile::AliasIdxRaw, "address must match or be raw");
 209       }
 210       mem = mem->in(MemNode::Memory);
 211     } else if (mem->is_ClearArray()) {
 212       if (!ClearArrayNode::step_through(&mem, alloc->_idx, phase)) {
 213         // Can not bypass initialization of the instance
 214         // we are looking.
 215         DEBUG_ONLY(intptr_t offset;)
 216         assert(alloc == AllocateNode::Ideal_allocation(mem->in(3), phase, offset), "sanity");
 217         InitializeNode* init = alloc->as_Allocate()->initialization();
 218         // We are looking for stored value, return Initialize node
 219         // or memory edge from Allocate node.
 220         if (init != nullptr) {

 225       }
 226       // Otherwise skip it (the call updated 'mem' value).
 227     } else if (mem->Opcode() == Op_SCMemProj) {
 228       mem = mem->in(0);
 229       Node* adr = nullptr;
 230       if (mem->is_LoadStore()) {
 231         adr = mem->in(MemNode::Address);
 232       } else {
 233         assert(mem->Opcode() == Op_EncodeISOArray ||
 234                mem->Opcode() == Op_StrCompressedCopy, "sanity");
 235         adr = mem->in(3); // Destination array
 236       }
 237       const TypePtr* atype = adr->bottom_type()->is_ptr();
 238       int adr_idx = phase->C->get_alias_index(atype);
 239       if (adr_idx == alias_idx) {
 240         DEBUG_ONLY(mem->dump();)
 241         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
 242         return nullptr;
 243       }
 244       mem = mem->in(MemNode::Memory);
 245     } else if (mem->Opcode() == Op_StrInflatedCopy) {
 246       Node* adr = mem->in(3); // Destination array
 247       const TypePtr* atype = adr->bottom_type()->is_ptr();
 248       int adr_idx = phase->C->get_alias_index(atype);
 249       if (adr_idx == alias_idx) {
 250         DEBUG_ONLY(mem->dump();)
 251         assert(false, "Object is not scalar replaceable if a StrInflatedCopy node accesses its field");
 252         return nullptr;
 253       }
 254       mem = mem->in(MemNode::Memory);
 255     } else {
 256       return mem;
 257     }
 258     assert(mem != orig_mem, "dead memory loop");
 259   }
 260 }
 261 
 262 // Generate loads from source of the arraycopy for fields of
 263 // destination needed at a deoptimization point
 264 Node* PhaseMacroExpand::make_arraycopy_load(ArrayCopyNode* ac, intptr_t offset, Node* ctl, Node* mem, BasicType ft, const Type *ftype, AllocateNode *alloc) {
 265   BasicType bt = ft;

 270   }
 271   Node* res = nullptr;
 272   if (ac->is_clonebasic()) {
 273     assert(ac->in(ArrayCopyNode::Src) != ac->in(ArrayCopyNode::Dest), "clone source equals destination");
 274     Node* base = ac->in(ArrayCopyNode::Src);
 275     Node* adr = _igvn.transform(AddPNode::make_with_base(base, _igvn.MakeConX(offset)));
 276     const TypePtr* adr_type = _igvn.type(base)->is_ptr()->add_offset(offset);
 277     MergeMemNode* mergemen = _igvn.transform(MergeMemNode::make(mem))->as_MergeMem();
 278     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 279     res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
 280   } else {
 281     if (ac->modifies(offset, offset, &_igvn, true)) {
 282       assert(ac->in(ArrayCopyNode::Dest) == alloc->result_cast(), "arraycopy destination should be allocation's result");
 283       uint shift = exact_log2(type2aelembytes(bt));
 284       Node* src_pos = ac->in(ArrayCopyNode::SrcPos);
 285       Node* dest_pos = ac->in(ArrayCopyNode::DestPos);
 286       const TypeInt* src_pos_t = _igvn.type(src_pos)->is_int();
 287       const TypeInt* dest_pos_t = _igvn.type(dest_pos)->is_int();
 288 
 289       Node* adr = nullptr;
 290       Node* base = ac->in(ArrayCopyNode::Src);
 291       const TypeAryPtr* adr_type = _igvn.type(base)->is_aryptr();
 292       if (adr_type->is_flat()) {
 293         shift = adr_type->flat_log_elem_size();
 294       }
 295       if (src_pos_t->is_con() && dest_pos_t->is_con()) {
 296         intptr_t off = ((src_pos_t->get_con() - dest_pos_t->get_con()) << shift) + offset;
 297         adr = _igvn.transform(AddPNode::make_with_base(base, base, _igvn.MakeConX(off)));
 298         adr_type = _igvn.type(adr)->is_aryptr();
 299         assert(adr_type == _igvn.type(base)->is_aryptr()->add_field_offset_and_offset(off), "incorrect address type");
 300         if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 301           // Don't emit a new load from src if src == dst but try to get the value from memory instead
 302           return value_from_mem(ac->in(TypeFunc::Memory), ctl, ft, ftype, adr_type, alloc);
 303         }
 304       } else {
 305         if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 306           // Non constant offset in the array: we can't statically
 307           // determine the value
 308           return nullptr;
 309         }
 310         Node* diff = _igvn.transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
 311 #ifdef _LP64
 312         diff = _igvn.transform(new ConvI2LNode(diff));
 313 #endif
 314         diff = _igvn.transform(new LShiftXNode(diff, _igvn.intcon(shift)));
 315 
 316         Node* off = _igvn.transform(new AddXNode(_igvn.MakeConX(offset), diff));
 317         adr = _igvn.transform(AddPNode::make_with_base(base, base, off));
 318         // In the case of a flat inline type array, each field has its
 319         // own slice so we need to extract the field being accessed from
 320         // the address computation
 321         adr_type = adr_type->add_field_offset_and_offset(offset)->add_offset(Type::OffsetBot)->is_aryptr();
 322         adr = _igvn.transform(new CastPPNode(ctl, adr, adr_type));


 323       }
 324       MergeMemNode* mergemen = _igvn.transform(MergeMemNode::make(mem))->as_MergeMem();
 325       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 326       res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
 327     }
 328   }
 329   if (res != nullptr) {
 330     if (ftype->isa_narrowoop()) {
 331       // PhaseMacroExpand::scalar_replacement adds DecodeN nodes
 332       assert(res->isa_DecodeN(), "should be narrow oop");
 333       res = _igvn.transform(new EncodePNode(res, ftype));
 334     }
 335     return res;
 336   }
 337   return nullptr;
 338 }
 339 
 340 //
 341 // Given a Memory Phi, compute a value Phi containing the values from stores
 342 // on the input paths.
 343 // Note: this function is recursive, its depth is limited by the "level" argument
 344 // Returns the computed Phi, or null if it cannot compute it.
 345 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) {
 346   assert(mem->is_Phi(), "sanity");
 347   int alias_idx = C->get_alias_index(adr_t);
 348   int offset = adr_t->flat_offset();
 349   int instance_id = adr_t->instance_id();
 350 
 351   // Check if an appropriate value phi already exists.
 352   Node* region = mem->in(0);
 353   for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) {
 354     Node* phi = region->fast_out(k);
 355     if (phi->is_Phi() && phi != mem &&
 356         phi->as_Phi()->is_same_inst_field(phi_type, (int)mem->_idx, instance_id, alias_idx, offset)) {
 357       return phi;
 358     }
 359   }
 360   // Check if an appropriate new value phi already exists.
 361   Node* new_phi = value_phis->find(mem->_idx);
 362   if (new_phi != nullptr)
 363     return new_phi;
 364 
 365   if (level <= 0) {
 366     return nullptr; // Give up: phi tree too deep
 367   }
 368   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
 369   Node *alloc_mem = alloc->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false);
 370   assert(alloc_mem != nullptr, "Allocation without a memory projection.");
 371 
 372   uint length = mem->req();
 373   GrowableArray <Node *> values(length, length, nullptr);
 374 
 375   // create a new Phi for the value
 376   PhiNode *phi = new PhiNode(mem->in(0), phi_type, nullptr, mem->_idx, instance_id, alias_idx, offset);
 377   transform_later(phi);
 378   value_phis->push(phi, mem->_idx);
 379 
 380   for (uint j = 1; j < length; j++) {
 381     Node *in = mem->in(j);
 382     if (in == nullptr || in->is_top()) {
 383       values.at_put(j, in);
 384     } else {
 385       Node *val = scan_mem_chain(in, alias_idx, offset, start_mem, alloc, &_igvn);
 386       if (val == start_mem || val == alloc_mem) {
 387         // hit a sentinel, return appropriate value
 388         Node* init_value = value_from_alloc(ft, adr_t, alloc);
 389         if (init_value == nullptr) {
 390           return nullptr;
 391         } else {
 392           values.at_put(j, init_value);
 393           continue;
 394         }
 395       }
 396       if (val->is_Initialize()) {
 397         val = val->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 398       }
 399       if (val == nullptr) {
 400         return nullptr;  // can't find a value on this path
 401       }
 402       if (val == mem) {
 403         values.at_put(j, mem);
 404       } else if (val->is_Store()) {
 405         Node* n = val->in(MemNode::ValueIn);
 406         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 407         n = bs->step_over_gc_barrier(n);
 408         if (is_subword_type(ft)) {
 409           n = Compile::narrow_value(ft, n, phi_type, &_igvn, true);
 410         }
 411         values.at_put(j, n);
 412       } else if (val->is_Proj() && val->in(0) == alloc) {
 413         Node* init_value = value_from_alloc(ft, adr_t, alloc);
 414         if (init_value == nullptr) {
 415           return nullptr;
 416         } else {
 417           values.at_put(j, init_value);
 418         }
 419       } else if (val->is_Phi()) {
 420         val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, value_phis, level-1);
 421         if (val == nullptr) {
 422           return nullptr;
 423         }
 424         values.at_put(j, val);
 425       } else if (val->Opcode() == Op_SCMemProj) {
 426         assert(val->in(0)->is_LoadStore() ||
 427                val->in(0)->Opcode() == Op_EncodeISOArray ||
 428                val->in(0)->Opcode() == Op_StrCompressedCopy, "sanity");
 429         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
 430         return nullptr;
 431       } else if (val->is_ArrayCopy()) {
 432         Node* res = make_arraycopy_load(val->as_ArrayCopy(), offset, val->in(0), val->in(TypeFunc::Memory), ft, phi_type, alloc);
 433         if (res == nullptr) {
 434           return nullptr;
 435         }
 436         values.at_put(j, res);
 437       } else if (val->is_top()) {
 438         // This indicates that this path into the phi is dead. Top will eventually also propagate into the Region.
 439         // IGVN will clean this up later.
 440         values.at_put(j, val);
 441       } else {
 442         DEBUG_ONLY( val->dump(); )
 443         assert(false, "unknown node on this path");
 444         return nullptr;  // unknown node on this path
 445       }
 446     }
 447   }
 448   // Set Phi's inputs
 449   for (uint j = 1; j < length; j++) {
 450     if (values.at(j) == mem) {
 451       phi->init_req(j, phi);
 452     } else {
 453       phi->init_req(j, values.at(j));
 454     }
 455   }
 456   return phi;
 457 }
 458 
 459 // Extract the initial value of a field in an allocation
 460 Node* PhaseMacroExpand::value_from_alloc(BasicType ft, const TypeOopPtr* adr_t, AllocateNode* alloc) {
 461   Node* init_value = alloc->in(AllocateNode::InitValue);
 462   if (init_value == nullptr) {
 463     assert(alloc->in(AllocateNode::RawInitValue) == nullptr, "conflicting InitValue and RawInitValue");
 464     return _igvn.zerocon(ft);
 465   }
 466 
 467   const TypeAryPtr* ary_t = adr_t->isa_aryptr();
 468   assert(ary_t != nullptr, "must be a pointer into an array");
 469 
 470   // If this is not a flat array, then it must be an oop array with elements being init_value
 471   if (ary_t->is_not_flat()) {
 472 #ifdef ASSERT
 473     BasicType init_bt = init_value->bottom_type()->basic_type();
 474     assert(ft == init_bt ||
 475            (!is_java_primitive(ft) && !is_java_primitive(init_bt) && type2aelembytes(ft, true) == type2aelembytes(init_bt, true)) ||
 476            (is_subword_type(ft) && init_bt == T_INT),
 477            "invalid init_value of type %s for field of type %s", type2name(init_bt), type2name(ft));
 478 #endif // ASSERT
 479     return init_value;
 480   }
 481 
 482   assert(ary_t->klass_is_exact() && ary_t->is_flat(), "must be an exact flat array");
 483   assert(ary_t->field_offset().get() != Type::OffsetBot, "unknown offset");
 484   if (init_value->is_EncodeP()) {
 485     init_value = init_value->in(1);
 486   }
 487   // Cannot look through init_value if it is an oop
 488   if (!init_value->is_InlineType()) {
 489     return nullptr;
 490   }
 491 
 492   ciInlineKlass* vk = init_value->bottom_type()->inline_klass();
 493   if (ary_t->field_offset().get() == vk->null_marker_offset_in_payload()) {
 494     init_value = init_value->as_InlineType()->get_null_marker();
 495   } else {
 496     init_value = init_value->as_InlineType()->field_value_by_offset(ary_t->field_offset().get() + vk->payload_offset(), true);
 497   }
 498 
 499   if (ft == T_NARROWOOP) {
 500     assert(init_value->bottom_type()->isa_ptr(), "must be a pointer");
 501     init_value = transform_later(new EncodePNode(init_value, init_value->bottom_type()->make_narrowoop()));
 502   }
 503 
 504 #ifdef ASSERT
 505   BasicType init_bt = init_value->bottom_type()->basic_type();
 506   assert(ft == init_bt ||
 507          (!is_java_primitive(ft) && !is_java_primitive(init_bt) && type2aelembytes(ft, true) == type2aelembytes(init_bt, true)) ||
 508          (is_subword_type(ft) && init_bt == T_INT),
 509          "invalid init_value of type %s for field of type %s", type2name(init_bt), type2name(ft));
 510 #endif // ASSERT
 511 
 512   return init_value;
 513 }
 514 
 515 // Search the last value stored into the object's field.
 516 Node *PhaseMacroExpand::value_from_mem(Node *sfpt_mem, Node *sfpt_ctl, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, AllocateNode *alloc) {
 517   assert(adr_t->is_known_instance_field(), "instance required");
 518   int instance_id = adr_t->instance_id();
 519   assert((uint)instance_id == alloc->_idx, "wrong allocation");
 520 
 521   int alias_idx = C->get_alias_index(adr_t);
 522   int offset = adr_t->flat_offset();
 523   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);

 524   Node *alloc_mem = alloc->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false);
 525   assert(alloc_mem != nullptr, "Allocation without a memory projection.");
 526   VectorSet visited;
 527 
 528   bool done = sfpt_mem == alloc_mem;
 529   Node *mem = sfpt_mem;
 530   while (!done) {
 531     if (visited.test_set(mem->_idx)) {
 532       return nullptr;  // found a loop, give up
 533     }
 534     mem = scan_mem_chain(mem, alias_idx, offset, start_mem, alloc, &_igvn);
 535     if (mem == start_mem || mem == alloc_mem) {
 536       done = true;  // hit a sentinel, return appropriate 0 value
 537     } else if (mem->is_Initialize()) {
 538       mem = mem->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 539       if (mem == nullptr) {
 540         done = true; // Something went wrong.
 541       } else if (mem->is_Store()) {
 542         const TypePtr* atype = mem->as_Store()->adr_type();
 543         assert(C->get_alias_index(atype) == Compile::AliasIdxRaw, "store is correct memory slice");
 544         done = true;
 545       }
 546     } else if (mem->is_Store()) {
 547       const TypeOopPtr* atype = mem->as_Store()->adr_type()->isa_oopptr();
 548       assert(atype != nullptr, "address type must be oopptr");
 549       assert(C->get_alias_index(atype) == alias_idx &&
 550              atype->is_known_instance_field() && atype->flat_offset() == offset &&
 551              atype->instance_id() == instance_id, "store is correct memory slice");
 552       done = true;
 553     } else if (mem->is_Phi()) {
 554       // try to find a phi's unique input
 555       Node *unique_input = nullptr;
 556       Node *top = C->top();
 557       for (uint i = 1; i < mem->req(); i++) {
 558         Node *n = scan_mem_chain(mem->in(i), alias_idx, offset, start_mem, alloc, &_igvn);
 559         if (n == nullptr || n == top || n == mem) {
 560           continue;
 561         } else if (unique_input == nullptr) {
 562           unique_input = n;
 563         } else if (unique_input != n) {
 564           unique_input = top;
 565           break;
 566         }
 567       }
 568       if (unique_input != nullptr && unique_input != top) {
 569         mem = unique_input;
 570       } else {
 571         done = true;
 572       }
 573     } else if (mem->is_ArrayCopy()) {
 574       done = true;
 575     } else if (mem->is_top()) {
 576       // The slice is on a dead path. Returning nullptr would lead to elimination
 577       // bailout, but we want to prevent that. Just forwarding the top is also legal,
 578       // and IGVN can just clean things up, and remove whatever receives top.
 579       return mem;
 580     } else {
 581       DEBUG_ONLY( mem->dump(); )
 582       assert(false, "unexpected node");
 583     }
 584   }
 585   if (mem != nullptr) {
 586     if (mem == start_mem || mem == alloc_mem) {
 587       // hit a sentinel, return appropriate value
 588       return value_from_alloc(ft, adr_t, alloc);
 589     } else if (mem->is_Store()) {
 590       Node* n = mem->in(MemNode::ValueIn);
 591       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 592       n = bs->step_over_gc_barrier(n);
 593       return n;
 594     } else if (mem->is_Phi()) {
 595       // attempt to produce a Phi reflecting the values on the input paths of the Phi
 596       Node_Stack value_phis(8);
 597       Node* phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, &value_phis, ValueSearchLimit);
 598       if (phi != nullptr) {
 599         return phi;
 600       } else {
 601         // Kill all new Phis
 602         while(value_phis.is_nonempty()) {
 603           Node* n = value_phis.node();
 604           _igvn.replace_node(n, C->top());
 605           value_phis.pop();
 606         }
 607       }
 608     } else if (mem->is_ArrayCopy()) {
 609       Node* ctl = mem->in(0);
 610       Node* m = mem->in(TypeFunc::Memory);
 611       if (sfpt_ctl->is_Proj() && sfpt_ctl->as_Proj()->is_uncommon_trap_proj()) {
 612         // pin the loads in the uncommon trap path
 613         ctl = sfpt_ctl;
 614         m = sfpt_mem;
 615       }
 616       return make_arraycopy_load(mem->as_ArrayCopy(), offset, ctl, m, ft, ftype, alloc);
 617     }
 618   }
 619   // Something went wrong.
 620   return nullptr;
 621 }
 622 
 623 // Search the last value stored into the inline type's fields (for flat arrays).
 624 Node* PhaseMacroExpand::inline_type_from_mem(ciInlineKlass* vk, const TypeAryPtr* elem_adr_type, int elem_idx, int offset_in_element, bool null_free, AllocateNode* alloc, SafePointNode* sfpt) {
 625   auto report_failure = [&](int field_offset_in_element) {
 626 #ifndef PRODUCT
 627     if (PrintEliminateAllocations) {
 628       ciInlineKlass* elem_klass = elem_adr_type->elem()->inline_klass();
 629       int offset = field_offset_in_element + elem_klass->payload_offset();
 630       ciField* flattened_field = elem_klass->get_field_by_offset(offset, false);
 631       assert(flattened_field != nullptr, "must have a field of type %s at offset %d", elem_klass->name()->as_utf8(), offset);
 632       tty->print("=== At SafePoint node %d can't find value of field [%s] of array element [%d]", sfpt->_idx, flattened_field->name()->as_utf8(), elem_idx);
 633       tty->print(", which prevents elimination of: ");
 634       alloc->dump();
 635     }
 636 #endif // PRODUCT
 637   };
 638 
 639   // Create a new InlineTypeNode and retrieve the field values from memory
 640   InlineTypeNode* vt = InlineTypeNode::make_uninitialized(_igvn, vk, false);
 641   transform_later(vt);
 642   if (null_free) {
 643     vt->set_null_marker(_igvn);
 644   } else {
 645     int nm_offset_in_element = offset_in_element + vk->null_marker_offset_in_payload();
 646     const TypeAryPtr* nm_adr_type = elem_adr_type->with_field_offset(nm_offset_in_element);
 647     Node* nm_value = value_from_mem(sfpt->memory(), sfpt->control(), T_BOOLEAN, TypeInt::BOOL, nm_adr_type, alloc);
 648     if (nm_value != nullptr) {
 649       vt->set_null_marker(_igvn, nm_value);
 650     } else {
 651       report_failure(nm_offset_in_element);
 652       return nullptr;
 653     }
 654   }
 655 
 656   for (int i = 0; i < vk->nof_declared_nonstatic_fields(); ++i) {
 657     ciField* field = vt->field(i);
 658     ciType* field_type = field->type();
 659     int field_offset_in_element = offset_in_element + field->offset_in_bytes() - vk->payload_offset();
 660     Node* field_value = nullptr;
 661     assert(!field->is_flat() || field->type()->is_inlinetype(), "must be an inline type");
 662     if (field->is_flat()) {
 663       field_value = inline_type_from_mem(field_type->as_inline_klass(), elem_adr_type, elem_idx, field_offset_in_element, field->is_null_free(), alloc, sfpt);
 664     } else {
 665       const Type* ft = Type::get_const_type(field_type);
 666       BasicType bt = type2field[field_type->basic_type()];
 667       if (UseCompressedOops && !is_java_primitive(bt)) {
 668         ft = ft->make_narrowoop();
 669         bt = T_NARROWOOP;
 670       }
 671       // Each inline type field has its own memory slice
 672       const TypeAryPtr* field_adr_type = elem_adr_type->with_field_offset(field_offset_in_element);
 673       field_value = value_from_mem(sfpt->memory(), sfpt->control(), bt, ft, field_adr_type, alloc);
 674       if (field_value == nullptr) {
 675         report_failure(field_offset_in_element);
 676       } else if (ft->isa_narrowoop()) {
 677         assert(UseCompressedOops, "unexpected narrow oop");
 678         if (field_value->is_EncodeP()) {
 679           field_value = field_value->in(1);
 680         } else if (!field_value->is_InlineType()) {
 681           field_value = transform_later(new DecodeNNode(field_value, field_value->get_ptr_type()));
 682         }
 683       }
 684     }
 685     if (field_value != nullptr) {
 686       vt->set_field_value(i, field_value);
 687     } else {
 688       return nullptr;
 689     }
 690   }
 691   return vt;
 692 }
 693 
 694 // Check the possibility of scalar replacement.
 695 bool PhaseMacroExpand::can_eliminate_allocation(PhaseIterGVN* igvn, AllocateNode *alloc, GrowableArray <SafePointNode *>* safepoints) {
 696   //  Scan the uses of the allocation to check for anything that would
 697   //  prevent us from eliminating it.
 698   NOT_PRODUCT( const char* fail_eliminate = nullptr; )
 699   DEBUG_ONLY( Node* disq_node = nullptr; )
 700   bool can_eliminate = true;
 701   bool reduce_merge_precheck = (safepoints == nullptr);
 702 
 703   Unique_Node_List worklist;
 704   Node* res = alloc->result_cast();
 705   const TypeOopPtr* res_type = nullptr;
 706   if (res == nullptr) {
 707     // All users were eliminated.
 708   } else if (!res->is_CheckCastPP()) {
 709     NOT_PRODUCT(fail_eliminate = "Allocation does not have unique CheckCastPP";)
 710     can_eliminate = false;
 711   } else {
 712     worklist.push(res);
 713     res_type = igvn->type(res)->isa_oopptr();
 714     if (res_type == nullptr) {
 715       NOT_PRODUCT(fail_eliminate = "Neither instance or array allocation";)
 716       can_eliminate = false;
 717     } else if (!res_type->klass_is_exact()) {
 718       NOT_PRODUCT(fail_eliminate = "Not an exact type.";)
 719       can_eliminate = false;
 720     } else if (res_type->isa_aryptr()) {
 721       int length = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 722       if (length < 0) {
 723         NOT_PRODUCT(fail_eliminate = "Array's size is not constant";)
 724         can_eliminate = false;
 725       }
 726     }
 727   }
 728 
 729   while (can_eliminate && worklist.size() > 0) {
 730     BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
 731     res = worklist.pop();
 732     for (DUIterator_Fast jmax, j = res->fast_outs(jmax); j < jmax && can_eliminate; j++) {
 733       Node* use = res->fast_out(j);
 734 
 735       if (use->is_AddP()) {
 736         const TypePtr* addp_type = igvn->type(use)->is_ptr();
 737         int offset = addp_type->offset();
 738 
 739         if (offset == Type::OffsetTop || offset == Type::OffsetBot) {
 740           NOT_PRODUCT(fail_eliminate = "Undefined field reference";)
 741           can_eliminate = false;
 742           break;
 743         }
 744         for (DUIterator_Fast kmax, k = use->fast_outs(kmax);
 745                                    k < kmax && can_eliminate; k++) {
 746           Node* n = use->fast_out(k);
 747           if ((n->is_Mem() && n->as_Mem()->is_mismatched_access()) || n->is_LoadFlat() || n->is_StoreFlat()) {
 748             DEBUG_ONLY(disq_node = n);
 749             NOT_PRODUCT(fail_eliminate = "Mismatched access");
 750             can_eliminate = false;
 751           }
 752           if (!n->is_Store() && n->Opcode() != Op_CastP2X && !bs->is_gc_pre_barrier_node(n) && !reduce_merge_precheck) {
 753             DEBUG_ONLY(disq_node = n;)
 754             if (n->is_Load() || n->is_LoadStore()) {
 755               NOT_PRODUCT(fail_eliminate = "Field load";)
 756             } else {
 757               NOT_PRODUCT(fail_eliminate = "Not store field reference";)
 758             }
 759             can_eliminate = false;
 760           }
 761         }
 762       } else if (use->is_ArrayCopy() &&
 763                  (use->as_ArrayCopy()->is_clonebasic() ||
 764                   use->as_ArrayCopy()->is_arraycopy_validated() ||
 765                   use->as_ArrayCopy()->is_copyof_validated() ||
 766                   use->as_ArrayCopy()->is_copyofrange_validated()) &&
 767                  use->in(ArrayCopyNode::Dest) == res) {
 768         // ok to eliminate
 769       } else if (use->is_SafePoint()) {
 770         SafePointNode* sfpt = use->as_SafePoint();
 771         if (sfpt->is_Call() && sfpt->as_Call()->has_non_debug_use(res)) {
 772           // Object is passed as argument.
 773           DEBUG_ONLY(disq_node = use;)
 774           NOT_PRODUCT(fail_eliminate = "Object is passed as argument";)
 775           can_eliminate = false;
 776         }
 777         Node* sfptMem = sfpt->memory();
 778         if (sfptMem == nullptr || sfptMem->is_top()) {
 779           DEBUG_ONLY(disq_node = use;)
 780           NOT_PRODUCT(fail_eliminate = "null or TOP memory";)
 781           can_eliminate = false;
 782         } else if (!reduce_merge_precheck) {
 783           assert(!res->is_Phi() || !res->as_Phi()->can_be_inline_type(), "Inline type allocations should not have safepoint uses");
 784           safepoints->append_if_missing(sfpt);
 785         }
 786       } else if (use->is_InlineType() && use->as_InlineType()->get_oop() == res) {
 787         // Look at uses
 788         for (DUIterator_Fast kmax, k = use->fast_outs(kmax); k < kmax; k++) {
 789           Node* u = use->fast_out(k);
 790           if (u->is_InlineType()) {
 791             // Use in flat field can be eliminated
 792             InlineTypeNode* vt = u->as_InlineType();
 793             for (uint i = 0; i < vt->field_count(); ++i) {
 794               if (vt->field_value(i) == use && !vt->field(i)->is_flat()) {
 795                 can_eliminate = false; // Use in non-flat field
 796                 break;
 797               }
 798             }
 799           } else {
 800             // Add other uses to the worklist to process individually
 801             worklist.push(use);
 802           }
 803         }
 804       } else if (use->Opcode() == Op_StoreX && use->in(MemNode::Address) == res) {
 805         // Store to mark word of inline type larval buffer
 806         assert(res_type->is_inlinetypeptr(), "Unexpected store to mark word");
 807       } else if (res_type->is_inlinetypeptr() && (use->Opcode() == Op_MemBarRelease || use->Opcode() == Op_MemBarStoreStore)) {
 808         // Inline type buffer allocations are followed by a membar
 809       } else if (reduce_merge_precheck &&
 810                  (use->is_Phi() || use->is_EncodeP() ||
 811                   use->Opcode() == Op_MemBarRelease ||
 812                   (UseStoreStoreForCtor && use->Opcode() == Op_MemBarStoreStore))) {
 813         // Nothing to do
 814       } else if (use->Opcode() != Op_CastP2X) { // CastP2X is used by card mark
 815         if (use->is_Phi()) {
 816           if (use->outcnt() == 1 && use->unique_out()->Opcode() == Op_Return) {
 817             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 818           } else {
 819             NOT_PRODUCT(fail_eliminate = "Object is referenced by Phi";)
 820           }
 821           DEBUG_ONLY(disq_node = use;)
 822         } else {
 823           if (use->Opcode() == Op_Return) {
 824             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 825           } else {
 826             NOT_PRODUCT(fail_eliminate = "Object is referenced by node";)
 827           }
 828           DEBUG_ONLY(disq_node = use;)
 829         }
 830         can_eliminate = false;
 831       } else {
 832         assert(use->Opcode() == Op_CastP2X, "should be");
 833         assert(!use->has_out_with(Op_OrL), "should have been removed because oop is never null");
 834       }
 835     }
 836   }
 837 
 838 #ifndef PRODUCT
 839   if (PrintEliminateAllocations && safepoints != nullptr) {
 840     if (can_eliminate) {
 841       tty->print("Scalar ");
 842       if (res == nullptr)
 843         alloc->dump();
 844       else
 845         res->dump();
 846     } else {
 847       tty->print("NotScalar (%s)", fail_eliminate);
 848       if (res == nullptr)
 849         alloc->dump();
 850       else
 851         res->dump();
 852 #ifdef ASSERT
 853       if (disq_node != nullptr) {
 854           tty->print("  >>>> ");
 855           disq_node->dump();
 856       }
 857 #endif /*ASSERT*/
 858     }
 859   }
 860 
 861   if (TraceReduceAllocationMerges && !can_eliminate && reduce_merge_precheck) {
 862     tty->print_cr("\tCan't eliminate allocation because '%s': ", fail_eliminate != nullptr ? fail_eliminate : "");
 863     DEBUG_ONLY(if (disq_node != nullptr) disq_node->dump();)
 864   }
 865 #endif
 866   return can_eliminate;

 931     // CheckCastPP result was not updated in the stack slot, and so
 932     // we ended up using the CastPP. That means that the field knows
 933     // that it should get an oop from an interface, but the value lost
 934     // that information, and so it is not a subtype.
 935     // There may be other issues, feel free to investigate further!
 936     if (!is_java_primitive(value_bt)) { return; }
 937 
 938     tty->print_cr("value not compatible for field: %s vs %s",
 939                   type2name(value_bt),
 940                   type2name(field_bt));
 941     tty->print("value_type: ");
 942     value_type->dump();
 943     tty->cr();
 944     tty->print("field_type: ");
 945     field_type->dump();
 946     tty->cr();
 947     assert(false, "value_type does not fit field_type");
 948   }
 949 #endif
 950 
 951 void PhaseMacroExpand::process_field_value_at_safepoint(const Type* field_type, Node* field_val, SafePointNode* sfpt, Unique_Node_List* value_worklist) {
 952   if (UseCompressedOops && field_type->isa_narrowoop()) {
 953     // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation
 954     // to be able scalar replace the allocation.
 955     if (field_val->is_EncodeP()) {
 956       field_val = field_val->in(1);
 957     } else if (!field_val->is_InlineType()) {
 958       field_val = transform_later(new DecodeNNode(field_val, field_val->get_ptr_type()));
 959     }
 960   }
 961 
 962   // Keep track of inline types to scalarize them later
 963   if (field_val->is_InlineType()) {
 964     value_worklist->push(field_val);
 965   } else if (field_val->is_Phi()) {
 966     PhiNode* phi = field_val->as_Phi();
 967     // Eagerly replace inline type phis now since we could be removing an inline type allocation where we must
 968     // scalarize all its fields in safepoints.
 969     field_val = phi->try_push_inline_types_down(&_igvn, true);
 970     if (field_val->is_InlineType()) {
 971       value_worklist->push(field_val);
 972     }
 973   }
 974   DEBUG_ONLY(verify_type_compatability(field_val->bottom_type(), field_type);)
 975   sfpt->add_req(field_val);
 976 }
 977 
 978 bool PhaseMacroExpand::add_array_elems_to_safepoint(AllocateNode* alloc, const TypeAryPtr* array_type, SafePointNode* sfpt, Unique_Node_List* value_worklist) {
 979   const Type* elem_type = array_type->elem();
 980   BasicType basic_elem_type = elem_type->array_element_basic_type();
 981 
 982   intptr_t elem_size;
 983   uint header_size;
 984   if (array_type->is_flat()) {
 985     elem_size = array_type->flat_elem_size();
 986     header_size = arrayOopDesc::base_offset_in_bytes(T_FLAT_ELEMENT);
 987   } else {
 988     elem_size = type2aelembytes(basic_elem_type);
 989     header_size = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
 990   }
 991 
 992   int n_elems = alloc->in(AllocateNode::ALength)->get_int();
 993   for (int elem_idx = 0; elem_idx < n_elems; elem_idx++) {
 994     intptr_t elem_offset = header_size + elem_idx * elem_size;
 995     const TypeAryPtr* elem_adr_type = array_type->with_offset(elem_offset);
 996     Node* elem_val;
 997     if (array_type->is_flat()) {
 998       ciInlineKlass* elem_klass = elem_type->inline_klass();
 999       assert(elem_klass->maybe_flat_in_array(), "must be flat in array");
1000       elem_val = inline_type_from_mem(elem_klass, elem_adr_type, elem_idx, 0, array_type->is_null_free(), alloc, sfpt);
1001     } else {
1002       elem_val = value_from_mem(sfpt->memory(), sfpt->control(), basic_elem_type, elem_type, elem_adr_type, alloc);
1003 #ifndef PRODUCT
1004       if (PrintEliminateAllocations && elem_val == nullptr) {
1005         tty->print("=== At SafePoint node %d can't find value of array element [%d]", sfpt->_idx, elem_idx);
1006         tty->print(", which prevents elimination of: ");
1007         alloc->dump();
1008       }
1009 #endif // PRODUCT
1010     }
1011     if (elem_val == nullptr) {
1012       return false;
1013     }
1014 
1015     process_field_value_at_safepoint(elem_type, elem_val, sfpt, value_worklist);
1016   }
1017 
1018   return true;
1019 }
1020 
1021 // Recursively adds all flattened fields of a type 'iklass' inside 'base' to 'sfpt'.
1022 // 'offset_minus_header' refers to the offset of the payload of 'iklass' inside 'base' minus the
1023 // payload offset of 'iklass'. If 'base' is of type 'iklass' then 'offset_minus_header' == 0.
1024 bool PhaseMacroExpand::add_inst_fields_to_safepoint(ciInstanceKlass* iklass, AllocateNode* alloc, Node* base, int offset_minus_header, SafePointNode* sfpt, Unique_Node_List* value_worklist) {
1025   const TypeInstPtr* base_type = _igvn.type(base)->is_instptr();
1026   auto report_failure = [&](int offset) {
1027 #ifndef PRODUCT
1028     if (PrintEliminateAllocations) {
1029       ciInstanceKlass* base_klass = base_type->instance_klass();
1030       ciField* flattened_field = base_klass->get_field_by_offset(offset, false);
1031       assert(flattened_field != nullptr, "must have a field of type %s at offset %d", base_klass->name()->as_utf8(), offset);
1032       tty->print("=== At SafePoint node %d can't find value of field: ", sfpt->_idx);
1033       flattened_field->print();
1034       int field_idx = C->alias_type(flattened_field)->index();
1035       tty->print(" (alias_idx=%d)", field_idx);
1036       tty->print(", which prevents elimination of: ");
1037       base->dump();
1038     }
1039 #endif // PRODUCT
1040   };
1041 
1042   for (int i = 0; i < iklass->nof_declared_nonstatic_fields(); i++) {
1043     ciField* field = iklass->declared_nonstatic_field_at(i);
1044     if (field->is_flat()) {
1045       ciInlineKlass* fvk = field->type()->as_inline_klass();
1046       int field_offset_minus_header = offset_minus_header + field->offset_in_bytes() - fvk->payload_offset();
1047       bool success = add_inst_fields_to_safepoint(fvk, alloc, base, field_offset_minus_header, sfpt, value_worklist);
1048       if (!success) {
1049         return false;
1050       }
1051 
1052       // The null marker of a field is added right after we scalarize that field
1053       if (!field->is_null_free()) {
1054         int nm_offset = offset_minus_header + field->null_marker_offset();
1055         Node* null_marker = value_from_mem(sfpt->memory(), sfpt->control(), T_BOOLEAN, TypeInt::BOOL, base_type->with_offset(nm_offset), alloc);
1056         if (null_marker == nullptr) {
1057           report_failure(nm_offset);
1058           return false;
1059         }
1060         process_field_value_at_safepoint(TypeInt::BOOL, null_marker, sfpt, value_worklist);
1061       }
1062 
1063       continue;
1064     }
1065 
1066     int offset = offset_minus_header + field->offset_in_bytes();
1067     ciType* elem_type = field->type();
1068     BasicType basic_elem_type = field->layout_type();
1069 
1070     const Type* field_type;
1071     if (is_reference_type(basic_elem_type)) {
1072       if (!elem_type->is_loaded()) {
1073         field_type = TypeInstPtr::BOTTOM;
1074       } else {
1075         field_type = TypeOopPtr::make_from_klass(elem_type->as_klass());
1076       }
1077       if (UseCompressedOops) {
1078         field_type = field_type->make_narrowoop();
1079         basic_elem_type = T_NARROWOOP;
1080       }
1081     } else {
1082       field_type = Type::get_const_basic_type(basic_elem_type);
1083     }
1084 
1085     const TypeInstPtr* field_addr_type = base_type->add_offset(offset)->isa_instptr();
1086     Node* field_val = value_from_mem(sfpt->memory(), sfpt->control(), basic_elem_type, field_type, field_addr_type, alloc);
1087     if (field_val == nullptr) {
1088       report_failure(offset);
1089       return false;
1090     }
1091     process_field_value_at_safepoint(field_type, field_val, sfpt, value_worklist);
1092   }
1093 
1094   return true;
1095 }
1096 
1097 SafePointScalarObjectNode* PhaseMacroExpand::create_scalarized_object_description(AllocateNode* alloc, SafePointNode* sfpt,
1098                                                                                   Unique_Node_List* value_worklist) {
1099   // Fields of scalar objs are referenced only at the end
1100   // of regular debuginfo at the last (youngest) JVMS.
1101   // Record relative start index.
1102   ciInstanceKlass* iklass    = nullptr;


1103   const TypeOopPtr* res_type = nullptr;
1104   int nfields                = 0;


1105   uint first_ind             = (sfpt->req() - sfpt->jvms()->scloff());
1106   Node* res                  = alloc->result_cast();
1107 
1108   assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");
1109   assert(sfpt->jvms() != nullptr, "missed JVMS");
1110   uint before_sfpt_req = sfpt->req();
1111 
1112   if (res != nullptr) { // Could be null when there are no users
1113     res_type = _igvn.type(res)->isa_oopptr();
1114 
1115     if (res_type->isa_instptr()) {
1116       // find the fields of the class which will be needed for safepoint debug information
1117       iklass = res_type->is_instptr()->instance_klass();
1118       nfields = iklass->nof_nonstatic_fields();
1119     } else {
1120       // find the array's elements which will be needed for safepoint debug information
1121       nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
1122       assert(nfields >= 0, "must be an array klass.");
1123     }
1124 
1125     if (res->bottom_type()->is_inlinetypeptr()) {
1126       // Nullable inline types have a null marker field which is added to the safepoint when scalarizing them (see
1127       // InlineTypeNode::make_scalar_in_safepoint()). When having circular inline types, we stop scalarizing at depth 1
1128       // to avoid an endless recursion. Therefore, we do not have a SafePointScalarObjectNode node here, yet.
1129       // We are about to create a SafePointScalarObjectNode as if this is a normal object. Add an additional int input
1130       // with value 1 which sets the null marker to true to indicate that the object is always non-null. This input is checked
1131       // later in PhaseOutput::filLocArray() for inline types.
1132       sfpt->add_req(_igvn.intcon(1));
1133     }
1134   }
1135 
1136   SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(res_type, alloc, first_ind, sfpt->jvms()->depth(), nfields);
1137   sobj->init_req(0, C->root());
1138   transform_later(sobj);
1139 
1140   if (res == nullptr) {
1141     sfpt->jvms()->set_endoff(sfpt->req());
1142     return sobj;
1143   }




























































1144 
1145   bool success;
1146   if (iklass == nullptr) {
1147     success = add_array_elems_to_safepoint(alloc, res_type->is_aryptr(), sfpt, value_worklist);
1148   } else {
1149     success = add_inst_fields_to_safepoint(iklass, alloc, res, 0, sfpt, value_worklist);
1150   }
1151 
1152   // We weren't able to find a value for this field, remove all the fields added to the safepoint
1153   if (!success) {
1154     for (uint i = sfpt->req() - 1; i >= before_sfpt_req; i--) {
1155       sfpt->del_req(i);




1156     }
1157     _igvn._worklist.push(sfpt);
1158     return nullptr;
1159   }
1160 
1161   sfpt->jvms()->set_endoff(sfpt->req());

1162   return sobj;
1163 }
1164 
1165 // Do scalar replacement.
1166 bool PhaseMacroExpand::scalar_replacement(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
1167   GrowableArray <SafePointNode *> safepoints_done;
1168   Node* res = alloc->result_cast();
1169   assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");
1170   const TypeOopPtr* res_type = nullptr;
1171   if (res != nullptr) { // Could be null when there are no users
1172     res_type = _igvn.type(res)->isa_oopptr();
1173   }
1174 
1175   // Process the safepoint uses
1176   Unique_Node_List value_worklist;
1177   while (safepoints.length() > 0) {
1178     SafePointNode* sfpt = safepoints.pop();
1179     SafePointScalarObjectNode* sobj = create_scalarized_object_description(alloc, sfpt, &value_worklist);
1180 
1181     if (sobj == nullptr) {
1182       undo_previous_scalarizations(safepoints_done, alloc);
1183       return false;
1184     }
1185 
1186     // Now make a pass over the debug information replacing any references
1187     // to the allocated object with "sobj"
1188     JVMState *jvms = sfpt->jvms();
1189     sfpt->replace_edges_in_range(res, sobj, jvms->debug_start(), jvms->debug_end(), &_igvn);
1190     _igvn._worklist.push(sfpt);
1191 
1192     // keep it for rollback
1193     safepoints_done.append_if_missing(sfpt);
1194   }
1195   // Scalarize inline types that were added to the safepoint.
1196   // Don't allow linking a constant oop (if available) for flat array elements
1197   // because Deoptimization::reassign_flat_array_elements needs field values.
1198   bool allow_oop = (res_type != nullptr) && !res_type->is_flat();
1199   for (uint i = 0; i < value_worklist.size(); ++i) {
1200     InlineTypeNode* vt = value_worklist.at(i)->as_InlineType();
1201     vt->make_scalar_in_safepoints(&_igvn, allow_oop);
1202   }
1203   return true;
1204 }
1205 
1206 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) {
1207   Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control);
1208   Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory);
1209   if (ctl_proj != nullptr) {
1210     igvn.replace_node(ctl_proj, n->in(0));
1211   }
1212   if (mem_proj != nullptr) {
1213     igvn.replace_node(mem_proj, n->in(TypeFunc::Memory));
1214   }
1215 }
1216 
1217 // Process users of eliminated allocation.
1218 void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc, bool inline_alloc) {
1219   Unique_Node_List worklist;
1220   Node* res = alloc->result_cast();
1221   if (res != nullptr) {
1222     worklist.push(res);
1223   }
1224   while (worklist.size() > 0) {
1225     res = worklist.pop();
1226     for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
1227       Node *use = res->last_out(j);
1228       uint oc1 = res->outcnt();
1229 
1230       if (use->is_AddP()) {
1231         for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
1232           Node *n = use->last_out(k);
1233           uint oc2 = use->outcnt();
1234           if (n->is_Store()) {
1235             for (DUIterator_Fast pmax, p = n->fast_outs(pmax); p < pmax; p++) {
1236               MemBarNode* mb = n->fast_out(p)->isa_MemBar();
1237               if (mb != nullptr && mb->req() <= MemBarNode::Precedent && mb->in(MemBarNode::Precedent) == n) {
1238                 // MemBarVolatiles should have been removed by MemBarNode::Ideal() for non-inline allocations
1239                 assert(inline_alloc, "MemBarVolatile should be eliminated for non-escaping object");
1240                 mb->remove(&_igvn);
1241               }



1242             }

1243             _igvn.replace_node(n, n->in(MemNode::Memory));
1244           } else {
1245             eliminate_gc_barrier(n);
1246           }
1247           k -= (oc2 - use->outcnt());
1248         }
1249         _igvn.remove_dead_node(use);
1250       } else if (use->is_ArrayCopy()) {
1251         // Disconnect ArrayCopy node
1252         ArrayCopyNode* ac = use->as_ArrayCopy();
1253         if (ac->is_clonebasic()) {
1254           Node* membar_after = ac->proj_out(TypeFunc::Control)->unique_ctrl_out();
1255           disconnect_projections(ac, _igvn);
1256           assert(alloc->in(TypeFunc::Memory)->is_Proj() && alloc->in(TypeFunc::Memory)->in(0)->Opcode() == Op_MemBarCPUOrder, "mem barrier expected before allocation");
1257           Node* membar_before = alloc->in(TypeFunc::Memory)->in(0);
1258           disconnect_projections(membar_before->as_MemBar(), _igvn);
1259           if (membar_after->is_MemBar()) {
1260             disconnect_projections(membar_after->as_MemBar(), _igvn);
1261           }
1262         } else {
1263           assert(ac->is_arraycopy_validated() ||
1264                  ac->is_copyof_validated() ||
1265                  ac->is_copyofrange_validated(), "unsupported");
1266           CallProjections* callprojs = ac->extract_projections(true);

1267 
1268           _igvn.replace_node(callprojs->fallthrough_ioproj, ac->in(TypeFunc::I_O));
1269           _igvn.replace_node(callprojs->fallthrough_memproj, ac->in(TypeFunc::Memory));
1270           _igvn.replace_node(callprojs->fallthrough_catchproj, ac->in(TypeFunc::Control));
1271 
1272           // Set control to top. IGVN will remove the remaining projections
1273           ac->set_req(0, top());
1274           ac->replace_edge(res, top(), &_igvn);
1275 
1276           // Disconnect src right away: it can help find new
1277           // opportunities for allocation elimination
1278           Node* src = ac->in(ArrayCopyNode::Src);
1279           ac->replace_edge(src, top(), &_igvn);
1280           // src can be top at this point if src and dest of the
1281           // arraycopy were the same
1282           if (src->outcnt() == 0 && !src->is_top()) {
1283             _igvn.remove_dead_node(src);
1284           }
1285         }
1286         _igvn._worklist.push(ac);
1287       } else if (use->is_InlineType()) {
1288         assert(use->as_InlineType()->get_oop() == res, "unexpected inline type ptr use");
1289         // Cut off oop input and remove known instance id from type
1290         _igvn.rehash_node_delayed(use);
1291         use->as_InlineType()->set_oop(_igvn, _igvn.zerocon(T_OBJECT));
1292         use->as_InlineType()->set_is_buffered(_igvn, false);
1293         const TypeOopPtr* toop = _igvn.type(use)->is_oopptr()->cast_to_instance_id(TypeOopPtr::InstanceBot);
1294         _igvn.set_type(use, toop);
1295         use->as_InlineType()->set_type(toop);
1296         // Process users
1297         for (DUIterator_Fast kmax, k = use->fast_outs(kmax); k < kmax; k++) {
1298           Node* u = use->fast_out(k);
1299           if (!u->is_InlineType() && !u->is_StoreFlat()) {
1300             worklist.push(u);
1301           }
1302         }
1303       } else if (use->Opcode() == Op_StoreX && use->in(MemNode::Address) == res) {
1304         // Store to mark word of inline type larval buffer
1305         assert(inline_alloc, "Unexpected store to mark word");
1306         _igvn.replace_node(use, use->in(MemNode::Memory));
1307       } else if (use->Opcode() == Op_MemBarRelease || use->Opcode() == Op_MemBarStoreStore) {
1308         // Inline type buffer allocations are followed by a membar
1309         assert(inline_alloc, "Unexpected MemBarRelease");
1310         use->as_MemBar()->remove(&_igvn);
1311       } else {
1312         eliminate_gc_barrier(use);
1313       }
1314       j -= (oc1 - res->outcnt());
1315     }
1316     assert(res->outcnt() == 0, "all uses of allocated objects must be deleted");
1317     _igvn.remove_dead_node(res);
1318   }
1319 
1320   //
1321   // Process other users of allocation's projections
1322   //
1323   if (_callprojs->resproj[0] != nullptr && _callprojs->resproj[0]->outcnt() != 0) {
1324     // First disconnect stores captured by Initialize node.
1325     // If Initialize node is eliminated first in the following code,
1326     // it will kill such stores and DUIterator_Last will assert.
1327     for (DUIterator_Fast jmax, j = _callprojs->resproj[0]->fast_outs(jmax);  j < jmax; j++) {
1328       Node* use = _callprojs->resproj[0]->fast_out(j);
1329       if (use->is_AddP()) {
1330         // raw memory addresses used only by the initialization
1331         _igvn.replace_node(use, C->top());
1332         --j; --jmax;
1333       }
1334     }
1335     for (DUIterator_Last jmin, j = _callprojs->resproj[0]->last_outs(jmin); j >= jmin; ) {
1336       Node* use = _callprojs->resproj[0]->last_out(j);
1337       uint oc1 = _callprojs->resproj[0]->outcnt();
1338       if (use->is_Initialize()) {
1339         // Eliminate Initialize node.
1340         InitializeNode *init = use->as_Initialize();
1341         Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
1342         if (ctrl_proj != nullptr) {
1343           _igvn.replace_node(ctrl_proj, init->in(TypeFunc::Control));
1344 #ifdef ASSERT
1345           // If the InitializeNode has no memory out, it will die, and tmp will become null
1346           Node* tmp = init->in(TypeFunc::Control);
1347           assert(tmp == nullptr || tmp == _callprojs->fallthrough_catchproj, "allocation control projection");
1348 #endif
1349         }
1350         Node* mem = init->in(TypeFunc::Memory);
1351 #ifdef ASSERT
1352         if (init->number_of_projs(TypeFunc::Memory) > 0) {
1353           if (mem->is_MergeMem()) {
1354             assert(mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw) == _callprojs->fallthrough_memproj, "allocation memory projection");
1355           } else {
1356             assert(mem == _callprojs->fallthrough_memproj, "allocation memory projection");
1357           }
1358         }
1359 #endif
1360         init->replace_mem_projs_by(mem, &_igvn);
1361         assert(init->outcnt() == 0, "should only have had a control and some memory projections, and we removed them");
1362       } else if (use->Opcode() == Op_MemBarStoreStore) {
1363         // Inline type buffer allocations are followed by a membar
1364         assert(inline_alloc, "Unexpected MemBarStoreStore");
1365         use->as_MemBar()->remove(&_igvn);
1366       } else  {
1367         assert(false, "only Initialize or AddP expected");
1368       }
1369       j -= (oc1 - _callprojs->resproj[0]->outcnt());
1370     }
1371   }
1372   if (_callprojs->fallthrough_catchproj != nullptr) {
1373     _igvn.replace_node(_callprojs->fallthrough_catchproj, alloc->in(TypeFunc::Control));
1374   }
1375   if (_callprojs->fallthrough_memproj != nullptr) {
1376     _igvn.replace_node(_callprojs->fallthrough_memproj, alloc->in(TypeFunc::Memory));
1377   }
1378   if (_callprojs->catchall_memproj != nullptr) {
1379     _igvn.replace_node(_callprojs->catchall_memproj, C->top());
1380   }
1381   if (_callprojs->fallthrough_ioproj != nullptr) {
1382     _igvn.replace_node(_callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
1383   }
1384   if (_callprojs->catchall_ioproj != nullptr) {
1385     _igvn.replace_node(_callprojs->catchall_ioproj, C->top());
1386   }
1387   if (_callprojs->catchall_catchproj != nullptr) {
1388     _igvn.replace_node(_callprojs->catchall_catchproj, C->top());
1389   }
1390 }
1391 
1392 bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) {
1393   // If reallocation fails during deoptimization we'll pop all
1394   // interpreter frames for this compiled frame and that won't play
1395   // nice with JVMTI popframe.
1396   // We avoid this issue by eager reallocation when the popframe request
1397   // is received.
1398   if (!EliminateAllocations) {
1399     return false;
1400   }
1401   Node* klass = alloc->in(AllocateNode::KlassNode);
1402   const TypeKlassPtr* tklass = _igvn.type(klass)->is_klassptr();
1403 
1404   // Attempt to eliminate inline type buffer allocations
1405   // regardless of usage and escape/replaceable status.
1406   bool inline_alloc = tklass->isa_instklassptr() &&
1407                       tklass->is_instklassptr()->instance_klass()->is_inlinetype();
1408   if (!alloc->_is_non_escaping && !inline_alloc) {
1409     return false;
1410   }
1411   // Eliminate boxing allocations which are not used
1412   // regardless scalar replaceable status.
1413   Node* res = alloc->result_cast();
1414   bool boxing_alloc = (res == nullptr) && C->eliminate_boxing() &&
1415                       tklass->isa_instklassptr() &&
1416                       tklass->is_instklassptr()->instance_klass()->is_box_klass();
1417   if (!alloc->_is_scalar_replaceable && !boxing_alloc && !inline_alloc) {
1418     return false;
1419   }
1420 
1421   _callprojs = alloc->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1422 
1423   GrowableArray <SafePointNode *> safepoints;
1424   if (!can_eliminate_allocation(&_igvn, alloc, &safepoints)) {
1425     return false;
1426   }
1427 
1428   if (!alloc->_is_scalar_replaceable) {
1429     assert(res == nullptr || inline_alloc, "sanity");
1430     // We can only eliminate allocation if all debug info references
1431     // are already replaced with SafePointScalarObject because
1432     // we can't search for a fields value without instance_id.
1433     if (safepoints.length() > 0) {
1434       return false;
1435     }
1436   }
1437 
1438   if (!scalar_replacement(alloc, safepoints)) {
1439     return false;
1440   }
1441 
1442   CompileLog* log = C->log();
1443   if (log != nullptr) {
1444     log->head("eliminate_allocation type='%d'",
1445               log->identify(tklass->exact_klass()));
1446     JVMState* p = alloc->jvms();
1447     while (p != nullptr) {
1448       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1449       p = p->caller();
1450     }
1451     log->tail("eliminate_allocation");
1452   }
1453 
1454   process_users_of_allocation(alloc, inline_alloc);
1455 
1456 #ifndef PRODUCT
1457   if (PrintEliminateAllocations) {
1458     if (alloc->is_AllocateArray())
1459       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1460     else
1461       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1462   }
1463 #endif
1464 
1465   return true;
1466 }
1467 
1468 bool PhaseMacroExpand::eliminate_boxing_node(CallStaticJavaNode *boxing) {
1469   // EA should remove all uses of non-escaping boxing node.
1470   if (!C->eliminate_boxing() || boxing->proj_out_or_null(TypeFunc::Parms) != nullptr) {
1471     return false;
1472   }
1473 
1474   assert(boxing->result_cast() == nullptr, "unexpected boxing node result");
1475 
1476   _callprojs = boxing->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1477 
1478   const TypeTuple* r = boxing->tf()->range_sig();
1479   assert(r->cnt() > TypeFunc::Parms, "sanity");
1480   const TypeInstPtr* t = r->field_at(TypeFunc::Parms)->isa_instptr();
1481   assert(t != nullptr, "sanity");
1482 
1483   CompileLog* log = C->log();
1484   if (log != nullptr) {
1485     log->head("eliminate_boxing type='%d'",
1486               log->identify(t->instance_klass()));
1487     JVMState* p = boxing->jvms();
1488     while (p != nullptr) {
1489       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1490       p = p->caller();
1491     }
1492     log->tail("eliminate_boxing");
1493   }
1494 
1495   process_users_of_allocation(boxing);
1496 
1497 #ifndef PRODUCT
1498   if (PrintEliminateAllocations) {

1562 // oop flavor.
1563 //
1564 //=============================================================================
1565 // FastAllocateSizeLimit value is in DOUBLEWORDS.
1566 // Allocations bigger than this always go the slow route.
1567 // This value must be small enough that allocation attempts that need to
1568 // trigger exceptions go the slow route.  Also, it must be small enough so
1569 // that heap_top + size_in_bytes does not wrap around the 4Gig limit.
1570 //=============================================================================j//
1571 // %%% Here is an old comment from parseHelper.cpp; is it outdated?
1572 // The allocator will coalesce int->oop copies away.  See comment in
1573 // coalesce.cpp about how this works.  It depends critically on the exact
1574 // code shape produced here, so if you are changing this code shape
1575 // make sure the GC info for the heap-top is correct in and around the
1576 // slow-path call.
1577 //
1578 
1579 void PhaseMacroExpand::expand_allocate_common(
1580             AllocateNode* alloc, // allocation node to be expanded
1581             Node* length,  // array length for an array allocation
1582             Node* init_val, // value to initialize the array with
1583             const TypeFunc* slow_call_type, // Type of slow call
1584             address slow_call_address,  // Address of slow call
1585             Node* valid_length_test // whether length is valid or not
1586     )
1587 {
1588   Node* ctrl = alloc->in(TypeFunc::Control);
1589   Node* mem  = alloc->in(TypeFunc::Memory);
1590   Node* i_o  = alloc->in(TypeFunc::I_O);
1591   Node* size_in_bytes     = alloc->in(AllocateNode::AllocSize);
1592   Node* klass_node        = alloc->in(AllocateNode::KlassNode);
1593   Node* initial_slow_test = alloc->in(AllocateNode::InitialTest);
1594   assert(ctrl != nullptr, "must have control");
1595 
1596   // We need a Region and corresponding Phi's to merge the slow-path and fast-path results.
1597   // they will not be used if "always_slow" is set
1598   enum { slow_result_path = 1, fast_result_path = 2 };
1599   Node *result_region = nullptr;
1600   Node *result_phi_rawmem = nullptr;
1601   Node *result_phi_rawoop = nullptr;
1602   Node *result_phi_i_o = nullptr;

1647 #endif
1648       yank_alloc_node(alloc);
1649       return;
1650     }
1651   }
1652 
1653   enum { too_big_or_final_path = 1, need_gc_path = 2 };
1654   Node *slow_region = nullptr;
1655   Node *toobig_false = ctrl;
1656 
1657   // generate the initial test if necessary
1658   if (initial_slow_test != nullptr ) {
1659     assert (expand_fast_path, "Only need test if there is a fast path");
1660     slow_region = new RegionNode(3);
1661 
1662     // Now make the initial failure test.  Usually a too-big test but
1663     // might be a TRUE for finalizers.
1664     IfNode *toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1665     transform_later(toobig_iff);
1666     // Plug the failing-too-big test into the slow-path region
1667     Node* toobig_true = new IfTrueNode(toobig_iff);
1668     transform_later(toobig_true);
1669     slow_region    ->init_req( too_big_or_final_path, toobig_true );
1670     toobig_false = new IfFalseNode(toobig_iff);
1671     transform_later(toobig_false);
1672   } else {
1673     // No initial test, just fall into next case
1674     assert(allocation_has_use || !expand_fast_path, "Should already have been handled");
1675     toobig_false = ctrl;
1676     DEBUG_ONLY(slow_region = NodeSentinel);
1677   }
1678 
1679   // If we are here there are several possibilities
1680   // - expand_fast_path is false - then only a slow path is expanded. That's it.
1681   // no_initial_check means a constant allocation.
1682   // - If check always evaluates to false -> expand_fast_path is false (see above)
1683   // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath)
1684   // if !allocation_has_use the fast path is empty
1685   // if !allocation_has_use && no_initial_check
1686   // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all.
1687   //   removed by yank_alloc_node above.
1688 
1689   Node *slow_mem = mem;  // save the current memory state for slow path
1690   // generate the fast allocation code unless we know that the initial test will always go slow
1691   if (expand_fast_path) {
1692     // Fast path modifies only raw memory.
1693     if (mem->is_MergeMem()) {
1694       mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1695     }
1696 
1697     // allocate the Region and Phi nodes for the result
1698     result_region = new RegionNode(3);
1699     result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1700     result_phi_i_o    = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1701 
1702     // Grab regular I/O before optional prefetch may change it.
1703     // Slow-path does no I/O so just set it to the original I/O.
1704     result_phi_i_o->init_req(slow_result_path, i_o);
1705 
1706     // Name successful fast-path variables
1707     Node* fast_oop_ctrl;
1708     Node* fast_oop_rawmem;
1709 
1710     if (allocation_has_use) {
1711       Node* needgc_ctrl = nullptr;
1712       result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1713 
1714       intx prefetch_lines = length != nullptr ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1715       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1716       Node* fast_oop = bs->obj_allocate(this, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1717                                         fast_oop_ctrl, fast_oop_rawmem,
1718                                         prefetch_lines);
1719 
1720       if (initial_slow_test != nullptr) {
1721         // This completes all paths into the slow merge point
1722         slow_region->init_req(need_gc_path, needgc_ctrl);
1723         transform_later(slow_region);
1724       } else {
1725         // No initial slow path needed!
1726         // Just fall from the need-GC path straight into the VM call.
1727         slow_region = needgc_ctrl;
1728       }
1729 

1747     result_phi_i_o   ->init_req(fast_result_path, i_o);
1748     result_phi_rawmem->init_req(fast_result_path, fast_oop_rawmem);
1749   } else {
1750     slow_region = ctrl;
1751     result_phi_i_o = i_o; // Rename it to use in the following code.
1752   }
1753 
1754   // Generate slow-path call
1755   CallNode *call = new CallStaticJavaNode(slow_call_type, slow_call_address,
1756                                OptoRuntime::stub_name(slow_call_address),
1757                                TypePtr::BOTTOM);
1758   call->init_req(TypeFunc::Control,   slow_region);
1759   call->init_req(TypeFunc::I_O,       top());    // does no i/o
1760   call->init_req(TypeFunc::Memory,    slow_mem); // may gc ptrs
1761   call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1762   call->init_req(TypeFunc::FramePtr,  alloc->in(TypeFunc::FramePtr));
1763 
1764   call->init_req(TypeFunc::Parms+0, klass_node);
1765   if (length != nullptr) {
1766     call->init_req(TypeFunc::Parms+1, length);
1767     if (init_val != nullptr) {
1768       call->init_req(TypeFunc::Parms+2, init_val);
1769     }
1770   } else {
1771     // Let the runtime know if this is a larval allocation
1772     call->init_req(TypeFunc::Parms+1, _igvn.intcon(alloc->_larval));
1773   }
1774 
1775   // Copy debug information and adjust JVMState information, then replace
1776   // allocate node with the call
1777   call->copy_call_debug_info(&_igvn, alloc);
1778   // For array allocations, copy the valid length check to the call node so Compile::final_graph_reshaping() can verify
1779   // that the call has the expected number of CatchProj nodes (in case the allocation always fails and the fallthrough
1780   // path dies).
1781   if (valid_length_test != nullptr) {
1782     call->add_req(valid_length_test);
1783   }
1784   if (expand_fast_path) {
1785     call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
1786   } else {
1787     // Hook i_o projection to avoid its elimination during allocation
1788     // replacement (when only a slow call is generated).
1789     call->set_req(TypeFunc::I_O, result_phi_i_o);
1790   }
1791   _igvn.replace_node(alloc, call);
1792   transform_later(call);
1793 
1794   // Identify the output projections from the allocate node and
1795   // adjust any references to them.
1796   // The control and io projections look like:
1797   //
1798   //        v---Proj(ctrl) <-----+   v---CatchProj(ctrl)
1799   //  Allocate                   Catch
1800   //        ^---Proj(io) <-------+   ^---CatchProj(io)
1801   //
1802   //  We are interested in the CatchProj nodes.
1803   //
1804   _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1805 
1806   // An allocate node has separate memory projections for the uses on
1807   // the control and i_o paths. Replace the control memory projection with
1808   // result_phi_rawmem (unless we are only generating a slow call when
1809   // both memory projections are combined)
1810   if (expand_fast_path && _callprojs->fallthrough_memproj != nullptr) {
1811     _igvn.replace_in_uses(_callprojs->fallthrough_memproj, result_phi_rawmem);
1812   }
1813   // Now change uses of catchall_memproj to use fallthrough_memproj and delete
1814   // catchall_memproj so we end up with a call that has only 1 memory projection.
1815   if (_callprojs->catchall_memproj != nullptr) {
1816     if (_callprojs->fallthrough_memproj == nullptr) {
1817       _callprojs->fallthrough_memproj = new ProjNode(call, TypeFunc::Memory);
1818       transform_later(_callprojs->fallthrough_memproj);
1819     }
1820     _igvn.replace_in_uses(_callprojs->catchall_memproj, _callprojs->fallthrough_memproj);
1821     _igvn.remove_dead_node(_callprojs->catchall_memproj);
1822   }
1823 
1824   // An allocate node has separate i_o projections for the uses on the control
1825   // and i_o paths. Always replace the control i_o projection with result i_o
1826   // otherwise incoming i_o become dead when only a slow call is generated
1827   // (it is different from memory projections where both projections are
1828   // combined in such case).
1829   if (_callprojs->fallthrough_ioproj != nullptr) {
1830     _igvn.replace_in_uses(_callprojs->fallthrough_ioproj, result_phi_i_o);
1831   }
1832   // Now change uses of catchall_ioproj to use fallthrough_ioproj and delete
1833   // catchall_ioproj so we end up with a call that has only 1 i_o projection.
1834   if (_callprojs->catchall_ioproj != nullptr) {
1835     if (_callprojs->fallthrough_ioproj == nullptr) {
1836       _callprojs->fallthrough_ioproj = new ProjNode(call, TypeFunc::I_O);
1837       transform_later(_callprojs->fallthrough_ioproj);
1838     }
1839     _igvn.replace_in_uses(_callprojs->catchall_ioproj, _callprojs->fallthrough_ioproj);
1840     _igvn.remove_dead_node(_callprojs->catchall_ioproj);
1841   }
1842 
1843   // if we generated only a slow call, we are done
1844   if (!expand_fast_path) {
1845     // Now we can unhook i_o.
1846     if (result_phi_i_o->outcnt() > 1) {
1847       call->set_req(TypeFunc::I_O, top());
1848     } else {
1849       assert(result_phi_i_o->unique_ctrl_out() == call, "sanity");
1850       // Case of new array with negative size known during compilation.
1851       // AllocateArrayNode::Ideal() optimization disconnect unreachable
1852       // following code since call to runtime will throw exception.
1853       // As result there will be no users of i_o after the call.
1854       // Leave i_o attached to this call to avoid problems in preceding graph.
1855     }
1856     return;
1857   }
1858 
1859   if (_callprojs->fallthrough_catchproj != nullptr) {
1860     ctrl = _callprojs->fallthrough_catchproj->clone();
1861     transform_later(ctrl);
1862     _igvn.replace_node(_callprojs->fallthrough_catchproj, result_region);
1863   } else {
1864     ctrl = top();
1865   }
1866   Node *slow_result;
1867   if (_callprojs->resproj[0] == nullptr) {
1868     // no uses of the allocation result
1869     slow_result = top();
1870   } else {
1871     slow_result = _callprojs->resproj[0]->clone();
1872     transform_later(slow_result);
1873     _igvn.replace_node(_callprojs->resproj[0], result_phi_rawoop);
1874   }
1875 
1876   // Plug slow-path into result merge point
1877   result_region->init_req( slow_result_path, ctrl);
1878   transform_later(result_region);
1879   if (allocation_has_use) {
1880     result_phi_rawoop->init_req(slow_result_path, slow_result);
1881     transform_later(result_phi_rawoop);
1882   }
1883   result_phi_rawmem->init_req(slow_result_path, _callprojs->fallthrough_memproj);
1884   transform_later(result_phi_rawmem);
1885   transform_later(result_phi_i_o);
1886   // This completes all paths into the result merge point
1887 }
1888 
1889 // Remove alloc node that has no uses.
1890 void PhaseMacroExpand::yank_alloc_node(AllocateNode* alloc) {
1891   Node* ctrl = alloc->in(TypeFunc::Control);
1892   Node* mem  = alloc->in(TypeFunc::Memory);
1893   Node* i_o  = alloc->in(TypeFunc::I_O);
1894 
1895   _callprojs = alloc->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1896   if (_callprojs->resproj[0] != nullptr) {
1897     for (DUIterator_Fast imax, i = _callprojs->resproj[0]->fast_outs(imax); i < imax; i++) {
1898       Node* use = _callprojs->resproj[0]->fast_out(i);
1899       use->isa_MemBar()->remove(&_igvn);
1900       --imax;
1901       --i; // back up iterator
1902     }
1903     assert(_callprojs->resproj[0]->outcnt() == 0, "all uses must be deleted");
1904     _igvn.remove_dead_node(_callprojs->resproj[0]);
1905   }
1906   if (_callprojs->fallthrough_catchproj != nullptr) {
1907     _igvn.replace_in_uses(_callprojs->fallthrough_catchproj, ctrl);
1908     _igvn.remove_dead_node(_callprojs->fallthrough_catchproj);
1909   }
1910   if (_callprojs->catchall_catchproj != nullptr) {
1911     _igvn.rehash_node_delayed(_callprojs->catchall_catchproj);
1912     _callprojs->catchall_catchproj->set_req(0, top());
1913   }
1914   if (_callprojs->fallthrough_proj != nullptr) {
1915     Node* catchnode = _callprojs->fallthrough_proj->unique_ctrl_out();
1916     _igvn.remove_dead_node(catchnode);
1917     _igvn.remove_dead_node(_callprojs->fallthrough_proj);
1918   }
1919   if (_callprojs->fallthrough_memproj != nullptr) {
1920     _igvn.replace_in_uses(_callprojs->fallthrough_memproj, mem);
1921     _igvn.remove_dead_node(_callprojs->fallthrough_memproj);
1922   }
1923   if (_callprojs->fallthrough_ioproj != nullptr) {
1924     _igvn.replace_in_uses(_callprojs->fallthrough_ioproj, i_o);
1925     _igvn.remove_dead_node(_callprojs->fallthrough_ioproj);
1926   }
1927   if (_callprojs->catchall_memproj != nullptr) {
1928     _igvn.rehash_node_delayed(_callprojs->catchall_memproj);
1929     _callprojs->catchall_memproj->set_req(0, top());
1930   }
1931   if (_callprojs->catchall_ioproj != nullptr) {
1932     _igvn.rehash_node_delayed(_callprojs->catchall_ioproj);
1933     _callprojs->catchall_ioproj->set_req(0, top());
1934   }
1935 #ifndef PRODUCT
1936   if (PrintEliminateAllocations) {
1937     if (alloc->is_AllocateArray()) {
1938       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1939     } else {
1940       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1941     }
1942   }
1943 #endif
1944   _igvn.remove_dead_node(alloc);
1945 }
1946 
1947 void PhaseMacroExpand::expand_initialize_membar(AllocateNode* alloc, InitializeNode* init,
1948                                                 Node*& fast_oop_ctrl, Node*& fast_oop_rawmem) {
1949   // If initialization is performed by an array copy, any required
1950   // MemBarStoreStore was already added. If the object does not
1951   // escape no need for a MemBarStoreStore. If the object does not
1952   // escape in its initializer and memory barrier (MemBarStoreStore or
1953   // stronger) is already added at exit of initializer, also no need

2047     Node* thread = new ThreadLocalNode();
2048     transform_later(thread);
2049 
2050     call->init_req(TypeFunc::Parms + 0, thread);
2051     call->init_req(TypeFunc::Parms + 1, oop);
2052     call->init_req(TypeFunc::Control, ctrl);
2053     call->init_req(TypeFunc::I_O    , top()); // does no i/o
2054     call->init_req(TypeFunc::Memory , rawmem);
2055     call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
2056     call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
2057     transform_later(call);
2058     ctrl = new ProjNode(call, TypeFunc::Control);
2059     transform_later(ctrl);
2060     rawmem = new ProjNode(call, TypeFunc::Memory);
2061     transform_later(rawmem);
2062   }
2063 }
2064 
2065 // Helper for PhaseMacroExpand::expand_allocate_common.
2066 // Initializes the newly-allocated storage.
2067 Node* PhaseMacroExpand::initialize_object(AllocateNode* alloc,
2068                                           Node* control, Node* rawmem, Node* object,
2069                                           Node* klass_node, Node* length,
2070                                           Node* size_in_bytes) {

2071   InitializeNode* init = alloc->initialization();
2072   // Store the klass & mark bits
2073   Node* mark_node = alloc->make_ideal_mark(&_igvn, control, rawmem);
2074   if (!mark_node->is_Con()) {
2075     transform_later(mark_node);
2076   }
2077   rawmem = make_store_raw(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
2078 
2079   if (!UseCompactObjectHeaders) {
2080     rawmem = make_store_raw(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
2081   }
2082   int header_size = alloc->minimum_header_size();  // conservatively small
2083 
2084   // Array length
2085   if (length != nullptr) {         // Arrays need length field
2086     rawmem = make_store_raw(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
2087     // conservatively small header size:
2088     header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
2089     if (_igvn.type(klass_node)->isa_aryklassptr()) {   // we know the exact header size in most cases:
2090       BasicType elem = _igvn.type(klass_node)->is_klassptr()->as_instance_type()->isa_aryptr()->elem()->array_element_basic_type();
2091       if (is_reference_type(elem, true)) {
2092         elem = T_OBJECT;
2093       }
2094       header_size = Klass::layout_helper_header_size(Klass::array_layout_helper(elem));
2095     }
2096   }
2097 
2098   // Clear the object body, if necessary.
2099   if (init == nullptr) {
2100     // The init has somehow disappeared; be cautious and clear everything.
2101     //
2102     // This can happen if a node is allocated but an uncommon trap occurs
2103     // immediately.  In this case, the Initialize gets associated with the
2104     // trap, and may be placed in a different (outer) loop, if the Allocate
2105     // is in a loop.  If (this is rare) the inner loop gets unrolled, then
2106     // there can be two Allocates to one Initialize.  The answer in all these
2107     // edge cases is safety first.  It is always safe to clear immediately
2108     // within an Allocate, and then (maybe or maybe not) clear some more later.
2109     if (!(UseTLAB && ZeroTLAB)) {
2110       rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
2111                                             alloc->in(AllocateNode::InitValue),
2112                                             alloc->in(AllocateNode::RawInitValue),
2113                                             header_size, size_in_bytes,
2114                                             true,
2115                                             &_igvn);
2116     }
2117   } else {
2118     if (!init->is_complete()) {
2119       // Try to win by zeroing only what the init does not store.
2120       // We can also try to do some peephole optimizations,
2121       // such as combining some adjacent subword stores.
2122       rawmem = init->complete_stores(control, rawmem, object,
2123                                      header_size, size_in_bytes, &_igvn);
2124     }
2125     // We have no more use for this link, since the AllocateNode goes away:
2126     init->set_req(InitializeNode::RawAddress, top());
2127     // (If we keep the link, it just confuses the register allocator,
2128     // who thinks he sees a real use of the address by the membar.)
2129   }
2130 
2131   return rawmem;
2132 }

2267       for (intx i = 0; i < lines; i++) {
2268         prefetch_adr = AddPNode::make_off_heap(new_eden_top,
2269                                                _igvn.MakeConX(distance));
2270         transform_later(prefetch_adr);
2271         prefetch = new PrefetchAllocationNode(i_o, prefetch_adr);
2272         // Do not let it float too high, since if eden_top == eden_end,
2273         // both might be null.
2274         if (i == 0) { // Set control for first prefetch, next follows it
2275           prefetch->init_req(0, needgc_false);
2276         }
2277         transform_later(prefetch);
2278         distance += step_size;
2279         i_o = prefetch;
2280       }
2281    }
2282    return i_o;
2283 }
2284 
2285 
2286 void PhaseMacroExpand::expand_allocate(AllocateNode *alloc) {
2287   expand_allocate_common(alloc, nullptr, nullptr,
2288                          OptoRuntime::new_instance_Type(),
2289                          OptoRuntime::new_instance_Java(), nullptr);
2290 }
2291 
2292 void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) {
2293   Node* length = alloc->in(AllocateNode::ALength);
2294   Node* valid_length_test = alloc->in(AllocateNode::ValidLengthTest);
2295   InitializeNode* init = alloc->initialization();
2296   Node* klass_node = alloc->in(AllocateNode::KlassNode);
2297   Node* init_value = alloc->in(AllocateNode::InitValue);
2298   const TypeAryKlassPtr* ary_klass_t = _igvn.type(klass_node)->isa_aryklassptr();
2299   assert(!ary_klass_t || !ary_klass_t->klass_is_exact() || !ary_klass_t->exact_klass()->is_obj_array_klass() ||
2300          ary_klass_t->is_refined_type(), "Must be a refined array klass");
2301   const TypeFunc* slow_call_type;
2302   address slow_call_address;  // Address of slow call
2303   if (init != nullptr && init->is_complete_with_arraycopy() &&
2304       ary_klass_t && ary_klass_t->elem()->isa_klassptr() == nullptr) {
2305     // Don't zero type array during slow allocation in VM since
2306     // it will be initialized later by arraycopy in compiled code.
2307     slow_call_address = OptoRuntime::new_array_nozero_Java();
2308     slow_call_type = OptoRuntime::new_array_nozero_Type();
2309   } else {
2310     slow_call_address = OptoRuntime::new_array_Java();
2311     slow_call_type = OptoRuntime::new_array_Type();
2312 
2313     if (init_value == nullptr) {
2314       init_value = _igvn.zerocon(T_OBJECT);
2315     } else if (UseCompressedOops) {
2316       init_value = transform_later(new DecodeNNode(init_value, init_value->bottom_type()->make_ptr()));
2317     }
2318   }
2319   expand_allocate_common(alloc, length, init_value,
2320                          slow_call_type,
2321                          slow_call_address, valid_length_test);
2322 }
2323 
2324 //-------------------mark_eliminated_box----------------------------------
2325 //
2326 // During EA obj may point to several objects but after few ideal graph
2327 // transformations (CCP) it may point to only one non escaping object
2328 // (but still using phi), corresponding locks and unlocks will be marked
2329 // for elimination. Later obj could be replaced with a new node (new phi)
2330 // and which does not have escape information. And later after some graph
2331 // reshape other locks and unlocks (which were not marked for elimination
2332 // before) are connected to this new obj (phi) but they still will not be
2333 // marked for elimination since new obj has no escape information.
2334 // Mark all associated (same box and obj) lock and unlock nodes for
2335 // elimination if some of them marked already.
2336 void PhaseMacroExpand::mark_eliminated_box(Node* box, Node* obj) {
2337   BoxLockNode* oldbox = box->as_BoxLock();
2338   if (oldbox->is_eliminated()) {
2339     return; // This BoxLock node was processed already.
2340   }

2512 #ifdef ASSERT
2513   if (!alock->is_coarsened()) {
2514     // Check that new "eliminated" BoxLock node is created.
2515     BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2516     assert(oldbox->is_eliminated(), "should be done already");
2517   }
2518 #endif
2519 
2520   alock->log_lock_optimization(C, "eliminate_lock");
2521 
2522 #ifndef PRODUCT
2523   if (PrintEliminateLocks) {
2524     tty->print_cr("++++ Eliminated: %d %s '%s'", alock->_idx, (alock->is_Lock() ? "Lock" : "Unlock"), alock->kind_as_string());
2525   }
2526 #endif
2527 
2528   Node* mem  = alock->in(TypeFunc::Memory);
2529   Node* ctrl = alock->in(TypeFunc::Control);
2530   guarantee(ctrl != nullptr, "missing control projection, cannot replace_node() with null");
2531 
2532   _callprojs = alock->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
2533   // There are 2 projections from the lock.  The lock node will
2534   // be deleted when its last use is subsumed below.
2535   assert(alock->outcnt() == 2 &&
2536          _callprojs->fallthrough_proj != nullptr &&
2537          _callprojs->fallthrough_memproj != nullptr,
2538          "Unexpected projections from Lock/Unlock");
2539 
2540   Node* fallthroughproj = _callprojs->fallthrough_proj;
2541   Node* memproj_fallthrough = _callprojs->fallthrough_memproj;
2542 
2543   // The memory projection from a lock/unlock is RawMem
2544   // The input to a Lock is merged memory, so extract its RawMem input
2545   // (unless the MergeMem has been optimized away.)
2546   if (alock->is_Lock()) {
2547     // Search for MemBarAcquireLock node and delete it also.
2548     MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
2549     assert(membar != nullptr && membar->Opcode() == Op_MemBarAcquireLock, "");
2550     Node* ctrlproj = membar->proj_out(TypeFunc::Control);
2551     Node* memproj = membar->proj_out(TypeFunc::Memory);
2552     _igvn.replace_node(ctrlproj, fallthroughproj);
2553     _igvn.replace_node(memproj, memproj_fallthrough);
2554 
2555     // Delete FastLock node also if this Lock node is unique user
2556     // (a loop peeling may clone a Lock node).
2557     Node* flock = alock->as_Lock()->fastlock_node();
2558     if (flock->outcnt() == 1) {
2559       assert(flock->unique_out() == alock, "sanity");
2560       _igvn.replace_node(flock, top());
2561     }

2592   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2593 
2594   // Make the merge point
2595   Node *region;
2596   Node *mem_phi;
2597   Node *slow_path;
2598 
2599   region  = new RegionNode(3);
2600   // create a Phi for the memory state
2601   mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2602 
2603   // Optimize test; set region slot 2
2604   slow_path = opt_bits_test(ctrl, region, 2, flock);
2605   mem_phi->init_req(2, mem);
2606 
2607   // Make slow path call
2608   CallNode* call = make_slow_call(lock, OptoRuntime::complete_monitor_enter_Type(),
2609                                   OptoRuntime::complete_monitor_locking_Java(), nullptr, slow_path,
2610                                   obj, box, nullptr);
2611 
2612   _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
2613 
2614   // Slow path can only throw asynchronous exceptions, which are always
2615   // de-opted.  So the compiler thinks the slow-call can never throw an
2616   // exception.  If it DOES throw an exception we would need the debug
2617   // info removed first (since if it throws there is no monitor).
2618   assert(_callprojs->fallthrough_ioproj == nullptr && _callprojs->catchall_ioproj == nullptr &&
2619          _callprojs->catchall_memproj == nullptr && _callprojs->catchall_catchproj == nullptr, "Unexpected projection from Lock");
2620 
2621   // Capture slow path
2622   // disconnect fall-through projection from call and create a new one
2623   // hook up users of fall-through projection to region
2624   Node *slow_ctrl = _callprojs->fallthrough_proj->clone();
2625   transform_later(slow_ctrl);
2626   _igvn.hash_delete(_callprojs->fallthrough_proj);
2627   _callprojs->fallthrough_proj->disconnect_inputs(C);
2628   region->init_req(1, slow_ctrl);
2629   // region inputs are now complete
2630   transform_later(region);
2631   _igvn.replace_node(_callprojs->fallthrough_proj, region);
2632 
2633   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2634 
2635   mem_phi->init_req(1, memproj);
2636 
2637   transform_later(mem_phi);
2638 
2639   _igvn.replace_node(_callprojs->fallthrough_memproj, mem_phi);
2640 }
2641 
2642 //------------------------------expand_unlock_node----------------------
2643 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
2644 
2645   Node* ctrl = unlock->in(TypeFunc::Control);
2646   Node* mem = unlock->in(TypeFunc::Memory);
2647   Node* obj = unlock->obj_node();
2648   Node* box = unlock->box_node();
2649 
2650   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2651 
2652   // No need for a null check on unlock
2653 
2654   // Make the merge point
2655   Node* region = new RegionNode(3);
2656 
2657   FastUnlockNode *funlock = new FastUnlockNode( ctrl, obj, box );
2658   funlock = transform_later( funlock )->as_FastUnlock();
2659   // Optimize test; set region slot 2
2660   Node *slow_path = opt_bits_test(ctrl, region, 2, funlock);
2661   Node *thread = transform_later(new ThreadLocalNode());
2662 
2663   CallNode *call = make_slow_call((CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(),
2664                                   CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C),
2665                                   "complete_monitor_unlocking_C", slow_path, obj, box, thread);
2666 
2667   _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
2668   assert(_callprojs->fallthrough_ioproj == nullptr && _callprojs->catchall_ioproj == nullptr &&
2669          _callprojs->catchall_memproj == nullptr && _callprojs->catchall_catchproj == nullptr, "Unexpected projection from Lock");
2670 
2671   // No exceptions for unlocking
2672   // Capture slow path
2673   // disconnect fall-through projection from call and create a new one
2674   // hook up users of fall-through projection to region
2675   Node *slow_ctrl = _callprojs->fallthrough_proj->clone();
2676   transform_later(slow_ctrl);
2677   _igvn.hash_delete(_callprojs->fallthrough_proj);
2678   _callprojs->fallthrough_proj->disconnect_inputs(C);
2679   region->init_req(1, slow_ctrl);
2680   // region inputs are now complete
2681   transform_later(region);
2682   _igvn.replace_node(_callprojs->fallthrough_proj, region);
2683 
2684   if (_callprojs->fallthrough_memproj != nullptr) {
2685     // create a Phi for the memory state
2686     Node* mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2687     Node* memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2688     mem_phi->init_req(1, memproj);
2689     mem_phi->init_req(2, mem);
2690     transform_later(mem_phi);
2691     _igvn.replace_node(_callprojs->fallthrough_memproj, mem_phi);
2692   }
2693 }
2694 
2695 // An inline type might be returned from the call but we don't know its
2696 // type. Either we get a buffered inline type (and nothing needs to be done)
2697 // or one of the values being returned is the klass of the inline type
2698 // and we need to allocate an inline type instance of that type and
2699 // initialize it with other values being returned. In that case, we
2700 // first try a fast path allocation and initialize the value with the
2701 // inline klass's pack handler or we fall back to a runtime call.
2702 void PhaseMacroExpand::expand_mh_intrinsic_return(CallStaticJavaNode* call) {
2703   assert(call->method()->is_method_handle_intrinsic(), "must be a method handle intrinsic call");
2704   Node* ret = call->proj_out_or_null(TypeFunc::Parms);
2705   if (ret == nullptr) {
2706     return;
2707   }
2708   const TypeFunc* tf = call->_tf;
2709   const TypeTuple* domain = OptoRuntime::store_inline_type_fields_Type()->domain_cc();
2710   const TypeFunc* new_tf = TypeFunc::make(tf->domain_sig(), tf->domain_cc(), tf->range_sig(), domain);
2711   call->_tf = new_tf;
2712   // Make sure the change of type is applied before projections are processed by igvn
2713   _igvn.set_type(call, call->Value(&_igvn));
2714   _igvn.set_type(ret, ret->Value(&_igvn));
2715 
2716   // Before any new projection is added:
2717   CallProjections* projs = call->extract_projections(true, true);
2718 
2719   // Create temporary hook nodes that will be replaced below.
2720   // Add an input to prevent hook nodes from being dead.
2721   Node* ctl = new Node(call);
2722   Node* mem = new Node(ctl);
2723   Node* io = new Node(ctl);
2724   Node* ex_ctl = new Node(ctl);
2725   Node* ex_mem = new Node(ctl);
2726   Node* ex_io = new Node(ctl);
2727   Node* res = new Node(ctl);
2728 
2729   // Allocate a new buffered inline type only if a new one is not returned
2730   Node* cast = transform_later(new CastP2XNode(ctl, res));
2731   Node* mask = MakeConX(0x1);
2732   Node* masked = transform_later(new AndXNode(cast, mask));
2733   Node* cmp = transform_later(new CmpXNode(masked, mask));
2734   Node* bol = transform_later(new BoolNode(cmp, BoolTest::eq));
2735   IfNode* allocation_iff = new IfNode(ctl, bol, PROB_MAX, COUNT_UNKNOWN);
2736   transform_later(allocation_iff);
2737   Node* allocation_ctl = transform_later(new IfTrueNode(allocation_iff));
2738   Node* no_allocation_ctl = transform_later(new IfFalseNode(allocation_iff));
2739   Node* no_allocation_res = transform_later(new CheckCastPPNode(no_allocation_ctl, res, TypeInstPtr::BOTTOM));
2740 
2741   // Try to allocate a new buffered inline instance either from TLAB or eden space
2742   Node* needgc_ctrl = nullptr; // needgc means slowcase, i.e. allocation failed
2743   CallLeafNoFPNode* handler_call;
2744   const bool alloc_in_place = UseTLAB;
2745   if (alloc_in_place) {
2746     Node* fast_oop_ctrl = nullptr;
2747     Node* fast_oop_rawmem = nullptr;
2748     Node* mask2 = MakeConX(-2);
2749     Node* masked2 = transform_later(new AndXNode(cast, mask2));
2750     Node* rawklassptr = transform_later(new CastX2PNode(masked2));
2751     Node* klass_node = transform_later(new CheckCastPPNode(allocation_ctl, rawklassptr, TypeInstKlassPtr::OBJECT_OR_NULL));
2752     Node* layout_val = make_load_raw(nullptr, mem, klass_node, in_bytes(Klass::layout_helper_offset()), TypeInt::INT, T_INT);
2753     Node* size_in_bytes = ConvI2X(layout_val);
2754     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2755     Node* fast_oop = bs->obj_allocate(this, mem, allocation_ctl, size_in_bytes, io, needgc_ctrl,
2756                                       fast_oop_ctrl, fast_oop_rawmem,
2757                                       AllocateInstancePrefetchLines);
2758     // Allocation succeed, initialize buffered inline instance header firstly,
2759     // and then initialize its fields with an inline class specific handler
2760     Node* mark_word_node;
2761     if (UseCompactObjectHeaders) {
2762       // COH: We need to load the prototype from the klass at runtime since it encodes the klass pointer already.
2763       mark_word_node = make_load_raw(fast_oop_ctrl, fast_oop_rawmem, klass_node, in_bytes(Klass::prototype_header_offset()), TypeRawPtr::BOTTOM, T_ADDRESS);
2764     } else {
2765       // Otherwise, use the static prototype.
2766       mark_word_node = makecon(TypeRawPtr::make((address)markWord::inline_type_prototype().value()));
2767     }
2768 
2769     fast_oop_rawmem = make_store_raw(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::mark_offset_in_bytes(), mark_word_node, T_ADDRESS);
2770     if (!UseCompactObjectHeaders) {
2771       // COH: Everything is encoded in the mark word, so nothing left to do.
2772       fast_oop_rawmem = make_store_raw(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
2773       if (UseCompressedClassPointers) {
2774         fast_oop_rawmem = make_store_raw(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::klass_gap_offset_in_bytes(), intcon(0), T_INT);
2775       }
2776     }
2777     Node* members  = make_load_raw(fast_oop_ctrl, fast_oop_rawmem, klass_node, in_bytes(InlineKlass::adr_members_offset()), TypeRawPtr::BOTTOM, T_ADDRESS);
2778     Node* pack_handler = make_load_raw(fast_oop_ctrl, fast_oop_rawmem, members, in_bytes(InlineKlass::pack_handler_offset()), TypeRawPtr::BOTTOM, T_ADDRESS);
2779     handler_call = new CallLeafNoFPNode(OptoRuntime::pack_inline_type_Type(),
2780                                         nullptr,
2781                                         "pack handler",
2782                                         TypeRawPtr::BOTTOM);
2783     handler_call->init_req(TypeFunc::Control, fast_oop_ctrl);
2784     handler_call->init_req(TypeFunc::Memory, fast_oop_rawmem);
2785     handler_call->init_req(TypeFunc::I_O, top());
2786     handler_call->init_req(TypeFunc::FramePtr, call->in(TypeFunc::FramePtr));
2787     handler_call->init_req(TypeFunc::ReturnAdr, top());
2788     handler_call->init_req(TypeFunc::Parms, pack_handler);
2789     handler_call->init_req(TypeFunc::Parms+1, fast_oop);
2790   } else {
2791     needgc_ctrl = allocation_ctl;
2792   }
2793 
2794   // Allocation failed, fall back to a runtime call
2795   CallStaticJavaNode* slow_call = new CallStaticJavaNode(OptoRuntime::store_inline_type_fields_Type(),
2796                                                          StubRoutines::store_inline_type_fields_to_buf(),
2797                                                          "store_inline_type_fields",
2798                                                          TypePtr::BOTTOM);
2799   slow_call->init_req(TypeFunc::Control, needgc_ctrl);
2800   slow_call->init_req(TypeFunc::Memory, mem);
2801   slow_call->init_req(TypeFunc::I_O, io);
2802   slow_call->init_req(TypeFunc::FramePtr, call->in(TypeFunc::FramePtr));
2803   slow_call->init_req(TypeFunc::ReturnAdr, call->in(TypeFunc::ReturnAdr));
2804   slow_call->init_req(TypeFunc::Parms, res);
2805 
2806   Node* slow_ctl = transform_later(new ProjNode(slow_call, TypeFunc::Control));
2807   Node* slow_mem = transform_later(new ProjNode(slow_call, TypeFunc::Memory));
2808   Node* slow_io = transform_later(new ProjNode(slow_call, TypeFunc::I_O));
2809   Node* slow_res = transform_later(new ProjNode(slow_call, TypeFunc::Parms));
2810   Node* slow_catc = transform_later(new CatchNode(slow_ctl, slow_io, 2));
2811   Node* slow_norm = transform_later(new CatchProjNode(slow_catc, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci));
2812   Node* slow_excp = transform_later(new CatchProjNode(slow_catc, CatchProjNode::catch_all_index,    CatchProjNode::no_handler_bci));
2813 
2814   Node* ex_r = new RegionNode(3);
2815   Node* ex_mem_phi = new PhiNode(ex_r, Type::MEMORY, TypePtr::BOTTOM);
2816   Node* ex_io_phi = new PhiNode(ex_r, Type::ABIO);
2817   ex_r->init_req(1, slow_excp);
2818   ex_mem_phi->init_req(1, slow_mem);
2819   ex_io_phi->init_req(1, slow_io);
2820   ex_r->init_req(2, ex_ctl);
2821   ex_mem_phi->init_req(2, ex_mem);
2822   ex_io_phi->init_req(2, ex_io);
2823   transform_later(ex_r);
2824   transform_later(ex_mem_phi);
2825   transform_later(ex_io_phi);
2826 
2827   // We don't know how many values are returned. This assumes the
2828   // worst case, that all available registers are used.
2829   for (uint i = TypeFunc::Parms+1; i < domain->cnt(); i++) {
2830     if (domain->field_at(i) == Type::HALF) {
2831       slow_call->init_req(i, top());
2832       if (alloc_in_place) {
2833         handler_call->init_req(i+1, top());
2834       }
2835       continue;
2836     }
2837     Node* proj = transform_later(new ProjNode(call, i));
2838     slow_call->init_req(i, proj);
2839     if (alloc_in_place) {
2840       handler_call->init_req(i+1, proj);
2841     }
2842   }
2843   // We can safepoint at that new call
2844   slow_call->copy_call_debug_info(&_igvn, call);
2845   transform_later(slow_call);
2846   if (alloc_in_place) {
2847     transform_later(handler_call);
2848   }
2849 
2850   Node* fast_ctl = nullptr;
2851   Node* fast_res = nullptr;
2852   MergeMemNode* fast_mem = nullptr;
2853   if (alloc_in_place) {
2854     fast_ctl = transform_later(new ProjNode(handler_call, TypeFunc::Control));
2855     Node* rawmem = transform_later(new ProjNode(handler_call, TypeFunc::Memory));
2856     fast_res = transform_later(new ProjNode(handler_call, TypeFunc::Parms));
2857     fast_mem = MergeMemNode::make(mem);
2858     fast_mem->set_memory_at(Compile::AliasIdxRaw, rawmem);
2859     transform_later(fast_mem);
2860   }
2861 
2862   Node* r = new RegionNode(alloc_in_place ? 4 : 3);
2863   Node* mem_phi = new PhiNode(r, Type::MEMORY, TypePtr::BOTTOM);
2864   Node* io_phi = new PhiNode(r, Type::ABIO);
2865   Node* res_phi = new PhiNode(r, TypeInstPtr::BOTTOM);
2866   r->init_req(1, no_allocation_ctl);
2867   mem_phi->init_req(1, mem);
2868   io_phi->init_req(1, io);
2869   res_phi->init_req(1, no_allocation_res);
2870   r->init_req(2, slow_norm);
2871   mem_phi->init_req(2, slow_mem);
2872   io_phi->init_req(2, slow_io);
2873   res_phi->init_req(2, slow_res);
2874   if (alloc_in_place) {
2875     r->init_req(3, fast_ctl);
2876     mem_phi->init_req(3, fast_mem);
2877     io_phi->init_req(3, io);
2878     res_phi->init_req(3, fast_res);
2879   }
2880   transform_later(r);
2881   transform_later(mem_phi);
2882   transform_later(io_phi);
2883   transform_later(res_phi);
2884 
2885   // Do not let stores that initialize this buffer be reordered with a subsequent
2886   // store that would make this buffer accessible by other threads.
2887   MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
2888   transform_later(mb);
2889   mb->init_req(TypeFunc::Memory, mem_phi);
2890   mb->init_req(TypeFunc::Control, r);
2891   r = new ProjNode(mb, TypeFunc::Control);
2892   transform_later(r);
2893   mem_phi = new ProjNode(mb, TypeFunc::Memory);
2894   transform_later(mem_phi);
2895 
2896   assert(projs->nb_resproj == 1, "unexpected number of results");
2897   _igvn.replace_in_uses(projs->fallthrough_catchproj, r);
2898   _igvn.replace_in_uses(projs->fallthrough_memproj, mem_phi);
2899   _igvn.replace_in_uses(projs->fallthrough_ioproj, io_phi);
2900   _igvn.replace_in_uses(projs->resproj[0], res_phi);
2901   _igvn.replace_in_uses(projs->catchall_catchproj, ex_r);
2902   _igvn.replace_in_uses(projs->catchall_memproj, ex_mem_phi);
2903   _igvn.replace_in_uses(projs->catchall_ioproj, ex_io_phi);
2904   // The CatchNode should not use the ex_io_phi. Re-connect it to the catchall_ioproj.
2905   Node* cn = projs->fallthrough_catchproj->in(0);
2906   _igvn.replace_input_of(cn, 1, projs->catchall_ioproj);
2907 
2908   _igvn.replace_node(ctl, projs->fallthrough_catchproj);
2909   _igvn.replace_node(mem, projs->fallthrough_memproj);
2910   _igvn.replace_node(io, projs->fallthrough_ioproj);
2911   _igvn.replace_node(res, projs->resproj[0]);
2912   _igvn.replace_node(ex_ctl, projs->catchall_catchproj);
2913   _igvn.replace_node(ex_mem, projs->catchall_memproj);
2914   _igvn.replace_node(ex_io, projs->catchall_ioproj);
2915  }
2916 
2917 void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) {
2918   assert(check->in(SubTypeCheckNode::Control) == nullptr, "should be pinned");
2919   Node* bol = check->unique_out();
2920   Node* obj_or_subklass = check->in(SubTypeCheckNode::ObjOrSubKlass);
2921   Node* superklass = check->in(SubTypeCheckNode::SuperKlass);
2922   assert(bol->is_Bool() && bol->as_Bool()->_test._test == BoolTest::ne, "unexpected bool node");
2923 
2924   for (DUIterator_Last imin, i = bol->last_outs(imin); i >= imin; --i) {
2925     Node* iff = bol->last_out(i);
2926     assert(iff->is_If(), "where's the if?");
2927 
2928     if (iff->in(0)->is_top()) {
2929       _igvn.replace_input_of(iff, 1, C->top());
2930       continue;
2931     }
2932 
2933     IfTrueNode* iftrue = iff->as_If()->true_proj();
2934     IfFalseNode* iffalse = iff->as_If()->false_proj();
2935     Node* ctrl = iff->in(0);
2936 
2937     Node* subklass = nullptr;
2938     if (_igvn.type(obj_or_subklass)->isa_klassptr()) {
2939       subklass = obj_or_subklass;
2940     } else {
2941       Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes());
2942       subklass = _igvn.transform(LoadKlassNode::make(_igvn, C->immutable_memory(), k_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
2943     }
2944 
2945     Node* not_subtype_ctrl = Phase::gen_subtype_check(subklass, superklass, &ctrl, nullptr, _igvn, check->method(), check->bci());
2946 
2947     _igvn.replace_input_of(iff, 0, C->top());
2948     _igvn.replace_node(iftrue, not_subtype_ctrl);
2949     _igvn.replace_node(iffalse, ctrl);
2950   }
2951   _igvn.replace_node(check, C->top());
2952 }
2953 
2954 // FlatArrayCheckNode (array1 array2 ...) is expanded into:
2955 //
2956 // long mark = array1.mark | array2.mark | ...;
2957 // long locked_bit = markWord::unlocked_value & array1.mark & array2.mark & ...;
2958 // if (locked_bit == 0) {
2959 //   // One array is locked, load prototype header from the klass
2960 //   mark = array1.klass.proto | array2.klass.proto | ...
2961 // }
2962 // if ((mark & markWord::flat_array_bit_in_place) == 0) {
2963 //    ...
2964 // }
2965 void PhaseMacroExpand::expand_flatarraycheck_node(FlatArrayCheckNode* check) {
2966   bool array_inputs = _igvn.type(check->in(FlatArrayCheckNode::ArrayOrKlass))->isa_oopptr() != nullptr;
2967   if (array_inputs) {
2968     Node* mark = MakeConX(0);
2969     Node* locked_bit = MakeConX(markWord::unlocked_value);
2970     Node* mem = check->in(FlatArrayCheckNode::Memory);
2971     for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) {
2972       Node* ary = check->in(i);
2973       const TypeOopPtr* t = _igvn.type(ary)->isa_oopptr();
2974       assert(t != nullptr, "Mixing array and klass inputs");
2975       assert(!t->is_flat() && !t->is_not_flat(), "Should have been optimized out");
2976       Node* mark_adr = basic_plus_adr(ary, oopDesc::mark_offset_in_bytes());
2977       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));
2978       mark = _igvn.transform(new OrXNode(mark, mark_load));
2979       locked_bit = _igvn.transform(new AndXNode(locked_bit, mark_load));
2980     }
2981     assert(!mark->is_Con(), "Should have been optimized out");
2982     Node* cmp = _igvn.transform(new CmpXNode(locked_bit, MakeConX(0)));
2983     Node* is_unlocked = _igvn.transform(new BoolNode(cmp, BoolTest::ne));
2984 
2985     // BoolNode might be shared, replace each if user
2986     Node* old_bol = check->unique_out();
2987     assert(old_bol->is_Bool() && old_bol->as_Bool()->_test._test == BoolTest::ne, "unexpected condition");
2988     for (DUIterator_Last imin, i = old_bol->last_outs(imin); i >= imin; --i) {
2989       IfNode* old_iff = old_bol->last_out(i)->as_If();
2990       Node* ctrl = old_iff->in(0);
2991       RegionNode* region = new RegionNode(3);
2992       Node* mark_phi = new PhiNode(region, TypeX_X);
2993 
2994       // Check if array is unlocked
2995       IfNode* iff = _igvn.transform(new IfNode(ctrl, is_unlocked, PROB_MAX, COUNT_UNKNOWN))->as_If();
2996 
2997       // Unlocked: Use bits from mark word
2998       region->init_req(1, _igvn.transform(new IfTrueNode(iff)));
2999       mark_phi->init_req(1, mark);
3000 
3001       // Locked: Load prototype header from klass
3002       ctrl = _igvn.transform(new IfFalseNode(iff));
3003       Node* proto = MakeConX(0);
3004       for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) {
3005         Node* ary = check->in(i);
3006         // Make loads control dependent to make sure they are only executed if array is locked
3007         Node* klass_adr = basic_plus_adr(ary, oopDesc::klass_offset_in_bytes());
3008         Node* klass = _igvn.transform(LoadKlassNode::make(_igvn, C->immutable_memory(), klass_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
3009         Node* proto_adr = basic_plus_adr(top(), klass, in_bytes(Klass::prototype_header_offset()));
3010         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));
3011         proto = _igvn.transform(new OrXNode(proto, proto_load));
3012       }
3013       region->init_req(2, ctrl);
3014       mark_phi->init_req(2, proto);
3015 
3016       // Check if flat array bits are set
3017       Node* mask = MakeConX(markWord::flat_array_bit_in_place);
3018       Node* masked = _igvn.transform(new AndXNode(_igvn.transform(mark_phi), mask));
3019       cmp = _igvn.transform(new CmpXNode(masked, MakeConX(0)));
3020       Node* is_not_flat = _igvn.transform(new BoolNode(cmp, BoolTest::eq));
3021 
3022       ctrl = _igvn.transform(region);
3023       iff = _igvn.transform(new IfNode(ctrl, is_not_flat, PROB_MAX, COUNT_UNKNOWN))->as_If();
3024       _igvn.replace_node(old_iff, iff);
3025     }
3026     _igvn.replace_node(check, C->top());
3027   } else {
3028     // Fall back to layout helper check
3029     Node* lhs = intcon(0);
3030     for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) {
3031       Node* array_or_klass = check->in(i);
3032       Node* klass = nullptr;
3033       const TypePtr* t = _igvn.type(array_or_klass)->is_ptr();
3034       assert(!t->is_flat() && !t->is_not_flat(), "Should have been optimized out");
3035       if (t->isa_oopptr() != nullptr) {
3036         Node* klass_adr = basic_plus_adr(array_or_klass, oopDesc::klass_offset_in_bytes());
3037         klass = transform_later(LoadKlassNode::make(_igvn, C->immutable_memory(), klass_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
3038       } else {
3039         assert(t->isa_klassptr(), "Unexpected input type");
3040         klass = array_or_klass;
3041       }
3042       Node* lh_addr = basic_plus_adr(top(), klass, in_bytes(Klass::layout_helper_offset()));
3043       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));
3044       lhs = _igvn.transform(new OrINode(lhs, lh_val));
3045     }
3046     Node* masked = transform_later(new AndINode(lhs, intcon(Klass::_lh_array_tag_flat_value_bit_inplace)));
3047     Node* cmp = transform_later(new CmpINode(masked, intcon(0)));
3048     Node* bol = transform_later(new BoolNode(cmp, BoolTest::eq));
3049     Node* m2b = transform_later(new Conv2BNode(masked));
3050     // The matcher expects the input to If/CMove nodes to be produced by a Bool(CmpI..)
3051     // pattern, but the input to other potential users (e.g. Phi) to be some
3052     // other pattern (e.g. a Conv2B node, possibly idealized as a CMoveI).
3053     Node* old_bol = check->unique_out();
3054     for (DUIterator_Last imin, i = old_bol->last_outs(imin); i >= imin; --i) {
3055       Node* user = old_bol->last_out(i);
3056       for (uint j = 0; j < user->req(); j++) {
3057         Node* n = user->in(j);
3058         if (n == old_bol) {
3059           _igvn.replace_input_of(user, j, (user->is_If() || user->is_CMove()) ? bol : m2b);
3060         }
3061       }
3062     }
3063     _igvn.replace_node(check, C->top());
3064   }
3065 }
3066 
3067 // Perform refining of strip mined loop nodes in the macro nodes list.
3068 void PhaseMacroExpand::refine_strip_mined_loop_macro_nodes() {
3069    for (int i = C->macro_count(); i > 0; i--) {
3070     Node* n = C->macro_node(i - 1);
3071     if (n->is_OuterStripMinedLoop()) {
3072       n->as_OuterStripMinedLoop()->adjust_strip_mined_loop(&_igvn);
3073     }
3074   }
3075 }
3076 
3077 //---------------------------eliminate_macro_nodes----------------------
3078 // Eliminate scalar replaced allocations and associated locks.
3079 void PhaseMacroExpand::eliminate_macro_nodes(bool eliminate_locks) {
3080   if (C->macro_count() == 0) {
3081     return;
3082   }
3083 
3084   if (StressMacroElimination) {
3085     C->shuffle_macro_nodes();
3086   }
3087   NOT_PRODUCT(int membar_before = count_MemBar(C);)
3088 
3089   int iteration = 0;
3090   while (C->macro_count() > 0) {
3091     if (iteration++ > 100) {
3092       assert(false, "Too slow convergence of macro elimination");
3093       break;


3094     }










3095 
3096     // Postpone lock elimination to after EA when most allocations are eliminated
3097     // because they might block lock elimination if their escape state isn't
3098     // determined yet and we only got one chance at eliminating the lock.
3099     if (eliminate_locks) {
3100       // Before elimination may re-mark (change to Nested or NonEscObj)
3101       // all associated (same box and obj) lock and unlock nodes.
3102       int cnt = C->macro_count();
3103       for (int i=0; i < cnt; i++) {
3104         Node *n = C->macro_node(i);
3105         if (n->is_AbstractLock()) { // Lock and Unlock nodes
3106           mark_eliminated_locking_nodes(n->as_AbstractLock());


3107         }

3108       }
3109       // Re-marking may break consistency of Coarsened locks.
3110       if (!C->coarsened_locks_consistent()) {
3111         return; // recompile without Coarsened locks if broken
3112       } else {
3113         // After coarsened locks are eliminated locking regions
3114         // become unbalanced. We should not execute any more
3115         // locks elimination optimizations on them.
3116         C->mark_unbalanced_boxes();
3117       }
3118     }
3119 
3120     bool progress = false;



3121     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
3122       Node* n = C->macro_node(i - 1);
3123       bool success = false;
3124       DEBUG_ONLY(int old_macro_count = C->macro_count();)
3125       switch (n->class_id()) {
3126       case Node::Class_Allocate:
3127       case Node::Class_AllocateArray:
3128         success = eliminate_allocate_node(n->as_Allocate());
3129 #ifndef PRODUCT
3130         if (success && PrintOptoStatistics) {
3131           AtomicAccess::inc(&PhaseMacroExpand::_objs_scalar_replaced_counter);
3132         }
3133 #endif
3134         break;
3135       case Node::Class_CallStaticJava: {
3136         CallStaticJavaNode* call = n->as_CallStaticJava();
3137         if (!call->method()->is_method_handle_intrinsic()) {
3138           success = eliminate_boxing_node(n->as_CallStaticJava());
3139         }
3140         break;
3141       }
3142       case Node::Class_Lock:
3143       case Node::Class_Unlock:
3144         if (eliminate_locks) {
3145           success = eliminate_locking_node(n->as_AbstractLock());
3146 #ifndef PRODUCT
3147           if (success && PrintOptoStatistics) {
3148             AtomicAccess::inc(&PhaseMacroExpand::_monitor_objects_removed_counter);
3149           }
3150 #endif
3151         }
3152         break;
3153       case Node::Class_ArrayCopy:
3154         break;
3155       case Node::Class_OuterStripMinedLoop:
3156         break;
3157       case Node::Class_SubTypeCheck:
3158         break;
3159       case Node::Class_Opaque1:
3160         break;
3161       case Node::Class_FlatArrayCheck:
3162         break;
3163       default:
3164         assert(n->Opcode() == Op_LoopLimit ||
3165                n->Opcode() == Op_ModD ||
3166                n->Opcode() == Op_ModF ||
3167                n->Opcode() == Op_PowD ||
3168                n->is_OpaqueConstantBool()    ||
3169                n->is_OpaqueInitializedAssertionPredicate() ||
3170                n->Opcode() == Op_MaxL      ||
3171                n->Opcode() == Op_MinL      ||
3172                BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
3173                "unknown node type in macro list");
3174       }
3175       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
3176       progress = progress || success;
3177       if (success) {
3178         C->print_method(PHASE_AFTER_MACRO_ELIMINATION_STEP, 5, n);
3179       }
3180     }
3181 
3182     // Ensure the graph after PhaseMacroExpand::eliminate_macro_nodes is canonical (no igvn
3183     // transformation is pending). If an allocation is used only in safepoints, elimination of
3184     // other macro nodes can remove all these safepoints, allowing the allocation to be removed.
3185     // Hence after igvn we retry removing macro nodes if some progress that has been made in this
3186     // iteration.
3187     _igvn.set_delay_transform(false);
3188     _igvn.optimize();
3189     if (C->failing()) {
3190       return;
3191     }
3192     _igvn.set_delay_transform(true);
3193 
3194     if (!progress) {
3195       break;
3196     }
3197   }
3198 #ifndef PRODUCT
3199   if (PrintOptoStatistics) {
3200     int membar_after = count_MemBar(C);
3201     AtomicAccess::add(&PhaseMacroExpand::_memory_barriers_removed_counter, membar_before - membar_after);
3202   }
3203 #endif
3204 }
3205 
3206 void PhaseMacroExpand::eliminate_opaque_looplimit_macro_nodes() {
3207   if (C->macro_count() == 0) {
3208     return;
3209   }
3210   refine_strip_mined_loop_macro_nodes();
3211   // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
3212   bool progress = true;
3213   while (progress) {
3214     progress = false;
3215     for (int i = C->macro_count(); i > 0; i--) {
3216       Node* n = C->macro_node(i-1);
3217       bool success = false;
3218       DEBUG_ONLY(int old_macro_count = C->macro_count();)
3219       if (n->Opcode() == Op_LoopLimit) {
3220         // Remove it from macro list and put on IGVN worklist to optimize.
3221         C->remove_macro_node(n);
3222         _igvn._worklist.push(n);
3223         success = true;
3224       } else if (n->Opcode() == Op_CallStaticJava) {
3225         CallStaticJavaNode* call = n->as_CallStaticJava();
3226         if (!call->method()->is_method_handle_intrinsic()) {
3227           // Remove it from macro list and put on IGVN worklist to optimize.
3228           C->remove_macro_node(n);
3229           _igvn._worklist.push(n);
3230           success = true;
3231         }
3232       } else if (n->is_Opaque1()) {
3233         _igvn.replace_node(n, n->in(1));
3234         success = true;
3235       } else if (n->is_OpaqueConstantBool()) {
3236         // Tests with OpaqueConstantBool nodes are implicitly known. Replace the node with true/false. In debug builds,
3237         // we leave the test in the graph to have an additional sanity check at runtime. If the test fails (i.e. a bug),
3238         // we will execute a Halt node.
3239 #ifdef ASSERT
3240         _igvn.replace_node(n, n->in(1));
3241 #else
3242         _igvn.replace_node(n, _igvn.intcon(n->as_OpaqueConstantBool()->constant()));
3243 #endif
3244         success = true;
3245       } else if (n->is_OpaqueInitializedAssertionPredicate()) {
3246           // Initialized Assertion Predicates must always evaluate to true. Therefore, we get rid of them in product
3247           // builds as they are useless. In debug builds we keep them as additional verification code. Even though
3248           // loop opts are already over, we want to keep Initialized Assertion Predicates alive as long as possible to
3249           // enable folding of dead control paths within which cast nodes become top after due to impossible types -
3250           // even after loop opts are over. Therefore, we delay the removal of these opaque nodes until now.
3251 #ifdef ASSERT

3320     // Worst case is a macro node gets expanded into about 200 nodes.
3321     // Allow 50% more for optimization.
3322     if (C->check_node_count(300, "out of nodes before macro expansion")) {
3323       return true;
3324     }
3325 
3326     DEBUG_ONLY(int old_macro_count = C->macro_count();)
3327     switch (n->class_id()) {
3328     case Node::Class_Lock:
3329       expand_lock_node(n->as_Lock());
3330       break;
3331     case Node::Class_Unlock:
3332       expand_unlock_node(n->as_Unlock());
3333       break;
3334     case Node::Class_ArrayCopy:
3335       expand_arraycopy_node(n->as_ArrayCopy());
3336       break;
3337     case Node::Class_SubTypeCheck:
3338       expand_subtypecheck_node(n->as_SubTypeCheck());
3339       break;
3340     case Node::Class_CallStaticJava:
3341       expand_mh_intrinsic_return(n->as_CallStaticJava());
3342       C->remove_macro_node(n);
3343       break;
3344     case Node::Class_FlatArrayCheck:
3345       expand_flatarraycheck_node(n->as_FlatArrayCheck());
3346       break;
3347     default:
3348       switch (n->Opcode()) {
3349       case Op_ModD:
3350       case Op_ModF:
3351       case Op_PowD: {
3352         CallLeafPureNode* call_macro = n->as_CallLeafPure();
3353         CallLeafPureNode* call = call_macro->inline_call_leaf_pure_node();
3354         _igvn.replace_node(call_macro, call);
3355         transform_later(call);
3356         break;
3357       }
3358       default:
3359         assert(false, "unknown node type in macro list");
3360       }
3361     }
3362     assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
3363     if (C->failing())  return true;
3364     C->print_method(PHASE_AFTER_MACRO_EXPANSION_STEP, 5, n);
3365 
3366     // Clean up the graph so we're less likely to hit the maximum node
< prev index next >