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