< 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(new AddPNode(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(new AddPNode(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(new AddPNode(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.

 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;

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

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

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






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

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


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

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

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



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

1985   } else {
1986     slow_call_address = OptoRuntime::new_array_Java();







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

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

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
















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



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

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







2656     default:
2657       switch (n->Opcode()) {
2658       case Op_ModD:
2659       case Op_ModF: {
2660         CallNode* mod_macro = n->as_Call();
2661         CallNode* call = new CallLeafPureNode(mod_macro->tf(), mod_macro->entry_point(),
2662                                               mod_macro->_name, TypeRawPtr::BOTTOM);
2663         call->init_req(TypeFunc::Control, mod_macro->in(TypeFunc::Control));
2664         call->init_req(TypeFunc::I_O, C->top());
2665         call->init_req(TypeFunc::Memory, C->top());
2666         call->init_req(TypeFunc::ReturnAdr, C->top());
2667         call->init_req(TypeFunc::FramePtr, C->top());
2668         for (unsigned int i = 0; i < mod_macro->tf()->domain()->cnt() - TypeFunc::Parms; i++) {
2669           call->init_req(TypeFunc::Parms + i, mod_macro->in(TypeFunc::Parms + i));
2670         }
2671         _igvn.replace_node(mod_macro, call);
2672         transform_later(call);
2673         break;
2674       }
2675       default:
2676         assert(false, "unknown node type in macro list");
2677       }
2678     }
2679     assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2680     if (C->failing())  return true;
2681     C->print_method(PHASE_AFTER_MACRO_EXPANSION_STEP, 5, n);
2682 
2683     // Clean up the graph so we're less likely to hit the maximum node
2684     // limit
2685     _igvn.set_delay_transform(false);
2686     _igvn.optimize();
2687     if (C->failing())  return true;
2688     _igvn.set_delay_transform(true);

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











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

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

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

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

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

 296         adr = _igvn.transform(new AddPNode(base, base, _igvn.MakeConX(off)));
 297         adr_type = _igvn.type(adr)->is_aryptr();
 298         assert(adr_type == _igvn.type(base)->is_aryptr()->add_field_offset_and_offset(off), "incorrect address type");
 299         if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 300           // Don't emit a new load from src if src == dst but try to get the value from memory instead
 301           return value_from_mem(ac->in(TypeFunc::Memory), ctl, ft, ftype, adr_type, alloc);
 302         }
 303       } else {
 304         if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 305           // Non constant offset in the array: we can't statically
 306           // determine the value
 307           return nullptr;
 308         }
 309         Node* diff = _igvn.transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
 310 #ifdef _LP64
 311         diff = _igvn.transform(new ConvI2LNode(diff));
 312 #endif
 313         diff = _igvn.transform(new LShiftXNode(diff, _igvn.intcon(shift)));
 314 
 315         Node* off = _igvn.transform(new AddXNode(_igvn.MakeConX(offset), diff));

 316         adr = _igvn.transform(new AddPNode(base, base, off));
 317         // In the case of a flat inline type array, each field has its
 318         // own slice so we need to extract the field being accessed from
 319         // the address computation
 320         adr_type = adr_type->add_field_offset_and_offset(offset)->add_offset(Type::OffsetBot)->is_aryptr();
 321         adr = _igvn.transform(new CastPPNode(ctl, adr, adr_type));

 322       }
 323       MergeMemNode* mergemen = _igvn.transform(MergeMemNode::make(mem))->as_MergeMem();
 324       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 325       res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
 326     }
 327   }
 328   if (res != nullptr) {
 329     if (ftype->isa_narrowoop()) {
 330       // PhaseMacroExpand::scalar_replacement adds DecodeN nodes
 331       assert(res->isa_DecodeN(), "should be narrow oop");
 332       res = _igvn.transform(new EncodePNode(res, ftype));
 333     }
 334     return res;
 335   }
 336   return nullptr;
 337 }
 338 
 339 //
 340 // Given a Memory Phi, compute a value Phi containing the values from stores
 341 // on the input paths.
 342 // Note: this function is recursive, its depth is limited by the "level" argument
 343 // Returns the computed Phi, or null if it cannot compute it.
 344 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) {
 345   assert(mem->is_Phi(), "sanity");
 346   int alias_idx = C->get_alias_index(adr_t);
 347   int offset = adr_t->flat_offset();
 348   int instance_id = adr_t->instance_id();
 349 
 350   // Check if an appropriate value phi already exists.
 351   Node* region = mem->in(0);
 352   for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) {
 353     Node* phi = region->fast_out(k);
 354     if (phi->is_Phi() && phi != mem &&
 355         phi->as_Phi()->is_same_inst_field(phi_type, (int)mem->_idx, instance_id, alias_idx, offset)) {
 356       return phi;
 357     }
 358   }
 359   // Check if an appropriate new value phi already exists.
 360   Node* new_phi = value_phis->find(mem->_idx);
 361   if (new_phi != nullptr)
 362     return new_phi;
 363 
 364   if (level <= 0) {
 365     return nullptr; // Give up: phi tree too deep
 366   }
 367   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
 368   Node *alloc_mem = alloc->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false);
 369   assert(alloc_mem != nullptr, "Allocation without a memory projection.");
 370 
 371   uint length = mem->req();
 372   GrowableArray <Node *> values(length, length, nullptr);
 373 
 374   // create a new Phi for the value
 375   PhiNode *phi = new PhiNode(mem->in(0), phi_type, nullptr, mem->_idx, instance_id, alias_idx, offset);
 376   transform_later(phi);
 377   value_phis->push(phi, mem->_idx);
 378 
 379   for (uint j = 1; j < length; j++) {
 380     Node *in = mem->in(j);
 381     if (in == nullptr || in->is_top()) {
 382       values.at_put(j, in);
 383     } else {
 384       Node *val = scan_mem_chain(in, alias_idx, offset, start_mem, alloc, &_igvn);
 385       if (val == start_mem || val == alloc_mem) {
 386         // hit a sentinel, return appropriate value
 387         Node* init_value = alloc->in(AllocateNode::InitValue);
 388         if (init_value != nullptr) {
 389           if (val == start_mem) {
 390             // TODO 8350865 Scalar replacement does not work well for flat arrays.
 391             // Somehow we ended up with root mem and therefore walked past the alloc. Fix this. Triggered by TestGenerated::test15
 392             // Don't we need field_value_by_offset?
 393             return nullptr;
 394           }
 395           values.at_put(j, init_value);
 396         } else {
 397           assert(alloc->in(AllocateNode::RawInitValue) == nullptr, "init value may not be null");
 398           values.at_put(j, _igvn.zerocon(ft));
 399         }
 400         continue;
 401       }
 402       if (val->is_Initialize()) {
 403         val = val->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 404       }
 405       if (val == nullptr) {
 406         return nullptr;  // can't find a value on this path
 407       }
 408       if (val == mem) {
 409         values.at_put(j, mem);
 410       } else if (val->is_Store()) {
 411         Node* n = val->in(MemNode::ValueIn);
 412         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 413         n = bs->step_over_gc_barrier(n);
 414         if (is_subword_type(ft)) {
 415           n = Compile::narrow_value(ft, n, phi_type, &_igvn, true);
 416         }
 417         values.at_put(j, n);
 418       } else if (val->is_Proj() && val->in(0) == alloc) {
 419         Node* init_value = alloc->in(AllocateNode::InitValue);
 420         if (init_value != nullptr) {
 421           // TODO 8350865 Scalar replacement does not work well for flat arrays.
 422           // Is this correct for non-all-zero init values? Don't we need field_value_by_offset?
 423           values.at_put(j, init_value);
 424         } else {
 425           assert(alloc->in(AllocateNode::RawInitValue) == nullptr, "init value may not be null");
 426           values.at_put(j, _igvn.zerocon(ft));
 427         }
 428       } else if (val->is_Phi()) {
 429         val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, value_phis, level-1);
 430         if (val == nullptr) {
 431           return nullptr;
 432         }
 433         values.at_put(j, val);
 434       } else if (val->Opcode() == Op_SCMemProj) {
 435         assert(val->in(0)->is_LoadStore() ||
 436                val->in(0)->Opcode() == Op_EncodeISOArray ||
 437                val->in(0)->Opcode() == Op_StrCompressedCopy, "sanity");
 438         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
 439         return nullptr;
 440       } else if (val->is_ArrayCopy()) {
 441         Node* res = make_arraycopy_load(val->as_ArrayCopy(), offset, val->in(0), val->in(TypeFunc::Memory), ft, phi_type, alloc);
 442         if (res == nullptr) {
 443           return nullptr;
 444         }
 445         values.at_put(j, res);
 446       } else if (val->is_top()) {
 447         // This indicates that this path into the phi is dead. Top will eventually also propagate into the Region.

 455     }
 456   }
 457   // Set Phi's inputs
 458   for (uint j = 1; j < length; j++) {
 459     if (values.at(j) == mem) {
 460       phi->init_req(j, phi);
 461     } else {
 462       phi->init_req(j, values.at(j));
 463     }
 464   }
 465   return phi;
 466 }
 467 
 468 // Search the last value stored into the object's field.
 469 Node *PhaseMacroExpand::value_from_mem(Node *sfpt_mem, Node *sfpt_ctl, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, AllocateNode *alloc) {
 470   assert(adr_t->is_known_instance_field(), "instance required");
 471   int instance_id = adr_t->instance_id();
 472   assert((uint)instance_id == alloc->_idx, "wrong allocation");
 473 
 474   int alias_idx = C->get_alias_index(adr_t);
 475   int offset = adr_t->flat_offset();
 476   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);

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

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


1070   const TypeOopPtr* res_type = nullptr;
1071   int nfields                = 0;


1072   uint first_ind             = (sfpt->req() - sfpt->jvms()->scloff());
1073   Node* res                  = alloc->result_cast();
1074 
1075   assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");
1076   assert(sfpt->jvms() != nullptr, "missed JVMS");
1077   uint before_sfpt_req = sfpt->req();
1078 
1079   if (res != nullptr) { // Could be null when there are no users
1080     res_type = _igvn.type(res)->isa_oopptr();
1081 
1082     if (res_type->isa_instptr()) {
1083       // find the fields of the class which will be needed for safepoint debug information
1084       iklass = res_type->is_instptr()->instance_klass();
1085       nfields = iklass->nof_nonstatic_fields();
1086     } else {
1087       // find the array's elements which will be needed for safepoint debug information
1088       nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
1089       assert(nfields >= 0, "must be an array klass.");
1090     }
1091 
1092     if (res->bottom_type()->is_inlinetypeptr()) {
1093       // Nullable inline types have a null marker field which is added to the safepoint when scalarizing them (see
1094       // InlineTypeNode::make_scalar_in_safepoint()). When having circular inline types, we stop scalarizing at depth 1
1095       // to avoid an endless recursion. Therefore, we do not have a SafePointScalarObjectNode node here, yet.
1096       // We are about to create a SafePointScalarObjectNode as if this is a normal object. Add an additional int input
1097       // with value 1 which sets the null marker to true to indicate that the object is always non-null. This input is checked
1098       // later in PhaseOutput::filLocArray() for inline types.
1099       sfpt->add_req(_igvn.intcon(1));
1100     }
1101   }
1102 
1103   SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(res_type, alloc, first_ind, sfpt->jvms()->depth(), nfields);
1104   sobj->init_req(0, C->root());
1105   transform_later(sobj);
1106 
1107   if (res == nullptr) {
1108     sfpt->jvms()->set_endoff(sfpt->req());
1109     return sobj;
1110   }




























































1111 
1112   bool success;
1113   if (iklass == nullptr) {
1114     success = add_array_elems_to_safepoint(alloc, res_type->is_aryptr(), sfpt, value_worklist);
1115   } else {
1116     success = add_inst_fields_to_safepoint(iklass, alloc, res, 0, sfpt, value_worklist);
1117   }
1118 
1119   // We weren't able to find a value for this field, remove all the fields added to the safepoint
1120   if (!success) {
1121     for (uint i = sfpt->req() - 1; i >= before_sfpt_req; i--) {
1122       sfpt->del_req(i);




1123     }
1124     _igvn._worklist.push(sfpt);
1125     return nullptr;
1126   }
1127 
1128   sfpt->jvms()->set_endoff(sfpt->req());

1129   return sobj;
1130 }
1131 
1132 // Do scalar replacement.
1133 bool PhaseMacroExpand::scalar_replacement(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
1134   GrowableArray <SafePointNode *> safepoints_done;
1135   Node* res = alloc->result_cast();
1136   assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");
1137   const TypeOopPtr* res_type = nullptr;
1138   if (res != nullptr) { // Could be null when there are no users
1139     res_type = _igvn.type(res)->isa_oopptr();
1140   }
1141 
1142   // Process the safepoint uses
1143   Unique_Node_List value_worklist;
1144   while (safepoints.length() > 0) {
1145     SafePointNode* sfpt = safepoints.pop();
1146     SafePointScalarObjectNode* sobj = create_scalarized_object_description(alloc, sfpt, &value_worklist);
1147 
1148     if (sobj == nullptr) {
1149       undo_previous_scalarizations(safepoints_done, alloc);
1150       return false;
1151     }
1152 
1153     // Now make a pass over the debug information replacing any references
1154     // to the allocated object with "sobj"
1155     JVMState *jvms = sfpt->jvms();
1156     sfpt->replace_edges_in_range(res, sobj, jvms->debug_start(), jvms->debug_end(), &_igvn);
1157     _igvn._worklist.push(sfpt);
1158 
1159     // keep it for rollback
1160     safepoints_done.append_if_missing(sfpt);
1161   }
1162   // Scalarize inline types that were added to the safepoint.
1163   // Don't allow linking a constant oop (if available) for flat array elements
1164   // because Deoptimization::reassign_flat_array_elements needs field values.
1165   bool allow_oop = (res_type != nullptr) && !res_type->is_flat();
1166   for (uint i = 0; i < value_worklist.size(); ++i) {
1167     InlineTypeNode* vt = value_worklist.at(i)->as_InlineType();
1168     vt->make_scalar_in_safepoints(&_igvn, allow_oop);
1169   }
1170   return true;
1171 }
1172 
1173 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) {
1174   Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control);
1175   Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory);
1176   if (ctl_proj != nullptr) {
1177     igvn.replace_node(ctl_proj, n->in(0));
1178   }
1179   if (mem_proj != nullptr) {
1180     igvn.replace_node(mem_proj, n->in(TypeFunc::Memory));
1181   }
1182 }
1183 
1184 // Process users of eliminated allocation.
1185 void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc, bool inline_alloc) {
1186   Unique_Node_List worklist;
1187   Node* res = alloc->result_cast();
1188   if (res != nullptr) {
1189     worklist.push(res);
1190   }
1191   while (worklist.size() > 0) {
1192     res = worklist.pop();
1193     for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
1194       Node *use = res->last_out(j);
1195       uint oc1 = res->outcnt();
1196 
1197       if (use->is_AddP()) {
1198         for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
1199           Node *n = use->last_out(k);
1200           uint oc2 = use->outcnt();
1201           if (n->is_Store()) {
1202             for (DUIterator_Fast pmax, p = n->fast_outs(pmax); p < pmax; p++) {
1203               MemBarNode* mb = n->fast_out(p)->isa_MemBar();
1204               if (mb != nullptr && mb->req() <= MemBarNode::Precedent && mb->in(MemBarNode::Precedent) == n) {
1205                 // MemBarVolatiles should have been removed by MemBarNode::Ideal() for non-inline allocations
1206                 assert(inline_alloc, "MemBarVolatile should be eliminated for non-escaping object");
1207                 mb->remove(&_igvn);
1208               }



1209             }

1210             _igvn.replace_node(n, n->in(MemNode::Memory));
1211           } else {
1212             eliminate_gc_barrier(n);
1213           }
1214           k -= (oc2 - use->outcnt());
1215         }
1216         _igvn.remove_dead_node(use);
1217       } else if (use->is_ArrayCopy()) {
1218         // Disconnect ArrayCopy node
1219         ArrayCopyNode* ac = use->as_ArrayCopy();
1220         if (ac->is_clonebasic()) {
1221           Node* membar_after = ac->proj_out(TypeFunc::Control)->unique_ctrl_out();
1222           disconnect_projections(ac, _igvn);
1223           assert(alloc->in(TypeFunc::Memory)->is_Proj() && alloc->in(TypeFunc::Memory)->in(0)->Opcode() == Op_MemBarCPUOrder, "mem barrier expected before allocation");
1224           Node* membar_before = alloc->in(TypeFunc::Memory)->in(0);
1225           disconnect_projections(membar_before->as_MemBar(), _igvn);
1226           if (membar_after->is_MemBar()) {
1227             disconnect_projections(membar_after->as_MemBar(), _igvn);
1228           }
1229         } else {
1230           assert(ac->is_arraycopy_validated() ||
1231                  ac->is_copyof_validated() ||
1232                  ac->is_copyofrange_validated(), "unsupported");
1233           CallProjections* callprojs = ac->extract_projections(true);

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

1529 // oop flavor.
1530 //
1531 //=============================================================================
1532 // FastAllocateSizeLimit value is in DOUBLEWORDS.
1533 // Allocations bigger than this always go the slow route.
1534 // This value must be small enough that allocation attempts that need to
1535 // trigger exceptions go the slow route.  Also, it must be small enough so
1536 // that heap_top + size_in_bytes does not wrap around the 4Gig limit.
1537 //=============================================================================j//
1538 // %%% Here is an old comment from parseHelper.cpp; is it outdated?
1539 // The allocator will coalesce int->oop copies away.  See comment in
1540 // coalesce.cpp about how this works.  It depends critically on the exact
1541 // code shape produced here, so if you are changing this code shape
1542 // make sure the GC info for the heap-top is correct in and around the
1543 // slow-path call.
1544 //
1545 
1546 void PhaseMacroExpand::expand_allocate_common(
1547             AllocateNode* alloc, // allocation node to be expanded
1548             Node* length,  // array length for an array allocation
1549             Node* init_val, // value to initialize the array with
1550             const TypeFunc* slow_call_type, // Type of slow call
1551             address slow_call_address,  // Address of slow call
1552             Node* valid_length_test // whether length is valid or not
1553     )
1554 {
1555   Node* ctrl = alloc->in(TypeFunc::Control);
1556   Node* mem  = alloc->in(TypeFunc::Memory);
1557   Node* i_o  = alloc->in(TypeFunc::I_O);
1558   Node* size_in_bytes     = alloc->in(AllocateNode::AllocSize);
1559   Node* klass_node        = alloc->in(AllocateNode::KlassNode);
1560   Node* initial_slow_test = alloc->in(AllocateNode::InitialTest);
1561   assert(ctrl != nullptr, "must have control");
1562 
1563   // We need a Region and corresponding Phi's to merge the slow-path and fast-path results.
1564   // they will not be used if "always_slow" is set
1565   enum { slow_result_path = 1, fast_result_path = 2 };
1566   Node *result_region = nullptr;
1567   Node *result_phi_rawmem = nullptr;
1568   Node *result_phi_rawoop = nullptr;
1569   Node *result_phi_i_o = nullptr;

1612 #endif
1613       yank_alloc_node(alloc);
1614       return;
1615     }
1616   }
1617 
1618   enum { too_big_or_final_path = 1, need_gc_path = 2 };
1619   Node *slow_region = nullptr;
1620   Node *toobig_false = ctrl;
1621 
1622   // generate the initial test if necessary
1623   if (initial_slow_test != nullptr ) {
1624     assert (expand_fast_path, "Only need test if there is a fast path");
1625     slow_region = new RegionNode(3);
1626 
1627     // Now make the initial failure test.  Usually a too-big test but
1628     // might be a TRUE for finalizers.
1629     IfNode *toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1630     transform_later(toobig_iff);
1631     // Plug the failing-too-big test into the slow-path region
1632     Node* toobig_true = new IfTrueNode(toobig_iff);
1633     transform_later(toobig_true);
1634     slow_region    ->init_req( too_big_or_final_path, toobig_true );
1635     toobig_false = new IfFalseNode(toobig_iff);
1636     transform_later(toobig_false);
1637   } else {
1638     // No initial test, just fall into next case
1639     assert(allocation_has_use || !expand_fast_path, "Should already have been handled");
1640     toobig_false = ctrl;
1641     DEBUG_ONLY(slow_region = NodeSentinel);
1642   }
1643 
1644   // If we are here there are several possibilities
1645   // - expand_fast_path is false - then only a slow path is expanded. That's it.
1646   // no_initial_check means a constant allocation.
1647   // - If check always evaluates to false -> expand_fast_path is false (see above)
1648   // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath)
1649   // if !allocation_has_use the fast path is empty
1650   // if !allocation_has_use && no_initial_check
1651   // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all.
1652   //   removed by yank_alloc_node above.
1653 
1654   Node *slow_mem = mem;  // save the current memory state for slow path
1655   // generate the fast allocation code unless we know that the initial test will always go slow
1656   if (expand_fast_path) {
1657     // Fast path modifies only raw memory.
1658     if (mem->is_MergeMem()) {
1659       mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1660     }
1661 
1662     // allocate the Region and Phi nodes for the result
1663     result_region = new RegionNode(3);
1664     result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1665     result_phi_i_o    = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1666 
1667     // Grab regular I/O before optional prefetch may change it.
1668     // Slow-path does no I/O so just set it to the original I/O.
1669     result_phi_i_o->init_req(slow_result_path, i_o);
1670 
1671     // Name successful fast-path variables
1672     Node* fast_oop_ctrl;
1673     Node* fast_oop_rawmem;
1674 
1675     if (allocation_has_use) {
1676       Node* needgc_ctrl = nullptr;
1677       result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1678 
1679       intx prefetch_lines = length != nullptr ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1680       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1681       Node* fast_oop = bs->obj_allocate(this, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1682                                         fast_oop_ctrl, fast_oop_rawmem,
1683                                         prefetch_lines);
1684 
1685       if (initial_slow_test != nullptr) {
1686         // This completes all paths into the slow merge point
1687         slow_region->init_req(need_gc_path, needgc_ctrl);
1688         transform_later(slow_region);
1689       } else {
1690         // No initial slow path needed!
1691         // Just fall from the need-GC path straight into the VM call.
1692         slow_region = needgc_ctrl;
1693       }
1694 

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

2012     Node* thread = new ThreadLocalNode();
2013     transform_later(thread);
2014 
2015     call->init_req(TypeFunc::Parms + 0, thread);
2016     call->init_req(TypeFunc::Parms + 1, oop);
2017     call->init_req(TypeFunc::Control, ctrl);
2018     call->init_req(TypeFunc::I_O    , top()); // does no i/o
2019     call->init_req(TypeFunc::Memory , rawmem);
2020     call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
2021     call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
2022     transform_later(call);
2023     ctrl = new ProjNode(call, TypeFunc::Control);
2024     transform_later(ctrl);
2025     rawmem = new ProjNode(call, TypeFunc::Memory);
2026     transform_later(rawmem);
2027   }
2028 }
2029 
2030 // Helper for PhaseMacroExpand::expand_allocate_common.
2031 // Initializes the newly-allocated storage.
2032 Node* PhaseMacroExpand::initialize_object(AllocateNode* alloc,
2033                                           Node* control, Node* rawmem, Node* object,
2034                                           Node* klass_node, Node* length,
2035                                           Node* size_in_bytes) {

2036   InitializeNode* init = alloc->initialization();
2037   // Store the klass & mark bits
2038   Node* mark_node = alloc->make_ideal_mark(&_igvn, control, rawmem);
2039   if (!mark_node->is_Con()) {
2040     transform_later(mark_node);
2041   }
2042   rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
2043 
2044   if (!UseCompactObjectHeaders) {
2045     rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
2046   }
2047   int header_size = alloc->minimum_header_size();  // conservatively small
2048 
2049   // Array length
2050   if (length != nullptr) {         // Arrays need length field
2051     rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
2052     // conservatively small header size:
2053     header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
2054     if (_igvn.type(klass_node)->isa_aryklassptr()) {   // we know the exact header size in most cases:
2055       BasicType elem = _igvn.type(klass_node)->is_klassptr()->as_instance_type()->isa_aryptr()->elem()->array_element_basic_type();
2056       if (is_reference_type(elem, true)) {
2057         elem = T_OBJECT;
2058       }
2059       header_size = Klass::layout_helper_header_size(Klass::array_layout_helper(elem));
2060     }
2061   }
2062 
2063   // Clear the object body, if necessary.
2064   if (init == nullptr) {
2065     // The init has somehow disappeared; be cautious and clear everything.
2066     //
2067     // This can happen if a node is allocated but an uncommon trap occurs
2068     // immediately.  In this case, the Initialize gets associated with the
2069     // trap, and may be placed in a different (outer) loop, if the Allocate
2070     // is in a loop.  If (this is rare) the inner loop gets unrolled, then
2071     // there can be two Allocates to one Initialize.  The answer in all these
2072     // edge cases is safety first.  It is always safe to clear immediately
2073     // within an Allocate, and then (maybe or maybe not) clear some more later.
2074     if (!(UseTLAB && ZeroTLAB)) {
2075       rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
2076                                             alloc->in(AllocateNode::InitValue),
2077                                             alloc->in(AllocateNode::RawInitValue),
2078                                             header_size, size_in_bytes,
2079                                             &_igvn);
2080     }
2081   } else {
2082     if (!init->is_complete()) {
2083       // Try to win by zeroing only what the init does not store.
2084       // We can also try to do some peephole optimizations,
2085       // such as combining some adjacent subword stores.
2086       rawmem = init->complete_stores(control, rawmem, object,
2087                                      header_size, size_in_bytes, &_igvn);
2088     }
2089     // We have no more use for this link, since the AllocateNode goes away:
2090     init->set_req(InitializeNode::RawAddress, top());
2091     // (If we keep the link, it just confuses the register allocator,
2092     // who thinks he sees a real use of the address by the membar.)
2093   }
2094 
2095   return rawmem;
2096 }
2097 

2232       for ( intx i = 0; i < lines; i++ ) {
2233         prefetch_adr = new AddPNode( old_eden_top, new_eden_top,
2234                                             _igvn.MakeConX(distance) );
2235         transform_later(prefetch_adr);
2236         prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
2237         // Do not let it float too high, since if eden_top == eden_end,
2238         // both might be null.
2239         if( i == 0 ) { // Set control for first prefetch, next follows it
2240           prefetch->init_req(0, needgc_false);
2241         }
2242         transform_later(prefetch);
2243         distance += step_size;
2244         i_o = prefetch;
2245       }
2246    }
2247    return i_o;
2248 }
2249 
2250 
2251 void PhaseMacroExpand::expand_allocate(AllocateNode *alloc) {
2252   expand_allocate_common(alloc, nullptr, nullptr,
2253                          OptoRuntime::new_instance_Type(),
2254                          OptoRuntime::new_instance_Java(), nullptr);
2255 }
2256 
2257 void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) {
2258   Node* length = alloc->in(AllocateNode::ALength);
2259   Node* valid_length_test = alloc->in(AllocateNode::ValidLengthTest);
2260   InitializeNode* init = alloc->initialization();
2261   Node* klass_node = alloc->in(AllocateNode::KlassNode);
2262   Node* init_value = alloc->in(AllocateNode::InitValue);
2263   const TypeAryKlassPtr* ary_klass_t = _igvn.type(klass_node)->isa_aryklassptr();
2264   assert(!ary_klass_t || !ary_klass_t->klass_is_exact() || !ary_klass_t->exact_klass()->is_obj_array_klass() ||
2265          ary_klass_t->is_refined_type(), "Must be a refined array klass");
2266   const TypeFunc* slow_call_type;
2267   address slow_call_address;  // Address of slow call
2268   if (init != nullptr && init->is_complete_with_arraycopy() &&
2269       ary_klass_t && ary_klass_t->elem()->isa_klassptr() == nullptr) {
2270     // Don't zero type array during slow allocation in VM since
2271     // it will be initialized later by arraycopy in compiled code.
2272     slow_call_address = OptoRuntime::new_array_nozero_Java();
2273     slow_call_type = OptoRuntime::new_array_nozero_Type();
2274   } else {
2275     slow_call_address = OptoRuntime::new_array_Java();
2276     slow_call_type = OptoRuntime::new_array_Type();
2277 
2278     if (init_value == nullptr) {
2279       init_value = _igvn.zerocon(T_OBJECT);
2280     } else if (UseCompressedOops) {
2281       init_value = transform_later(new DecodeNNode(init_value, init_value->bottom_type()->make_ptr()));
2282     }
2283   }
2284   expand_allocate_common(alloc, length, init_value,
2285                          slow_call_type,
2286                          slow_call_address, valid_length_test);
2287 }
2288 
2289 //-------------------mark_eliminated_box----------------------------------
2290 //
2291 // During EA obj may point to several objects but after few ideal graph
2292 // transformations (CCP) it may point to only one non escaping object
2293 // (but still using phi), corresponding locks and unlocks will be marked
2294 // for elimination. Later obj could be replaced with a new node (new phi)
2295 // and which does not have escape information. And later after some graph
2296 // reshape other locks and unlocks (which were not marked for elimination
2297 // before) are connected to this new obj (phi) but they still will not be
2298 // marked for elimination since new obj has no escape information.
2299 // Mark all associated (same box and obj) lock and unlock nodes for
2300 // elimination if some of them marked already.
2301 void PhaseMacroExpand::mark_eliminated_box(Node* box, Node* obj) {
2302   BoxLockNode* oldbox = box->as_BoxLock();
2303   if (oldbox->is_eliminated()) {
2304     return; // This BoxLock node was processed already.
2305   }

2477 #ifdef ASSERT
2478   if (!alock->is_coarsened()) {
2479     // Check that new "eliminated" BoxLock node is created.
2480     BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2481     assert(oldbox->is_eliminated(), "should be done already");
2482   }
2483 #endif
2484 
2485   alock->log_lock_optimization(C, "eliminate_lock");
2486 
2487 #ifndef PRODUCT
2488   if (PrintEliminateLocks) {
2489     tty->print_cr("++++ Eliminated: %d %s '%s'", alock->_idx, (alock->is_Lock() ? "Lock" : "Unlock"), alock->kind_as_string());
2490   }
2491 #endif
2492 
2493   Node* mem  = alock->in(TypeFunc::Memory);
2494   Node* ctrl = alock->in(TypeFunc::Control);
2495   guarantee(ctrl != nullptr, "missing control projection, cannot replace_node() with null");
2496 
2497   _callprojs = alock->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
2498   // There are 2 projections from the lock.  The lock node will
2499   // be deleted when its last use is subsumed below.
2500   assert(alock->outcnt() == 2 &&
2501          _callprojs->fallthrough_proj != nullptr &&
2502          _callprojs->fallthrough_memproj != nullptr,
2503          "Unexpected projections from Lock/Unlock");
2504 
2505   Node* fallthroughproj = _callprojs->fallthrough_proj;
2506   Node* memproj_fallthrough = _callprojs->fallthrough_memproj;
2507 
2508   // The memory projection from a lock/unlock is RawMem
2509   // The input to a Lock is merged memory, so extract its RawMem input
2510   // (unless the MergeMem has been optimized away.)
2511   if (alock->is_Lock()) {
2512     // Search for MemBarAcquireLock node and delete it also.
2513     MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
2514     assert(membar != nullptr && membar->Opcode() == Op_MemBarAcquireLock, "");
2515     Node* ctrlproj = membar->proj_out(TypeFunc::Control);
2516     Node* memproj = membar->proj_out(TypeFunc::Memory);
2517     _igvn.replace_node(ctrlproj, fallthroughproj);
2518     _igvn.replace_node(memproj, memproj_fallthrough);
2519 
2520     // Delete FastLock node also if this Lock node is unique user
2521     // (a loop peeling may clone a Lock node).
2522     Node* flock = alock->as_Lock()->fastlock_node();
2523     if (flock->outcnt() == 1) {
2524       assert(flock->unique_out() == alock, "sanity");
2525       _igvn.replace_node(flock, top());
2526     }

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


3061     }










3062 
3063     // Postpone lock elimination to after EA when most allocations are eliminated
3064     // because they might block lock elimination if their escape state isn't
3065     // determined yet and we only got one chance at eliminating the lock.
3066     if (eliminate_locks) {
3067       // Before elimination may re-mark (change to Nested or NonEscObj)
3068       // all associated (same box and obj) lock and unlock nodes.
3069       int cnt = C->macro_count();
3070       for (int i=0; i < cnt; i++) {
3071         Node *n = C->macro_node(i);
3072         if (n->is_AbstractLock()) { // Lock and Unlock nodes
3073           mark_eliminated_locking_nodes(n->as_AbstractLock());


3074         }

3075       }
3076       // Re-marking may break consistency of Coarsened locks.
3077       if (!C->coarsened_locks_consistent()) {
3078         return; // recompile without Coarsened locks if broken
3079       } else {
3080         // After coarsened locks are eliminated locking regions
3081         // become unbalanced. We should not execute any more
3082         // locks elimination optimizations on them.
3083         C->mark_unbalanced_boxes();
3084       }
3085     }
3086 
3087     bool progress = false;



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

3286     // Worst case is a macro node gets expanded into about 200 nodes.
3287     // Allow 50% more for optimization.
3288     if (C->check_node_count(300, "out of nodes before macro expansion")) {
3289       return true;
3290     }
3291 
3292     DEBUG_ONLY(int old_macro_count = C->macro_count();)
3293     switch (n->class_id()) {
3294     case Node::Class_Lock:
3295       expand_lock_node(n->as_Lock());
3296       break;
3297     case Node::Class_Unlock:
3298       expand_unlock_node(n->as_Unlock());
3299       break;
3300     case Node::Class_ArrayCopy:
3301       expand_arraycopy_node(n->as_ArrayCopy());
3302       break;
3303     case Node::Class_SubTypeCheck:
3304       expand_subtypecheck_node(n->as_SubTypeCheck());
3305       break;
3306     case Node::Class_CallStaticJava:
3307       expand_mh_intrinsic_return(n->as_CallStaticJava());
3308       C->remove_macro_node(n);
3309       break;
3310     case Node::Class_FlatArrayCheck:
3311       expand_flatarraycheck_node(n->as_FlatArrayCheck());
3312       break;
3313     default:
3314       switch (n->Opcode()) {
3315       case Op_ModD:
3316       case Op_ModF: {
3317         CallNode* mod_macro = n->as_Call();
3318         CallNode* call = new CallLeafPureNode(mod_macro->tf(), mod_macro->entry_point(),
3319                                               mod_macro->_name, TypeRawPtr::BOTTOM);
3320         call->init_req(TypeFunc::Control, mod_macro->in(TypeFunc::Control));
3321         call->init_req(TypeFunc::I_O, C->top());
3322         call->init_req(TypeFunc::Memory, C->top());
3323         call->init_req(TypeFunc::ReturnAdr, C->top());
3324         call->init_req(TypeFunc::FramePtr, C->top());
3325         for (unsigned int i = 0; i < mod_macro->tf()->domain_cc()->cnt() - TypeFunc::Parms; i++) {
3326           call->init_req(TypeFunc::Parms + i, mod_macro->in(TypeFunc::Parms + i));
3327         }
3328         _igvn.replace_node(mod_macro, call);
3329         transform_later(call);
3330         break;
3331       }
3332       default:
3333         assert(false, "unknown node type in macro list");
3334       }
3335     }
3336     assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
3337     if (C->failing())  return true;
3338     C->print_method(PHASE_AFTER_MACRO_EXPANSION_STEP, 5, n);
3339 
3340     // Clean up the graph so we're less likely to hit the maximum node
3341     // limit
3342     _igvn.set_delay_transform(false);
3343     _igvn.optimize();
3344     if (C->failing())  return true;
3345     _igvn.set_delay_transform(true);
< prev index next >