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