< prev index next >

src/hotspot/share/opto/macro.cpp

Print this page

   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"

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

  39 #include "opto/intrinsicnode.hpp"
  40 #include "opto/locknode.hpp"
  41 #include "opto/loopnode.hpp"
  42 #include "opto/macro.hpp"
  43 #include "opto/memnode.hpp"
  44 #include "opto/narrowptrnode.hpp"
  45 #include "opto/node.hpp"
  46 #include "opto/opaquenode.hpp"
  47 #include "opto/phaseX.hpp"
  48 #include "opto/rootnode.hpp"
  49 #include "opto/runtime.hpp"
  50 #include "opto/subnode.hpp"
  51 #include "opto/subtypenode.hpp"
  52 #include "opto/type.hpp"
  53 #include "prims/jvmtiExport.hpp"
  54 #include "runtime/continuation.hpp"
  55 #include "runtime/sharedRuntime.hpp"

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

 139   // Slow-path call
 140  CallNode *call = leaf_name
 141    ? (CallNode*)new CallLeafNode      ( slow_call_type, slow_call, leaf_name, TypeRawPtr::BOTTOM )
 142    : (CallNode*)new CallStaticJavaNode( slow_call_type, slow_call, OptoRuntime::stub_name(slow_call), TypeRawPtr::BOTTOM );
 143 
 144   // Slow path call has no side-effects, uses few values
 145   copy_predefined_input_for_runtime_call(slow_path, oldcall, call );
 146   if (parm0 != nullptr)  call->init_req(TypeFunc::Parms+0, parm0);
 147   if (parm1 != nullptr)  call->init_req(TypeFunc::Parms+1, parm1);
 148   if (parm2 != nullptr)  call->init_req(TypeFunc::Parms+2, parm2);
 149   call->copy_call_debug_info(&_igvn, oldcall);
 150   call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
 151   _igvn.replace_node(oldcall, call);
 152   transform_later(call);
 153 
 154   return call;
 155 }
 156 
 157 void PhaseMacroExpand::eliminate_gc_barrier(Node* p2x) {
 158   BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
 159   bs->eliminate_gc_barrier(this, p2x);
 160 #ifndef PRODUCT
 161   if (PrintOptoStatistics) {
 162     Atomic::inc(&PhaseMacroExpand::_GC_barriers_removed_counter);
 163   }
 164 #endif
 165 }
 166 
 167 // Search for a memory operation for the specified memory slice.
 168 static Node *scan_mem_chain(Node *mem, int alias_idx, int offset, Node *start_mem, Node *alloc, PhaseGVN *phase) {
 169   Node *orig_mem = mem;
 170   Node *alloc_mem = alloc->in(TypeFunc::Memory);
 171   const TypeOopPtr *tinst = phase->C->get_adr_type(alias_idx)->isa_oopptr();
 172   while (true) {
 173     if (mem == alloc_mem || mem == start_mem ) {
 174       return mem;  // hit one of our sentinels
 175     } else if (mem->is_MergeMem()) {
 176       mem = mem->as_MergeMem()->memory_at(alias_idx);
 177     } else if (mem->is_Proj() && mem->as_Proj()->_con == TypeFunc::Memory) {
 178       Node *in = mem->in(0);
 179       // we can safely skip over safepoints, calls, locks and membars because we

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

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

 283   }
 284   Node* res = nullptr;
 285   if (ac->is_clonebasic()) {
 286     assert(ac->in(ArrayCopyNode::Src) != ac->in(ArrayCopyNode::Dest), "clone source equals destination");
 287     Node* base = ac->in(ArrayCopyNode::Src);
 288     Node* adr = _igvn.transform(new AddPNode(base, base, _igvn.MakeConX(offset)));
 289     const TypePtr* adr_type = _igvn.type(base)->is_ptr()->add_offset(offset);
 290     MergeMemNode* mergemen = _igvn.transform(MergeMemNode::make(mem))->as_MergeMem();
 291     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 292     res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
 293   } else {
 294     if (ac->modifies(offset, offset, &_igvn, true)) {
 295       assert(ac->in(ArrayCopyNode::Dest) == alloc->result_cast(), "arraycopy destination should be allocation's result");
 296       uint shift = exact_log2(type2aelembytes(bt));
 297       Node* src_pos = ac->in(ArrayCopyNode::SrcPos);
 298       Node* dest_pos = ac->in(ArrayCopyNode::DestPos);
 299       const TypeInt* src_pos_t = _igvn.type(src_pos)->is_int();
 300       const TypeInt* dest_pos_t = _igvn.type(dest_pos)->is_int();
 301 
 302       Node* adr = nullptr;
 303       const TypePtr* adr_type = nullptr;




 304       if (src_pos_t->is_con() && dest_pos_t->is_con()) {
 305         intptr_t off = ((src_pos_t->get_con() - dest_pos_t->get_con()) << shift) + offset;
 306         Node* base = ac->in(ArrayCopyNode::Src);
 307         adr = _igvn.transform(new AddPNode(base, base, _igvn.MakeConX(off)));
 308         adr_type = _igvn.type(base)->is_ptr()->add_offset(off);

 309         if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 310           // Don't emit a new load from src if src == dst but try to get the value from memory instead
 311           return value_from_mem(ac->in(TypeFunc::Memory), ctl, ft, ftype, adr_type->isa_oopptr(), alloc);
 312         }
 313       } else {





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

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






 393         continue;
 394       }
 395       if (val->is_Initialize()) {
 396         val = val->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 397       }
 398       if (val == nullptr) {
 399         return nullptr;  // can't find a value on this path
 400       }
 401       if (val == mem) {
 402         values.at_put(j, mem);
 403       } else if (val->is_Store()) {
 404         Node* n = val->in(MemNode::ValueIn);
 405         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 406         n = bs->step_over_gc_barrier(n);
 407         if (is_subword_type(ft)) {
 408           n = Compile::narrow_value(ft, n, phi_type, &_igvn, true);
 409         }
 410         values.at_put(j, n);
 411       } else if(val->is_Proj() && val->in(0) == alloc) {
 412         values.at_put(j, _igvn.zerocon(ft));






 413       } else if (val->is_Phi()) {
 414         val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, value_phis, level-1);
 415         if (val == nullptr) {
 416           return nullptr;
 417         }
 418         values.at_put(j, val);
 419       } else if (val->Opcode() == Op_SCMemProj) {
 420         assert(val->in(0)->is_LoadStore() ||
 421                val->in(0)->Opcode() == Op_EncodeISOArray ||
 422                val->in(0)->Opcode() == Op_StrCompressedCopy, "sanity");
 423         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
 424         return nullptr;
 425       } else if (val->is_ArrayCopy()) {
 426         Node* res = make_arraycopy_load(val->as_ArrayCopy(), offset, val->in(0), val->in(TypeFunc::Memory), ft, phi_type, alloc);
 427         if (res == nullptr) {
 428           return nullptr;
 429         }
 430         values.at_put(j, res);
 431       } else {
 432         DEBUG_ONLY( val->dump(); )

 436     }
 437   }
 438   // Set Phi's inputs
 439   for (uint j = 1; j < length; j++) {
 440     if (values.at(j) == mem) {
 441       phi->init_req(j, phi);
 442     } else {
 443       phi->init_req(j, values.at(j));
 444     }
 445   }
 446   return phi;
 447 }
 448 
 449 // Search the last value stored into the object's field.
 450 Node *PhaseMacroExpand::value_from_mem(Node *sfpt_mem, Node *sfpt_ctl, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, AllocateNode *alloc) {
 451   assert(adr_t->is_known_instance_field(), "instance required");
 452   int instance_id = adr_t->instance_id();
 453   assert((uint)instance_id == alloc->_idx, "wrong allocation");
 454 
 455   int alias_idx = C->get_alias_index(adr_t);
 456   int offset = adr_t->offset();
 457   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
 458   Node *alloc_ctrl = alloc->in(TypeFunc::Control);
 459   Node *alloc_mem = alloc->in(TypeFunc::Memory);
 460   VectorSet visited;
 461 
 462   bool done = sfpt_mem == alloc_mem;
 463   Node *mem = sfpt_mem;
 464   while (!done) {
 465     if (visited.test_set(mem->_idx)) {
 466       return nullptr;  // found a loop, give up
 467     }
 468     mem = scan_mem_chain(mem, alias_idx, offset, start_mem, alloc, &_igvn);
 469     if (mem == start_mem || mem == alloc_mem) {
 470       done = true;  // hit a sentinel, return appropriate 0 value
 471     } else if (mem->is_Initialize()) {
 472       mem = mem->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 473       if (mem == nullptr) {
 474         done = true; // Something go wrong.
 475       } else if (mem->is_Store()) {
 476         const TypePtr* atype = mem->as_Store()->adr_type();
 477         assert(C->get_alias_index(atype) == Compile::AliasIdxRaw, "store is correct memory slice");
 478         done = true;
 479       }
 480     } else if (mem->is_Store()) {
 481       const TypeOopPtr* atype = mem->as_Store()->adr_type()->isa_oopptr();
 482       assert(atype != nullptr, "address type must be oopptr");
 483       assert(C->get_alias_index(atype) == alias_idx &&
 484              atype->is_known_instance_field() && atype->offset() == offset &&
 485              atype->instance_id() == instance_id, "store is correct memory slice");
 486       done = true;
 487     } else if (mem->is_Phi()) {
 488       // try to find a phi's unique input
 489       Node *unique_input = nullptr;
 490       Node *top = C->top();
 491       for (uint i = 1; i < mem->req(); i++) {
 492         Node *n = scan_mem_chain(mem->in(i), alias_idx, offset, start_mem, alloc, &_igvn);
 493         if (n == nullptr || n == top || n == mem) {
 494           continue;
 495         } else if (unique_input == nullptr) {
 496           unique_input = n;
 497         } else if (unique_input != n) {
 498           unique_input = top;
 499           break;
 500         }
 501       }
 502       if (unique_input != nullptr && unique_input != top) {
 503         mem = unique_input;
 504       } else {
 505         done = true;
 506       }
 507     } else if (mem->is_ArrayCopy()) {
 508       done = true;
 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->isa_aryptr()) {
 574       int length = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 575       if (length < 0) {
 576         NOT_PRODUCT(fail_eliminate = "Array's size is not constant";)
 577         can_eliminate = false;
 578       }
 579     }
 580   }
 581 
 582   if (can_eliminate && res != nullptr) {
 583     BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
 584     for (DUIterator_Fast jmax, j = res->fast_outs(jmax);
 585                                j < jmax && can_eliminate; j++) {
 586       Node* use = res->fast_out(j);
 587 
 588       if (use->is_AddP()) {
 589         const TypePtr* addp_type = igvn->type(use)->is_ptr();
 590         int offset = addp_type->offset();
 591 
 592         if (offset == Type::OffsetTop || offset == Type::OffsetBot) {
 593           NOT_PRODUCT(fail_eliminate = "Undefined field reference";)
 594           can_eliminate = false;
 595           break;
 596         }
 597         for (DUIterator_Fast kmax, k = use->fast_outs(kmax);
 598                                    k < kmax && can_eliminate; k++) {
 599           Node* n = use->fast_out(k);
 600           if (!n->is_Store() && n->Opcode() != Op_CastP2X && !bs->is_gc_pre_barrier_node(n) && !reduce_merge_precheck) {
 601             DEBUG_ONLY(disq_node = n;)
 602             if (n->is_Load() || n->is_LoadStore()) {
 603               NOT_PRODUCT(fail_eliminate = "Field load";)
 604             } else {
 605               NOT_PRODUCT(fail_eliminate = "Not store field reference";)

 613                   use->as_ArrayCopy()->is_copyof_validated() ||
 614                   use->as_ArrayCopy()->is_copyofrange_validated()) &&
 615                  use->in(ArrayCopyNode::Dest) == res) {
 616         // ok to eliminate
 617       } else if (use->is_SafePoint()) {
 618         SafePointNode* sfpt = use->as_SafePoint();
 619         if (sfpt->is_Call() && sfpt->as_Call()->has_non_debug_use(res)) {
 620           // Object is passed as argument.
 621           DEBUG_ONLY(disq_node = use;)
 622           NOT_PRODUCT(fail_eliminate = "Object is passed as argument";)
 623           can_eliminate = false;
 624         }
 625         Node* sfptMem = sfpt->memory();
 626         if (sfptMem == nullptr || sfptMem->is_top()) {
 627           DEBUG_ONLY(disq_node = use;)
 628           NOT_PRODUCT(fail_eliminate = "null or TOP memory";)
 629           can_eliminate = false;
 630         } else if (!reduce_merge_precheck) {
 631           safepoints->append_if_missing(sfpt);
 632         }





















 633       } else if (reduce_merge_precheck && (use->is_Phi() || use->is_EncodeP() || use->Opcode() == Op_MemBarRelease)) {
 634         // Nothing to do
 635       } else if (use->Opcode() != Op_CastP2X) { // CastP2X is used by card mark
 636         if (use->is_Phi()) {
 637           if (use->outcnt() == 1 && use->unique_out()->Opcode() == Op_Return) {
 638             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 639           } else {
 640             NOT_PRODUCT(fail_eliminate = "Object is referenced by Phi";)
 641           }
 642           DEBUG_ONLY(disq_node = use;)
 643         } else {
 644           if (use->Opcode() == Op_Return) {
 645             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 646           } else {
 647             NOT_PRODUCT(fail_eliminate = "Object is referenced by node";)
 648           }
 649           DEBUG_ONLY(disq_node = use;)
 650         }
 651         can_eliminate = false;



 652       }
 653     }
 654   }
 655 
 656 #ifndef PRODUCT
 657   if (PrintEliminateAllocations && safepoints != nullptr) {
 658     if (can_eliminate) {
 659       tty->print("Scalar ");
 660       if (res == nullptr)
 661         alloc->dump();
 662       else
 663         res->dump();
 664     } else if (alloc->_is_scalar_replaceable) {
 665       tty->print("NotScalar (%s)", fail_eliminate);
 666       if (res == nullptr)
 667         alloc->dump();
 668       else
 669         res->dump();
 670 #ifdef ASSERT
 671       if (disq_node != nullptr) {
 672           tty->print("  >>>> ");
 673           disq_node->dump();
 674       }
 675 #endif /*ASSERT*/
 676     }
 677   }
 678 
 679   if (TraceReduceAllocationMerges && !can_eliminate && reduce_merge_precheck) {
 680     tty->print_cr("\tCan't eliminate allocation because '%s': ", fail_eliminate != nullptr ? fail_eliminate : "");
 681     DEBUG_ONLY(if (disq_node != nullptr) disq_node->dump();)
 682   }
 683 #endif
 684   return can_eliminate;

 714     JVMState *jvms = sfpt_done->jvms();
 715     jvms->set_endoff(sfpt_done->req());
 716     // Now make a pass over the debug information replacing any references
 717     // to SafePointScalarObjectNode with the allocated object.
 718     int start = jvms->debug_start();
 719     int end   = jvms->debug_end();
 720     for (int i = start; i < end; i++) {
 721       if (sfpt_done->in(i)->is_SafePointScalarObject()) {
 722         SafePointScalarObjectNode* scobj = sfpt_done->in(i)->as_SafePointScalarObject();
 723         if (scobj->first_index(jvms) == sfpt_done->req() &&
 724             scobj->n_fields() == (uint)nfields) {
 725           assert(scobj->alloc() == alloc, "sanity");
 726           sfpt_done->set_req(i, res);
 727         }
 728       }
 729     }
 730     _igvn._worklist.push(sfpt_done);
 731   }
 732 }
 733 
 734 SafePointScalarObjectNode* PhaseMacroExpand::create_scalarized_object_description(AllocateNode *alloc, SafePointNode* sfpt) {

 735   // Fields of scalar objs are referenced only at the end
 736   // of regular debuginfo at the last (youngest) JVMS.
 737   // Record relative start index.
 738   ciInstanceKlass* iklass    = nullptr;
 739   BasicType basic_elem_type  = T_ILLEGAL;
 740   const Type* field_type     = nullptr;
 741   const TypeOopPtr* res_type = nullptr;
 742   int nfields                = 0;
 743   int array_base             = 0;
 744   int element_size           = 0;
 745   uint first_ind             = (sfpt->req() - sfpt->jvms()->scloff());
 746   Node* res                  = alloc->result_cast();
 747 
 748   assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");
 749   assert(sfpt->jvms() != nullptr, "missed JVMS");
 750 
 751   if (res != nullptr) { // Could be null when there are no users
 752     res_type = _igvn.type(res)->isa_oopptr();
 753 
 754     if (res_type->isa_instptr()) {
 755       // find the fields of the class which will be needed for safepoint debug information
 756       iklass = res_type->is_instptr()->instance_klass();
 757       nfields = iklass->nof_nonstatic_fields();
 758     } else {
 759       // find the array's elements which will be needed for safepoint debug information
 760       nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 761       assert(nfields >= 0, "must be an array klass.");
 762       basic_elem_type = res_type->is_aryptr()->elem()->array_element_basic_type();
 763       array_base = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
 764       element_size = type2aelembytes(basic_elem_type);
 765       field_type = res_type->is_aryptr()->elem();




 766     }
 767   }
 768 
 769   SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(res_type, alloc, first_ind, nfields);
 770   sobj->init_req(0, C->root());
 771   transform_later(sobj);
 772 
 773   // Scan object's fields adding an input to the safepoint for each field.
 774   for (int j = 0; j < nfields; j++) {
 775     intptr_t offset;
 776     ciField* field = nullptr;
 777     if (iklass != nullptr) {
 778       field = iklass->nonstatic_field_at(j);
 779       offset = field->offset_in_bytes();
 780       ciType* elem_type = field->type();
 781       basic_elem_type = field->layout_type();

 782 
 783       // The next code is taken from Parse::do_get_xxx().
 784       if (is_reference_type(basic_elem_type)) {
 785         if (!elem_type->is_loaded()) {
 786           field_type = TypeInstPtr::BOTTOM;
 787         } else if (field != nullptr && field->is_static_constant()) {
 788           ciObject* con = field->constant_value().as_object();
 789           // Do not "join" in the previous type; it doesn't add value,
 790           // and may yield a vacuous result if the field is of interface type.
 791           field_type = TypeOopPtr::make_from_constant(con)->isa_oopptr();
 792           assert(field_type != nullptr, "field singleton type must be consistent");
 793         } else {
 794           field_type = TypeOopPtr::make_from_klass(elem_type->as_klass());
 795         }
 796         if (UseCompressedOops) {
 797           field_type = field_type->make_narrowoop();
 798           basic_elem_type = T_NARROWOOP;
 799         }
 800       } else {
 801         field_type = Type::get_const_basic_type(basic_elem_type);
 802       }
 803     } else {
 804       offset = array_base + j * (intptr_t)element_size;
 805     }
 806 
 807     const TypeOopPtr *field_addr_type = res_type->add_offset(offset)->isa_oopptr();
 808 
 809     Node *field_val = value_from_mem(sfpt->memory(), sfpt->control(), basic_elem_type, field_type, field_addr_type, alloc);






 810 
 811     // We weren't able to find a value for this field,
 812     // give up on eliminating this allocation.
 813     if (field_val == nullptr) {
 814       uint last = sfpt->req() - 1;
 815       for (int k = 0;  k < j; k++) {
 816         sfpt->del_req(last--);
 817       }
 818       _igvn._worklist.push(sfpt);
 819 
 820 #ifndef PRODUCT
 821       if (PrintEliminateAllocations) {
 822         if (field != nullptr) {
 823           tty->print("=== At SafePoint node %d can't find value of field: ", sfpt->_idx);
 824           field->print();
 825           int field_idx = C->get_alias_index(field_addr_type);
 826           tty->print(" (alias_idx=%d)", field_idx);
 827         } else { // Array's element
 828           tty->print("=== At SafePoint node %d can't find value of array element [%d]", sfpt->_idx, j);
 829         }
 830         tty->print(", which prevents elimination of: ");
 831         if (res == nullptr)
 832           alloc->dump();
 833         else
 834           res->dump();
 835       }
 836 #endif
 837 
 838       return nullptr;
 839     }
 840 
 841     if (UseCompressedOops && field_type->isa_narrowoop()) {
 842       // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation
 843       // to be able scalar replace the allocation.
 844       if (field_val->is_EncodeP()) {
 845         field_val = field_val->in(1);
 846       } else {
 847         field_val = transform_later(new DecodeNNode(field_val, field_val->get_ptr_type()));
 848       }
 849     }




 850     sfpt->add_req(field_val);
 851   }
 852 
 853   sfpt->jvms()->set_endoff(sfpt->req());
 854 
 855   return sobj;
 856 }
 857 
 858 // Do scalar replacement.
 859 bool PhaseMacroExpand::scalar_replacement(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
 860   GrowableArray <SafePointNode *> safepoints_done;
 861   Node* res = alloc->result_cast();
 862   assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");




 863 
 864   // Process the safepoint uses


 865   while (safepoints.length() > 0) {
 866     SafePointNode* sfpt = safepoints.pop();
 867     SafePointScalarObjectNode* sobj = create_scalarized_object_description(alloc, sfpt);
 868 
 869     if (sobj == nullptr) {
 870       undo_previous_scalarizations(safepoints_done, alloc);
 871       return false;
 872     }
 873 
 874     // Now make a pass over the debug information replacing any references
 875     // to the allocated object with "sobj"
 876     JVMState *jvms = sfpt->jvms();
 877     sfpt->replace_edges_in_range(res, sobj, jvms->debug_start(), jvms->debug_end(), &_igvn);
 878     _igvn._worklist.push(sfpt);
 879 
 880     // keep it for rollback
 881     safepoints_done.append_if_missing(sfpt);
 882   }
 883 







 884   return true;
 885 }
 886 
 887 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) {
 888   Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control);
 889   Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory);
 890   if (ctl_proj != nullptr) {
 891     igvn.replace_node(ctl_proj, n->in(0));
 892   }
 893   if (mem_proj != nullptr) {
 894     igvn.replace_node(mem_proj, n->in(TypeFunc::Memory));
 895   }
 896 }
 897 
 898 // Process users of eliminated allocation.
 899 void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc) {

 900   Node* res = alloc->result_cast();
 901   if (res != nullptr) {




 902     for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
 903       Node *use = res->last_out(j);
 904       uint oc1 = res->outcnt();
 905 
 906       if (use->is_AddP()) {
 907         for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
 908           Node *n = use->last_out(k);
 909           uint oc2 = use->outcnt();
 910           if (n->is_Store()) {
 911 #ifdef ASSERT
 912             // Verify that there is no dependent MemBarVolatile nodes,
 913             // they should be removed during IGVN, see MemBarNode::Ideal().
 914             for (DUIterator_Fast pmax, p = n->fast_outs(pmax);
 915                                        p < pmax; p++) {
 916               Node* mb = n->fast_out(p);
 917               assert(mb->is_Initialize() || !mb->is_MemBar() ||
 918                      mb->req() <= MemBarNode::Precedent ||
 919                      mb->in(MemBarNode::Precedent) != n,
 920                      "MemBarVolatile should be eliminated for non-escaping object");
 921             }
 922 #endif
 923             _igvn.replace_node(n, n->in(MemNode::Memory));
 924           } else {
 925             eliminate_gc_barrier(n);
 926           }
 927           k -= (oc2 - use->outcnt());
 928         }
 929         _igvn.remove_dead_node(use);
 930       } else if (use->is_ArrayCopy()) {
 931         // Disconnect ArrayCopy node
 932         ArrayCopyNode* ac = use->as_ArrayCopy();
 933         if (ac->is_clonebasic()) {
 934           Node* membar_after = ac->proj_out(TypeFunc::Control)->unique_ctrl_out();
 935           disconnect_projections(ac, _igvn);
 936           assert(alloc->in(TypeFunc::Memory)->is_Proj() && alloc->in(TypeFunc::Memory)->in(0)->Opcode() == Op_MemBarCPUOrder, "mem barrier expected before allocation");
 937           Node* membar_before = alloc->in(TypeFunc::Memory)->in(0);
 938           disconnect_projections(membar_before->as_MemBar(), _igvn);
 939           if (membar_after->is_MemBar()) {
 940             disconnect_projections(membar_after->as_MemBar(), _igvn);
 941           }
 942         } else {
 943           assert(ac->is_arraycopy_validated() ||
 944                  ac->is_copyof_validated() ||
 945                  ac->is_copyofrange_validated(), "unsupported");
 946           CallProjections callprojs;
 947           ac->extract_projections(&callprojs, true);
 948 
 949           _igvn.replace_node(callprojs.fallthrough_ioproj, ac->in(TypeFunc::I_O));
 950           _igvn.replace_node(callprojs.fallthrough_memproj, ac->in(TypeFunc::Memory));
 951           _igvn.replace_node(callprojs.fallthrough_catchproj, ac->in(TypeFunc::Control));
 952 
 953           // Set control to top. IGVN will remove the remaining projections
 954           ac->set_req(0, top());
 955           ac->replace_edge(res, top(), &_igvn);
 956 
 957           // Disconnect src right away: it can help find new
 958           // opportunities for allocation elimination
 959           Node* src = ac->in(ArrayCopyNode::Src);
 960           ac->replace_edge(src, top(), &_igvn);
 961           // src can be top at this point if src and dest of the
 962           // arraycopy were the same
 963           if (src->outcnt() == 0 && !src->is_top()) {
 964             _igvn.remove_dead_node(src);
 965           }
 966         }
 967         _igvn._worklist.push(ac);



















 968       } else {
 969         eliminate_gc_barrier(use);
 970       }
 971       j -= (oc1 - res->outcnt());
 972     }
 973     assert(res->outcnt() == 0, "all uses of allocated objects must be deleted");
 974     _igvn.remove_dead_node(res);
 975   }
 976 
 977   //
 978   // Process other users of allocation's projections
 979   //
 980   if (_callprojs.resproj != nullptr && _callprojs.resproj->outcnt() != 0) {
 981     // First disconnect stores captured by Initialize node.
 982     // If Initialize node is eliminated first in the following code,
 983     // it will kill such stores and DUIterator_Last will assert.
 984     for (DUIterator_Fast jmax, j = _callprojs.resproj->fast_outs(jmax);  j < jmax; j++) {
 985       Node* use = _callprojs.resproj->fast_out(j);
 986       if (use->is_AddP()) {
 987         // raw memory addresses used only by the initialization
 988         _igvn.replace_node(use, C->top());
 989         --j; --jmax;
 990       }
 991     }
 992     for (DUIterator_Last jmin, j = _callprojs.resproj->last_outs(jmin); j >= jmin; ) {
 993       Node* use = _callprojs.resproj->last_out(j);
 994       uint oc1 = _callprojs.resproj->outcnt();
 995       if (use->is_Initialize()) {
 996         // Eliminate Initialize node.
 997         InitializeNode *init = use->as_Initialize();
 998         assert(init->outcnt() <= 2, "only a control and memory projection expected");
 999         Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
1000         if (ctrl_proj != nullptr) {
1001           _igvn.replace_node(ctrl_proj, init->in(TypeFunc::Control));
1002 #ifdef ASSERT
1003           // If the InitializeNode has no memory out, it will die, and tmp will become null
1004           Node* tmp = init->in(TypeFunc::Control);
1005           assert(tmp == nullptr || tmp == _callprojs.fallthrough_catchproj, "allocation control projection");
1006 #endif
1007         }
1008         Node *mem_proj = init->proj_out_or_null(TypeFunc::Memory);
1009         if (mem_proj != nullptr) {
1010           Node *mem = init->in(TypeFunc::Memory);
1011 #ifdef ASSERT
1012           if (mem->is_MergeMem()) {
1013             assert(mem->in(TypeFunc::Memory) == _callprojs.fallthrough_memproj, "allocation memory projection");
1014           } else {
1015             assert(mem == _callprojs.fallthrough_memproj, "allocation memory projection");
1016           }
1017 #endif
1018           _igvn.replace_node(mem_proj, mem);
1019         }




1020       } else  {
1021         assert(false, "only Initialize or AddP expected");
1022       }
1023       j -= (oc1 - _callprojs.resproj->outcnt());
1024     }
1025   }
1026   if (_callprojs.fallthrough_catchproj != nullptr) {
1027     _igvn.replace_node(_callprojs.fallthrough_catchproj, alloc->in(TypeFunc::Control));
1028   }
1029   if (_callprojs.fallthrough_memproj != nullptr) {
1030     _igvn.replace_node(_callprojs.fallthrough_memproj, alloc->in(TypeFunc::Memory));
1031   }
1032   if (_callprojs.catchall_memproj != nullptr) {
1033     _igvn.replace_node(_callprojs.catchall_memproj, C->top());
1034   }
1035   if (_callprojs.fallthrough_ioproj != nullptr) {
1036     _igvn.replace_node(_callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
1037   }
1038   if (_callprojs.catchall_ioproj != nullptr) {
1039     _igvn.replace_node(_callprojs.catchall_ioproj, C->top());
1040   }
1041   if (_callprojs.catchall_catchproj != nullptr) {
1042     _igvn.replace_node(_callprojs.catchall_catchproj, C->top());
1043   }
1044 }
1045 
1046 bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) {
1047   // If reallocation fails during deoptimization we'll pop all
1048   // interpreter frames for this compiled frame and that won't play
1049   // nice with JVMTI popframe.
1050   // We avoid this issue by eager reallocation when the popframe request
1051   // is received.
1052   if (!EliminateAllocations || !alloc->_is_non_escaping) {
1053     return false;
1054   }
1055   Node* klass = alloc->in(AllocateNode::KlassNode);
1056   const TypeKlassPtr* tklass = _igvn.type(klass)->is_klassptr();
1057   Node* res = alloc->result_cast();







1058   // Eliminate boxing allocations which are not used
1059   // regardless scalar replaceable status.
1060   bool boxing_alloc = C->eliminate_boxing() &&

1061                       tklass->isa_instklassptr() &&
1062                       tklass->is_instklassptr()->instance_klass()->is_box_klass();
1063   if (!alloc->_is_scalar_replaceable && (!boxing_alloc || (res != nullptr))) {
1064     return false;
1065   }
1066 
1067   alloc->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1068 
1069   GrowableArray <SafePointNode *> safepoints;
1070   if (!can_eliminate_allocation(&_igvn, alloc, &safepoints)) {
1071     return false;
1072   }
1073 
1074   if (!alloc->_is_scalar_replaceable) {
1075     assert(res == nullptr, "sanity");
1076     // We can only eliminate allocation if all debug info references
1077     // are already replaced with SafePointScalarObject because
1078     // we can't search for a fields value without instance_id.
1079     if (safepoints.length() > 0) {

1080       return false;
1081     }
1082   }
1083 
1084   if (!scalar_replacement(alloc, safepoints)) {
1085     return false;
1086   }
1087 
1088   CompileLog* log = C->log();
1089   if (log != nullptr) {
1090     log->head("eliminate_allocation type='%d'",
1091               log->identify(tklass->exact_klass()));
1092     JVMState* p = alloc->jvms();
1093     while (p != nullptr) {
1094       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1095       p = p->caller();
1096     }
1097     log->tail("eliminate_allocation");
1098   }
1099 
1100   process_users_of_allocation(alloc);
1101 
1102 #ifndef PRODUCT
1103   if (PrintEliminateAllocations) {
1104     if (alloc->is_AllocateArray())
1105       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1106     else
1107       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1108   }
1109 #endif
1110 
1111   return true;
1112 }
1113 
1114 bool PhaseMacroExpand::eliminate_boxing_node(CallStaticJavaNode *boxing) {
1115   // EA should remove all uses of non-escaping boxing node.
1116   if (!C->eliminate_boxing() || boxing->proj_out_or_null(TypeFunc::Parms) != nullptr) {
1117     return false;
1118   }
1119 
1120   assert(boxing->result_cast() == nullptr, "unexpected boxing node result");
1121 
1122   boxing->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1123 
1124   const TypeTuple* r = boxing->tf()->range();
1125   assert(r->cnt() > TypeFunc::Parms, "sanity");
1126   const TypeInstPtr* t = r->field_at(TypeFunc::Parms)->isa_instptr();
1127   assert(t != nullptr, "sanity");
1128 
1129   CompileLog* log = C->log();
1130   if (log != nullptr) {
1131     log->head("eliminate_boxing type='%d'",
1132               log->identify(t->instance_klass()));
1133     JVMState* p = boxing->jvms();
1134     while (p != nullptr) {
1135       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1136       p = p->caller();
1137     }
1138     log->tail("eliminate_boxing");
1139   }
1140 
1141   process_users_of_allocation(boxing);
1142 
1143 #ifndef PRODUCT
1144   if (PrintEliminateAllocations) {

1288         }
1289       }
1290 #endif
1291       yank_alloc_node(alloc);
1292       return;
1293     }
1294   }
1295 
1296   enum { too_big_or_final_path = 1, need_gc_path = 2 };
1297   Node *slow_region = nullptr;
1298   Node *toobig_false = ctrl;
1299 
1300   // generate the initial test if necessary
1301   if (initial_slow_test != nullptr ) {
1302     assert (expand_fast_path, "Only need test if there is a fast path");
1303     slow_region = new RegionNode(3);
1304 
1305     // Now make the initial failure test.  Usually a too-big test but
1306     // might be a TRUE for finalizers or a fancy class check for
1307     // newInstance0.
1308     IfNode *toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1309     transform_later(toobig_iff);
1310     // Plug the failing-too-big test into the slow-path region
1311     Node *toobig_true = new IfTrueNode( toobig_iff );
1312     transform_later(toobig_true);
1313     slow_region    ->init_req( too_big_or_final_path, toobig_true );
1314     toobig_false = new IfFalseNode( toobig_iff );
1315     transform_later(toobig_false);
1316   } else {
1317     // No initial test, just fall into next case
1318     assert(allocation_has_use || !expand_fast_path, "Should already have been handled");
1319     toobig_false = ctrl;
1320     debug_only(slow_region = NodeSentinel);
1321   }
1322 
1323   // If we are here there are several possibilities
1324   // - expand_fast_path is false - then only a slow path is expanded. That's it.
1325   // no_initial_check means a constant allocation.
1326   // - If check always evaluates to false -> expand_fast_path is false (see above)
1327   // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath)
1328   // if !allocation_has_use the fast path is empty
1329   // if !allocation_has_use && no_initial_check
1330   // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all.
1331   //   removed by yank_alloc_node above.
1332 
1333   Node *slow_mem = mem;  // save the current memory state for slow path
1334   // generate the fast allocation code unless we know that the initial test will always go slow
1335   if (expand_fast_path) {
1336     // Fast path modifies only raw memory.
1337     if (mem->is_MergeMem()) {
1338       mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1339     }
1340 
1341     // allocate the Region and Phi nodes for the result
1342     result_region = new RegionNode(3);
1343     result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1344     result_phi_i_o    = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1345 
1346     // Grab regular I/O before optional prefetch may change it.
1347     // Slow-path does no I/O so just set it to the original I/O.
1348     result_phi_i_o->init_req(slow_result_path, i_o);
1349 
1350     // Name successful fast-path variables
1351     Node* fast_oop_ctrl;
1352     Node* fast_oop_rawmem;

1353     if (allocation_has_use) {
1354       Node* needgc_ctrl = nullptr;
1355       result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1356 
1357       intx prefetch_lines = length != nullptr ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1358       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1359       Node* fast_oop = bs->obj_allocate(this, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1360                                         fast_oop_ctrl, fast_oop_rawmem,
1361                                         prefetch_lines);
1362 
1363       if (initial_slow_test != nullptr) {
1364         // This completes all paths into the slow merge point
1365         slow_region->init_req(need_gc_path, needgc_ctrl);
1366         transform_later(slow_region);
1367       } else {
1368         // No initial slow path needed!
1369         // Just fall from the need-GC path straight into the VM call.
1370         slow_region = needgc_ctrl;
1371       }
1372 

1390     result_phi_i_o   ->init_req(fast_result_path, i_o);
1391     result_phi_rawmem->init_req(fast_result_path, fast_oop_rawmem);
1392   } else {
1393     slow_region = ctrl;
1394     result_phi_i_o = i_o; // Rename it to use in the following code.
1395   }
1396 
1397   // Generate slow-path call
1398   CallNode *call = new CallStaticJavaNode(slow_call_type, slow_call_address,
1399                                OptoRuntime::stub_name(slow_call_address),
1400                                TypePtr::BOTTOM);
1401   call->init_req(TypeFunc::Control,   slow_region);
1402   call->init_req(TypeFunc::I_O,       top());    // does no i/o
1403   call->init_req(TypeFunc::Memory,    slow_mem); // may gc ptrs
1404   call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1405   call->init_req(TypeFunc::FramePtr,  alloc->in(TypeFunc::FramePtr));
1406 
1407   call->init_req(TypeFunc::Parms+0, klass_node);
1408   if (length != nullptr) {
1409     call->init_req(TypeFunc::Parms+1, length);



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

1668     Node* thread = new ThreadLocalNode();
1669     transform_later(thread);
1670 
1671     call->init_req(TypeFunc::Parms + 0, thread);
1672     call->init_req(TypeFunc::Parms + 1, oop);
1673     call->init_req(TypeFunc::Control, ctrl);
1674     call->init_req(TypeFunc::I_O    , top()); // does no i/o
1675     call->init_req(TypeFunc::Memory , rawmem);
1676     call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1677     call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1678     transform_later(call);
1679     ctrl = new ProjNode(call, TypeFunc::Control);
1680     transform_later(ctrl);
1681     rawmem = new ProjNode(call, TypeFunc::Memory);
1682     transform_later(rawmem);
1683   }
1684 }
1685 
1686 // Helper for PhaseMacroExpand::expand_allocate_common.
1687 // Initializes the newly-allocated storage.
1688 Node*
1689 PhaseMacroExpand::initialize_object(AllocateNode* alloc,
1690                                     Node* control, Node* rawmem, Node* object,
1691                                     Node* klass_node, Node* length,
1692                                     Node* size_in_bytes) {
1693   InitializeNode* init = alloc->initialization();
1694   // Store the klass & mark bits
1695   Node* mark_node = alloc->make_ideal_mark(&_igvn, object, control, rawmem);
1696   if (!mark_node->is_Con()) {
1697     transform_later(mark_node);
1698   }
1699   rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
1700 
1701   rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
1702   int header_size = alloc->minimum_header_size();  // conservatively small
1703 
1704   // Array length
1705   if (length != nullptr) {         // Arrays need length field
1706     rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1707     // conservatively small header size:
1708     header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1709     if (_igvn.type(klass_node)->isa_aryklassptr()) {   // we know the exact header size in most cases:
1710       BasicType elem = _igvn.type(klass_node)->is_klassptr()->as_instance_type()->isa_aryptr()->elem()->array_element_basic_type();
1711       if (is_reference_type(elem, true)) {
1712         elem = T_OBJECT;
1713       }
1714       header_size = Klass::layout_helper_header_size(Klass::array_layout_helper(elem));
1715     }
1716   }
1717 
1718   // Clear the object body, if necessary.
1719   if (init == nullptr) {
1720     // The init has somehow disappeared; be cautious and clear everything.
1721     //
1722     // This can happen if a node is allocated but an uncommon trap occurs
1723     // immediately.  In this case, the Initialize gets associated with the
1724     // trap, and may be placed in a different (outer) loop, if the Allocate
1725     // is in a loop.  If (this is rare) the inner loop gets unrolled, then
1726     // there can be two Allocates to one Initialize.  The answer in all these
1727     // edge cases is safety first.  It is always safe to clear immediately
1728     // within an Allocate, and then (maybe or maybe not) clear some more later.
1729     if (!(UseTLAB && ZeroTLAB)) {
1730       rawmem = ClearArrayNode::clear_memory(control, rawmem, object,


1731                                             header_size, size_in_bytes,
1732                                             &_igvn);
1733     }
1734   } else {
1735     if (!init->is_complete()) {
1736       // Try to win by zeroing only what the init does not store.
1737       // We can also try to do some peephole optimizations,
1738       // such as combining some adjacent subword stores.
1739       rawmem = init->complete_stores(control, rawmem, object,
1740                                      header_size, size_in_bytes, &_igvn);
1741     }
1742     // We have no more use for this link, since the AllocateNode goes away:
1743     init->set_req(InitializeNode::RawAddress, top());
1744     // (If we keep the link, it just confuses the register allocator,
1745     // who thinks he sees a real use of the address by the membar.)
1746   }
1747 
1748   return rawmem;
1749 }
1750 

2080   } // EliminateNestedLocks
2081 
2082   if (alock->is_non_esc_obj()) { // Lock is used for non escaping object
2083     // Look for all locks of this object and mark them and
2084     // corresponding BoxLock nodes as eliminated.
2085     Node* obj = alock->obj_node();
2086     for (uint j = 0; j < obj->outcnt(); j++) {
2087       Node* o = obj->raw_out(j);
2088       if (o->is_AbstractLock() &&
2089           o->as_AbstractLock()->obj_node()->eqv_uncast(obj)) {
2090         alock = o->as_AbstractLock();
2091         Node* box = alock->box_node();
2092         // Replace old box node with new eliminated box for all users
2093         // of the same object and mark related locks as eliminated.
2094         mark_eliminated_box(box, obj);
2095       }
2096     }
2097   }
2098 }
2099 











































2100 // we have determined that this lock/unlock can be eliminated, we simply
2101 // eliminate the node without expanding it.
2102 //
2103 // Note:  The membar's associated with the lock/unlock are currently not
2104 //        eliminated.  This should be investigated as a future enhancement.
2105 //
2106 bool PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) {
2107 
2108   if (!alock->is_eliminated()) {
2109     return false;
2110   }
2111 #ifdef ASSERT
2112   if (!alock->is_coarsened()) {
2113     // Check that new "eliminated" BoxLock node is created.
2114     BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2115     assert(oldbox->is_eliminated(), "should be done already");
2116   }
2117 #endif
2118 
2119   alock->log_lock_optimization(C, "eliminate_lock");
2120 
2121 #ifndef PRODUCT
2122   if (PrintEliminateLocks) {
2123     tty->print_cr("++++ Eliminated: %d %s '%s'", alock->_idx, (alock->is_Lock() ? "Lock" : "Unlock"), alock->kind_as_string());
2124   }
2125 #endif
2126 
2127   Node* mem  = alock->in(TypeFunc::Memory);
2128   Node* ctrl = alock->in(TypeFunc::Control);
2129   guarantee(ctrl != nullptr, "missing control projection, cannot replace_node() with null");
2130 
2131   alock->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2132   // There are 2 projections from the lock.  The lock node will
2133   // be deleted when its last use is subsumed below.
2134   assert(alock->outcnt() == 2 &&
2135          _callprojs.fallthrough_proj != nullptr &&
2136          _callprojs.fallthrough_memproj != nullptr,
2137          "Unexpected projections from Lock/Unlock");
2138 
2139   Node* fallthroughproj = _callprojs.fallthrough_proj;
2140   Node* memproj_fallthrough = _callprojs.fallthrough_memproj;
2141 
2142   // The memory projection from a lock/unlock is RawMem
2143   // The input to a Lock is merged memory, so extract its RawMem input
2144   // (unless the MergeMem has been optimized away.)
2145   if (alock->is_Lock()) {



2146     // Search for MemBarAcquireLock node and delete it also.
2147     MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
2148     assert(membar != nullptr && membar->Opcode() == Op_MemBarAcquireLock, "");
2149     Node* ctrlproj = membar->proj_out(TypeFunc::Control);
2150     Node* memproj = membar->proj_out(TypeFunc::Memory);
2151     _igvn.replace_node(ctrlproj, fallthroughproj);
2152     _igvn.replace_node(memproj, memproj_fallthrough);
2153 
2154     // Delete FastLock node also if this Lock node is unique user
2155     // (a loop peeling may clone a Lock node).
2156     Node* flock = alock->as_Lock()->fastlock_node();
2157     if (flock->outcnt() == 1) {
2158       assert(flock->unique_out() == alock, "sanity");
2159       _igvn.replace_node(flock, top());
2160     }
2161   }
2162 
2163   // Search for MemBarReleaseLock node and delete it also.
2164   if (alock->is_Unlock() && ctrl->is_Proj() && ctrl->in(0)->is_MemBar()) {
2165     MemBarNode* membar = ctrl->in(0)->as_MemBar();

2186   Node* mem = lock->in(TypeFunc::Memory);
2187   Node* obj = lock->obj_node();
2188   Node* box = lock->box_node();
2189   Node* flock = lock->fastlock_node();
2190 
2191   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2192 
2193   // Make the merge point
2194   Node *region;
2195   Node *mem_phi;
2196   Node *slow_path;
2197 
2198   region  = new RegionNode(3);
2199   // create a Phi for the memory state
2200   mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2201 
2202   // Optimize test; set region slot 2
2203   slow_path = opt_bits_test(ctrl, region, 2, flock, 0, 0);
2204   mem_phi->init_req(2, mem);
2205 



2206   // Make slow path call
2207   CallNode *call = make_slow_call((CallNode *) lock, OptoRuntime::complete_monitor_enter_Type(),
2208                                   OptoRuntime::complete_monitor_locking_Java(), nullptr, slow_path,
2209                                   obj, box, nullptr);
2210 
2211   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2212 
2213   // Slow path can only throw asynchronous exceptions, which are always
2214   // de-opted.  So the compiler thinks the slow-call can never throw an
2215   // exception.  If it DOES throw an exception we would need the debug
2216   // info removed first (since if it throws there is no monitor).
2217   assert(_callprojs.fallthrough_ioproj == nullptr && _callprojs.catchall_ioproj == nullptr &&
2218          _callprojs.catchall_memproj == nullptr && _callprojs.catchall_catchproj == nullptr, "Unexpected projection from Lock");
2219 
2220   // Capture slow path
2221   // disconnect fall-through projection from call and create a new one
2222   // hook up users of fall-through projection to region
2223   Node *slow_ctrl = _callprojs.fallthrough_proj->clone();
2224   transform_later(slow_ctrl);
2225   _igvn.hash_delete(_callprojs.fallthrough_proj);
2226   _callprojs.fallthrough_proj->disconnect_inputs(C);
2227   region->init_req(1, slow_ctrl);
2228   // region inputs are now complete
2229   transform_later(region);
2230   _igvn.replace_node(_callprojs.fallthrough_proj, region);
2231 
2232   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2233 
2234   mem_phi->init_req(1, memproj);
2235 
2236   transform_later(mem_phi);
2237 
2238   _igvn.replace_node(_callprojs.fallthrough_memproj, mem_phi);
2239 }
2240 
2241 //------------------------------expand_unlock_node----------------------
2242 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
2243 
2244   Node* ctrl = unlock->in(TypeFunc::Control);
2245   Node* mem = unlock->in(TypeFunc::Memory);
2246   Node* obj = unlock->obj_node();
2247   Node* box = unlock->box_node();
2248 
2249   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2250 
2251   // No need for a null check on unlock
2252 
2253   // Make the merge point
2254   Node *region;
2255   Node *mem_phi;
2256 
2257   region  = new RegionNode(3);
2258   // create a Phi for the memory state
2259   mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2260 
2261   FastUnlockNode *funlock = new FastUnlockNode( ctrl, obj, box );
2262   funlock = transform_later( funlock )->as_FastUnlock();
2263   // Optimize test; set region slot 2
2264   Node *slow_path = opt_bits_test(ctrl, region, 2, funlock, 0, 0);
2265   Node *thread = transform_later(new ThreadLocalNode());
2266 
2267   CallNode *call = make_slow_call((CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(),
2268                                   CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C),
2269                                   "complete_monitor_unlocking_C", slow_path, obj, box, thread);
2270 
2271   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2272   assert(_callprojs.fallthrough_ioproj == nullptr && _callprojs.catchall_ioproj == nullptr &&
2273          _callprojs.catchall_memproj == nullptr && _callprojs.catchall_catchproj == nullptr, "Unexpected projection from Lock");
2274 
2275   // No exceptions for unlocking
2276   // Capture slow path
2277   // disconnect fall-through projection from call and create a new one
2278   // hook up users of fall-through projection to region
2279   Node *slow_ctrl = _callprojs.fallthrough_proj->clone();
2280   transform_later(slow_ctrl);
2281   _igvn.hash_delete(_callprojs.fallthrough_proj);
2282   _callprojs.fallthrough_proj->disconnect_inputs(C);
2283   region->init_req(1, slow_ctrl);
2284   // region inputs are now complete
2285   transform_later(region);
2286   _igvn.replace_node(_callprojs.fallthrough_proj, region);
2287 
2288   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory) );
2289   mem_phi->init_req(1, memproj );
2290   mem_phi->init_req(2, mem);
2291   transform_later(mem_phi);
2292 
2293   _igvn.replace_node(_callprojs.fallthrough_memproj, mem_phi);
2294 }
2295 



















































































































































































































2296 void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) {
2297   assert(check->in(SubTypeCheckNode::Control) == nullptr, "should be pinned");
2298   Node* bol = check->unique_out();
2299   Node* obj_or_subklass = check->in(SubTypeCheckNode::ObjOrSubKlass);
2300   Node* superklass = check->in(SubTypeCheckNode::SuperKlass);
2301   assert(bol->is_Bool() && bol->as_Bool()->_test._test == BoolTest::ne, "unexpected bool node");
2302 
2303   for (DUIterator_Last imin, i = bol->last_outs(imin); i >= imin; --i) {
2304     Node* iff = bol->last_out(i);
2305     assert(iff->is_If(), "where's the if?");
2306 
2307     if (iff->in(0)->is_top()) {
2308       _igvn.replace_input_of(iff, 1, C->top());
2309       continue;
2310     }
2311 
2312     Node* iftrue = iff->as_If()->proj_out(1);
2313     Node* iffalse = iff->as_If()->proj_out(0);
2314     Node* ctrl = iff->in(0);
2315 
2316     Node* subklass = nullptr;
2317     if (_igvn.type(obj_or_subklass)->isa_klassptr()) {
2318       subklass = obj_or_subklass;
2319     } else {
2320       Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes());
2321       subklass = _igvn.transform(LoadKlassNode::make(_igvn, nullptr, C->immutable_memory(), k_adr, TypeInstPtr::KLASS));
2322     }
2323 
2324     Node* not_subtype_ctrl = Phase::gen_subtype_check(subklass, superklass, &ctrl, nullptr, _igvn, check->method(), check->bci());
2325 
2326     _igvn.replace_input_of(iff, 0, C->top());
2327     _igvn.replace_node(iftrue, not_subtype_ctrl);
2328     _igvn.replace_node(iffalse, ctrl);
2329   }
2330   _igvn.replace_node(check, C->top());
2331 }
2332 

















































































































2333 //---------------------------eliminate_macro_nodes----------------------
2334 // Eliminate scalar replaced allocations and associated locks.
2335 void PhaseMacroExpand::eliminate_macro_nodes() {
2336   if (C->macro_count() == 0)
2337     return;
2338   NOT_PRODUCT(int membar_before = count_MemBar(C);)
2339 
2340   // Before elimination may re-mark (change to Nested or NonEscObj)
2341   // all associated (same box and obj) lock and unlock nodes.
2342   int cnt = C->macro_count();
2343   for (int i=0; i < cnt; i++) {
2344     Node *n = C->macro_node(i);
2345     if (n->is_AbstractLock()) { // Lock and Unlock nodes
2346       mark_eliminated_locking_nodes(n->as_AbstractLock());
2347     }
2348   }
2349   // Re-marking may break consistency of Coarsened locks.
2350   if (!C->coarsened_locks_consistent()) {
2351     return; // recompile without Coarsened locks if broken
2352   }

2373   }
2374   // Next, attempt to eliminate allocations
2375   _has_locks = false;
2376   progress = true;
2377   while (progress) {
2378     progress = false;
2379     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
2380       Node* n = C->macro_node(i - 1);
2381       bool success = false;
2382       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2383       switch (n->class_id()) {
2384       case Node::Class_Allocate:
2385       case Node::Class_AllocateArray:
2386         success = eliminate_allocate_node(n->as_Allocate());
2387 #ifndef PRODUCT
2388         if (success && PrintOptoStatistics) {
2389           Atomic::inc(&PhaseMacroExpand::_objs_scalar_replaced_counter);
2390         }
2391 #endif
2392         break;
2393       case Node::Class_CallStaticJava:
2394         success = eliminate_boxing_node(n->as_CallStaticJava());



2395         break;

2396       case Node::Class_Lock:
2397       case Node::Class_Unlock:
2398         assert(!n->as_AbstractLock()->is_eliminated(), "sanity");
2399         _has_locks = true;
2400         break;
2401       case Node::Class_ArrayCopy:
2402         break;
2403       case Node::Class_OuterStripMinedLoop:
2404         break;
2405       case Node::Class_SubTypeCheck:
2406         break;
2407       case Node::Class_Opaque1:
2408         break;


2409       default:
2410         assert(n->Opcode() == Op_LoopLimit ||
2411                n->Opcode() == Op_Opaque3   ||
2412                n->Opcode() == Op_Opaque4   ||
2413                n->Opcode() == Op_MaxL      ||
2414                n->Opcode() == Op_MinL      ||
2415                BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
2416                "unknown node type in macro list");
2417       }
2418       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2419       progress = progress || success;
2420     }
2421   }
2422 #ifndef PRODUCT
2423   if (PrintOptoStatistics) {
2424     int membar_after = count_MemBar(C);
2425     Atomic::add(&PhaseMacroExpand::_memory_barriers_removed_counter, membar_before - membar_after);
2426   }
2427 #endif
2428 }

2431 //  Returns true if a failure occurred.
2432 bool PhaseMacroExpand::expand_macro_nodes() {
2433   // Last attempt to eliminate macro nodes.
2434   eliminate_macro_nodes();
2435   if (C->failing())  return true;
2436 
2437   // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
2438   bool progress = true;
2439   while (progress) {
2440     progress = false;
2441     for (int i = C->macro_count(); i > 0; i--) {
2442       Node* n = C->macro_node(i-1);
2443       bool success = false;
2444       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2445       if (n->Opcode() == Op_LoopLimit) {
2446         // Remove it from macro list and put on IGVN worklist to optimize.
2447         C->remove_macro_node(n);
2448         _igvn._worklist.push(n);
2449         success = true;
2450       } else if (n->Opcode() == Op_CallStaticJava) {
2451         // Remove it from macro list and put on IGVN worklist to optimize.
2452         C->remove_macro_node(n);
2453         _igvn._worklist.push(n);
2454         success = true;



2455       } else if (n->is_Opaque1()) {
2456         _igvn.replace_node(n, n->in(1));
2457         success = true;
2458 #if INCLUDE_RTM_OPT
2459       } else if ((n->Opcode() == Op_Opaque3) && ((Opaque3Node*)n)->rtm_opt()) {
2460         assert(C->profile_rtm(), "should be used only in rtm deoptimization code");
2461         assert((n->outcnt() == 1) && n->unique_out()->is_Cmp(), "");
2462         Node* cmp = n->unique_out();
2463 #ifdef ASSERT
2464         // Validate graph.
2465         assert((cmp->outcnt() == 1) && cmp->unique_out()->is_Bool(), "");
2466         BoolNode* bol = cmp->unique_out()->as_Bool();
2467         assert((bol->outcnt() == 1) && bol->unique_out()->is_If() &&
2468                (bol->_test._test == BoolTest::ne), "");
2469         IfNode* ifn = bol->unique_out()->as_If();
2470         assert((ifn->outcnt() == 2) &&
2471                ifn->proj_out(1)->is_uncommon_trap_proj(Deoptimization::Reason_rtm_state_change) != nullptr, "");
2472 #endif
2473         Node* repl = n->in(1);
2474         if (!_has_locks) {

2549     // Worst case is a macro node gets expanded into about 200 nodes.
2550     // Allow 50% more for optimization.
2551     if (C->check_node_count(300, "out of nodes before macro expansion")) {
2552       return true;
2553     }
2554 
2555     DEBUG_ONLY(int old_macro_count = C->macro_count();)
2556     switch (n->class_id()) {
2557     case Node::Class_Lock:
2558       expand_lock_node(n->as_Lock());
2559       break;
2560     case Node::Class_Unlock:
2561       expand_unlock_node(n->as_Unlock());
2562       break;
2563     case Node::Class_ArrayCopy:
2564       expand_arraycopy_node(n->as_ArrayCopy());
2565       break;
2566     case Node::Class_SubTypeCheck:
2567       expand_subtypecheck_node(n->as_SubTypeCheck());
2568       break;







2569     default:
2570       assert(false, "unknown node type in macro list");
2571     }
2572     assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2573     if (C->failing())  return true;
2574 
2575     // Clean up the graph so we're less likely to hit the maximum node
2576     // limit
2577     _igvn.set_delay_transform(false);
2578     _igvn.optimize();
2579     if (C->failing())  return true;
2580     _igvn.set_delay_transform(true);
2581   }
2582 
2583   // All nodes except Allocate nodes are expanded now. There could be
2584   // new optimization opportunities (such as folding newly created
2585   // load from a just allocated object). Run IGVN.
2586 
2587   // expand "macro" nodes
2588   // nodes are removed from the macro list as they are processed

   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "ci/ciFlatArrayKlass.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/phaseX.hpp"
  50 #include "opto/rootnode.hpp"
  51 #include "opto/runtime.hpp"
  52 #include "opto/subnode.hpp"
  53 #include "opto/subtypenode.hpp"
  54 #include "opto/type.hpp"
  55 #include "prims/jvmtiExport.hpp"
  56 #include "runtime/continuation.hpp"
  57 #include "runtime/sharedRuntime.hpp"
  58 #include "runtime/stubRoutines.hpp"
  59 #include "utilities/macros.hpp"
  60 #include "utilities/powerOfTwo.hpp"
  61 #if INCLUDE_G1GC
  62 #include "gc/g1/g1ThreadLocalData.hpp"
  63 #endif // INCLUDE_G1GC
  64 
  65 
  66 //
  67 // Replace any references to "oldref" in inputs to "use" with "newref".
  68 // Returns the number of replacements made.
  69 //
  70 int PhaseMacroExpand::replace_input(Node *use, Node *oldref, Node *newref) {
  71   int nreplacements = 0;
  72   uint req = use->req();
  73   for (uint j = 0; j < use->len(); j++) {
  74     Node *uin = use->in(j);
  75     if (uin == oldref) {
  76       if (j < req)
  77         use->set_req(j, newref);
  78       else
  79         use->set_prec(j, newref);
  80       nreplacements++;
  81     } else if (j >= req && uin == nullptr) {
  82       break;
  83     }
  84   }
  85   return nreplacements;
  86 }
  87 












  88 Node* PhaseMacroExpand::opt_bits_test(Node* ctrl, Node* region, int edge, Node* word, int mask, int bits, bool return_fast_path) {
  89   Node* cmp;
  90   if (mask != 0) {
  91     Node* and_node = transform_later(new AndXNode(word, MakeConX(mask)));
  92     cmp = transform_later(new CmpXNode(and_node, MakeConX(bits)));
  93   } else {
  94     cmp = word;
  95   }
  96   Node* bol = transform_later(new BoolNode(cmp, BoolTest::ne));
  97   IfNode* iff = new IfNode( ctrl, bol, PROB_MIN, COUNT_UNKNOWN );
  98   transform_later(iff);
  99 
 100   // Fast path taken.
 101   Node *fast_taken = transform_later(new IfFalseNode(iff));
 102 
 103   // Fast path not-taken, i.e. slow path
 104   Node *slow_taken = transform_later(new IfTrueNode(iff));
 105 
 106   if (return_fast_path) {
 107     region->init_req(edge, slow_taken); // Capture slow-control

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

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

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

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

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

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

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

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

 469   Node *alloc_mem = alloc->in(TypeFunc::Memory);
 470   VectorSet visited;
 471 
 472   bool done = sfpt_mem == alloc_mem;
 473   Node *mem = sfpt_mem;
 474   while (!done) {
 475     if (visited.test_set(mem->_idx)) {
 476       return nullptr;  // found a loop, give up
 477     }
 478     mem = scan_mem_chain(mem, alias_idx, offset, start_mem, alloc, &_igvn);
 479     if (mem == start_mem || mem == alloc_mem) {
 480       done = true;  // hit a sentinel, return appropriate 0 value
 481     } else if (mem->is_Initialize()) {
 482       mem = mem->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 483       if (mem == nullptr) {
 484         done = true; // Something went wrong.
 485       } else if (mem->is_Store()) {
 486         const TypePtr* atype = mem->as_Store()->adr_type();
 487         assert(C->get_alias_index(atype) == Compile::AliasIdxRaw, "store is correct memory slice");
 488         done = true;
 489       }
 490     } else if (mem->is_Store()) {
 491       const TypeOopPtr* atype = mem->as_Store()->adr_type()->isa_oopptr();
 492       assert(atype != nullptr, "address type must be oopptr");
 493       assert(C->get_alias_index(atype) == alias_idx &&
 494              atype->is_known_instance_field() && atype->flat_offset() == offset &&
 495              atype->instance_id() == instance_id, "store is correct memory slice");
 496       done = true;
 497     } else if (mem->is_Phi()) {
 498       // try to find a phi's unique input
 499       Node *unique_input = nullptr;
 500       Node *top = C->top();
 501       for (uint i = 1; i < mem->req(); i++) {
 502         Node *n = scan_mem_chain(mem->in(i), alias_idx, offset, start_mem, alloc, &_igvn);
 503         if (n == nullptr || n == top || n == mem) {
 504           continue;
 505         } else if (unique_input == nullptr) {
 506           unique_input = n;
 507         } else if (unique_input != n) {
 508           unique_input = top;
 509           break;
 510         }
 511       }
 512       if (unique_input != nullptr && unique_input != top) {
 513         mem = unique_input;
 514       } else {
 515         done = true;
 516       }
 517     } else if (mem->is_ArrayCopy()) {
 518       done = true;
 519     } else {
 520       DEBUG_ONLY( mem->dump(); )
 521       assert(false, "unexpected node");
 522     }
 523   }
 524   if (mem != nullptr) {
 525     if (mem == start_mem || mem == alloc_mem) {
 526       // hit a sentinel, return appropriate 0 value
 527       Node* default_value = alloc->in(AllocateNode::DefaultValue);
 528       if (default_value != nullptr) {
 529         return default_value;
 530       }
 531       assert(alloc->in(AllocateNode::RawDefaultValue) == nullptr, "default value may not be null");
 532       return _igvn.zerocon(ft);
 533     } else if (mem->is_Store()) {
 534       Node* n = mem->in(MemNode::ValueIn);
 535       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 536       n = bs->step_over_gc_barrier(n);
 537       return n;
 538     } else if (mem->is_Phi()) {
 539       // attempt to produce a Phi reflecting the values on the input paths of the Phi
 540       Node_Stack value_phis(8);
 541       Node* phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, &value_phis, ValueSearchLimit);
 542       if (phi != nullptr) {
 543         return phi;
 544       } else {
 545         // Kill all new Phis
 546         while(value_phis.is_nonempty()) {
 547           Node* n = value_phis.node();
 548           _igvn.replace_node(n, C->top());
 549           value_phis.pop();
 550         }
 551       }
 552     } else if (mem->is_ArrayCopy()) {
 553       Node* ctl = mem->in(0);
 554       Node* m = mem->in(TypeFunc::Memory);
 555       if (sfpt_ctl->is_Proj() && sfpt_ctl->as_Proj()->is_uncommon_trap_proj()) {
 556         // pin the loads in the uncommon trap path
 557         ctl = sfpt_ctl;
 558         m = sfpt_mem;
 559       }
 560       return make_arraycopy_load(mem->as_ArrayCopy(), offset, ctl, m, ft, ftype, alloc);
 561     }
 562   }
 563   // Something went wrong.
 564   return nullptr;
 565 }
 566 
 567 // Search the last value stored into the inline type's fields.
 568 Node* PhaseMacroExpand::inline_type_from_mem(Node* mem, Node* ctl, ciInlineKlass* vk, const TypeAryPtr* adr_type, int offset, AllocateNode* alloc) {
 569   // Subtract the offset of the first field to account for the missing oop header
 570   offset -= vk->first_field_offset();
 571   // Create a new InlineTypeNode and retrieve the field values from memory
 572   InlineTypeNode* vt = InlineTypeNode::make_uninitialized(_igvn, vk);
 573   transform_later(vt);
 574   for (int i = 0; i < vk->nof_declared_nonstatic_fields(); ++i) {
 575     ciType* field_type = vt->field_type(i);
 576     int field_offset = offset + vt->field_offset(i);
 577     Node* value = nullptr;
 578     if (vt->field_is_flat(i)) {
 579       value = inline_type_from_mem(mem, ctl, field_type->as_inline_klass(), adr_type, field_offset, alloc);
 580     } else {
 581       const Type* ft = Type::get_const_type(field_type);
 582       BasicType bt = type2field[field_type->basic_type()];
 583       if (UseCompressedOops && !is_java_primitive(bt)) {
 584         ft = ft->make_narrowoop();
 585         bt = T_NARROWOOP;
 586       }
 587       // Each inline type field has its own memory slice
 588       adr_type = adr_type->with_field_offset(field_offset);
 589       value = value_from_mem(mem, ctl, bt, ft, adr_type, alloc);
 590       if (value != nullptr && ft->isa_narrowoop()) {
 591         assert(UseCompressedOops, "unexpected narrow oop");
 592         if (value->is_EncodeP()) {
 593           value = value->in(1);
 594         } else {
 595           value = transform_later(new DecodeNNode(value, value->get_ptr_type()));
 596         }
 597       }
 598     }
 599     if (value != nullptr) {
 600       vt->set_field_value(i, value);
 601     } else {
 602       // We might have reached the TrackedInitializationLimit
 603       return nullptr;
 604     }
 605   }
 606   return vt;
 607 }
 608 
 609 // Check the possibility of scalar replacement.
 610 bool PhaseMacroExpand::can_eliminate_allocation(PhaseIterGVN* igvn, AllocateNode *alloc, GrowableArray <SafePointNode *>* safepoints) {
 611   //  Scan the uses of the allocation to check for anything that would
 612   //  prevent us from eliminating it.
 613   NOT_PRODUCT( const char* fail_eliminate = nullptr; )
 614   DEBUG_ONLY( Node* disq_node = nullptr; )
 615   bool can_eliminate = true;
 616   bool reduce_merge_precheck = (safepoints == nullptr);
 617 
 618   Unique_Node_List worklist;
 619   Node* res = alloc->result_cast();
 620   const TypeOopPtr* res_type = nullptr;
 621   if (res == nullptr) {
 622     // All users were eliminated.
 623   } else if (!res->is_CheckCastPP()) {
 624     NOT_PRODUCT(fail_eliminate = "Allocation does not have unique CheckCastPP";)
 625     can_eliminate = false;
 626   } else {
 627     worklist.push(res);
 628     res_type = igvn->type(res)->isa_oopptr();
 629     if (res_type == nullptr) {
 630       NOT_PRODUCT(fail_eliminate = "Neither instance or array allocation";)
 631       can_eliminate = false;
 632     } else if (res_type->isa_aryptr()) {
 633       int length = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 634       if (length < 0) {
 635         NOT_PRODUCT(fail_eliminate = "Array's size is not constant";)
 636         can_eliminate = false;
 637       }
 638     }
 639   }
 640 
 641   while (can_eliminate && worklist.size() > 0) {
 642     BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
 643     res = worklist.pop();
 644     for (DUIterator_Fast jmax, j = res->fast_outs(jmax); j < jmax && can_eliminate; j++) {
 645       Node* use = res->fast_out(j);
 646 
 647       if (use->is_AddP()) {
 648         const TypePtr* addp_type = igvn->type(use)->is_ptr();
 649         int offset = addp_type->offset();
 650 
 651         if (offset == Type::OffsetTop || offset == Type::OffsetBot) {
 652           NOT_PRODUCT(fail_eliminate = "Undefined field reference";)
 653           can_eliminate = false;
 654           break;
 655         }
 656         for (DUIterator_Fast kmax, k = use->fast_outs(kmax);
 657                                    k < kmax && can_eliminate; k++) {
 658           Node* n = use->fast_out(k);
 659           if (!n->is_Store() && n->Opcode() != Op_CastP2X && !bs->is_gc_pre_barrier_node(n) && !reduce_merge_precheck) {
 660             DEBUG_ONLY(disq_node = n;)
 661             if (n->is_Load() || n->is_LoadStore()) {
 662               NOT_PRODUCT(fail_eliminate = "Field load";)
 663             } else {
 664               NOT_PRODUCT(fail_eliminate = "Not store field reference";)

 672                   use->as_ArrayCopy()->is_copyof_validated() ||
 673                   use->as_ArrayCopy()->is_copyofrange_validated()) &&
 674                  use->in(ArrayCopyNode::Dest) == res) {
 675         // ok to eliminate
 676       } else if (use->is_SafePoint()) {
 677         SafePointNode* sfpt = use->as_SafePoint();
 678         if (sfpt->is_Call() && sfpt->as_Call()->has_non_debug_use(res)) {
 679           // Object is passed as argument.
 680           DEBUG_ONLY(disq_node = use;)
 681           NOT_PRODUCT(fail_eliminate = "Object is passed as argument";)
 682           can_eliminate = false;
 683         }
 684         Node* sfptMem = sfpt->memory();
 685         if (sfptMem == nullptr || sfptMem->is_top()) {
 686           DEBUG_ONLY(disq_node = use;)
 687           NOT_PRODUCT(fail_eliminate = "null or TOP memory";)
 688           can_eliminate = false;
 689         } else if (!reduce_merge_precheck) {
 690           safepoints->append_if_missing(sfpt);
 691         }
 692       } else if (use->is_InlineType() && use->as_InlineType()->get_oop() == res) {
 693         // Look at uses
 694         for (DUIterator_Fast kmax, k = use->fast_outs(kmax); k < kmax; k++) {
 695           Node* u = use->fast_out(k);
 696           if (u->is_InlineType()) {
 697             // Use in flat field can be eliminated
 698             InlineTypeNode* vt = u->as_InlineType();
 699             for (uint i = 0; i < vt->field_count(); ++i) {
 700               if (vt->field_value(i) == use && !vt->field_is_flat(i)) {
 701                 can_eliminate = false; // Use in non-flat field
 702                 break;
 703               }
 704             }
 705           } else {
 706             // Add other uses to the worklist to process individually
 707             worklist.push(u);
 708           }
 709         }
 710       } else if (use->Opcode() == Op_StoreX && use->in(MemNode::Address) == res) {
 711         // Store to mark word of inline type larval buffer
 712         assert(res_type->is_inlinetypeptr(), "Unexpected store to mark word");
 713       } else if (reduce_merge_precheck && (use->is_Phi() || use->is_EncodeP() || use->Opcode() == Op_MemBarRelease)) {
 714         // Nothing to do
 715       } else if (use->Opcode() != Op_CastP2X) { // CastP2X is used by card mark
 716         if (use->is_Phi()) {
 717           if (use->outcnt() == 1 && use->unique_out()->Opcode() == Op_Return) {
 718             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 719           } else {
 720             NOT_PRODUCT(fail_eliminate = "Object is referenced by Phi";)
 721           }
 722           DEBUG_ONLY(disq_node = use;)
 723         } else {
 724           if (use->Opcode() == Op_Return) {
 725             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 726           } else {
 727             NOT_PRODUCT(fail_eliminate = "Object is referenced by node";)
 728           }
 729           DEBUG_ONLY(disq_node = use;)
 730         }
 731         can_eliminate = false;
 732       } else {
 733         assert(use->Opcode() == Op_CastP2X, "should be");
 734         assert(!use->has_out_with(Op_OrL), "should have been removed because oop is never null");
 735       }
 736     }
 737   }
 738 
 739 #ifndef PRODUCT
 740   if (PrintEliminateAllocations && safepoints != nullptr) {
 741     if (can_eliminate) {
 742       tty->print("Scalar ");
 743       if (res == nullptr)
 744         alloc->dump();
 745       else
 746         res->dump();
 747     } else {
 748       tty->print("NotScalar (%s)", fail_eliminate);
 749       if (res == nullptr)
 750         alloc->dump();
 751       else
 752         res->dump();
 753 #ifdef ASSERT
 754       if (disq_node != nullptr) {
 755           tty->print("  >>>> ");
 756           disq_node->dump();
 757       }
 758 #endif /*ASSERT*/
 759     }
 760   }
 761 
 762   if (TraceReduceAllocationMerges && !can_eliminate && reduce_merge_precheck) {
 763     tty->print_cr("\tCan't eliminate allocation because '%s': ", fail_eliminate != nullptr ? fail_eliminate : "");
 764     DEBUG_ONLY(if (disq_node != nullptr) disq_node->dump();)
 765   }
 766 #endif
 767   return can_eliminate;

 797     JVMState *jvms = sfpt_done->jvms();
 798     jvms->set_endoff(sfpt_done->req());
 799     // Now make a pass over the debug information replacing any references
 800     // to SafePointScalarObjectNode with the allocated object.
 801     int start = jvms->debug_start();
 802     int end   = jvms->debug_end();
 803     for (int i = start; i < end; i++) {
 804       if (sfpt_done->in(i)->is_SafePointScalarObject()) {
 805         SafePointScalarObjectNode* scobj = sfpt_done->in(i)->as_SafePointScalarObject();
 806         if (scobj->first_index(jvms) == sfpt_done->req() &&
 807             scobj->n_fields() == (uint)nfields) {
 808           assert(scobj->alloc() == alloc, "sanity");
 809           sfpt_done->set_req(i, res);
 810         }
 811       }
 812     }
 813     _igvn._worklist.push(sfpt_done);
 814   }
 815 }
 816 
 817 SafePointScalarObjectNode* PhaseMacroExpand::create_scalarized_object_description(AllocateNode *alloc, SafePointNode* sfpt,
 818                                                                                   Unique_Node_List* value_worklist) {
 819   // Fields of scalar objs are referenced only at the end
 820   // of regular debuginfo at the last (youngest) JVMS.
 821   // Record relative start index.
 822   ciInstanceKlass* iklass    = nullptr;
 823   BasicType basic_elem_type  = T_ILLEGAL;
 824   const Type* field_type     = nullptr;
 825   const TypeOopPtr* res_type = nullptr;
 826   int nfields                = 0;
 827   int array_base             = 0;
 828   int element_size           = 0;
 829   uint first_ind             = (sfpt->req() - sfpt->jvms()->scloff());
 830   Node* res                  = alloc->result_cast();
 831 
 832   assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");
 833   assert(sfpt->jvms() != nullptr, "missed JVMS");
 834 
 835   if (res != nullptr) { // Could be null when there are no users
 836     res_type = _igvn.type(res)->isa_oopptr();
 837 
 838     if (res_type->isa_instptr()) {
 839       // find the fields of the class which will be needed for safepoint debug information
 840       iklass = res_type->is_instptr()->instance_klass();
 841       nfields = iklass->nof_nonstatic_fields();
 842     } else {
 843       // find the array's elements which will be needed for safepoint debug information
 844       nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 845       assert(nfields >= 0, "must be an array klass.");
 846       basic_elem_type = res_type->is_aryptr()->elem()->array_element_basic_type();
 847       array_base = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
 848       element_size = type2aelembytes(basic_elem_type);
 849       field_type = res_type->is_aryptr()->elem();
 850       if (res_type->is_flat()) {
 851         // Flat inline type array
 852         element_size = res_type->is_aryptr()->flat_elem_size();
 853       }
 854     }
 855   }
 856 
 857   SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(res_type, alloc, first_ind, nfields);
 858   sobj->init_req(0, C->root());
 859   transform_later(sobj);
 860 
 861   // Scan object's fields adding an input to the safepoint for each field.
 862   for (int j = 0; j < nfields; j++) {
 863     intptr_t offset;
 864     ciField* field = nullptr;
 865     if (iklass != nullptr) {
 866       field = iklass->nonstatic_field_at(j);
 867       offset = field->offset_in_bytes();
 868       ciType* elem_type = field->type();
 869       basic_elem_type = field->layout_type();
 870       assert(!field->is_flat(), "flat inline type fields should not have safepoint uses");
 871 
 872       // The next code is taken from Parse::do_get_xxx().
 873       if (is_reference_type(basic_elem_type)) {
 874         if (!elem_type->is_loaded()) {
 875           field_type = TypeInstPtr::BOTTOM;
 876         } else if (field != nullptr && field->is_static_constant()) {
 877           ciObject* con = field->constant_value().as_object();
 878           // Do not "join" in the previous type; it doesn't add value,
 879           // and may yield a vacuous result if the field is of interface type.
 880           field_type = TypeOopPtr::make_from_constant(con)->isa_oopptr();
 881           assert(field_type != nullptr, "field singleton type must be consistent");
 882         } else {
 883           field_type = TypeOopPtr::make_from_klass(elem_type->as_klass());
 884         }
 885         if (UseCompressedOops) {
 886           field_type = field_type->make_narrowoop();
 887           basic_elem_type = T_NARROWOOP;
 888         }
 889       } else {
 890         field_type = Type::get_const_basic_type(basic_elem_type);
 891       }
 892     } else {
 893       offset = array_base + j * (intptr_t)element_size;
 894     }
 895 
 896     Node* field_val = nullptr;
 897     const TypeOopPtr* field_addr_type = res_type->add_offset(offset)->isa_oopptr();
 898     if (res_type->is_flat()) {
 899       ciInlineKlass* vk = res_type->is_aryptr()->elem()->inline_klass();
 900       assert(vk->flat_in_array(), "must be flat in array");
 901       field_val = inline_type_from_mem(sfpt->memory(), sfpt->control(), vk, field_addr_type->isa_aryptr(), 0, alloc);
 902     } else {
 903       field_val = value_from_mem(sfpt->memory(), sfpt->control(), basic_elem_type, field_type, field_addr_type, alloc);
 904     }
 905 
 906     // We weren't able to find a value for this field,
 907     // give up on eliminating this allocation.
 908     if (field_val == nullptr) {
 909       uint last = sfpt->req() - 1;
 910       for (int k = 0;  k < j; k++) {
 911         sfpt->del_req(last--);
 912       }
 913       _igvn._worklist.push(sfpt);
 914 
 915 #ifndef PRODUCT
 916       if (PrintEliminateAllocations) {
 917         if (field != nullptr) {
 918           tty->print("=== At SafePoint node %d can't find value of field: ", sfpt->_idx);
 919           field->print();
 920           int field_idx = C->get_alias_index(field_addr_type);
 921           tty->print(" (alias_idx=%d)", field_idx);
 922         } else { // Array's element
 923           tty->print("=== At SafePoint node %d can't find value of array element [%d]", sfpt->_idx, j);
 924         }
 925         tty->print(", which prevents elimination of: ");
 926         if (res == nullptr)
 927           alloc->dump();
 928         else
 929           res->dump();
 930       }
 931 #endif
 932 
 933       return nullptr;
 934     }
 935 
 936     if (UseCompressedOops && field_type->isa_narrowoop()) {
 937       // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation
 938       // to be able scalar replace the allocation.
 939       if (field_val->is_EncodeP()) {
 940         field_val = field_val->in(1);
 941       } else if (!field_val->is_InlineType()) {
 942         field_val = transform_later(new DecodeNNode(field_val, field_val->get_ptr_type()));
 943       }
 944     }
 945     if (field_val->is_InlineType()) {
 946       // Keep track of inline types to scalarize them later
 947       value_worklist->push(field_val);
 948     }
 949     sfpt->add_req(field_val);
 950   }
 951 
 952   sfpt->jvms()->set_endoff(sfpt->req());
 953 
 954   return sobj;
 955 }
 956 
 957 // Do scalar replacement.
 958 bool PhaseMacroExpand::scalar_replacement(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
 959   GrowableArray <SafePointNode *> safepoints_done;
 960   Node* res = alloc->result_cast();
 961   assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");
 962   const TypeOopPtr* res_type = nullptr;
 963   if (res != nullptr) { // Could be null when there are no users
 964     res_type = _igvn.type(res)->isa_oopptr();
 965   }
 966 
 967   // Process the safepoint uses
 968   assert(safepoints.length() == 0 || !res_type->is_inlinetypeptr(), "Inline type allocations should not have safepoint uses");
 969   Unique_Node_List value_worklist;
 970   while (safepoints.length() > 0) {
 971     SafePointNode* sfpt = safepoints.pop();
 972     SafePointScalarObjectNode* sobj = create_scalarized_object_description(alloc, sfpt, &value_worklist);
 973 
 974     if (sobj == nullptr) {
 975       undo_previous_scalarizations(safepoints_done, alloc);
 976       return false;
 977     }
 978 
 979     // Now make a pass over the debug information replacing any references
 980     // to the allocated object with "sobj"
 981     JVMState *jvms = sfpt->jvms();
 982     sfpt->replace_edges_in_range(res, sobj, jvms->debug_start(), jvms->debug_end(), &_igvn);
 983     _igvn._worklist.push(sfpt);
 984 
 985     // keep it for rollback
 986     safepoints_done.append_if_missing(sfpt);
 987   }
 988   // Scalarize inline types that were added to the safepoint.
 989   // Don't allow linking a constant oop (if available) for flat array elements
 990   // because Deoptimization::reassign_flat_array_elements needs field values.
 991   bool allow_oop = (res_type != nullptr) && !res_type->is_flat();
 992   for (uint i = 0; i < value_worklist.size(); ++i) {
 993     InlineTypeNode* vt = value_worklist.at(i)->as_InlineType();
 994     vt->make_scalar_in_safepoints(&_igvn, allow_oop);
 995   }
 996   return true;
 997 }
 998 
 999 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) {
1000   Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control);
1001   Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory);
1002   if (ctl_proj != nullptr) {
1003     igvn.replace_node(ctl_proj, n->in(0));
1004   }
1005   if (mem_proj != nullptr) {
1006     igvn.replace_node(mem_proj, n->in(TypeFunc::Memory));
1007   }
1008 }
1009 
1010 // Process users of eliminated allocation.
1011 void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc, bool inline_alloc) {
1012   Unique_Node_List worklist;
1013   Node* res = alloc->result_cast();
1014   if (res != nullptr) {
1015     worklist.push(res);
1016   }
1017   while (worklist.size() > 0) {
1018     res = worklist.pop();
1019     for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
1020       Node *use = res->last_out(j);
1021       uint oc1 = res->outcnt();
1022 
1023       if (use->is_AddP()) {
1024         for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
1025           Node *n = use->last_out(k);
1026           uint oc2 = use->outcnt();
1027           if (n->is_Store()) {
1028             for (DUIterator_Fast pmax, p = n->fast_outs(pmax); p < pmax; p++) {
1029               MemBarNode* mb = n->fast_out(p)->isa_MemBar();
1030               if (mb != nullptr && mb->req() <= MemBarNode::Precedent && mb->in(MemBarNode::Precedent) == n) {
1031                 // MemBarVolatiles should have been removed by MemBarNode::Ideal() for non-inline allocations
1032                 assert(inline_alloc, "MemBarVolatile should be eliminated for non-escaping object");
1033                 mb->remove(&_igvn);
1034               }



1035             }

1036             _igvn.replace_node(n, n->in(MemNode::Memory));
1037           } else {
1038             eliminate_gc_barrier(n);
1039           }
1040           k -= (oc2 - use->outcnt());
1041         }
1042         _igvn.remove_dead_node(use);
1043       } else if (use->is_ArrayCopy()) {
1044         // Disconnect ArrayCopy node
1045         ArrayCopyNode* ac = use->as_ArrayCopy();
1046         if (ac->is_clonebasic()) {
1047           Node* membar_after = ac->proj_out(TypeFunc::Control)->unique_ctrl_out();
1048           disconnect_projections(ac, _igvn);
1049           assert(alloc->in(TypeFunc::Memory)->is_Proj() && alloc->in(TypeFunc::Memory)->in(0)->Opcode() == Op_MemBarCPUOrder, "mem barrier expected before allocation");
1050           Node* membar_before = alloc->in(TypeFunc::Memory)->in(0);
1051           disconnect_projections(membar_before->as_MemBar(), _igvn);
1052           if (membar_after->is_MemBar()) {
1053             disconnect_projections(membar_after->as_MemBar(), _igvn);
1054           }
1055         } else {
1056           assert(ac->is_arraycopy_validated() ||
1057                  ac->is_copyof_validated() ||
1058                  ac->is_copyofrange_validated(), "unsupported");
1059           CallProjections* callprojs = ac->extract_projections(true);

1060 
1061           _igvn.replace_node(callprojs->fallthrough_ioproj, ac->in(TypeFunc::I_O));
1062           _igvn.replace_node(callprojs->fallthrough_memproj, ac->in(TypeFunc::Memory));
1063           _igvn.replace_node(callprojs->fallthrough_catchproj, ac->in(TypeFunc::Control));
1064 
1065           // Set control to top. IGVN will remove the remaining projections
1066           ac->set_req(0, top());
1067           ac->replace_edge(res, top(), &_igvn);
1068 
1069           // Disconnect src right away: it can help find new
1070           // opportunities for allocation elimination
1071           Node* src = ac->in(ArrayCopyNode::Src);
1072           ac->replace_edge(src, top(), &_igvn);
1073           // src can be top at this point if src and dest of the
1074           // arraycopy were the same
1075           if (src->outcnt() == 0 && !src->is_top()) {
1076             _igvn.remove_dead_node(src);
1077           }
1078         }
1079         _igvn._worklist.push(ac);
1080       } else if (use->is_InlineType()) {
1081         assert(use->as_InlineType()->get_oop() == res, "unexpected inline type ptr use");
1082         // Cut off oop input and remove known instance id from type
1083         _igvn.rehash_node_delayed(use);
1084         use->as_InlineType()->set_oop(_igvn.zerocon(T_OBJECT));
1085         const TypeOopPtr* toop = _igvn.type(use)->is_oopptr()->cast_to_instance_id(TypeOopPtr::InstanceBot);
1086         _igvn.set_type(use, toop);
1087         use->as_InlineType()->set_type(toop);
1088         // Process users
1089         for (DUIterator_Fast kmax, k = use->fast_outs(kmax); k < kmax; k++) {
1090           Node* u = use->fast_out(k);
1091           if (!u->is_InlineType()) {
1092             worklist.push(u);
1093           }
1094         }
1095       } else if (use->Opcode() == Op_StoreX && use->in(MemNode::Address) == res) {
1096         // Store to mark word of inline type larval buffer
1097         assert(inline_alloc, "Unexpected store to mark word");
1098         _igvn.replace_node(use, use->in(MemNode::Memory));
1099       } else {
1100         eliminate_gc_barrier(use);
1101       }
1102       j -= (oc1 - res->outcnt());
1103     }
1104     assert(res->outcnt() == 0, "all uses of allocated objects must be deleted");
1105     _igvn.remove_dead_node(res);
1106   }
1107 
1108   //
1109   // Process other users of allocation's projections
1110   //
1111   if (_callprojs->resproj[0] != nullptr && _callprojs->resproj[0]->outcnt() != 0) {
1112     // First disconnect stores captured by Initialize node.
1113     // If Initialize node is eliminated first in the following code,
1114     // it will kill such stores and DUIterator_Last will assert.
1115     for (DUIterator_Fast jmax, j = _callprojs->resproj[0]->fast_outs(jmax);  j < jmax; j++) {
1116       Node* use = _callprojs->resproj[0]->fast_out(j);
1117       if (use->is_AddP()) {
1118         // raw memory addresses used only by the initialization
1119         _igvn.replace_node(use, C->top());
1120         --j; --jmax;
1121       }
1122     }
1123     for (DUIterator_Last jmin, j = _callprojs->resproj[0]->last_outs(jmin); j >= jmin; ) {
1124       Node* use = _callprojs->resproj[0]->last_out(j);
1125       uint oc1 = _callprojs->resproj[0]->outcnt();
1126       if (use->is_Initialize()) {
1127         // Eliminate Initialize node.
1128         InitializeNode *init = use->as_Initialize();
1129         assert(init->outcnt() <= 2, "only a control and memory projection expected");
1130         Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
1131         if (ctrl_proj != nullptr) {
1132           _igvn.replace_node(ctrl_proj, init->in(TypeFunc::Control));
1133 #ifdef ASSERT
1134           // If the InitializeNode has no memory out, it will die, and tmp will become null
1135           Node* tmp = init->in(TypeFunc::Control);
1136           assert(tmp == nullptr || tmp == _callprojs->fallthrough_catchproj, "allocation control projection");
1137 #endif
1138         }
1139         Node *mem_proj = init->proj_out_or_null(TypeFunc::Memory);
1140         if (mem_proj != nullptr) {
1141           Node *mem = init->in(TypeFunc::Memory);
1142 #ifdef ASSERT
1143           if (mem->is_MergeMem()) {
1144             assert(mem->in(TypeFunc::Memory) == _callprojs->fallthrough_memproj, "allocation memory projection");
1145           } else {
1146             assert(mem == _callprojs->fallthrough_memproj, "allocation memory projection");
1147           }
1148 #endif
1149           _igvn.replace_node(mem_proj, mem);
1150         }
1151       } else if (use->Opcode() == Op_MemBarStoreStore) {
1152         // Inline type buffer allocations are followed by a membar
1153         assert(inline_alloc, "Unexpected MemBarStoreStore");
1154         use->as_MemBar()->remove(&_igvn);
1155       } else  {
1156         assert(false, "only Initialize or AddP expected");
1157       }
1158       j -= (oc1 - _callprojs->resproj[0]->outcnt());
1159     }
1160   }
1161   if (_callprojs->fallthrough_catchproj != nullptr) {
1162     _igvn.replace_node(_callprojs->fallthrough_catchproj, alloc->in(TypeFunc::Control));
1163   }
1164   if (_callprojs->fallthrough_memproj != nullptr) {
1165     _igvn.replace_node(_callprojs->fallthrough_memproj, alloc->in(TypeFunc::Memory));
1166   }
1167   if (_callprojs->catchall_memproj != nullptr) {
1168     _igvn.replace_node(_callprojs->catchall_memproj, C->top());
1169   }
1170   if (_callprojs->fallthrough_ioproj != nullptr) {
1171     _igvn.replace_node(_callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
1172   }
1173   if (_callprojs->catchall_ioproj != nullptr) {
1174     _igvn.replace_node(_callprojs->catchall_ioproj, C->top());
1175   }
1176   if (_callprojs->catchall_catchproj != nullptr) {
1177     _igvn.replace_node(_callprojs->catchall_catchproj, C->top());
1178   }
1179 }
1180 
1181 bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) {
1182   // If reallocation fails during deoptimization we'll pop all
1183   // interpreter frames for this compiled frame and that won't play
1184   // nice with JVMTI popframe.
1185   // We avoid this issue by eager reallocation when the popframe request
1186   // is received.
1187   if (!EliminateAllocations) {
1188     return false;
1189   }
1190   Node* klass = alloc->in(AllocateNode::KlassNode);
1191   const TypeKlassPtr* tklass = _igvn.type(klass)->is_klassptr();
1192 
1193   // Attempt to eliminate inline type buffer allocations
1194   // regardless of usage and escape/replaceable status.
1195   bool inline_alloc = tklass->isa_instklassptr() &&
1196                       tklass->is_instklassptr()->instance_klass()->is_inlinetype();
1197   if (!alloc->_is_non_escaping && !inline_alloc) {
1198     return false;
1199   }
1200   // Eliminate boxing allocations which are not used
1201   // regardless scalar replaceable status.
1202   Node* res = alloc->result_cast();
1203   bool boxing_alloc = (res == nullptr) && C->eliminate_boxing() &&
1204                       tklass->isa_instklassptr() &&
1205                       tklass->is_instklassptr()->instance_klass()->is_box_klass();
1206   if (!alloc->_is_scalar_replaceable && (!boxing_alloc || (res != nullptr))) {
1207     return false;
1208   }
1209 
1210   _callprojs = alloc->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1211 
1212   GrowableArray <SafePointNode *> safepoints;
1213   if (!can_eliminate_allocation(&_igvn, alloc, &safepoints)) {
1214     return false;
1215   }
1216 
1217   if (!alloc->_is_scalar_replaceable) {
1218     assert(res == nullptr || inline_alloc, "sanity");
1219     // We can only eliminate allocation if all debug info references
1220     // are already replaced with SafePointScalarObject because
1221     // we can't search for a fields value without instance_id.
1222     if (safepoints.length() > 0) {
1223       assert(!inline_alloc, "Inline type allocations should not have safepoint uses");
1224       return false;
1225     }
1226   }
1227 
1228   if (!scalar_replacement(alloc, safepoints)) {
1229     return false;
1230   }
1231 
1232   CompileLog* log = C->log();
1233   if (log != nullptr) {
1234     log->head("eliminate_allocation type='%d'",
1235               log->identify(tklass->exact_klass()));
1236     JVMState* p = alloc->jvms();
1237     while (p != nullptr) {
1238       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1239       p = p->caller();
1240     }
1241     log->tail("eliminate_allocation");
1242   }
1243 
1244   process_users_of_allocation(alloc, inline_alloc);
1245 
1246 #ifndef PRODUCT
1247   if (PrintEliminateAllocations) {
1248     if (alloc->is_AllocateArray())
1249       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1250     else
1251       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1252   }
1253 #endif
1254 
1255   return true;
1256 }
1257 
1258 bool PhaseMacroExpand::eliminate_boxing_node(CallStaticJavaNode *boxing) {
1259   // EA should remove all uses of non-escaping boxing node.
1260   if (!C->eliminate_boxing() || boxing->proj_out_or_null(TypeFunc::Parms) != nullptr) {
1261     return false;
1262   }
1263 
1264   assert(boxing->result_cast() == nullptr, "unexpected boxing node result");
1265 
1266   _callprojs = boxing->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1267 
1268   const TypeTuple* r = boxing->tf()->range_sig();
1269   assert(r->cnt() > TypeFunc::Parms, "sanity");
1270   const TypeInstPtr* t = r->field_at(TypeFunc::Parms)->isa_instptr();
1271   assert(t != nullptr, "sanity");
1272 
1273   CompileLog* log = C->log();
1274   if (log != nullptr) {
1275     log->head("eliminate_boxing type='%d'",
1276               log->identify(t->instance_klass()));
1277     JVMState* p = boxing->jvms();
1278     while (p != nullptr) {
1279       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1280       p = p->caller();
1281     }
1282     log->tail("eliminate_boxing");
1283   }
1284 
1285   process_users_of_allocation(boxing);
1286 
1287 #ifndef PRODUCT
1288   if (PrintEliminateAllocations) {

1432         }
1433       }
1434 #endif
1435       yank_alloc_node(alloc);
1436       return;
1437     }
1438   }
1439 
1440   enum { too_big_or_final_path = 1, need_gc_path = 2 };
1441   Node *slow_region = nullptr;
1442   Node *toobig_false = ctrl;
1443 
1444   // generate the initial test if necessary
1445   if (initial_slow_test != nullptr ) {
1446     assert (expand_fast_path, "Only need test if there is a fast path");
1447     slow_region = new RegionNode(3);
1448 
1449     // Now make the initial failure test.  Usually a too-big test but
1450     // might be a TRUE for finalizers or a fancy class check for
1451     // newInstance0.
1452     IfNode* toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1453     transform_later(toobig_iff);
1454     // Plug the failing-too-big test into the slow-path region
1455     Node* toobig_true = new IfTrueNode(toobig_iff);
1456     transform_later(toobig_true);
1457     slow_region    ->init_req( too_big_or_final_path, toobig_true );
1458     toobig_false = new IfFalseNode(toobig_iff);
1459     transform_later(toobig_false);
1460   } else {
1461     // No initial test, just fall into next case
1462     assert(allocation_has_use || !expand_fast_path, "Should already have been handled");
1463     toobig_false = ctrl;
1464     debug_only(slow_region = NodeSentinel);
1465   }
1466 
1467   // If we are here there are several possibilities
1468   // - expand_fast_path is false - then only a slow path is expanded. That's it.
1469   // no_initial_check means a constant allocation.
1470   // - If check always evaluates to false -> expand_fast_path is false (see above)
1471   // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath)
1472   // if !allocation_has_use the fast path is empty
1473   // if !allocation_has_use && no_initial_check
1474   // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all.
1475   //   removed by yank_alloc_node above.
1476 
1477   Node *slow_mem = mem;  // save the current memory state for slow path
1478   // generate the fast allocation code unless we know that the initial test will always go slow
1479   if (expand_fast_path) {
1480     // Fast path modifies only raw memory.
1481     if (mem->is_MergeMem()) {
1482       mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1483     }
1484 
1485     // allocate the Region and Phi nodes for the result
1486     result_region = new RegionNode(3);
1487     result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1488     result_phi_i_o    = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1489 
1490     // Grab regular I/O before optional prefetch may change it.
1491     // Slow-path does no I/O so just set it to the original I/O.
1492     result_phi_i_o->init_req(slow_result_path, i_o);
1493 
1494     // Name successful fast-path variables
1495     Node* fast_oop_ctrl;
1496     Node* fast_oop_rawmem;
1497 
1498     if (allocation_has_use) {
1499       Node* needgc_ctrl = nullptr;
1500       result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1501 
1502       intx prefetch_lines = length != nullptr ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1503       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1504       Node* fast_oop = bs->obj_allocate(this, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1505                                         fast_oop_ctrl, fast_oop_rawmem,
1506                                         prefetch_lines);
1507 
1508       if (initial_slow_test != nullptr) {
1509         // This completes all paths into the slow merge point
1510         slow_region->init_req(need_gc_path, needgc_ctrl);
1511         transform_later(slow_region);
1512       } else {
1513         // No initial slow path needed!
1514         // Just fall from the need-GC path straight into the VM call.
1515         slow_region = needgc_ctrl;
1516       }
1517 

1535     result_phi_i_o   ->init_req(fast_result_path, i_o);
1536     result_phi_rawmem->init_req(fast_result_path, fast_oop_rawmem);
1537   } else {
1538     slow_region = ctrl;
1539     result_phi_i_o = i_o; // Rename it to use in the following code.
1540   }
1541 
1542   // Generate slow-path call
1543   CallNode *call = new CallStaticJavaNode(slow_call_type, slow_call_address,
1544                                OptoRuntime::stub_name(slow_call_address),
1545                                TypePtr::BOTTOM);
1546   call->init_req(TypeFunc::Control,   slow_region);
1547   call->init_req(TypeFunc::I_O,       top());    // does no i/o
1548   call->init_req(TypeFunc::Memory,    slow_mem); // may gc ptrs
1549   call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1550   call->init_req(TypeFunc::FramePtr,  alloc->in(TypeFunc::FramePtr));
1551 
1552   call->init_req(TypeFunc::Parms+0, klass_node);
1553   if (length != nullptr) {
1554     call->init_req(TypeFunc::Parms+1, length);
1555   } else {
1556     // Let the runtime know if this is a larval allocation
1557     call->init_req(TypeFunc::Parms+1, _igvn.intcon(alloc->_larval));
1558   }
1559 
1560   // Copy debug information and adjust JVMState information, then replace
1561   // allocate node with the call
1562   call->copy_call_debug_info(&_igvn, alloc);
1563   // For array allocations, copy the valid length check to the call node so Compile::final_graph_reshaping() can verify
1564   // that the call has the expected number of CatchProj nodes (in case the allocation always fails and the fallthrough
1565   // path dies).
1566   if (valid_length_test != nullptr) {
1567     call->add_req(valid_length_test);
1568   }
1569   if (expand_fast_path) {
1570     call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
1571   } else {
1572     // Hook i_o projection to avoid its elimination during allocation
1573     // replacement (when only a slow call is generated).
1574     call->set_req(TypeFunc::I_O, result_phi_i_o);
1575   }
1576   _igvn.replace_node(alloc, call);
1577   transform_later(call);
1578 
1579   // Identify the output projections from the allocate node and
1580   // adjust any references to them.
1581   // The control and io projections look like:
1582   //
1583   //        v---Proj(ctrl) <-----+   v---CatchProj(ctrl)
1584   //  Allocate                   Catch
1585   //        ^---Proj(io) <-------+   ^---CatchProj(io)
1586   //
1587   //  We are interested in the CatchProj nodes.
1588   //
1589   _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1590 
1591   // An allocate node has separate memory projections for the uses on
1592   // the control and i_o paths. Replace the control memory projection with
1593   // result_phi_rawmem (unless we are only generating a slow call when
1594   // both memory projections are combined)
1595   if (expand_fast_path && _callprojs->fallthrough_memproj != nullptr) {
1596     _igvn.replace_in_uses(_callprojs->fallthrough_memproj, result_phi_rawmem);
1597   }
1598   // Now change uses of catchall_memproj to use fallthrough_memproj and delete
1599   // catchall_memproj so we end up with a call that has only 1 memory projection.
1600   if (_callprojs->catchall_memproj != nullptr) {
1601     if (_callprojs->fallthrough_memproj == nullptr) {
1602       _callprojs->fallthrough_memproj = new ProjNode(call, TypeFunc::Memory);
1603       transform_later(_callprojs->fallthrough_memproj);
1604     }
1605     _igvn.replace_in_uses(_callprojs->catchall_memproj, _callprojs->fallthrough_memproj);
1606     _igvn.remove_dead_node(_callprojs->catchall_memproj);
1607   }
1608 
1609   // An allocate node has separate i_o projections for the uses on the control
1610   // and i_o paths. Always replace the control i_o projection with result i_o
1611   // otherwise incoming i_o become dead when only a slow call is generated
1612   // (it is different from memory projections where both projections are
1613   // combined in such case).
1614   if (_callprojs->fallthrough_ioproj != nullptr) {
1615     _igvn.replace_in_uses(_callprojs->fallthrough_ioproj, result_phi_i_o);
1616   }
1617   // Now change uses of catchall_ioproj to use fallthrough_ioproj and delete
1618   // catchall_ioproj so we end up with a call that has only 1 i_o projection.
1619   if (_callprojs->catchall_ioproj != nullptr) {
1620     if (_callprojs->fallthrough_ioproj == nullptr) {
1621       _callprojs->fallthrough_ioproj = new ProjNode(call, TypeFunc::I_O);
1622       transform_later(_callprojs->fallthrough_ioproj);
1623     }
1624     _igvn.replace_in_uses(_callprojs->catchall_ioproj, _callprojs->fallthrough_ioproj);
1625     _igvn.remove_dead_node(_callprojs->catchall_ioproj);
1626   }
1627 
1628   // if we generated only a slow call, we are done
1629   if (!expand_fast_path) {
1630     // Now we can unhook i_o.
1631     if (result_phi_i_o->outcnt() > 1) {
1632       call->set_req(TypeFunc::I_O, top());
1633     } else {
1634       assert(result_phi_i_o->unique_ctrl_out() == call, "sanity");
1635       // Case of new array with negative size known during compilation.
1636       // AllocateArrayNode::Ideal() optimization disconnect unreachable
1637       // following code since call to runtime will throw exception.
1638       // As result there will be no users of i_o after the call.
1639       // Leave i_o attached to this call to avoid problems in preceding graph.
1640     }
1641     return;
1642   }
1643 
1644   if (_callprojs->fallthrough_catchproj != nullptr) {
1645     ctrl = _callprojs->fallthrough_catchproj->clone();
1646     transform_later(ctrl);
1647     _igvn.replace_node(_callprojs->fallthrough_catchproj, result_region);
1648   } else {
1649     ctrl = top();
1650   }
1651   Node *slow_result;
1652   if (_callprojs->resproj[0] == nullptr) {
1653     // no uses of the allocation result
1654     slow_result = top();
1655   } else {
1656     slow_result = _callprojs->resproj[0]->clone();
1657     transform_later(slow_result);
1658     _igvn.replace_node(_callprojs->resproj[0], result_phi_rawoop);
1659   }
1660 
1661   // Plug slow-path into result merge point
1662   result_region->init_req( slow_result_path, ctrl);
1663   transform_later(result_region);
1664   if (allocation_has_use) {
1665     result_phi_rawoop->init_req(slow_result_path, slow_result);
1666     transform_later(result_phi_rawoop);
1667   }
1668   result_phi_rawmem->init_req(slow_result_path, _callprojs->fallthrough_memproj);
1669   transform_later(result_phi_rawmem);
1670   transform_later(result_phi_i_o);
1671   // This completes all paths into the result merge point
1672 }
1673 
1674 // Remove alloc node that has no uses.
1675 void PhaseMacroExpand::yank_alloc_node(AllocateNode* alloc) {
1676   Node* ctrl = alloc->in(TypeFunc::Control);
1677   Node* mem  = alloc->in(TypeFunc::Memory);
1678   Node* i_o  = alloc->in(TypeFunc::I_O);
1679 
1680   _callprojs = alloc->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1681   if (_callprojs->resproj[0] != nullptr) {
1682     for (DUIterator_Fast imax, i = _callprojs->resproj[0]->fast_outs(imax); i < imax; i++) {
1683       Node* use = _callprojs->resproj[0]->fast_out(i);
1684       use->isa_MemBar()->remove(&_igvn);
1685       --imax;
1686       --i; // back up iterator
1687     }
1688     assert(_callprojs->resproj[0]->outcnt() == 0, "all uses must be deleted");
1689     _igvn.remove_dead_node(_callprojs->resproj[0]);
1690   }
1691   if (_callprojs->fallthrough_catchproj != nullptr) {
1692     _igvn.replace_in_uses(_callprojs->fallthrough_catchproj, ctrl);
1693     _igvn.remove_dead_node(_callprojs->fallthrough_catchproj);
1694   }
1695   if (_callprojs->catchall_catchproj != nullptr) {
1696     _igvn.rehash_node_delayed(_callprojs->catchall_catchproj);
1697     _callprojs->catchall_catchproj->set_req(0, top());
1698   }
1699   if (_callprojs->fallthrough_proj != nullptr) {
1700     Node* catchnode = _callprojs->fallthrough_proj->unique_ctrl_out();
1701     _igvn.remove_dead_node(catchnode);
1702     _igvn.remove_dead_node(_callprojs->fallthrough_proj);
1703   }
1704   if (_callprojs->fallthrough_memproj != nullptr) {
1705     _igvn.replace_in_uses(_callprojs->fallthrough_memproj, mem);
1706     _igvn.remove_dead_node(_callprojs->fallthrough_memproj);
1707   }
1708   if (_callprojs->fallthrough_ioproj != nullptr) {
1709     _igvn.replace_in_uses(_callprojs->fallthrough_ioproj, i_o);
1710     _igvn.remove_dead_node(_callprojs->fallthrough_ioproj);
1711   }
1712   if (_callprojs->catchall_memproj != nullptr) {
1713     _igvn.rehash_node_delayed(_callprojs->catchall_memproj);
1714     _callprojs->catchall_memproj->set_req(0, top());
1715   }
1716   if (_callprojs->catchall_ioproj != nullptr) {
1717     _igvn.rehash_node_delayed(_callprojs->catchall_ioproj);
1718     _callprojs->catchall_ioproj->set_req(0, top());
1719   }
1720 #ifndef PRODUCT
1721   if (PrintEliminateAllocations) {
1722     if (alloc->is_AllocateArray()) {
1723       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1724     } else {
1725       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1726     }
1727   }
1728 #endif
1729   _igvn.remove_dead_node(alloc);
1730 }
1731 
1732 void PhaseMacroExpand::expand_initialize_membar(AllocateNode* alloc, InitializeNode* init,
1733                                                 Node*& fast_oop_ctrl, Node*& fast_oop_rawmem) {
1734   // If initialization is performed by an array copy, any required
1735   // MemBarStoreStore was already added. If the object does not
1736   // escape no need for a MemBarStoreStore. If the object does not
1737   // escape in its initializer and memory barrier (MemBarStoreStore or
1738   // stronger) is already added at exit of initializer, also no need

1816     Node* thread = new ThreadLocalNode();
1817     transform_later(thread);
1818 
1819     call->init_req(TypeFunc::Parms + 0, thread);
1820     call->init_req(TypeFunc::Parms + 1, oop);
1821     call->init_req(TypeFunc::Control, ctrl);
1822     call->init_req(TypeFunc::I_O    , top()); // does no i/o
1823     call->init_req(TypeFunc::Memory , rawmem);
1824     call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1825     call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1826     transform_later(call);
1827     ctrl = new ProjNode(call, TypeFunc::Control);
1828     transform_later(ctrl);
1829     rawmem = new ProjNode(call, TypeFunc::Memory);
1830     transform_later(rawmem);
1831   }
1832 }
1833 
1834 // Helper for PhaseMacroExpand::expand_allocate_common.
1835 // Initializes the newly-allocated storage.
1836 Node* PhaseMacroExpand::initialize_object(AllocateNode* alloc,
1837                                           Node* control, Node* rawmem, Node* object,
1838                                           Node* klass_node, Node* length,
1839                                           Node* size_in_bytes) {

1840   InitializeNode* init = alloc->initialization();
1841   // Store the klass & mark bits
1842   Node* mark_node = alloc->make_ideal_mark(&_igvn, control, rawmem);
1843   if (!mark_node->is_Con()) {
1844     transform_later(mark_node);
1845   }
1846   rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
1847 
1848   rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
1849   int header_size = alloc->minimum_header_size();  // conservatively small
1850 
1851   // Array length
1852   if (length != nullptr) {         // Arrays need length field
1853     rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1854     // conservatively small header size:
1855     header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1856     if (_igvn.type(klass_node)->isa_aryklassptr()) {   // we know the exact header size in most cases:
1857       BasicType elem = _igvn.type(klass_node)->is_klassptr()->as_instance_type()->isa_aryptr()->elem()->array_element_basic_type();
1858       if (is_reference_type(elem, true)) {
1859         elem = T_OBJECT;
1860       }
1861       header_size = Klass::layout_helper_header_size(Klass::array_layout_helper(elem));
1862     }
1863   }
1864 
1865   // Clear the object body, if necessary.
1866   if (init == nullptr) {
1867     // The init has somehow disappeared; be cautious and clear everything.
1868     //
1869     // This can happen if a node is allocated but an uncommon trap occurs
1870     // immediately.  In this case, the Initialize gets associated with the
1871     // trap, and may be placed in a different (outer) loop, if the Allocate
1872     // is in a loop.  If (this is rare) the inner loop gets unrolled, then
1873     // there can be two Allocates to one Initialize.  The answer in all these
1874     // edge cases is safety first.  It is always safe to clear immediately
1875     // within an Allocate, and then (maybe or maybe not) clear some more later.
1876     if (!(UseTLAB && ZeroTLAB)) {
1877       rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
1878                                             alloc->in(AllocateNode::DefaultValue),
1879                                             alloc->in(AllocateNode::RawDefaultValue),
1880                                             header_size, size_in_bytes,
1881                                             &_igvn);
1882     }
1883   } else {
1884     if (!init->is_complete()) {
1885       // Try to win by zeroing only what the init does not store.
1886       // We can also try to do some peephole optimizations,
1887       // such as combining some adjacent subword stores.
1888       rawmem = init->complete_stores(control, rawmem, object,
1889                                      header_size, size_in_bytes, &_igvn);
1890     }
1891     // We have no more use for this link, since the AllocateNode goes away:
1892     init->set_req(InitializeNode::RawAddress, top());
1893     // (If we keep the link, it just confuses the register allocator,
1894     // who thinks he sees a real use of the address by the membar.)
1895   }
1896 
1897   return rawmem;
1898 }
1899 

2229   } // EliminateNestedLocks
2230 
2231   if (alock->is_non_esc_obj()) { // Lock is used for non escaping object
2232     // Look for all locks of this object and mark them and
2233     // corresponding BoxLock nodes as eliminated.
2234     Node* obj = alock->obj_node();
2235     for (uint j = 0; j < obj->outcnt(); j++) {
2236       Node* o = obj->raw_out(j);
2237       if (o->is_AbstractLock() &&
2238           o->as_AbstractLock()->obj_node()->eqv_uncast(obj)) {
2239         alock = o->as_AbstractLock();
2240         Node* box = alock->box_node();
2241         // Replace old box node with new eliminated box for all users
2242         // of the same object and mark related locks as eliminated.
2243         mark_eliminated_box(box, obj);
2244       }
2245     }
2246   }
2247 }
2248 
2249 void PhaseMacroExpand::inline_type_guard(Node** ctrl, LockNode* lock) {
2250   Node* obj = lock->obj_node();
2251   const TypePtr* obj_type = _igvn.type(obj)->make_ptr();
2252   if (!obj_type->can_be_inline_type()) {
2253     return;
2254   }
2255   Node* mark = make_load(*ctrl, lock->memory(), obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
2256   Node* value_mask = _igvn.MakeConX(markWord::inline_type_pattern);
2257   Node* is_value = _igvn.transform(new AndXNode(mark, value_mask));
2258   Node* cmp = _igvn.transform(new CmpXNode(is_value, value_mask));
2259   Node* bol = _igvn.transform(new BoolNode(cmp, BoolTest::eq));
2260   Node* unc_ctrl = generate_slow_guard(ctrl, bol, nullptr);
2261 
2262   int trap_request = Deoptimization::make_trap_request(Deoptimization::Reason_class_check, Deoptimization::Action_none);
2263   address call_addr = SharedRuntime::uncommon_trap_blob()->entry_point();
2264   const TypePtr* no_memory_effects = nullptr;
2265   CallNode* unc = new CallStaticJavaNode(OptoRuntime::uncommon_trap_Type(), call_addr, "uncommon_trap",
2266                                          no_memory_effects);
2267   unc->init_req(TypeFunc::Control, unc_ctrl);
2268   unc->init_req(TypeFunc::I_O, lock->i_o());
2269   unc->init_req(TypeFunc::Memory, lock->memory());
2270   unc->init_req(TypeFunc::FramePtr,  lock->in(TypeFunc::FramePtr));
2271   unc->init_req(TypeFunc::ReturnAdr, lock->in(TypeFunc::ReturnAdr));
2272   unc->init_req(TypeFunc::Parms+0, _igvn.intcon(trap_request));
2273   unc->set_cnt(PROB_UNLIKELY_MAG(4));
2274   unc->copy_call_debug_info(&_igvn, lock);
2275 
2276   assert(unc->peek_monitor_box() == lock->box_node(), "wrong monitor");
2277   assert((obj_type->is_inlinetypeptr() && unc->peek_monitor_obj()->is_SafePointScalarObject()) ||
2278          (obj->is_InlineType() && obj->in(1) == unc->peek_monitor_obj()) ||
2279          (obj == unc->peek_monitor_obj()), "wrong monitor");
2280 
2281   // pop monitor and push obj back on stack: we trap before the monitorenter
2282   unc->pop_monitor();
2283   unc->grow_stack(unc->jvms(), 1);
2284   unc->set_stack(unc->jvms(), unc->jvms()->stk_size()-1, obj);
2285   _igvn.register_new_node_with_optimizer(unc);
2286 
2287   unc_ctrl = _igvn.transform(new ProjNode(unc, TypeFunc::Control));
2288   Node* halt = _igvn.transform(new HaltNode(unc_ctrl, lock->in(TypeFunc::FramePtr), "monitor enter on inline type"));
2289   _igvn.add_input_to(C->root(), halt);
2290 }
2291 
2292 // we have determined that this lock/unlock can be eliminated, we simply
2293 // eliminate the node without expanding it.
2294 //
2295 // Note:  The membar's associated with the lock/unlock are currently not
2296 //        eliminated.  This should be investigated as a future enhancement.
2297 //
2298 bool PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) {
2299 
2300   if (!alock->is_eliminated()) {
2301     return false;
2302   }
2303 #ifdef ASSERT
2304   if (!alock->is_coarsened()) {
2305     // Check that new "eliminated" BoxLock node is created.
2306     BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2307     assert(oldbox->is_eliminated(), "should be done already");
2308   }
2309 #endif
2310 
2311   alock->log_lock_optimization(C, "eliminate_lock");
2312 
2313 #ifndef PRODUCT
2314   if (PrintEliminateLocks) {
2315     tty->print_cr("++++ Eliminated: %d %s '%s'", alock->_idx, (alock->is_Lock() ? "Lock" : "Unlock"), alock->kind_as_string());
2316   }
2317 #endif
2318 
2319   Node* mem  = alock->in(TypeFunc::Memory);
2320   Node* ctrl = alock->in(TypeFunc::Control);
2321   guarantee(ctrl != nullptr, "missing control projection, cannot replace_node() with null");
2322 
2323   _callprojs = alock->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
2324   // There are 2 projections from the lock.  The lock node will
2325   // be deleted when its last use is subsumed below.
2326   assert(alock->outcnt() == 2 &&
2327          _callprojs->fallthrough_proj != nullptr &&
2328          _callprojs->fallthrough_memproj != nullptr,
2329          "Unexpected projections from Lock/Unlock");
2330 
2331   Node* fallthroughproj = _callprojs->fallthrough_proj;
2332   Node* memproj_fallthrough = _callprojs->fallthrough_memproj;
2333 
2334   // The memory projection from a lock/unlock is RawMem
2335   // The input to a Lock is merged memory, so extract its RawMem input
2336   // (unless the MergeMem has been optimized away.)
2337   if (alock->is_Lock()) {
2338     // Deoptimize and re-execute if object is an inline type
2339     inline_type_guard(&ctrl, alock->as_Lock());
2340 
2341     // Search for MemBarAcquireLock node and delete it also.
2342     MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
2343     assert(membar != nullptr && membar->Opcode() == Op_MemBarAcquireLock, "");
2344     Node* ctrlproj = membar->proj_out(TypeFunc::Control);
2345     Node* memproj = membar->proj_out(TypeFunc::Memory);
2346     _igvn.replace_node(ctrlproj, fallthroughproj);
2347     _igvn.replace_node(memproj, memproj_fallthrough);
2348 
2349     // Delete FastLock node also if this Lock node is unique user
2350     // (a loop peeling may clone a Lock node).
2351     Node* flock = alock->as_Lock()->fastlock_node();
2352     if (flock->outcnt() == 1) {
2353       assert(flock->unique_out() == alock, "sanity");
2354       _igvn.replace_node(flock, top());
2355     }
2356   }
2357 
2358   // Search for MemBarReleaseLock node and delete it also.
2359   if (alock->is_Unlock() && ctrl->is_Proj() && ctrl->in(0)->is_MemBar()) {
2360     MemBarNode* membar = ctrl->in(0)->as_MemBar();

2381   Node* mem = lock->in(TypeFunc::Memory);
2382   Node* obj = lock->obj_node();
2383   Node* box = lock->box_node();
2384   Node* flock = lock->fastlock_node();
2385 
2386   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2387 
2388   // Make the merge point
2389   Node *region;
2390   Node *mem_phi;
2391   Node *slow_path;
2392 
2393   region  = new RegionNode(3);
2394   // create a Phi for the memory state
2395   mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2396 
2397   // Optimize test; set region slot 2
2398   slow_path = opt_bits_test(ctrl, region, 2, flock, 0, 0);
2399   mem_phi->init_req(2, mem);
2400 
2401   // Deoptimize and re-execute if object is an inline type
2402   inline_type_guard(&slow_path, lock);
2403 
2404   // Make slow path call
2405   CallNode *call = make_slow_call((CallNode *) lock, OptoRuntime::complete_monitor_enter_Type(),
2406                                   OptoRuntime::complete_monitor_locking_Java(), nullptr, slow_path,
2407                                   obj, box, nullptr);
2408 
2409   _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
2410 
2411   // Slow path can only throw asynchronous exceptions, which are always
2412   // de-opted.  So the compiler thinks the slow-call can never throw an
2413   // exception.  If it DOES throw an exception we would need the debug
2414   // info removed first (since if it throws there is no monitor).
2415   assert(_callprojs->fallthrough_ioproj == nullptr && _callprojs->catchall_ioproj == nullptr &&
2416          _callprojs->catchall_memproj == nullptr && _callprojs->catchall_catchproj == nullptr, "Unexpected projection from Lock");
2417 
2418   // Capture slow path
2419   // disconnect fall-through projection from call and create a new one
2420   // hook up users of fall-through projection to region
2421   Node *slow_ctrl = _callprojs->fallthrough_proj->clone();
2422   transform_later(slow_ctrl);
2423   _igvn.hash_delete(_callprojs->fallthrough_proj);
2424   _callprojs->fallthrough_proj->disconnect_inputs(C);
2425   region->init_req(1, slow_ctrl);
2426   // region inputs are now complete
2427   transform_later(region);
2428   _igvn.replace_node(_callprojs->fallthrough_proj, region);
2429 
2430   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2431 
2432   mem_phi->init_req(1, memproj);
2433 
2434   transform_later(mem_phi);
2435 
2436   _igvn.replace_node(_callprojs->fallthrough_memproj, mem_phi);
2437 }
2438 
2439 //------------------------------expand_unlock_node----------------------
2440 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
2441 
2442   Node* ctrl = unlock->in(TypeFunc::Control);
2443   Node* mem = unlock->in(TypeFunc::Memory);
2444   Node* obj = unlock->obj_node();
2445   Node* box = unlock->box_node();
2446 
2447   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2448 
2449   // No need for a null check on unlock
2450 
2451   // Make the merge point
2452   Node *region;
2453   Node *mem_phi;
2454 
2455   region  = new RegionNode(3);
2456   // create a Phi for the memory state
2457   mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2458 
2459   FastUnlockNode *funlock = new FastUnlockNode( ctrl, obj, box );
2460   funlock = transform_later( funlock )->as_FastUnlock();
2461   // Optimize test; set region slot 2
2462   Node *slow_path = opt_bits_test(ctrl, region, 2, funlock, 0, 0);
2463   Node *thread = transform_later(new ThreadLocalNode());
2464 
2465   CallNode *call = make_slow_call((CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(),
2466                                   CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C),
2467                                   "complete_monitor_unlocking_C", slow_path, obj, box, thread);
2468 
2469   _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
2470   assert(_callprojs->fallthrough_ioproj == nullptr && _callprojs->catchall_ioproj == nullptr &&
2471          _callprojs->catchall_memproj == nullptr && _callprojs->catchall_catchproj == nullptr, "Unexpected projection from Lock");
2472 
2473   // No exceptions for unlocking
2474   // Capture slow path
2475   // disconnect fall-through projection from call and create a new one
2476   // hook up users of fall-through projection to region
2477   Node *slow_ctrl = _callprojs->fallthrough_proj->clone();
2478   transform_later(slow_ctrl);
2479   _igvn.hash_delete(_callprojs->fallthrough_proj);
2480   _callprojs->fallthrough_proj->disconnect_inputs(C);
2481   region->init_req(1, slow_ctrl);
2482   // region inputs are now complete
2483   transform_later(region);
2484   _igvn.replace_node(_callprojs->fallthrough_proj, region);
2485 
2486   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory) );
2487   mem_phi->init_req(1, memproj );
2488   mem_phi->init_req(2, mem);
2489   transform_later(mem_phi);
2490 
2491   _igvn.replace_node(_callprojs->fallthrough_memproj, mem_phi);
2492 }
2493 
2494 // An inline type might be returned from the call but we don't know its
2495 // type. Either we get a buffered inline type (and nothing needs to be done)
2496 // or one of the values being returned is the klass of the inline type
2497 // and we need to allocate an inline type instance of that type and
2498 // initialize it with other values being returned. In that case, we
2499 // first try a fast path allocation and initialize the value with the
2500 // inline klass's pack handler or we fall back to a runtime call.
2501 void PhaseMacroExpand::expand_mh_intrinsic_return(CallStaticJavaNode* call) {
2502   assert(call->method()->is_method_handle_intrinsic(), "must be a method handle intrinsic call");
2503   Node* ret = call->proj_out_or_null(TypeFunc::Parms);
2504   if (ret == nullptr) {
2505     return;
2506   }
2507   const TypeFunc* tf = call->_tf;
2508   const TypeTuple* domain = OptoRuntime::store_inline_type_fields_Type()->domain_cc();
2509   const TypeFunc* new_tf = TypeFunc::make(tf->domain_sig(), tf->domain_cc(), tf->range_sig(), domain);
2510   call->_tf = new_tf;
2511   // Make sure the change of type is applied before projections are processed by igvn
2512   _igvn.set_type(call, call->Value(&_igvn));
2513   _igvn.set_type(ret, ret->Value(&_igvn));
2514 
2515   // Before any new projection is added:
2516   CallProjections* projs = call->extract_projections(true, true);
2517 
2518   // Create temporary hook nodes that will be replaced below.
2519   // Add an input to prevent hook nodes from being dead.
2520   Node* ctl = new Node(call);
2521   Node* mem = new Node(ctl);
2522   Node* io = new Node(ctl);
2523   Node* ex_ctl = new Node(ctl);
2524   Node* ex_mem = new Node(ctl);
2525   Node* ex_io = new Node(ctl);
2526   Node* res = new Node(ctl);
2527 
2528   // Allocate a new buffered inline type only if a new one is not returned
2529   Node* cast = transform_later(new CastP2XNode(ctl, res));
2530   Node* mask = MakeConX(0x1);
2531   Node* masked = transform_later(new AndXNode(cast, mask));
2532   Node* cmp = transform_later(new CmpXNode(masked, mask));
2533   Node* bol = transform_later(new BoolNode(cmp, BoolTest::eq));
2534   IfNode* allocation_iff = new IfNode(ctl, bol, PROB_MAX, COUNT_UNKNOWN);
2535   transform_later(allocation_iff);
2536   Node* allocation_ctl = transform_later(new IfTrueNode(allocation_iff));
2537   Node* no_allocation_ctl = transform_later(new IfFalseNode(allocation_iff));
2538   Node* no_allocation_res = transform_later(new CheckCastPPNode(no_allocation_ctl, res, TypeInstPtr::BOTTOM));
2539 
2540   // Try to allocate a new buffered inline instance either from TLAB or eden space
2541   Node* needgc_ctrl = nullptr; // needgc means slowcase, i.e. allocation failed
2542   CallLeafNoFPNode* handler_call;
2543   const bool alloc_in_place = UseTLAB;
2544   if (alloc_in_place) {
2545     Node* fast_oop_ctrl = nullptr;
2546     Node* fast_oop_rawmem = nullptr;
2547     Node* mask2 = MakeConX(-2);
2548     Node* masked2 = transform_later(new AndXNode(cast, mask2));
2549     Node* rawklassptr = transform_later(new CastX2PNode(masked2));
2550     Node* klass_node = transform_later(new CheckCastPPNode(allocation_ctl, rawklassptr, TypeInstKlassPtr::OBJECT_OR_NULL));
2551     Node* layout_val = make_load(nullptr, mem, klass_node, in_bytes(Klass::layout_helper_offset()), TypeInt::INT, T_INT);
2552     Node* size_in_bytes = ConvI2X(layout_val);
2553     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2554     Node* fast_oop = bs->obj_allocate(this, mem, allocation_ctl, size_in_bytes, io, needgc_ctrl,
2555                                       fast_oop_ctrl, fast_oop_rawmem,
2556                                       AllocateInstancePrefetchLines);
2557     // Allocation succeed, initialize buffered inline instance header firstly,
2558     // and then initialize its fields with an inline class specific handler
2559     Node* mark_node = makecon(TypeRawPtr::make((address)markWord::inline_type_prototype().value()));
2560     fast_oop_rawmem = make_store(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::mark_offset_in_bytes(), mark_node, T_ADDRESS);
2561     fast_oop_rawmem = make_store(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
2562     if (UseCompressedClassPointers) {
2563       fast_oop_rawmem = make_store(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::klass_gap_offset_in_bytes(), intcon(0), T_INT);
2564     }
2565     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);
2566     Node* pack_handler = make_load(fast_oop_ctrl, fast_oop_rawmem, fixed_block, in_bytes(InlineKlass::pack_handler_offset()), TypeRawPtr::BOTTOM, T_ADDRESS);
2567     handler_call = new CallLeafNoFPNode(OptoRuntime::pack_inline_type_Type(),
2568                                         nullptr,
2569                                         "pack handler",
2570                                         TypeRawPtr::BOTTOM);
2571     handler_call->init_req(TypeFunc::Control, fast_oop_ctrl);
2572     handler_call->init_req(TypeFunc::Memory, fast_oop_rawmem);
2573     handler_call->init_req(TypeFunc::I_O, top());
2574     handler_call->init_req(TypeFunc::FramePtr, call->in(TypeFunc::FramePtr));
2575     handler_call->init_req(TypeFunc::ReturnAdr, top());
2576     handler_call->init_req(TypeFunc::Parms, pack_handler);
2577     handler_call->init_req(TypeFunc::Parms+1, fast_oop);
2578   } else {
2579     needgc_ctrl = allocation_ctl;
2580   }
2581 
2582   // Allocation failed, fall back to a runtime call
2583   CallStaticJavaNode* slow_call = new CallStaticJavaNode(OptoRuntime::store_inline_type_fields_Type(),
2584                                                          StubRoutines::store_inline_type_fields_to_buf(),
2585                                                          "store_inline_type_fields",
2586                                                          TypePtr::BOTTOM);
2587   slow_call->init_req(TypeFunc::Control, needgc_ctrl);
2588   slow_call->init_req(TypeFunc::Memory, mem);
2589   slow_call->init_req(TypeFunc::I_O, io);
2590   slow_call->init_req(TypeFunc::FramePtr, call->in(TypeFunc::FramePtr));
2591   slow_call->init_req(TypeFunc::ReturnAdr, call->in(TypeFunc::ReturnAdr));
2592   slow_call->init_req(TypeFunc::Parms, res);
2593 
2594   Node* slow_ctl = transform_later(new ProjNode(slow_call, TypeFunc::Control));
2595   Node* slow_mem = transform_later(new ProjNode(slow_call, TypeFunc::Memory));
2596   Node* slow_io = transform_later(new ProjNode(slow_call, TypeFunc::I_O));
2597   Node* slow_res = transform_later(new ProjNode(slow_call, TypeFunc::Parms));
2598   Node* slow_catc = transform_later(new CatchNode(slow_ctl, slow_io, 2));
2599   Node* slow_norm = transform_later(new CatchProjNode(slow_catc, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci));
2600   Node* slow_excp = transform_later(new CatchProjNode(slow_catc, CatchProjNode::catch_all_index,    CatchProjNode::no_handler_bci));
2601 
2602   Node* ex_r = new RegionNode(3);
2603   Node* ex_mem_phi = new PhiNode(ex_r, Type::MEMORY, TypePtr::BOTTOM);
2604   Node* ex_io_phi = new PhiNode(ex_r, Type::ABIO);
2605   ex_r->init_req(1, slow_excp);
2606   ex_mem_phi->init_req(1, slow_mem);
2607   ex_io_phi->init_req(1, slow_io);
2608   ex_r->init_req(2, ex_ctl);
2609   ex_mem_phi->init_req(2, ex_mem);
2610   ex_io_phi->init_req(2, ex_io);
2611   transform_later(ex_r);
2612   transform_later(ex_mem_phi);
2613   transform_later(ex_io_phi);
2614 
2615   // We don't know how many values are returned. This assumes the
2616   // worst case, that all available registers are used.
2617   for (uint i = TypeFunc::Parms+1; i < domain->cnt(); i++) {
2618     if (domain->field_at(i) == Type::HALF) {
2619       slow_call->init_req(i, top());
2620       if (alloc_in_place) {
2621         handler_call->init_req(i+1, top());
2622       }
2623       continue;
2624     }
2625     Node* proj = transform_later(new ProjNode(call, i));
2626     slow_call->init_req(i, proj);
2627     if (alloc_in_place) {
2628       handler_call->init_req(i+1, proj);
2629     }
2630   }
2631   // We can safepoint at that new call
2632   slow_call->copy_call_debug_info(&_igvn, call);
2633   transform_later(slow_call);
2634   if (alloc_in_place) {
2635     transform_later(handler_call);
2636   }
2637 
2638   Node* fast_ctl = nullptr;
2639   Node* fast_res = nullptr;
2640   MergeMemNode* fast_mem = nullptr;
2641   if (alloc_in_place) {
2642     fast_ctl = transform_later(new ProjNode(handler_call, TypeFunc::Control));
2643     Node* rawmem = transform_later(new ProjNode(handler_call, TypeFunc::Memory));
2644     fast_res = transform_later(new ProjNode(handler_call, TypeFunc::Parms));
2645     fast_mem = MergeMemNode::make(mem);
2646     fast_mem->set_memory_at(Compile::AliasIdxRaw, rawmem);
2647     transform_later(fast_mem);
2648   }
2649 
2650   Node* r = new RegionNode(alloc_in_place ? 4 : 3);
2651   Node* mem_phi = new PhiNode(r, Type::MEMORY, TypePtr::BOTTOM);
2652   Node* io_phi = new PhiNode(r, Type::ABIO);
2653   Node* res_phi = new PhiNode(r, TypeInstPtr::BOTTOM);
2654   r->init_req(1, no_allocation_ctl);
2655   mem_phi->init_req(1, mem);
2656   io_phi->init_req(1, io);
2657   res_phi->init_req(1, no_allocation_res);
2658   r->init_req(2, slow_norm);
2659   mem_phi->init_req(2, slow_mem);
2660   io_phi->init_req(2, slow_io);
2661   res_phi->init_req(2, slow_res);
2662   if (alloc_in_place) {
2663     r->init_req(3, fast_ctl);
2664     mem_phi->init_req(3, fast_mem);
2665     io_phi->init_req(3, io);
2666     res_phi->init_req(3, fast_res);
2667   }
2668   transform_later(r);
2669   transform_later(mem_phi);
2670   transform_later(io_phi);
2671   transform_later(res_phi);
2672 
2673   // Do not let stores that initialize this buffer be reordered with a subsequent
2674   // store that would make this buffer accessible by other threads.
2675   MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
2676   transform_later(mb);
2677   mb->init_req(TypeFunc::Memory, mem_phi);
2678   mb->init_req(TypeFunc::Control, r);
2679   r = new ProjNode(mb, TypeFunc::Control);
2680   transform_later(r);
2681   mem_phi = new ProjNode(mb, TypeFunc::Memory);
2682   transform_later(mem_phi);
2683 
2684   assert(projs->nb_resproj == 1, "unexpected number of results");
2685   _igvn.replace_in_uses(projs->fallthrough_catchproj, r);
2686   _igvn.replace_in_uses(projs->fallthrough_memproj, mem_phi);
2687   _igvn.replace_in_uses(projs->fallthrough_ioproj, io_phi);
2688   _igvn.replace_in_uses(projs->resproj[0], res_phi);
2689   _igvn.replace_in_uses(projs->catchall_catchproj, ex_r);
2690   _igvn.replace_in_uses(projs->catchall_memproj, ex_mem_phi);
2691   _igvn.replace_in_uses(projs->catchall_ioproj, ex_io_phi);
2692   // The CatchNode should not use the ex_io_phi. Re-connect it to the catchall_ioproj.
2693   Node* cn = projs->fallthrough_catchproj->in(0);
2694   _igvn.replace_input_of(cn, 1, projs->catchall_ioproj);
2695 
2696   _igvn.replace_node(ctl, projs->fallthrough_catchproj);
2697   _igvn.replace_node(mem, projs->fallthrough_memproj);
2698   _igvn.replace_node(io, projs->fallthrough_ioproj);
2699   _igvn.replace_node(res, projs->resproj[0]);
2700   _igvn.replace_node(ex_ctl, projs->catchall_catchproj);
2701   _igvn.replace_node(ex_mem, projs->catchall_memproj);
2702   _igvn.replace_node(ex_io, projs->catchall_ioproj);
2703  }
2704 
2705 void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) {
2706   assert(check->in(SubTypeCheckNode::Control) == nullptr, "should be pinned");
2707   Node* bol = check->unique_out();
2708   Node* obj_or_subklass = check->in(SubTypeCheckNode::ObjOrSubKlass);
2709   Node* superklass = check->in(SubTypeCheckNode::SuperKlass);
2710   assert(bol->is_Bool() && bol->as_Bool()->_test._test == BoolTest::ne, "unexpected bool node");
2711 
2712   for (DUIterator_Last imin, i = bol->last_outs(imin); i >= imin; --i) {
2713     Node* iff = bol->last_out(i);
2714     assert(iff->is_If(), "where's the if?");
2715 
2716     if (iff->in(0)->is_top()) {
2717       _igvn.replace_input_of(iff, 1, C->top());
2718       continue;
2719     }
2720 
2721     Node* iftrue = iff->as_If()->proj_out(1);
2722     Node* iffalse = iff->as_If()->proj_out(0);
2723     Node* ctrl = iff->in(0);
2724 
2725     Node* subklass = nullptr;
2726     if (_igvn.type(obj_or_subklass)->isa_klassptr()) {
2727       subklass = obj_or_subklass;
2728     } else {
2729       Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes());
2730       subklass = _igvn.transform(LoadKlassNode::make(_igvn, nullptr, C->immutable_memory(), k_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
2731     }
2732 
2733     Node* not_subtype_ctrl = Phase::gen_subtype_check(subklass, superklass, &ctrl, nullptr, _igvn, check->method(), check->bci());
2734 
2735     _igvn.replace_input_of(iff, 0, C->top());
2736     _igvn.replace_node(iftrue, not_subtype_ctrl);
2737     _igvn.replace_node(iffalse, ctrl);
2738   }
2739   _igvn.replace_node(check, C->top());
2740 }
2741 
2742 // FlatArrayCheckNode (array1 array2 ...) is expanded into:
2743 //
2744 // long mark = array1.mark | array2.mark | ...;
2745 // long locked_bit = markWord::unlocked_value & array1.mark & array2.mark & ...;
2746 // if (locked_bit == 0) {
2747 //   // One array is locked, load prototype header from the klass
2748 //   mark = array1.klass.proto | array2.klass.proto | ...
2749 // }
2750 // if ((mark & markWord::flat_array_bit_in_place) == 0) {
2751 //    ...
2752 // }
2753 void PhaseMacroExpand::expand_flatarraycheck_node(FlatArrayCheckNode* check) {
2754   bool array_inputs = _igvn.type(check->in(FlatArrayCheckNode::ArrayOrKlass))->isa_oopptr() != nullptr;
2755   if (UseArrayMarkWordCheck && array_inputs) {
2756     Node* mark = MakeConX(0);
2757     Node* locked_bit = MakeConX(markWord::unlocked_value);
2758     Node* mem = check->in(FlatArrayCheckNode::Memory);
2759     for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) {
2760       Node* ary = check->in(i);
2761       const TypeOopPtr* t = _igvn.type(ary)->isa_oopptr();
2762       assert(t != nullptr, "Mixing array and klass inputs");
2763       assert(!t->is_flat() && !t->is_not_flat(), "Should have been optimized out");
2764       Node* mark_adr = basic_plus_adr(ary, oopDesc::mark_offset_in_bytes());
2765       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));
2766       mark = _igvn.transform(new OrXNode(mark, mark_load));
2767       locked_bit = _igvn.transform(new AndXNode(locked_bit, mark_load));
2768     }
2769     assert(!mark->is_Con(), "Should have been optimized out");
2770     Node* cmp = _igvn.transform(new CmpXNode(locked_bit, MakeConX(0)));
2771     Node* is_unlocked = _igvn.transform(new BoolNode(cmp, BoolTest::ne));
2772 
2773     // BoolNode might be shared, replace each if user
2774     Node* old_bol = check->unique_out();
2775     assert(old_bol->is_Bool() && old_bol->as_Bool()->_test._test == BoolTest::ne, "unexpected condition");
2776     for (DUIterator_Last imin, i = old_bol->last_outs(imin); i >= imin; --i) {
2777       IfNode* old_iff = old_bol->last_out(i)->as_If();
2778       Node* ctrl = old_iff->in(0);
2779       RegionNode* region = new RegionNode(3);
2780       Node* mark_phi = new PhiNode(region, TypeX_X);
2781 
2782       // Check if array is unlocked
2783       IfNode* iff = _igvn.transform(new IfNode(ctrl, is_unlocked, PROB_MAX, COUNT_UNKNOWN))->as_If();
2784 
2785       // Unlocked: Use bits from mark word
2786       region->init_req(1, _igvn.transform(new IfTrueNode(iff)));
2787       mark_phi->init_req(1, mark);
2788 
2789       // Locked: Load prototype header from klass
2790       ctrl = _igvn.transform(new IfFalseNode(iff));
2791       Node* proto = MakeConX(0);
2792       for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) {
2793         Node* ary = check->in(i);
2794         // Make loads control dependent to make sure they are only executed if array is locked
2795         Node* klass_adr = basic_plus_adr(ary, oopDesc::klass_offset_in_bytes());
2796         Node* klass = _igvn.transform(LoadKlassNode::make(_igvn, ctrl, C->immutable_memory(), klass_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
2797         Node* proto_adr = basic_plus_adr(klass, in_bytes(Klass::prototype_header_offset()));
2798         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));
2799         proto = _igvn.transform(new OrXNode(proto, proto_load));
2800       }
2801       region->init_req(2, ctrl);
2802       mark_phi->init_req(2, proto);
2803 
2804       // Check if flat array bits are set
2805       Node* mask = MakeConX(markWord::flat_array_bit_in_place);
2806       Node* masked = _igvn.transform(new AndXNode(_igvn.transform(mark_phi), mask));
2807       cmp = _igvn.transform(new CmpXNode(masked, MakeConX(0)));
2808       Node* is_not_flat = _igvn.transform(new BoolNode(cmp, BoolTest::eq));
2809 
2810       ctrl = _igvn.transform(region);
2811       iff = _igvn.transform(new IfNode(ctrl, is_not_flat, PROB_MAX, COUNT_UNKNOWN))->as_If();
2812       _igvn.replace_node(old_iff, iff);
2813     }
2814     _igvn.replace_node(check, C->top());
2815   } else {
2816     // Fall back to layout helper check
2817     Node* lhs = intcon(0);
2818     for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) {
2819       Node* array_or_klass = check->in(i);
2820       Node* klass = nullptr;
2821       const TypePtr* t = _igvn.type(array_or_klass)->is_ptr();
2822       assert(!t->is_flat() && !t->is_not_flat(), "Should have been optimized out");
2823       if (t->isa_oopptr() != nullptr) {
2824         Node* klass_adr = basic_plus_adr(array_or_klass, oopDesc::klass_offset_in_bytes());
2825         klass = transform_later(LoadKlassNode::make(_igvn, nullptr, C->immutable_memory(), klass_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
2826       } else {
2827         assert(t->isa_klassptr(), "Unexpected input type");
2828         klass = array_or_klass;
2829       }
2830       Node* lh_addr = basic_plus_adr(klass, in_bytes(Klass::layout_helper_offset()));
2831       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));
2832       lhs = _igvn.transform(new OrINode(lhs, lh_val));
2833     }
2834     Node* masked = transform_later(new AndINode(lhs, intcon(Klass::_lh_array_tag_flat_value_bit_inplace)));
2835     Node* cmp = transform_later(new CmpINode(masked, intcon(0)));
2836     Node* bol = transform_later(new BoolNode(cmp, BoolTest::eq));
2837     Node* m2b = transform_later(new Conv2BNode(masked));
2838     // The matcher expects the input to If nodes to be produced by a Bool(CmpI..)
2839     // pattern, but the input to other potential users (e.g. Phi) to be some
2840     // other pattern (e.g. a Conv2B node, possibly idealized as a CMoveI).
2841     Node* old_bol = check->unique_out();
2842     for (DUIterator_Last imin, i = old_bol->last_outs(imin); i >= imin; --i) {
2843       Node* user = old_bol->last_out(i);
2844       for (uint j = 0; j < user->req(); j++) {
2845         Node* n = user->in(j);
2846         if (n == old_bol) {
2847           _igvn.replace_input_of(user, j, user->is_If() ? bol : m2b);
2848         }
2849       }
2850     }
2851     _igvn.replace_node(check, C->top());
2852   }
2853 }
2854 
2855 //---------------------------eliminate_macro_nodes----------------------
2856 // Eliminate scalar replaced allocations and associated locks.
2857 void PhaseMacroExpand::eliminate_macro_nodes() {
2858   if (C->macro_count() == 0)
2859     return;
2860   NOT_PRODUCT(int membar_before = count_MemBar(C);)
2861 
2862   // Before elimination may re-mark (change to Nested or NonEscObj)
2863   // all associated (same box and obj) lock and unlock nodes.
2864   int cnt = C->macro_count();
2865   for (int i=0; i < cnt; i++) {
2866     Node *n = C->macro_node(i);
2867     if (n->is_AbstractLock()) { // Lock and Unlock nodes
2868       mark_eliminated_locking_nodes(n->as_AbstractLock());
2869     }
2870   }
2871   // Re-marking may break consistency of Coarsened locks.
2872   if (!C->coarsened_locks_consistent()) {
2873     return; // recompile without Coarsened locks if broken
2874   }

2895   }
2896   // Next, attempt to eliminate allocations
2897   _has_locks = false;
2898   progress = true;
2899   while (progress) {
2900     progress = false;
2901     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
2902       Node* n = C->macro_node(i - 1);
2903       bool success = false;
2904       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2905       switch (n->class_id()) {
2906       case Node::Class_Allocate:
2907       case Node::Class_AllocateArray:
2908         success = eliminate_allocate_node(n->as_Allocate());
2909 #ifndef PRODUCT
2910         if (success && PrintOptoStatistics) {
2911           Atomic::inc(&PhaseMacroExpand::_objs_scalar_replaced_counter);
2912         }
2913 #endif
2914         break;
2915       case Node::Class_CallStaticJava: {
2916         CallStaticJavaNode* call = n->as_CallStaticJava();
2917         if (!call->method()->is_method_handle_intrinsic()) {
2918           success = eliminate_boxing_node(n->as_CallStaticJava());
2919         }
2920         break;
2921       }
2922       case Node::Class_Lock:
2923       case Node::Class_Unlock:
2924         assert(!n->as_AbstractLock()->is_eliminated(), "sanity");
2925         _has_locks = true;
2926         break;
2927       case Node::Class_ArrayCopy:
2928         break;
2929       case Node::Class_OuterStripMinedLoop:
2930         break;
2931       case Node::Class_SubTypeCheck:
2932         break;
2933       case Node::Class_Opaque1:
2934         break;
2935       case Node::Class_FlatArrayCheck:
2936         break;
2937       default:
2938         assert(n->Opcode() == Op_LoopLimit ||
2939                n->Opcode() == Op_Opaque3   ||
2940                n->Opcode() == Op_Opaque4   ||
2941                n->Opcode() == Op_MaxL      ||
2942                n->Opcode() == Op_MinL      ||
2943                BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
2944                "unknown node type in macro list");
2945       }
2946       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2947       progress = progress || success;
2948     }
2949   }
2950 #ifndef PRODUCT
2951   if (PrintOptoStatistics) {
2952     int membar_after = count_MemBar(C);
2953     Atomic::add(&PhaseMacroExpand::_memory_barriers_removed_counter, membar_before - membar_after);
2954   }
2955 #endif
2956 }

2959 //  Returns true if a failure occurred.
2960 bool PhaseMacroExpand::expand_macro_nodes() {
2961   // Last attempt to eliminate macro nodes.
2962   eliminate_macro_nodes();
2963   if (C->failing())  return true;
2964 
2965   // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
2966   bool progress = true;
2967   while (progress) {
2968     progress = false;
2969     for (int i = C->macro_count(); i > 0; i--) {
2970       Node* n = C->macro_node(i-1);
2971       bool success = false;
2972       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2973       if (n->Opcode() == Op_LoopLimit) {
2974         // Remove it from macro list and put on IGVN worklist to optimize.
2975         C->remove_macro_node(n);
2976         _igvn._worklist.push(n);
2977         success = true;
2978       } else if (n->Opcode() == Op_CallStaticJava) {
2979         CallStaticJavaNode* call = n->as_CallStaticJava();
2980         if (!call->method()->is_method_handle_intrinsic()) {
2981           // Remove it from macro list and put on IGVN worklist to optimize.
2982           C->remove_macro_node(n);
2983           _igvn._worklist.push(n);
2984           success = true;
2985         }
2986       } else if (n->is_Opaque1()) {
2987         _igvn.replace_node(n, n->in(1));
2988         success = true;
2989 #if INCLUDE_RTM_OPT
2990       } else if ((n->Opcode() == Op_Opaque3) && ((Opaque3Node*)n)->rtm_opt()) {
2991         assert(C->profile_rtm(), "should be used only in rtm deoptimization code");
2992         assert((n->outcnt() == 1) && n->unique_out()->is_Cmp(), "");
2993         Node* cmp = n->unique_out();
2994 #ifdef ASSERT
2995         // Validate graph.
2996         assert((cmp->outcnt() == 1) && cmp->unique_out()->is_Bool(), "");
2997         BoolNode* bol = cmp->unique_out()->as_Bool();
2998         assert((bol->outcnt() == 1) && bol->unique_out()->is_If() &&
2999                (bol->_test._test == BoolTest::ne), "");
3000         IfNode* ifn = bol->unique_out()->as_If();
3001         assert((ifn->outcnt() == 2) &&
3002                ifn->proj_out(1)->is_uncommon_trap_proj(Deoptimization::Reason_rtm_state_change) != nullptr, "");
3003 #endif
3004         Node* repl = n->in(1);
3005         if (!_has_locks) {

3080     // Worst case is a macro node gets expanded into about 200 nodes.
3081     // Allow 50% more for optimization.
3082     if (C->check_node_count(300, "out of nodes before macro expansion")) {
3083       return true;
3084     }
3085 
3086     DEBUG_ONLY(int old_macro_count = C->macro_count();)
3087     switch (n->class_id()) {
3088     case Node::Class_Lock:
3089       expand_lock_node(n->as_Lock());
3090       break;
3091     case Node::Class_Unlock:
3092       expand_unlock_node(n->as_Unlock());
3093       break;
3094     case Node::Class_ArrayCopy:
3095       expand_arraycopy_node(n->as_ArrayCopy());
3096       break;
3097     case Node::Class_SubTypeCheck:
3098       expand_subtypecheck_node(n->as_SubTypeCheck());
3099       break;
3100     case Node::Class_CallStaticJava:
3101       expand_mh_intrinsic_return(n->as_CallStaticJava());
3102       C->remove_macro_node(n);
3103       break;
3104     case Node::Class_FlatArrayCheck:
3105       expand_flatarraycheck_node(n->as_FlatArrayCheck());
3106       break;
3107     default:
3108       assert(false, "unknown node type in macro list");
3109     }
3110     assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
3111     if (C->failing())  return true;
3112 
3113     // Clean up the graph so we're less likely to hit the maximum node
3114     // limit
3115     _igvn.set_delay_transform(false);
3116     _igvn.optimize();
3117     if (C->failing())  return true;
3118     _igvn.set_delay_transform(true);
3119   }
3120 
3121   // All nodes except Allocate nodes are expanded now. There could be
3122   // new optimization opportunities (such as folding newly created
3123   // load from a just allocated object). Run IGVN.
3124 
3125   // expand "macro" nodes
3126   // nodes are removed from the macro list as they are processed
< prev index next >