1 /*
   2  * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "compiler/compileLog.hpp"
  27 #include "gc/shared/collectedHeap.inline.hpp"
  28 #include "gc/shared/tlab_globals.hpp"
  29 #include "libadt/vectset.hpp"
  30 #include "memory/universe.hpp"
  31 #include "opto/addnode.hpp"
  32 #include "opto/arraycopynode.hpp"
  33 #include "opto/callnode.hpp"
  34 #include "opto/castnode.hpp"
  35 #include "opto/cfgnode.hpp"
  36 #include "opto/compile.hpp"
  37 #include "opto/convertnode.hpp"
  38 #include "opto/graphKit.hpp"
  39 #include "opto/intrinsicnode.hpp"
  40 #include "opto/locknode.hpp"
  41 #include "opto/loopnode.hpp"
  42 #include "opto/macro.hpp"
  43 #include "opto/memnode.hpp"
  44 #include "opto/narrowptrnode.hpp"
  45 #include "opto/node.hpp"
  46 #include "opto/opaquenode.hpp"
  47 #include "opto/phaseX.hpp"
  48 #include "opto/rootnode.hpp"
  49 #include "opto/runtime.hpp"
  50 #include "opto/subnode.hpp"
  51 #include "opto/subtypenode.hpp"
  52 #include "opto/type.hpp"
  53 #include "prims/jvmtiExport.hpp"
  54 #include "runtime/sharedRuntime.hpp"
  55 #include "utilities/macros.hpp"
  56 #include "utilities/powerOfTwo.hpp"
  57 #if INCLUDE_G1GC
  58 #include "gc/g1/g1ThreadLocalData.hpp"
  59 #endif // INCLUDE_G1GC
  60 
  61 
  62 //
  63 // Replace any references to "oldref" in inputs to "use" with "newref".
  64 // Returns the number of replacements made.
  65 //
  66 int PhaseMacroExpand::replace_input(Node *use, Node *oldref, Node *newref) {
  67   int nreplacements = 0;
  68   uint req = use->req();
  69   for (uint j = 0; j < use->len(); j++) {
  70     Node *uin = use->in(j);
  71     if (uin == oldref) {
  72       if (j < req)
  73         use->set_req(j, newref);
  74       else
  75         use->set_prec(j, newref);
  76       nreplacements++;
  77     } else if (j >= req && uin == nullptr) {
  78       break;
  79     }
  80   }
  81   return nreplacements;
  82 }
  83 
  84 void PhaseMacroExpand::migrate_outs(Node *old, Node *target) {
  85   assert(old != nullptr, "sanity");
  86   for (DUIterator_Fast imax, i = old->fast_outs(imax); i < imax; i++) {
  87     Node* use = old->fast_out(i);
  88     _igvn.rehash_node_delayed(use);
  89     imax -= replace_input(use, old, target);
  90     // back up iterator
  91     --i;
  92   }
  93   assert(old->outcnt() == 0, "all uses must be deleted");
  94 }
  95 
  96 Node* PhaseMacroExpand::opt_bits_test(Node* ctrl, Node* region, int edge, Node* word, int mask, int bits, bool return_fast_path) {
  97   Node* cmp;
  98   if (mask != 0) {
  99     Node* and_node = transform_later(new AndXNode(word, MakeConX(mask)));
 100     cmp = transform_later(new CmpXNode(and_node, MakeConX(bits)));
 101   } else {
 102     cmp = word;
 103   }
 104   Node* bol = transform_later(new BoolNode(cmp, BoolTest::ne));
 105   IfNode* iff = new IfNode( ctrl, bol, PROB_MIN, COUNT_UNKNOWN );
 106   transform_later(iff);
 107 
 108   // Fast path taken.
 109   Node *fast_taken = transform_later(new IfFalseNode(iff));
 110 
 111   // Fast path not-taken, i.e. slow path
 112   Node *slow_taken = transform_later(new IfTrueNode(iff));
 113 
 114   if (return_fast_path) {
 115     region->init_req(edge, slow_taken); // Capture slow-control
 116     return fast_taken;
 117   } else {
 118     region->init_req(edge, fast_taken); // Capture fast-control
 119     return slow_taken;
 120   }
 121 }
 122 
 123 //--------------------copy_predefined_input_for_runtime_call--------------------
 124 void PhaseMacroExpand::copy_predefined_input_for_runtime_call(Node * ctrl, CallNode* oldcall, CallNode* call) {
 125   // Set fixed predefined input arguments
 126   call->init_req( TypeFunc::Control, ctrl );
 127   call->init_req( TypeFunc::I_O    , oldcall->in( TypeFunc::I_O) );
 128   call->init_req( TypeFunc::Memory , oldcall->in( TypeFunc::Memory ) ); // ?????
 129   call->init_req( TypeFunc::ReturnAdr, oldcall->in( TypeFunc::ReturnAdr ) );
 130   call->init_req( TypeFunc::FramePtr, oldcall->in( TypeFunc::FramePtr ) );
 131 }
 132 
 133 //------------------------------make_slow_call---------------------------------
 134 CallNode* PhaseMacroExpand::make_slow_call(CallNode *oldcall, const TypeFunc* slow_call_type,
 135                                            address slow_call, const char* leaf_name, Node* slow_path,
 136                                            Node* parm0, Node* parm1, Node* parm2) {
 137 
 138   // Slow-path call
 139  CallNode *call = leaf_name
 140    ? (CallNode*)new CallLeafNode      ( slow_call_type, slow_call, leaf_name, TypeRawPtr::BOTTOM )
 141    : (CallNode*)new CallStaticJavaNode( slow_call_type, slow_call, OptoRuntime::stub_name(slow_call), TypeRawPtr::BOTTOM );
 142 
 143   // Slow path call has no side-effects, uses few values
 144   copy_predefined_input_for_runtime_call(slow_path, oldcall, call );
 145   if (parm0 != nullptr)  call->init_req(TypeFunc::Parms+0, parm0);
 146   if (parm1 != nullptr)  call->init_req(TypeFunc::Parms+1, parm1);
 147   if (parm2 != nullptr)  call->init_req(TypeFunc::Parms+2, parm2);
 148   call->copy_call_debug_info(&_igvn, oldcall);
 149   call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
 150   _igvn.replace_node(oldcall, call);
 151   transform_later(call);
 152 
 153   return call;
 154 }
 155 
 156 void PhaseMacroExpand::eliminate_gc_barrier(Node* p2x) {
 157   BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
 158   bs->eliminate_gc_barrier(this, p2x);
 159 }
 160 
 161 // Search for a memory operation for the specified memory slice.
 162 static Node *scan_mem_chain(Node *mem, int alias_idx, int offset, Node *start_mem, Node *alloc, PhaseGVN *phase) {
 163   Node *orig_mem = mem;
 164   Node *alloc_mem = alloc->in(TypeFunc::Memory);
 165   const TypeOopPtr *tinst = phase->C->get_adr_type(alias_idx)->isa_oopptr();
 166   while (true) {
 167     if (mem == alloc_mem || mem == start_mem ) {
 168       return mem;  // hit one of our sentinels
 169     } else if (mem->is_MergeMem()) {
 170       mem = mem->as_MergeMem()->memory_at(alias_idx);
 171     } else if (mem->is_Proj() && mem->as_Proj()->_con == TypeFunc::Memory) {
 172       Node *in = mem->in(0);
 173       // we can safely skip over safepoints, calls, locks and membars because we
 174       // already know that the object is safe to eliminate.
 175       if (in->is_Initialize() && in->as_Initialize()->allocation() == alloc) {
 176         return in;
 177       } else if (in->is_Call()) {
 178         CallNode *call = in->as_Call();
 179         if (call->may_modify(tinst, phase)) {
 180           assert(call->is_ArrayCopy(), "ArrayCopy is the only call node that doesn't make allocation escape");
 181           if (call->as_ArrayCopy()->modifies(offset, offset, phase, false)) {
 182             return in;
 183           }
 184         }
 185         mem = in->in(TypeFunc::Memory);
 186       } else if (in->is_MemBar()) {
 187         ArrayCopyNode* ac = nullptr;
 188         if (ArrayCopyNode::may_modify(tinst, in->as_MemBar(), phase, ac)) {
 189           if (ac != nullptr) {
 190             assert(ac->is_clonebasic(), "Only basic clone is a non escaping clone");
 191             return ac;
 192           }
 193         }
 194         mem = in->in(TypeFunc::Memory);
 195       } else {
 196 #ifdef ASSERT
 197         in->dump();
 198         mem->dump();
 199         assert(false, "unexpected projection");
 200 #endif
 201       }
 202     } else if (mem->is_Store()) {
 203       const TypePtr* atype = mem->as_Store()->adr_type();
 204       int adr_idx = phase->C->get_alias_index(atype);
 205       if (adr_idx == alias_idx) {
 206         assert(atype->isa_oopptr(), "address type must be oopptr");
 207         int adr_offset = atype->offset();
 208         uint adr_iid = atype->is_oopptr()->instance_id();
 209         // Array elements references have the same alias_idx
 210         // but different offset and different instance_id.
 211         if (adr_offset == offset && adr_iid == alloc->_idx) {
 212           return mem;
 213         }
 214       } else {
 215         assert(adr_idx == Compile::AliasIdxRaw, "address must match or be raw");
 216       }
 217       mem = mem->in(MemNode::Memory);
 218     } else if (mem->is_ClearArray()) {
 219       if (!ClearArrayNode::step_through(&mem, alloc->_idx, phase)) {
 220         // Can not bypass initialization of the instance
 221         // we are looking.
 222         debug_only(intptr_t offset;)
 223         assert(alloc == AllocateNode::Ideal_allocation(mem->in(3), phase, offset), "sanity");
 224         InitializeNode* init = alloc->as_Allocate()->initialization();
 225         // We are looking for stored value, return Initialize node
 226         // or memory edge from Allocate node.
 227         if (init != nullptr) {
 228           return init;
 229         } else {
 230           return alloc->in(TypeFunc::Memory); // It will produce zero value (see callers).
 231         }
 232       }
 233       // Otherwise skip it (the call updated 'mem' value).
 234     } else if (mem->Opcode() == Op_SCMemProj) {
 235       mem = mem->in(0);
 236       Node* adr = nullptr;
 237       if (mem->is_LoadStore()) {
 238         adr = mem->in(MemNode::Address);
 239       } else {
 240         assert(mem->Opcode() == Op_EncodeISOArray ||
 241                mem->Opcode() == Op_StrCompressedCopy, "sanity");
 242         adr = mem->in(3); // Destination array
 243       }
 244       const TypePtr* atype = adr->bottom_type()->is_ptr();
 245       int adr_idx = phase->C->get_alias_index(atype);
 246       if (adr_idx == alias_idx) {
 247         DEBUG_ONLY(mem->dump();)
 248         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
 249         return nullptr;
 250       }
 251       mem = mem->in(MemNode::Memory);
 252    } else if (mem->Opcode() == Op_StrInflatedCopy) {
 253       Node* adr = mem->in(3); // Destination array
 254       const TypePtr* atype = adr->bottom_type()->is_ptr();
 255       int adr_idx = phase->C->get_alias_index(atype);
 256       if (adr_idx == alias_idx) {
 257         DEBUG_ONLY(mem->dump();)
 258         assert(false, "Object is not scalar replaceable if a StrInflatedCopy node accesses its field");
 259         return nullptr;
 260       }
 261       mem = mem->in(MemNode::Memory);
 262     } else {
 263       return mem;
 264     }
 265     assert(mem != orig_mem, "dead memory loop");
 266   }
 267 }
 268 
 269 // Generate loads from source of the arraycopy for fields of
 270 // destination needed at a deoptimization point
 271 Node* PhaseMacroExpand::make_arraycopy_load(ArrayCopyNode* ac, intptr_t offset, Node* ctl, Node* mem, BasicType ft, const Type *ftype, AllocateNode *alloc) {
 272   BasicType bt = ft;
 273   const Type *type = ftype;
 274   if (ft == T_NARROWOOP) {
 275     bt = T_OBJECT;
 276     type = ftype->make_oopptr();
 277   }
 278   Node* res = nullptr;
 279   if (ac->is_clonebasic()) {
 280     assert(ac->in(ArrayCopyNode::Src) != ac->in(ArrayCopyNode::Dest), "clone source equals destination");
 281     Node* base = ac->in(ArrayCopyNode::Src);
 282     Node* adr = _igvn.transform(new AddPNode(base, base, MakeConX(offset)));
 283     const TypePtr* adr_type = _igvn.type(base)->is_ptr()->add_offset(offset);
 284     MergeMemNode* mergemen = _igvn.transform(MergeMemNode::make(mem))->as_MergeMem();
 285     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 286     res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
 287   } else {
 288     if (ac->modifies(offset, offset, &_igvn, true)) {
 289       assert(ac->in(ArrayCopyNode::Dest) == alloc->result_cast(), "arraycopy destination should be allocation's result");
 290       uint shift = exact_log2(type2aelembytes(bt));
 291       Node* src_pos = ac->in(ArrayCopyNode::SrcPos);
 292       Node* dest_pos = ac->in(ArrayCopyNode::DestPos);
 293       const TypeInt* src_pos_t = _igvn.type(src_pos)->is_int();
 294       const TypeInt* dest_pos_t = _igvn.type(dest_pos)->is_int();
 295 
 296       Node* adr = nullptr;
 297       const TypePtr* adr_type = nullptr;
 298       if (src_pos_t->is_con() && dest_pos_t->is_con()) {
 299         intptr_t off = ((src_pos_t->get_con() - dest_pos_t->get_con()) << shift) + offset;
 300         Node* base = ac->in(ArrayCopyNode::Src);
 301         adr = _igvn.transform(new AddPNode(base, base, MakeConX(off)));
 302         adr_type = _igvn.type(base)->is_ptr()->add_offset(off);
 303         if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 304           // Don't emit a new load from src if src == dst but try to get the value from memory instead
 305           return value_from_mem(ac->in(TypeFunc::Memory), ctl, ft, ftype, adr_type->isa_oopptr(), alloc);
 306         }
 307       } else {
 308         Node* diff = _igvn.transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
 309 #ifdef _LP64
 310         diff = _igvn.transform(new ConvI2LNode(diff));
 311 #endif
 312         diff = _igvn.transform(new LShiftXNode(diff, intcon(shift)));
 313 
 314         Node* off = _igvn.transform(new AddXNode(MakeConX(offset), diff));
 315         Node* base = ac->in(ArrayCopyNode::Src);
 316         adr = _igvn.transform(new AddPNode(base, base, off));
 317         adr_type = _igvn.type(base)->is_ptr()->add_offset(Type::OffsetBot);
 318         if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 319           // Non constant offset in the array: we can't statically
 320           // determine the value
 321           return nullptr;
 322         }
 323       }
 324       MergeMemNode* mergemen = _igvn.transform(MergeMemNode::make(mem))->as_MergeMem();
 325       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 326       res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
 327     }
 328   }
 329   if (res != nullptr) {
 330     if (ftype->isa_narrowoop()) {
 331       // PhaseMacroExpand::scalar_replacement adds DecodeN nodes
 332       res = _igvn.transform(new EncodePNode(res, ftype));
 333     }
 334     return res;
 335   }
 336   return nullptr;
 337 }
 338 
 339 //
 340 // Given a Memory Phi, compute a value Phi containing the values from stores
 341 // on the input paths.
 342 // Note: this function is recursive, its depth is limited by the "level" argument
 343 // Returns the computed Phi, or null if it cannot compute it.
 344 Node *PhaseMacroExpand::value_from_mem_phi(Node *mem, BasicType ft, const Type *phi_type, const TypeOopPtr *adr_t, AllocateNode *alloc, Node_Stack *value_phis, int level) {
 345   assert(mem->is_Phi(), "sanity");
 346   int alias_idx = C->get_alias_index(adr_t);
 347   int offset = adr_t->offset();
 348   int instance_id = adr_t->instance_id();
 349 
 350   // Check if an appropriate value phi already exists.
 351   Node* region = mem->in(0);
 352   for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) {
 353     Node* phi = region->fast_out(k);
 354     if (phi->is_Phi() && phi != mem &&
 355         phi->as_Phi()->is_same_inst_field(phi_type, (int)mem->_idx, instance_id, alias_idx, offset)) {
 356       return phi;
 357     }
 358   }
 359   // Check if an appropriate new value phi already exists.
 360   Node* new_phi = value_phis->find(mem->_idx);
 361   if (new_phi != nullptr)
 362     return new_phi;
 363 
 364   if (level <= 0) {
 365     return nullptr; // Give up: phi tree too deep
 366   }
 367   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
 368   Node *alloc_mem = alloc->in(TypeFunc::Memory);
 369 
 370   uint length = mem->req();
 371   GrowableArray <Node *> values(length, length, nullptr);
 372 
 373   // create a new Phi for the value
 374   PhiNode *phi = new PhiNode(mem->in(0), phi_type, nullptr, mem->_idx, instance_id, alias_idx, offset);
 375   transform_later(phi);
 376   value_phis->push(phi, mem->_idx);
 377 
 378   for (uint j = 1; j < length; j++) {
 379     Node *in = mem->in(j);
 380     if (in == nullptr || in->is_top()) {
 381       values.at_put(j, in);
 382     } else  {
 383       Node *val = scan_mem_chain(in, alias_idx, offset, start_mem, alloc, &_igvn);
 384       if (val == start_mem || val == alloc_mem) {
 385         // hit a sentinel, return appropriate 0 value
 386         values.at_put(j, _igvn.zerocon(ft));
 387         continue;
 388       }
 389       if (val->is_Initialize()) {
 390         val = val->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 391       }
 392       if (val == nullptr) {
 393         return nullptr;  // can't find a value on this path
 394       }
 395       if (val == mem) {
 396         values.at_put(j, mem);
 397       } else if (val->is_Store()) {
 398         Node* n = val->in(MemNode::ValueIn);
 399         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 400         n = bs->step_over_gc_barrier(n);
 401         if (is_subword_type(ft)) {
 402           n = Compile::narrow_value(ft, n, phi_type, &_igvn, true);
 403         }
 404         values.at_put(j, n);
 405       } else if(val->is_Proj() && val->in(0) == alloc) {
 406         values.at_put(j, _igvn.zerocon(ft));
 407       } else if (val->is_Phi()) {
 408         val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, value_phis, level-1);
 409         if (val == nullptr) {
 410           return nullptr;
 411         }
 412         values.at_put(j, val);
 413       } else if (val->Opcode() == Op_SCMemProj) {
 414         assert(val->in(0)->is_LoadStore() ||
 415                val->in(0)->Opcode() == Op_EncodeISOArray ||
 416                val->in(0)->Opcode() == Op_StrCompressedCopy, "sanity");
 417         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
 418         return nullptr;
 419       } else if (val->is_ArrayCopy()) {
 420         Node* res = make_arraycopy_load(val->as_ArrayCopy(), offset, val->in(0), val->in(TypeFunc::Memory), ft, phi_type, alloc);
 421         if (res == nullptr) {
 422           return nullptr;
 423         }
 424         values.at_put(j, res);
 425       } else {
 426         DEBUG_ONLY( val->dump(); )
 427         assert(false, "unknown node on this path");
 428         return nullptr;  // unknown node on this path
 429       }
 430     }
 431   }
 432   // Set Phi's inputs
 433   for (uint j = 1; j < length; j++) {
 434     if (values.at(j) == mem) {
 435       phi->init_req(j, phi);
 436     } else {
 437       phi->init_req(j, values.at(j));
 438     }
 439   }
 440   return phi;
 441 }
 442 
 443 // Search the last value stored into the object's field.
 444 Node *PhaseMacroExpand::value_from_mem(Node *sfpt_mem, Node *sfpt_ctl, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, AllocateNode *alloc) {
 445   assert(adr_t->is_known_instance_field(), "instance required");
 446   int instance_id = adr_t->instance_id();
 447   assert((uint)instance_id == alloc->_idx, "wrong allocation");
 448 
 449   int alias_idx = C->get_alias_index(adr_t);
 450   int offset = adr_t->offset();
 451   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
 452   Node *alloc_ctrl = alloc->in(TypeFunc::Control);
 453   Node *alloc_mem = alloc->in(TypeFunc::Memory);
 454   VectorSet visited;
 455 
 456   bool done = sfpt_mem == alloc_mem;
 457   Node *mem = sfpt_mem;
 458   while (!done) {
 459     if (visited.test_set(mem->_idx)) {
 460       return nullptr;  // found a loop, give up
 461     }
 462     mem = scan_mem_chain(mem, alias_idx, offset, start_mem, alloc, &_igvn);
 463     if (mem == start_mem || mem == alloc_mem) {
 464       done = true;  // hit a sentinel, return appropriate 0 value
 465     } else if (mem->is_Initialize()) {
 466       mem = mem->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 467       if (mem == nullptr) {
 468         done = true; // Something go wrong.
 469       } else if (mem->is_Store()) {
 470         const TypePtr* atype = mem->as_Store()->adr_type();
 471         assert(C->get_alias_index(atype) == Compile::AliasIdxRaw, "store is correct memory slice");
 472         done = true;
 473       }
 474     } else if (mem->is_Store()) {
 475       const TypeOopPtr* atype = mem->as_Store()->adr_type()->isa_oopptr();
 476       assert(atype != nullptr, "address type must be oopptr");
 477       assert(C->get_alias_index(atype) == alias_idx &&
 478              atype->is_known_instance_field() && atype->offset() == offset &&
 479              atype->instance_id() == instance_id, "store is correct memory slice");
 480       done = true;
 481     } else if (mem->is_Phi()) {
 482       // try to find a phi's unique input
 483       Node *unique_input = nullptr;
 484       Node *top = C->top();
 485       for (uint i = 1; i < mem->req(); i++) {
 486         Node *n = scan_mem_chain(mem->in(i), alias_idx, offset, start_mem, alloc, &_igvn);
 487         if (n == nullptr || n == top || n == mem) {
 488           continue;
 489         } else if (unique_input == nullptr) {
 490           unique_input = n;
 491         } else if (unique_input != n) {
 492           unique_input = top;
 493           break;
 494         }
 495       }
 496       if (unique_input != nullptr && unique_input != top) {
 497         mem = unique_input;
 498       } else {
 499         done = true;
 500       }
 501     } else if (mem->is_ArrayCopy()) {
 502       done = true;
 503     } else {
 504       DEBUG_ONLY( mem->dump(); )
 505       assert(false, "unexpected node");
 506     }
 507   }
 508   if (mem != nullptr) {
 509     if (mem == start_mem || mem == alloc_mem) {
 510       // hit a sentinel, return appropriate 0 value
 511       return _igvn.zerocon(ft);
 512     } else if (mem->is_Store()) {
 513       Node* n = mem->in(MemNode::ValueIn);
 514       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 515       n = bs->step_over_gc_barrier(n);
 516       return n;
 517     } else if (mem->is_Phi()) {
 518       // attempt to produce a Phi reflecting the values on the input paths of the Phi
 519       Node_Stack value_phis(8);
 520       Node* phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, &value_phis, ValueSearchLimit);
 521       if (phi != nullptr) {
 522         return phi;
 523       } else {
 524         // Kill all new Phis
 525         while(value_phis.is_nonempty()) {
 526           Node* n = value_phis.node();
 527           _igvn.replace_node(n, C->top());
 528           value_phis.pop();
 529         }
 530       }
 531     } else if (mem->is_ArrayCopy()) {
 532       Node* ctl = mem->in(0);
 533       Node* m = mem->in(TypeFunc::Memory);
 534       if (sfpt_ctl->is_Proj() && sfpt_ctl->as_Proj()->is_uncommon_trap_proj(Deoptimization::Reason_none)) {
 535         // pin the loads in the uncommon trap path
 536         ctl = sfpt_ctl;
 537         m = sfpt_mem;
 538       }
 539       return make_arraycopy_load(mem->as_ArrayCopy(), offset, ctl, m, ft, ftype, alloc);
 540     }
 541   }
 542   // Something go wrong.
 543   return nullptr;
 544 }
 545 
 546 // Check the possibility of scalar replacement.
 547 bool PhaseMacroExpand::can_eliminate_allocation(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
 548   //  Scan the uses of the allocation to check for anything that would
 549   //  prevent us from eliminating it.
 550   NOT_PRODUCT( const char* fail_eliminate = nullptr; )
 551   DEBUG_ONLY( Node* disq_node = nullptr; )
 552   bool  can_eliminate = true;
 553 
 554   Node* res = alloc->result_cast();
 555   const TypeOopPtr* res_type = nullptr;
 556   if (res == nullptr) {
 557     // All users were eliminated.
 558   } else if (!res->is_CheckCastPP()) {
 559     NOT_PRODUCT(fail_eliminate = "Allocation does not have unique CheckCastPP";)
 560     can_eliminate = false;
 561   } else {
 562     res_type = _igvn.type(res)->isa_oopptr();
 563     if (res_type == nullptr) {
 564       NOT_PRODUCT(fail_eliminate = "Neither instance or array allocation";)
 565       can_eliminate = false;
 566     } else if (res_type->isa_aryptr()) {
 567       int length = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 568       if (length < 0) {
 569         NOT_PRODUCT(fail_eliminate = "Array's size is not constant";)
 570         can_eliminate = false;
 571       }
 572     }
 573   }
 574 
 575   if (can_eliminate && res != nullptr) {
 576     BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
 577     for (DUIterator_Fast jmax, j = res->fast_outs(jmax);
 578                                j < jmax && can_eliminate; j++) {
 579       Node* use = res->fast_out(j);
 580 
 581       if (use->is_AddP()) {
 582         const TypePtr* addp_type = _igvn.type(use)->is_ptr();
 583         int offset = addp_type->offset();
 584 
 585         if (offset == Type::OffsetTop || offset == Type::OffsetBot) {
 586           NOT_PRODUCT(fail_eliminate = "Undefined field referrence";)
 587           can_eliminate = false;
 588           break;
 589         }
 590         for (DUIterator_Fast kmax, k = use->fast_outs(kmax);
 591                                    k < kmax && can_eliminate; k++) {
 592           Node* n = use->fast_out(k);
 593           if (!n->is_Store() && n->Opcode() != Op_CastP2X && !bs->is_gc_pre_barrier_node(n)) {
 594             DEBUG_ONLY(disq_node = n;)
 595             if (n->is_Load() || n->is_LoadStore()) {
 596               NOT_PRODUCT(fail_eliminate = "Field load";)
 597             } else {
 598               NOT_PRODUCT(fail_eliminate = "Not store field referrence";)
 599             }
 600             can_eliminate = false;
 601           }
 602         }
 603       } else if (use->is_ArrayCopy() &&
 604                  (use->as_ArrayCopy()->is_clonebasic() ||
 605                   use->as_ArrayCopy()->is_arraycopy_validated() ||
 606                   use->as_ArrayCopy()->is_copyof_validated() ||
 607                   use->as_ArrayCopy()->is_copyofrange_validated()) &&
 608                  use->in(ArrayCopyNode::Dest) == res) {
 609         // ok to eliminate
 610       } else if (use->is_SafePoint()) {
 611         SafePointNode* sfpt = use->as_SafePoint();
 612         if (sfpt->is_Call() && sfpt->as_Call()->has_non_debug_use(res)) {
 613           // Object is passed as argument.
 614           DEBUG_ONLY(disq_node = use;)
 615           NOT_PRODUCT(fail_eliminate = "Object is passed as argument";)
 616           can_eliminate = false;
 617         }
 618         Node* sfptMem = sfpt->memory();
 619         if (sfptMem == nullptr || sfptMem->is_top()) {
 620           DEBUG_ONLY(disq_node = use;)
 621           NOT_PRODUCT(fail_eliminate = "null or TOP memory";)
 622           can_eliminate = false;
 623         } else {
 624           safepoints.append_if_missing(sfpt);
 625         }
 626       } else if (use->Opcode() != Op_CastP2X) { // CastP2X is used by card mark
 627         if (use->is_Phi()) {
 628           if (use->outcnt() == 1 && use->unique_out()->Opcode() == Op_Return) {
 629             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 630           } else {
 631             NOT_PRODUCT(fail_eliminate = "Object is referenced by Phi";)
 632           }
 633           DEBUG_ONLY(disq_node = use;)
 634         } else {
 635           if (use->Opcode() == Op_Return) {
 636             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 637           }else {
 638             NOT_PRODUCT(fail_eliminate = "Object is referenced by node";)
 639           }
 640           DEBUG_ONLY(disq_node = use;)
 641         }
 642         can_eliminate = false;
 643       }
 644     }
 645   }
 646 
 647 #ifndef PRODUCT
 648   if (PrintEliminateAllocations) {
 649     if (can_eliminate) {
 650       tty->print("Scalar ");
 651       if (res == nullptr)
 652         alloc->dump();
 653       else
 654         res->dump();
 655     } else if (alloc->_is_scalar_replaceable) {
 656       tty->print("NotScalar (%s)", fail_eliminate);
 657       if (res == nullptr)
 658         alloc->dump();
 659       else
 660         res->dump();
 661 #ifdef ASSERT
 662       if (disq_node != nullptr) {
 663           tty->print("  >>>> ");
 664           disq_node->dump();
 665       }
 666 #endif /*ASSERT*/
 667     }
 668   }
 669 #endif
 670   return can_eliminate;
 671 }
 672 
 673 // Do scalar replacement.
 674 bool PhaseMacroExpand::scalar_replacement(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
 675   GrowableArray <SafePointNode *> safepoints_done;
 676 
 677   ciKlass* klass = NULL;
 678   ciInstanceKlass* iklass = nullptr;
 679   int nfields = 0;
 680   int array_base = 0;
 681   int element_size = 0;
 682   BasicType basic_elem_type = T_ILLEGAL;
 683   ciType* elem_type = nullptr;
 684 
 685   Node* res = alloc->result_cast();
 686   assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");
 687   const TypeOopPtr* res_type = nullptr;
 688   if (res != nullptr) { // Could be null when there are no users
 689     res_type = _igvn.type(res)->isa_oopptr();
 690   }
 691 
 692   if (res != nullptr) {
 693     klass = res_type->klass();
 694     if (res_type->isa_instptr()) {
 695       // find the fields of the class which will be needed for safepoint debug information
 696       assert(klass->is_instance_klass(), "must be an instance klass.");
 697       iklass = klass->as_instance_klass();
 698       nfields = iklass->nof_nonstatic_fields();
 699     } else {
 700       // find the array's elements which will be needed for safepoint debug information
 701       nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 702       assert(klass->is_array_klass() && nfields >= 0, "must be an array klass.");
 703       elem_type = klass->as_array_klass()->element_type();
 704       basic_elem_type = elem_type->basic_type();
 705       array_base = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
 706       element_size = type2aelembytes(basic_elem_type);
 707     }
 708   }
 709   //
 710   // Process the safepoint uses
 711   //
 712   while (safepoints.length() > 0) {
 713     SafePointNode* sfpt = safepoints.pop();
 714     Node* mem = sfpt->memory();
 715     Node* ctl = sfpt->control();
 716     assert(sfpt->jvms() != nullptr, "missed JVMS");
 717     // Fields of scalar objs are referenced only at the end
 718     // of regular debuginfo at the last (youngest) JVMS.
 719     // Record relative start index.
 720     uint first_ind = (sfpt->req() - sfpt->jvms()->scloff());
 721     SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(res_type,
 722 #ifdef ASSERT
 723                                                  alloc,
 724 #endif
 725                                                  first_ind, nfields);
 726     sobj->init_req(0, C->root());
 727     transform_later(sobj);
 728 
 729     // Scan object's fields adding an input to the safepoint for each field.
 730     for (int j = 0; j < nfields; j++) {
 731       intptr_t offset;
 732       ciField* field = nullptr;
 733       if (iklass != nullptr) {
 734         field = iklass->nonstatic_field_at(j);
 735         offset = field->offset();
 736         elem_type = field->type();
 737         basic_elem_type = field->layout_type();
 738       } else {
 739         offset = array_base + j * (intptr_t)element_size;
 740       }
 741 
 742       const Type *field_type;
 743       // The next code is taken from Parse::do_get_xxx().
 744       if (is_reference_type(basic_elem_type)) {
 745         if (!elem_type->is_loaded()) {
 746           field_type = TypeInstPtr::BOTTOM;
 747         } else if (field != nullptr && field->is_static_constant()) {
 748           // This can happen if the constant oop is non-perm.
 749           ciObject* con = field->constant_value().as_object();
 750           // Do not "join" in the previous type; it doesn't add value,
 751           // and may yield a vacuous result if the field is of interface type.
 752           field_type = TypeOopPtr::make_from_constant(con)->isa_oopptr();
 753           assert(field_type != nullptr, "field singleton type must be consistent");
 754         } else {
 755           field_type = TypeOopPtr::make_from_klass(elem_type->as_klass());
 756         }
 757         if (UseCompressedOops) {
 758           field_type = field_type->make_narrowoop();
 759           basic_elem_type = T_NARROWOOP;
 760         }
 761       } else {
 762         field_type = Type::get_const_basic_type(basic_elem_type);
 763       }
 764 
 765       const TypeOopPtr *field_addr_type = res_type->add_offset(offset)->isa_oopptr();
 766 
 767       Node *field_val = value_from_mem(mem, ctl, basic_elem_type, field_type, field_addr_type, alloc);
 768       if (field_val == nullptr) {
 769         // We weren't able to find a value for this field,
 770         // give up on eliminating this allocation.
 771 
 772         // Remove any extra entries we added to the safepoint.
 773         uint last = sfpt->req() - 1;
 774         for (int k = 0;  k < j; k++) {
 775           sfpt->del_req(last--);
 776         }
 777         _igvn._worklist.push(sfpt);
 778         // rollback processed safepoints
 779         while (safepoints_done.length() > 0) {
 780           SafePointNode* sfpt_done = safepoints_done.pop();
 781           // remove any extra entries we added to the safepoint
 782           last = sfpt_done->req() - 1;
 783           for (int k = 0;  k < nfields; k++) {
 784             sfpt_done->del_req(last--);
 785           }
 786           JVMState *jvms = sfpt_done->jvms();
 787           jvms->set_endoff(sfpt_done->req());
 788           // Now make a pass over the debug information replacing any references
 789           // to SafePointScalarObjectNode with the allocated object.
 790           int start = jvms->debug_start();
 791           int end   = jvms->debug_end();
 792           for (int i = start; i < end; i++) {
 793             if (sfpt_done->in(i)->is_SafePointScalarObject()) {
 794               SafePointScalarObjectNode* scobj = sfpt_done->in(i)->as_SafePointScalarObject();
 795               if (scobj->first_index(jvms) == sfpt_done->req() &&
 796                   scobj->n_fields() == (uint)nfields) {
 797                 assert(scobj->alloc() == alloc, "sanity");
 798                 sfpt_done->set_req(i, res);
 799               }
 800             }
 801           }
 802           _igvn._worklist.push(sfpt_done);
 803         }
 804 #ifndef PRODUCT
 805         if (PrintEliminateAllocations) {
 806           if (field != nullptr) {
 807             tty->print("=== At SafePoint node %d can't find value of Field: ",
 808                        sfpt->_idx);
 809             field->print();
 810             int field_idx = C->get_alias_index(field_addr_type);
 811             tty->print(" (alias_idx=%d)", field_idx);
 812           } else { // Array's element
 813             tty->print("=== At SafePoint node %d can't find value of array element [%d]",
 814                        sfpt->_idx, j);
 815           }
 816           tty->print(", which prevents elimination of: ");
 817           if (res == nullptr)
 818             alloc->dump();
 819           else
 820             res->dump();
 821         }
 822 #endif
 823         return false;
 824       }
 825       if (UseCompressedOops && field_type->isa_narrowoop()) {
 826         // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation
 827         // to be able scalar replace the allocation.
 828         if (field_val->is_EncodeP()) {
 829           field_val = field_val->in(1);
 830         } else {
 831           field_val = transform_later(new DecodeNNode(field_val, field_val->get_ptr_type()));
 832         }
 833       }
 834       sfpt->add_req(field_val);
 835     }
 836     JVMState *jvms = sfpt->jvms();
 837     jvms->set_endoff(sfpt->req());
 838     // Now make a pass over the debug information replacing any references
 839     // to the allocated object with "sobj"
 840     int start = jvms->debug_start();
 841     int end   = jvms->debug_end();
 842     sfpt->replace_edges_in_range(res, sobj, start, end, &_igvn);
 843     _igvn._worklist.push(sfpt);
 844     safepoints_done.append_if_missing(sfpt); // keep it for rollback
 845   }
 846   return true;
 847 }
 848 
 849 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) {
 850   Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control);
 851   Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory);
 852   if (ctl_proj != nullptr) {
 853     igvn.replace_node(ctl_proj, n->in(0));
 854   }
 855   if (mem_proj != nullptr) {
 856     igvn.replace_node(mem_proj, n->in(TypeFunc::Memory));
 857   }
 858 }
 859 
 860 // Process users of eliminated allocation.
 861 void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc) {
 862   Node* res = alloc->result_cast();
 863   if (res != nullptr) {
 864     for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
 865       Node *use = res->last_out(j);
 866       uint oc1 = res->outcnt();
 867 
 868       if (use->is_AddP()) {
 869         for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
 870           Node *n = use->last_out(k);
 871           uint oc2 = use->outcnt();
 872           if (n->is_Store()) {
 873 #ifdef ASSERT
 874             // Verify that there is no dependent MemBarVolatile nodes,
 875             // they should be removed during IGVN, see MemBarNode::Ideal().
 876             for (DUIterator_Fast pmax, p = n->fast_outs(pmax);
 877                                        p < pmax; p++) {
 878               Node* mb = n->fast_out(p);
 879               assert(mb->is_Initialize() || !mb->is_MemBar() ||
 880                      mb->req() <= MemBarNode::Precedent ||
 881                      mb->in(MemBarNode::Precedent) != n,
 882                      "MemBarVolatile should be eliminated for non-escaping object");
 883             }
 884 #endif
 885             _igvn.replace_node(n, n->in(MemNode::Memory));
 886           } else {
 887             eliminate_gc_barrier(n);
 888           }
 889           k -= (oc2 - use->outcnt());
 890         }
 891         _igvn.remove_dead_node(use);
 892       } else if (use->is_ArrayCopy()) {
 893         // Disconnect ArrayCopy node
 894         ArrayCopyNode* ac = use->as_ArrayCopy();
 895         if (ac->is_clonebasic()) {
 896           Node* membar_after = ac->proj_out(TypeFunc::Control)->unique_ctrl_out();
 897           disconnect_projections(ac, _igvn);
 898           assert(alloc->in(TypeFunc::Memory)->is_Proj() && alloc->in(TypeFunc::Memory)->in(0)->Opcode() == Op_MemBarCPUOrder, "mem barrier expected before allocation");
 899           Node* membar_before = alloc->in(TypeFunc::Memory)->in(0);
 900           disconnect_projections(membar_before->as_MemBar(), _igvn);
 901           if (membar_after->is_MemBar()) {
 902             disconnect_projections(membar_after->as_MemBar(), _igvn);
 903           }
 904         } else {
 905           assert(ac->is_arraycopy_validated() ||
 906                  ac->is_copyof_validated() ||
 907                  ac->is_copyofrange_validated(), "unsupported");
 908           CallProjections callprojs;
 909           ac->extract_projections(&callprojs, true);
 910 
 911           _igvn.replace_node(callprojs.fallthrough_ioproj, ac->in(TypeFunc::I_O));
 912           _igvn.replace_node(callprojs.fallthrough_memproj, ac->in(TypeFunc::Memory));
 913           _igvn.replace_node(callprojs.fallthrough_catchproj, ac->in(TypeFunc::Control));
 914 
 915           // Set control to top. IGVN will remove the remaining projections
 916           ac->set_req(0, top());
 917           ac->replace_edge(res, top(), &_igvn);
 918 
 919           // Disconnect src right away: it can help find new
 920           // opportunities for allocation elimination
 921           Node* src = ac->in(ArrayCopyNode::Src);
 922           ac->replace_edge(src, top(), &_igvn);
 923           // src can be top at this point if src and dest of the
 924           // arraycopy were the same
 925           if (src->outcnt() == 0 && !src->is_top()) {
 926             _igvn.remove_dead_node(src);
 927           }
 928         }
 929         _igvn._worklist.push(ac);
 930       } else {
 931         eliminate_gc_barrier(use);
 932       }
 933       j -= (oc1 - res->outcnt());
 934     }
 935     assert(res->outcnt() == 0, "all uses of allocated objects must be deleted");
 936     _igvn.remove_dead_node(res);
 937   }
 938 
 939   //
 940   // Process other users of allocation's projections
 941   //
 942   if (_callprojs.resproj != nullptr && _callprojs.resproj->outcnt() != 0) {
 943     // First disconnect stores captured by Initialize node.
 944     // If Initialize node is eliminated first in the following code,
 945     // it will kill such stores and DUIterator_Last will assert.
 946     for (DUIterator_Fast jmax, j = _callprojs.resproj->fast_outs(jmax);  j < jmax; j++) {
 947       Node* use = _callprojs.resproj->fast_out(j);
 948       if (use->is_AddP()) {
 949         // raw memory addresses used only by the initialization
 950         _igvn.replace_node(use, C->top());
 951         --j; --jmax;
 952       }
 953     }
 954     for (DUIterator_Last jmin, j = _callprojs.resproj->last_outs(jmin); j >= jmin; ) {
 955       Node* use = _callprojs.resproj->last_out(j);
 956       uint oc1 = _callprojs.resproj->outcnt();
 957       if (use->is_Initialize()) {
 958         // Eliminate Initialize node.
 959         InitializeNode *init = use->as_Initialize();
 960         assert(init->outcnt() <= 2, "only a control and memory projection expected");
 961         Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
 962         if (ctrl_proj != nullptr) {
 963           _igvn.replace_node(ctrl_proj, init->in(TypeFunc::Control));
 964 #ifdef ASSERT
 965           // If the InitializeNode has no memory out, it will die, and tmp will become null
 966           Node* tmp = init->in(TypeFunc::Control);
 967           assert(tmp == nullptr || tmp == _callprojs.fallthrough_catchproj, "allocation control projection");
 968 #endif
 969         }
 970         Node *mem_proj = init->proj_out_or_null(TypeFunc::Memory);
 971         if (mem_proj != nullptr) {
 972           Node *mem = init->in(TypeFunc::Memory);
 973 #ifdef ASSERT
 974           if (mem->is_MergeMem()) {
 975             assert(mem->in(TypeFunc::Memory) == _callprojs.fallthrough_memproj, "allocation memory projection");
 976           } else {
 977             assert(mem == _callprojs.fallthrough_memproj, "allocation memory projection");
 978           }
 979 #endif
 980           _igvn.replace_node(mem_proj, mem);
 981         }
 982       } else  {
 983         assert(false, "only Initialize or AddP expected");
 984       }
 985       j -= (oc1 - _callprojs.resproj->outcnt());
 986     }
 987   }
 988   if (_callprojs.fallthrough_catchproj != nullptr) {
 989     _igvn.replace_node(_callprojs.fallthrough_catchproj, alloc->in(TypeFunc::Control));
 990   }
 991   if (_callprojs.fallthrough_memproj != nullptr) {
 992     _igvn.replace_node(_callprojs.fallthrough_memproj, alloc->in(TypeFunc::Memory));
 993   }
 994   if (_callprojs.catchall_memproj != nullptr) {
 995     _igvn.replace_node(_callprojs.catchall_memproj, C->top());
 996   }
 997   if (_callprojs.fallthrough_ioproj != nullptr) {
 998     _igvn.replace_node(_callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
 999   }
1000   if (_callprojs.catchall_ioproj != nullptr) {
1001     _igvn.replace_node(_callprojs.catchall_ioproj, C->top());
1002   }
1003   if (_callprojs.catchall_catchproj != nullptr) {
1004     _igvn.replace_node(_callprojs.catchall_catchproj, C->top());
1005   }
1006 }
1007 
1008 bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) {
1009   // If reallocation fails during deoptimization we'll pop all
1010   // interpreter frames for this compiled frame and that won't play
1011   // nice with JVMTI popframe.
1012   // We avoid this issue by eager reallocation when the popframe request
1013   // is received.
1014   if (!EliminateAllocations || !alloc->_is_non_escaping) {
1015     return false;
1016   }
1017   Node* klass = alloc->in(AllocateNode::KlassNode);
1018   const TypeKlassPtr* tklass = _igvn.type(klass)->is_klassptr();
1019   Node* res = alloc->result_cast();
1020   // Eliminate boxing allocations which are not used
1021   // regardless scalar replacable status.
1022   bool boxing_alloc = C->eliminate_boxing() &&
1023                       tklass->klass()->is_instance_klass()  &&
1024                       tklass->klass()->as_instance_klass()->is_box_klass();
1025   if (!alloc->_is_scalar_replaceable && (!boxing_alloc || (res != nullptr))) {
1026     return false;
1027   }
1028 
1029   alloc->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1030 
1031   GrowableArray <SafePointNode *> safepoints;
1032   if (!can_eliminate_allocation(alloc, safepoints)) {
1033     return false;
1034   }
1035 
1036   if (!alloc->_is_scalar_replaceable) {
1037     assert(res == nullptr, "sanity");
1038     // We can only eliminate allocation if all debug info references
1039     // are already replaced with SafePointScalarObject because
1040     // we can't search for a fields value without instance_id.
1041     if (safepoints.length() > 0) {
1042       return false;
1043     }
1044   }
1045 
1046   if (!scalar_replacement(alloc, safepoints)) {
1047     return false;
1048   }
1049 
1050   CompileLog* log = C->log();
1051   if (log != nullptr) {
1052     log->head("eliminate_allocation type='%d'",
1053               log->identify(tklass->klass()));
1054     JVMState* p = alloc->jvms();
1055     while (p != nullptr) {
1056       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1057       p = p->caller();
1058     }
1059     log->tail("eliminate_allocation");
1060   }
1061 
1062   process_users_of_allocation(alloc);
1063 
1064 #ifndef PRODUCT
1065   if (PrintEliminateAllocations) {
1066     if (alloc->is_AllocateArray())
1067       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1068     else
1069       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1070   }
1071 #endif
1072 
1073   return true;
1074 }
1075 
1076 bool PhaseMacroExpand::eliminate_boxing_node(CallStaticJavaNode *boxing) {
1077   // EA should remove all uses of non-escaping boxing node.
1078   if (!C->eliminate_boxing() || boxing->proj_out_or_null(TypeFunc::Parms) != nullptr) {
1079     return false;
1080   }
1081 
1082   assert(boxing->result_cast() == nullptr, "unexpected boxing node result");
1083 
1084   boxing->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1085 
1086   const TypeTuple* r = boxing->tf()->range();
1087   assert(r->cnt() > TypeFunc::Parms, "sanity");
1088   const TypeInstPtr* t = r->field_at(TypeFunc::Parms)->isa_instptr();
1089   assert(t != nullptr, "sanity");
1090 
1091   CompileLog* log = C->log();
1092   if (log != nullptr) {
1093     log->head("eliminate_boxing type='%d'",
1094               log->identify(t->klass()));
1095     JVMState* p = boxing->jvms();
1096     while (p != nullptr) {
1097       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1098       p = p->caller();
1099     }
1100     log->tail("eliminate_boxing");
1101   }
1102 
1103   process_users_of_allocation(boxing);
1104 
1105 #ifndef PRODUCT
1106   if (PrintEliminateAllocations) {
1107     tty->print("++++ Eliminated: %d ", boxing->_idx);
1108     boxing->method()->print_short_name(tty);
1109     tty->cr();
1110   }
1111 #endif
1112 
1113   return true;
1114 }
1115 
1116 //---------------------------set_eden_pointers-------------------------
1117 void PhaseMacroExpand::set_eden_pointers(Node* &eden_top_adr, Node* &eden_end_adr) {
1118   if (UseTLAB) {                // Private allocation: load from TLS
1119     Node* thread = transform_later(new ThreadLocalNode());
1120     int tlab_top_offset = in_bytes(JavaThread::tlab_top_offset());
1121     int tlab_end_offset = in_bytes(JavaThread::tlab_end_offset());
1122     eden_top_adr = basic_plus_adr(top()/*not oop*/, thread, tlab_top_offset);
1123     eden_end_adr = basic_plus_adr(top()/*not oop*/, thread, tlab_end_offset);
1124   } else {                      // Shared allocation: load from globals
1125     CollectedHeap* ch = Universe::heap();
1126     address top_adr = (address)ch->top_addr();
1127     address end_adr = (address)ch->end_addr();
1128     eden_top_adr = makecon(TypeRawPtr::make(top_adr));
1129     eden_end_adr = basic_plus_adr(eden_top_adr, end_adr - top_adr);
1130   }
1131 }
1132 
1133 
1134 Node* PhaseMacroExpand::make_load(Node* ctl, Node* mem, Node* base, int offset, const Type* value_type, BasicType bt) {
1135   Node* adr = basic_plus_adr(base, offset);
1136   const TypePtr* adr_type = adr->bottom_type()->is_ptr();
1137   Node* value = LoadNode::make(_igvn, ctl, mem, adr, adr_type, value_type, bt, MemNode::unordered);
1138   transform_later(value);
1139   return value;
1140 }
1141 
1142 
1143 Node* PhaseMacroExpand::make_store(Node* ctl, Node* mem, Node* base, int offset, Node* value, BasicType bt) {
1144   Node* adr = basic_plus_adr(base, offset);
1145   mem = StoreNode::make(_igvn, ctl, mem, adr, nullptr, value, bt, MemNode::unordered);
1146   transform_later(mem);
1147   return mem;
1148 }
1149 
1150 //=============================================================================
1151 //
1152 //                              A L L O C A T I O N
1153 //
1154 // Allocation attempts to be fast in the case of frequent small objects.
1155 // It breaks down like this:
1156 //
1157 // 1) Size in doublewords is computed.  This is a constant for objects and
1158 // variable for most arrays.  Doubleword units are used to avoid size
1159 // overflow of huge doubleword arrays.  We need doublewords in the end for
1160 // rounding.
1161 //
1162 // 2) Size is checked for being 'too large'.  Too-large allocations will go
1163 // the slow path into the VM.  The slow path can throw any required
1164 // exceptions, and does all the special checks for very large arrays.  The
1165 // size test can constant-fold away for objects.  For objects with
1166 // finalizers it constant-folds the otherway: you always go slow with
1167 // finalizers.
1168 //
1169 // 3) If NOT using TLABs, this is the contended loop-back point.
1170 // Load-Locked the heap top.  If using TLABs normal-load the heap top.
1171 //
1172 // 4) Check that heap top + size*8 < max.  If we fail go the slow ` route.
1173 // NOTE: "top+size*8" cannot wrap the 4Gig line!  Here's why: for largish
1174 // "size*8" we always enter the VM, where "largish" is a constant picked small
1175 // enough that there's always space between the eden max and 4Gig (old space is
1176 // there so it's quite large) and large enough that the cost of entering the VM
1177 // is dwarfed by the cost to initialize the space.
1178 //
1179 // 5) If NOT using TLABs, Store-Conditional the adjusted heap top back
1180 // down.  If contended, repeat at step 3.  If using TLABs normal-store
1181 // adjusted heap top back down; there is no contention.
1182 //
1183 // 6) If !ZeroTLAB then Bulk-clear the object/array.  Fill in klass & mark
1184 // fields.
1185 //
1186 // 7) Merge with the slow-path; cast the raw memory pointer to the correct
1187 // oop flavor.
1188 //
1189 //=============================================================================
1190 // FastAllocateSizeLimit value is in DOUBLEWORDS.
1191 // Allocations bigger than this always go the slow route.
1192 // This value must be small enough that allocation attempts that need to
1193 // trigger exceptions go the slow route.  Also, it must be small enough so
1194 // that heap_top + size_in_bytes does not wrap around the 4Gig limit.
1195 //=============================================================================j//
1196 // %%% Here is an old comment from parseHelper.cpp; is it outdated?
1197 // The allocator will coalesce int->oop copies away.  See comment in
1198 // coalesce.cpp about how this works.  It depends critically on the exact
1199 // code shape produced here, so if you are changing this code shape
1200 // make sure the GC info for the heap-top is correct in and around the
1201 // slow-path call.
1202 //
1203 
1204 void PhaseMacroExpand::expand_allocate_common(
1205             AllocateNode* alloc, // allocation node to be expanded
1206             Node* length,  // array length for an array allocation
1207             const TypeFunc* slow_call_type, // Type of slow call
1208             address slow_call_address,  // Address of slow call
1209             Node* valid_length_test // whether length is valid or not
1210     )
1211 {
1212   Node* ctrl = alloc->in(TypeFunc::Control);
1213   Node* mem  = alloc->in(TypeFunc::Memory);
1214   Node* i_o  = alloc->in(TypeFunc::I_O);
1215   Node* size_in_bytes     = alloc->in(AllocateNode::AllocSize);
1216   Node* klass_node        = alloc->in(AllocateNode::KlassNode);
1217   Node* initial_slow_test = alloc->in(AllocateNode::InitialTest);
1218   assert(ctrl != nullptr, "must have control");
1219 
1220   // We need a Region and corresponding Phi's to merge the slow-path and fast-path results.
1221   // they will not be used if "always_slow" is set
1222   enum { slow_result_path = 1, fast_result_path = 2 };
1223   Node *result_region = nullptr;
1224   Node *result_phi_rawmem = nullptr;
1225   Node *result_phi_rawoop = nullptr;
1226   Node *result_phi_i_o = nullptr;
1227 
1228   // The initial slow comparison is a size check, the comparison
1229   // we want to do is a BoolTest::gt
1230   bool expand_fast_path = true;
1231   int tv = _igvn.find_int_con(initial_slow_test, -1);
1232   if (tv >= 0) {
1233     // InitialTest has constant result
1234     //   0 - can fit in TLAB
1235     //   1 - always too big or negative
1236     assert(tv <= 1, "0 or 1 if a constant");
1237     expand_fast_path = (tv == 0);
1238     initial_slow_test = nullptr;
1239   } else {
1240     initial_slow_test = BoolNode::make_predicate(initial_slow_test, &_igvn);
1241   }
1242 
1243   if (C->env()->dtrace_alloc_probes() ||
1244       (!UseTLAB && !Universe::heap()->supports_inline_contig_alloc())) {
1245     // Force slow-path allocation
1246     expand_fast_path = false;
1247     initial_slow_test = nullptr;
1248   }
1249 
1250   bool allocation_has_use = (alloc->result_cast() != nullptr);
1251   if (!allocation_has_use) {
1252     InitializeNode* init = alloc->initialization();
1253     if (init != nullptr) {
1254       init->remove(&_igvn);
1255     }
1256     if (expand_fast_path && (initial_slow_test == nullptr)) {
1257       // Remove allocation node and return.
1258       // Size is a non-negative constant -> no initial check needed -> directly to fast path.
1259       // Also, no usages -> empty fast path -> no fall out to slow path -> nothing left.
1260 #ifndef PRODUCT
1261       if (PrintEliminateAllocations) {
1262         tty->print("NotUsed ");
1263         Node* res = alloc->proj_out_or_null(TypeFunc::Parms);
1264         if (res != nullptr) {
1265           res->dump();
1266         } else {
1267           alloc->dump();
1268         }
1269       }
1270 #endif
1271       yank_alloc_node(alloc);
1272       return;
1273     }
1274   }
1275 
1276   enum { too_big_or_final_path = 1, need_gc_path = 2 };
1277   Node *slow_region = nullptr;
1278   Node *toobig_false = ctrl;
1279 
1280   // generate the initial test if necessary
1281   if (initial_slow_test != nullptr ) {
1282     assert (expand_fast_path, "Only need test if there is a fast path");
1283     slow_region = new RegionNode(3);
1284 
1285     // Now make the initial failure test.  Usually a too-big test but
1286     // might be a TRUE for finalizers or a fancy class check for
1287     // newInstance0.
1288     IfNode *toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1289     transform_later(toobig_iff);
1290     // Plug the failing-too-big test into the slow-path region
1291     Node *toobig_true = new IfTrueNode( toobig_iff );
1292     transform_later(toobig_true);
1293     slow_region    ->init_req( too_big_or_final_path, toobig_true );
1294     toobig_false = new IfFalseNode( toobig_iff );
1295     transform_later(toobig_false);
1296   } else {
1297     // No initial test, just fall into next case
1298     assert(allocation_has_use || !expand_fast_path, "Should already have been handled");
1299     toobig_false = ctrl;
1300     debug_only(slow_region = NodeSentinel);
1301   }
1302 
1303   // If we are here there are several possibilities
1304   // - expand_fast_path is false - then only a slow path is expanded. That's it.
1305   // no_initial_check means a constant allocation.
1306   // - If check always evaluates to false -> expand_fast_path is false (see above)
1307   // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath)
1308   // if !allocation_has_use the fast path is empty
1309   // if !allocation_has_use && no_initial_check
1310   // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all.
1311   //   removed by yank_alloc_node above.
1312 
1313   Node *slow_mem = mem;  // save the current memory state for slow path
1314   // generate the fast allocation code unless we know that the initial test will always go slow
1315   if (expand_fast_path) {
1316     // Fast path modifies only raw memory.
1317     if (mem->is_MergeMem()) {
1318       mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1319     }
1320 
1321     // allocate the Region and Phi nodes for the result
1322     result_region = new RegionNode(3);
1323     result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1324     result_phi_i_o    = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1325 
1326     // Grab regular I/O before optional prefetch may change it.
1327     // Slow-path does no I/O so just set it to the original I/O.
1328     result_phi_i_o->init_req(slow_result_path, i_o);
1329 
1330     // Name successful fast-path variables
1331     Node* fast_oop_ctrl;
1332     Node* fast_oop_rawmem;
1333     if (allocation_has_use) {
1334       Node* needgc_ctrl = nullptr;
1335       result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1336 
1337       intx prefetch_lines = length != nullptr ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1338       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1339       Node* fast_oop = bs->obj_allocate(this, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1340                                         fast_oop_ctrl, fast_oop_rawmem,
1341                                         prefetch_lines);
1342 
1343       if (initial_slow_test != nullptr) {
1344         // This completes all paths into the slow merge point
1345         slow_region->init_req(need_gc_path, needgc_ctrl);
1346         transform_later(slow_region);
1347       } else {
1348         // No initial slow path needed!
1349         // Just fall from the need-GC path straight into the VM call.
1350         slow_region = needgc_ctrl;
1351       }
1352 
1353       InitializeNode* init = alloc->initialization();
1354       fast_oop_rawmem = initialize_object(alloc,
1355                                           fast_oop_ctrl, fast_oop_rawmem, fast_oop,
1356                                           klass_node, length, size_in_bytes);
1357       expand_initialize_membar(alloc, init, fast_oop_ctrl, fast_oop_rawmem);
1358       expand_dtrace_alloc_probe(alloc, fast_oop, fast_oop_ctrl, fast_oop_rawmem);
1359 
1360       result_phi_rawoop->init_req(fast_result_path, fast_oop);
1361     } else {
1362       assert (initial_slow_test != nullptr, "sanity");
1363       fast_oop_ctrl   = toobig_false;
1364       fast_oop_rawmem = mem;
1365       transform_later(slow_region);
1366     }
1367 
1368     // Plug in the successful fast-path into the result merge point
1369     result_region    ->init_req(fast_result_path, fast_oop_ctrl);
1370     result_phi_i_o   ->init_req(fast_result_path, i_o);
1371     result_phi_rawmem->init_req(fast_result_path, fast_oop_rawmem);
1372   } else {
1373     slow_region = ctrl;
1374     result_phi_i_o = i_o; // Rename it to use in the following code.
1375   }
1376 
1377   // Generate slow-path call
1378   CallNode *call = new CallStaticJavaNode(slow_call_type, slow_call_address,
1379                                OptoRuntime::stub_name(slow_call_address),
1380                                TypePtr::BOTTOM);
1381   call->init_req(TypeFunc::Control,   slow_region);
1382   call->init_req(TypeFunc::I_O,       top());    // does no i/o
1383   call->init_req(TypeFunc::Memory,    slow_mem); // may gc ptrs
1384   call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1385   call->init_req(TypeFunc::FramePtr,  alloc->in(TypeFunc::FramePtr));
1386 
1387   call->init_req(TypeFunc::Parms+0, klass_node);
1388   if (length != nullptr) {
1389     call->init_req(TypeFunc::Parms+1, length);
1390   }
1391 
1392   // Copy debug information and adjust JVMState information, then replace
1393   // allocate node with the call
1394   call->copy_call_debug_info(&_igvn, alloc);
1395   // For array allocations, copy the valid length check to the call node so Compile::final_graph_reshaping() can verify
1396   // that the call has the expected number of CatchProj nodes (in case the allocation always fails and the fallthrough
1397   // path dies).
1398   if (valid_length_test != nullptr) {
1399     call->add_req(valid_length_test);
1400   }
1401   if (expand_fast_path) {
1402     call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
1403   } else {
1404     // Hook i_o projection to avoid its elimination during allocation
1405     // replacement (when only a slow call is generated).
1406     call->set_req(TypeFunc::I_O, result_phi_i_o);
1407   }
1408   _igvn.replace_node(alloc, call);
1409   transform_later(call);
1410 
1411   // Identify the output projections from the allocate node and
1412   // adjust any references to them.
1413   // The control and io projections look like:
1414   //
1415   //        v---Proj(ctrl) <-----+   v---CatchProj(ctrl)
1416   //  Allocate                   Catch
1417   //        ^---Proj(io) <-------+   ^---CatchProj(io)
1418   //
1419   //  We are interested in the CatchProj nodes.
1420   //
1421   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1422 
1423   // An allocate node has separate memory projections for the uses on
1424   // the control and i_o paths. Replace the control memory projection with
1425   // result_phi_rawmem (unless we are only generating a slow call when
1426   // both memory projections are combined)
1427   if (expand_fast_path && _callprojs.fallthrough_memproj != nullptr) {
1428     migrate_outs(_callprojs.fallthrough_memproj, result_phi_rawmem);
1429   }
1430   // Now change uses of catchall_memproj to use fallthrough_memproj and delete
1431   // catchall_memproj so we end up with a call that has only 1 memory projection.
1432   if (_callprojs.catchall_memproj != nullptr ) {
1433     if (_callprojs.fallthrough_memproj == nullptr) {
1434       _callprojs.fallthrough_memproj = new ProjNode(call, TypeFunc::Memory);
1435       transform_later(_callprojs.fallthrough_memproj);
1436     }
1437     migrate_outs(_callprojs.catchall_memproj, _callprojs.fallthrough_memproj);
1438     _igvn.remove_dead_node(_callprojs.catchall_memproj);
1439   }
1440 
1441   // An allocate node has separate i_o projections for the uses on the control
1442   // and i_o paths. Always replace the control i_o projection with result i_o
1443   // otherwise incoming i_o become dead when only a slow call is generated
1444   // (it is different from memory projections where both projections are
1445   // combined in such case).
1446   if (_callprojs.fallthrough_ioproj != nullptr) {
1447     migrate_outs(_callprojs.fallthrough_ioproj, result_phi_i_o);
1448   }
1449   // Now change uses of catchall_ioproj to use fallthrough_ioproj and delete
1450   // catchall_ioproj so we end up with a call that has only 1 i_o projection.
1451   if (_callprojs.catchall_ioproj != nullptr ) {
1452     if (_callprojs.fallthrough_ioproj == nullptr) {
1453       _callprojs.fallthrough_ioproj = new ProjNode(call, TypeFunc::I_O);
1454       transform_later(_callprojs.fallthrough_ioproj);
1455     }
1456     migrate_outs(_callprojs.catchall_ioproj, _callprojs.fallthrough_ioproj);
1457     _igvn.remove_dead_node(_callprojs.catchall_ioproj);
1458   }
1459 
1460   // if we generated only a slow call, we are done
1461   if (!expand_fast_path) {
1462     // Now we can unhook i_o.
1463     if (result_phi_i_o->outcnt() > 1) {
1464       call->set_req(TypeFunc::I_O, top());
1465     } else {
1466       assert(result_phi_i_o->unique_ctrl_out() == call, "sanity");
1467       // Case of new array with negative size known during compilation.
1468       // AllocateArrayNode::Ideal() optimization disconnect unreachable
1469       // following code since call to runtime will throw exception.
1470       // As result there will be no users of i_o after the call.
1471       // Leave i_o attached to this call to avoid problems in preceding graph.
1472     }
1473     return;
1474   }
1475 
1476   if (_callprojs.fallthrough_catchproj != nullptr) {
1477     ctrl = _callprojs.fallthrough_catchproj->clone();
1478     transform_later(ctrl);
1479     _igvn.replace_node(_callprojs.fallthrough_catchproj, result_region);
1480   } else {
1481     ctrl = top();
1482   }
1483   Node *slow_result;
1484   if (_callprojs.resproj == nullptr) {
1485     // no uses of the allocation result
1486     slow_result = top();
1487   } else {
1488     slow_result = _callprojs.resproj->clone();
1489     transform_later(slow_result);
1490     _igvn.replace_node(_callprojs.resproj, result_phi_rawoop);
1491   }
1492 
1493   // Plug slow-path into result merge point
1494   result_region->init_req( slow_result_path, ctrl);
1495   transform_later(result_region);
1496   if (allocation_has_use) {
1497     result_phi_rawoop->init_req(slow_result_path, slow_result);
1498     transform_later(result_phi_rawoop);
1499   }
1500   result_phi_rawmem->init_req(slow_result_path, _callprojs.fallthrough_memproj);
1501   transform_later(result_phi_rawmem);
1502   transform_later(result_phi_i_o);
1503   // This completes all paths into the result merge point
1504 }
1505 
1506 // Remove alloc node that has no uses.
1507 void PhaseMacroExpand::yank_alloc_node(AllocateNode* alloc) {
1508   Node* ctrl = alloc->in(TypeFunc::Control);
1509   Node* mem  = alloc->in(TypeFunc::Memory);
1510   Node* i_o  = alloc->in(TypeFunc::I_O);
1511 
1512   alloc->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1513   if (_callprojs.resproj != nullptr) {
1514     for (DUIterator_Fast imax, i = _callprojs.resproj->fast_outs(imax); i < imax; i++) {
1515       Node* use = _callprojs.resproj->fast_out(i);
1516       use->isa_MemBar()->remove(&_igvn);
1517       --imax;
1518       --i; // back up iterator
1519     }
1520     assert(_callprojs.resproj->outcnt() == 0, "all uses must be deleted");
1521     _igvn.remove_dead_node(_callprojs.resproj);
1522   }
1523   if (_callprojs.fallthrough_catchproj != nullptr) {
1524     migrate_outs(_callprojs.fallthrough_catchproj, ctrl);
1525     _igvn.remove_dead_node(_callprojs.fallthrough_catchproj);
1526   }
1527   if (_callprojs.catchall_catchproj != nullptr) {
1528     _igvn.rehash_node_delayed(_callprojs.catchall_catchproj);
1529     _callprojs.catchall_catchproj->set_req(0, top());
1530   }
1531   if (_callprojs.fallthrough_proj != nullptr) {
1532     Node* catchnode = _callprojs.fallthrough_proj->unique_ctrl_out();
1533     _igvn.remove_dead_node(catchnode);
1534     _igvn.remove_dead_node(_callprojs.fallthrough_proj);
1535   }
1536   if (_callprojs.fallthrough_memproj != nullptr) {
1537     migrate_outs(_callprojs.fallthrough_memproj, mem);
1538     _igvn.remove_dead_node(_callprojs.fallthrough_memproj);
1539   }
1540   if (_callprojs.fallthrough_ioproj != nullptr) {
1541     migrate_outs(_callprojs.fallthrough_ioproj, i_o);
1542     _igvn.remove_dead_node(_callprojs.fallthrough_ioproj);
1543   }
1544   if (_callprojs.catchall_memproj != nullptr) {
1545     _igvn.rehash_node_delayed(_callprojs.catchall_memproj);
1546     _callprojs.catchall_memproj->set_req(0, top());
1547   }
1548   if (_callprojs.catchall_ioproj != nullptr) {
1549     _igvn.rehash_node_delayed(_callprojs.catchall_ioproj);
1550     _callprojs.catchall_ioproj->set_req(0, top());
1551   }
1552 #ifndef PRODUCT
1553   if (PrintEliminateAllocations) {
1554     if (alloc->is_AllocateArray()) {
1555       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1556     } else {
1557       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1558     }
1559   }
1560 #endif
1561   _igvn.remove_dead_node(alloc);
1562 }
1563 
1564 void PhaseMacroExpand::expand_initialize_membar(AllocateNode* alloc, InitializeNode* init,
1565                                                 Node*& fast_oop_ctrl, Node*& fast_oop_rawmem) {
1566   // If initialization is performed by an array copy, any required
1567   // MemBarStoreStore was already added. If the object does not
1568   // escape no need for a MemBarStoreStore. If the object does not
1569   // escape in its initializer and memory barrier (MemBarStoreStore or
1570   // stronger) is already added at exit of initializer, also no need
1571   // for a MemBarStoreStore. Otherwise we need a MemBarStoreStore
1572   // so that stores that initialize this object can't be reordered
1573   // with a subsequent store that makes this object accessible by
1574   // other threads.
1575   // Other threads include java threads and JVM internal threads
1576   // (for example concurrent GC threads). Current concurrent GC
1577   // implementation: G1 will not scan newly created object,
1578   // so it's safe to skip storestore barrier when allocation does
1579   // not escape.
1580   if (!alloc->does_not_escape_thread() &&
1581     !alloc->is_allocation_MemBar_redundant() &&
1582     (init == nullptr || !init->is_complete_with_arraycopy())) {
1583     if (init == nullptr || init->req() < InitializeNode::RawStores) {
1584       // No InitializeNode or no stores captured by zeroing
1585       // elimination. Simply add the MemBarStoreStore after object
1586       // initialization.
1587       MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
1588       transform_later(mb);
1589 
1590       mb->init_req(TypeFunc::Memory, fast_oop_rawmem);
1591       mb->init_req(TypeFunc::Control, fast_oop_ctrl);
1592       fast_oop_ctrl = new ProjNode(mb, TypeFunc::Control);
1593       transform_later(fast_oop_ctrl);
1594       fast_oop_rawmem = new ProjNode(mb, TypeFunc::Memory);
1595       transform_later(fast_oop_rawmem);
1596     } else {
1597       // Add the MemBarStoreStore after the InitializeNode so that
1598       // all stores performing the initialization that were moved
1599       // before the InitializeNode happen before the storestore
1600       // barrier.
1601 
1602       Node* init_ctrl = init->proj_out_or_null(TypeFunc::Control);
1603       Node* init_mem = init->proj_out_or_null(TypeFunc::Memory);
1604 
1605       MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
1606       transform_later(mb);
1607 
1608       Node* ctrl = new ProjNode(init, TypeFunc::Control);
1609       transform_later(ctrl);
1610       Node* mem = new ProjNode(init, TypeFunc::Memory);
1611       transform_later(mem);
1612 
1613       // The MemBarStoreStore depends on control and memory coming
1614       // from the InitializeNode
1615       mb->init_req(TypeFunc::Memory, mem);
1616       mb->init_req(TypeFunc::Control, ctrl);
1617 
1618       ctrl = new ProjNode(mb, TypeFunc::Control);
1619       transform_later(ctrl);
1620       mem = new ProjNode(mb, TypeFunc::Memory);
1621       transform_later(mem);
1622 
1623       // All nodes that depended on the InitializeNode for control
1624       // and memory must now depend on the MemBarNode that itself
1625       // depends on the InitializeNode
1626       if (init_ctrl != nullptr) {
1627         _igvn.replace_node(init_ctrl, ctrl);
1628       }
1629       if (init_mem != nullptr) {
1630         _igvn.replace_node(init_mem, mem);
1631       }
1632     }
1633   }
1634 }
1635 
1636 void PhaseMacroExpand::expand_dtrace_alloc_probe(AllocateNode* alloc, Node* oop,
1637                                                 Node*& ctrl, Node*& rawmem) {
1638   if (C->env()->dtrace_extended_probes()) {
1639     // Slow-path call
1640     int size = TypeFunc::Parms + 2;
1641     CallLeafNode *call = new CallLeafNode(OptoRuntime::dtrace_object_alloc_Type(),
1642                                           CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_object_alloc_base),
1643                                           "dtrace_object_alloc",
1644                                           TypeRawPtr::BOTTOM);
1645 
1646     // Get base of thread-local storage area
1647     Node* thread = new ThreadLocalNode();
1648     transform_later(thread);
1649 
1650     call->init_req(TypeFunc::Parms + 0, thread);
1651     call->init_req(TypeFunc::Parms + 1, oop);
1652     call->init_req(TypeFunc::Control, ctrl);
1653     call->init_req(TypeFunc::I_O    , top()); // does no i/o
1654     call->init_req(TypeFunc::Memory , ctrl);
1655     call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1656     call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1657     transform_later(call);
1658     ctrl = new ProjNode(call, TypeFunc::Control);
1659     transform_later(ctrl);
1660     rawmem = new ProjNode(call, TypeFunc::Memory);
1661     transform_later(rawmem);
1662   }
1663 }
1664 
1665 // Helper for PhaseMacroExpand::expand_allocate_common.
1666 // Initializes the newly-allocated storage.
1667 Node*
1668 PhaseMacroExpand::initialize_object(AllocateNode* alloc,
1669                                     Node* control, Node* rawmem, Node* object,
1670                                     Node* klass_node, Node* length,
1671                                     Node* size_in_bytes) {
1672   InitializeNode* init = alloc->initialization();
1673   // Store the klass & mark bits
1674   Node* mark_node = alloc->make_ideal_mark(&_igvn, object, control, rawmem);
1675   if (!mark_node->is_Con()) {
1676     transform_later(mark_node);
1677   }
1678   rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
1679 
1680   if (!UseCompactObjectHeaders) {
1681     rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
1682   }
1683 
1684   int header_size = alloc->minimum_header_size();  // conservatively small
1685 
1686   // Array length
1687   if (length != nullptr) {         // Arrays need length field
1688     rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1689     // conservatively small header size:
1690     header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1691     ciKlass* k = _igvn.type(klass_node)->is_klassptr()->klass();
1692     if (k->is_array_klass())    // we know the exact header size in most cases:
1693       header_size = Klass::layout_helper_header_size(k->layout_helper());
1694   }
1695 
1696   // Clear the object body, if necessary.
1697   if (init == nullptr) {
1698     // The init has somehow disappeared; be cautious and clear everything.
1699     //
1700     // This can happen if a node is allocated but an uncommon trap occurs
1701     // immediately.  In this case, the Initialize gets associated with the
1702     // trap, and may be placed in a different (outer) loop, if the Allocate
1703     // is in a loop.  If (this is rare) the inner loop gets unrolled, then
1704     // there can be two Allocates to one Initialize.  The answer in all these
1705     // edge cases is safety first.  It is always safe to clear immediately
1706     // within an Allocate, and then (maybe or maybe not) clear some more later.
1707     if (!(UseTLAB && ZeroTLAB)) {
1708       rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
1709                                             header_size, size_in_bytes,
1710                                             &_igvn);
1711     }
1712   } else {
1713     if (!init->is_complete()) {
1714       // Try to win by zeroing only what the init does not store.
1715       // We can also try to do some peephole optimizations,
1716       // such as combining some adjacent subword stores.
1717       rawmem = init->complete_stores(control, rawmem, object,
1718                                      header_size, size_in_bytes, &_igvn);
1719     }
1720     // We have no more use for this link, since the AllocateNode goes away:
1721     init->set_req(InitializeNode::RawAddress, top());
1722     // (If we keep the link, it just confuses the register allocator,
1723     // who thinks he sees a real use of the address by the membar.)
1724   }
1725 
1726   return rawmem;
1727 }
1728 
1729 // Generate prefetch instructions for next allocations.
1730 Node* PhaseMacroExpand::prefetch_allocation(Node* i_o, Node*& needgc_false,
1731                                         Node*& contended_phi_rawmem,
1732                                         Node* old_eden_top, Node* new_eden_top,
1733                                         intx lines) {
1734    enum { fall_in_path = 1, pf_path = 2 };
1735    if( UseTLAB && AllocatePrefetchStyle == 2 ) {
1736       // Generate prefetch allocation with watermark check.
1737       // As an allocation hits the watermark, we will prefetch starting
1738       // at a "distance" away from watermark.
1739 
1740       Node *pf_region = new RegionNode(3);
1741       Node *pf_phi_rawmem = new PhiNode( pf_region, Type::MEMORY,
1742                                                 TypeRawPtr::BOTTOM );
1743       // I/O is used for Prefetch
1744       Node *pf_phi_abio = new PhiNode( pf_region, Type::ABIO );
1745 
1746       Node *thread = new ThreadLocalNode();
1747       transform_later(thread);
1748 
1749       Node *eden_pf_adr = new AddPNode( top()/*not oop*/, thread,
1750                    _igvn.MakeConX(in_bytes(JavaThread::tlab_pf_top_offset())) );
1751       transform_later(eden_pf_adr);
1752 
1753       Node *old_pf_wm = new LoadPNode(needgc_false,
1754                                    contended_phi_rawmem, eden_pf_adr,
1755                                    TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM,
1756                                    MemNode::unordered);
1757       transform_later(old_pf_wm);
1758 
1759       // check against new_eden_top
1760       Node *need_pf_cmp = new CmpPNode( new_eden_top, old_pf_wm );
1761       transform_later(need_pf_cmp);
1762       Node *need_pf_bol = new BoolNode( need_pf_cmp, BoolTest::ge );
1763       transform_later(need_pf_bol);
1764       IfNode *need_pf_iff = new IfNode( needgc_false, need_pf_bol,
1765                                        PROB_UNLIKELY_MAG(4), COUNT_UNKNOWN );
1766       transform_later(need_pf_iff);
1767 
1768       // true node, add prefetchdistance
1769       Node *need_pf_true = new IfTrueNode( need_pf_iff );
1770       transform_later(need_pf_true);
1771 
1772       Node *need_pf_false = new IfFalseNode( need_pf_iff );
1773       transform_later(need_pf_false);
1774 
1775       Node *new_pf_wmt = new AddPNode( top(), old_pf_wm,
1776                                     _igvn.MakeConX(AllocatePrefetchDistance) );
1777       transform_later(new_pf_wmt );
1778       new_pf_wmt->set_req(0, need_pf_true);
1779 
1780       Node *store_new_wmt = new StorePNode(need_pf_true,
1781                                        contended_phi_rawmem, eden_pf_adr,
1782                                        TypeRawPtr::BOTTOM, new_pf_wmt,
1783                                        MemNode::unordered);
1784       transform_later(store_new_wmt);
1785 
1786       // adding prefetches
1787       pf_phi_abio->init_req( fall_in_path, i_o );
1788 
1789       Node *prefetch_adr;
1790       Node *prefetch;
1791       uint step_size = AllocatePrefetchStepSize;
1792       uint distance = 0;
1793 
1794       for ( intx i = 0; i < lines; i++ ) {
1795         prefetch_adr = new AddPNode( old_pf_wm, new_pf_wmt,
1796                                             _igvn.MakeConX(distance) );
1797         transform_later(prefetch_adr);
1798         prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
1799         transform_later(prefetch);
1800         distance += step_size;
1801         i_o = prefetch;
1802       }
1803       pf_phi_abio->set_req( pf_path, i_o );
1804 
1805       pf_region->init_req( fall_in_path, need_pf_false );
1806       pf_region->init_req( pf_path, need_pf_true );
1807 
1808       pf_phi_rawmem->init_req( fall_in_path, contended_phi_rawmem );
1809       pf_phi_rawmem->init_req( pf_path, store_new_wmt );
1810 
1811       transform_later(pf_region);
1812       transform_later(pf_phi_rawmem);
1813       transform_later(pf_phi_abio);
1814 
1815       needgc_false = pf_region;
1816       contended_phi_rawmem = pf_phi_rawmem;
1817       i_o = pf_phi_abio;
1818    } else if( UseTLAB && AllocatePrefetchStyle == 3 ) {
1819       // Insert a prefetch instruction for each allocation.
1820       // This code is used to generate 1 prefetch instruction per cache line.
1821 
1822       // Generate several prefetch instructions.
1823       uint step_size = AllocatePrefetchStepSize;
1824       uint distance = AllocatePrefetchDistance;
1825 
1826       // Next cache address.
1827       Node *cache_adr = new AddPNode(old_eden_top, old_eden_top,
1828                                      _igvn.MakeConX(step_size + distance));
1829       transform_later(cache_adr);
1830       cache_adr = new CastP2XNode(needgc_false, cache_adr);
1831       transform_later(cache_adr);
1832       // Address is aligned to execute prefetch to the beginning of cache line size
1833       // (it is important when BIS instruction is used on SPARC as prefetch).
1834       Node* mask = _igvn.MakeConX(~(intptr_t)(step_size-1));
1835       cache_adr = new AndXNode(cache_adr, mask);
1836       transform_later(cache_adr);
1837       cache_adr = new CastX2PNode(cache_adr);
1838       transform_later(cache_adr);
1839 
1840       // Prefetch
1841       Node *prefetch = new PrefetchAllocationNode( contended_phi_rawmem, cache_adr );
1842       prefetch->set_req(0, needgc_false);
1843       transform_later(prefetch);
1844       contended_phi_rawmem = prefetch;
1845       Node *prefetch_adr;
1846       distance = step_size;
1847       for ( intx i = 1; i < lines; i++ ) {
1848         prefetch_adr = new AddPNode( cache_adr, cache_adr,
1849                                             _igvn.MakeConX(distance) );
1850         transform_later(prefetch_adr);
1851         prefetch = new PrefetchAllocationNode( contended_phi_rawmem, prefetch_adr );
1852         transform_later(prefetch);
1853         distance += step_size;
1854         contended_phi_rawmem = prefetch;
1855       }
1856    } else if( AllocatePrefetchStyle > 0 ) {
1857       // Insert a prefetch for each allocation only on the fast-path
1858       Node *prefetch_adr;
1859       Node *prefetch;
1860       // Generate several prefetch instructions.
1861       uint step_size = AllocatePrefetchStepSize;
1862       uint distance = AllocatePrefetchDistance;
1863       for ( intx i = 0; i < lines; i++ ) {
1864         prefetch_adr = new AddPNode( old_eden_top, new_eden_top,
1865                                             _igvn.MakeConX(distance) );
1866         transform_later(prefetch_adr);
1867         prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
1868         // Do not let it float too high, since if eden_top == eden_end,
1869         // both might be null.
1870         if( i == 0 ) { // Set control for first prefetch, next follows it
1871           prefetch->init_req(0, needgc_false);
1872         }
1873         transform_later(prefetch);
1874         distance += step_size;
1875         i_o = prefetch;
1876       }
1877    }
1878    return i_o;
1879 }
1880 
1881 
1882 void PhaseMacroExpand::expand_allocate(AllocateNode *alloc) {
1883   expand_allocate_common(alloc, nullptr,
1884                          OptoRuntime::new_instance_Type(),
1885                          OptoRuntime::new_instance_Java(), nullptr);
1886 }
1887 
1888 void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) {
1889   Node* length = alloc->in(AllocateNode::ALength);
1890   Node* valid_length_test = alloc->in(AllocateNode::ValidLengthTest);
1891   InitializeNode* init = alloc->initialization();
1892   Node* klass_node = alloc->in(AllocateNode::KlassNode);
1893   ciKlass* k = _igvn.type(klass_node)->is_klassptr()->klass();
1894   address slow_call_address;  // Address of slow call
1895   if (init != nullptr && init->is_complete_with_arraycopy() &&
1896       k->is_type_array_klass()) {
1897     // Don't zero type array during slow allocation in VM since
1898     // it will be initialized later by arraycopy in compiled code.
1899     slow_call_address = OptoRuntime::new_array_nozero_Java();
1900   } else {
1901     slow_call_address = OptoRuntime::new_array_Java();
1902   }
1903   expand_allocate_common(alloc, length,
1904                          OptoRuntime::new_array_Type(),
1905                          slow_call_address, valid_length_test);
1906 }
1907 
1908 //-------------------mark_eliminated_box----------------------------------
1909 //
1910 // During EA obj may point to several objects but after few ideal graph
1911 // transformations (CCP) it may point to only one non escaping object
1912 // (but still using phi), corresponding locks and unlocks will be marked
1913 // for elimination. Later obj could be replaced with a new node (new phi)
1914 // and which does not have escape information. And later after some graph
1915 // reshape other locks and unlocks (which were not marked for elimination
1916 // before) are connected to this new obj (phi) but they still will not be
1917 // marked for elimination since new obj has no escape information.
1918 // Mark all associated (same box and obj) lock and unlock nodes for
1919 // elimination if some of them marked already.
1920 void PhaseMacroExpand::mark_eliminated_box(Node* oldbox, Node* obj) {
1921   if (oldbox->as_BoxLock()->is_eliminated()) {
1922     return; // This BoxLock node was processed already.
1923   }
1924   // New implementation (EliminateNestedLocks) has separate BoxLock
1925   // node for each locked region so mark all associated locks/unlocks as
1926   // eliminated even if different objects are referenced in one locked region
1927   // (for example, OSR compilation of nested loop inside locked scope).
1928   if (EliminateNestedLocks ||
1929       oldbox->as_BoxLock()->is_simple_lock_region(nullptr, obj, nullptr)) {
1930     // Box is used only in one lock region. Mark this box as eliminated.
1931     _igvn.hash_delete(oldbox);
1932     oldbox->as_BoxLock()->set_eliminated(); // This changes box's hash value
1933      _igvn.hash_insert(oldbox);
1934 
1935     for (uint i = 0; i < oldbox->outcnt(); i++) {
1936       Node* u = oldbox->raw_out(i);
1937       if (u->is_AbstractLock() && !u->as_AbstractLock()->is_non_esc_obj()) {
1938         AbstractLockNode* alock = u->as_AbstractLock();
1939         // Check lock's box since box could be referenced by Lock's debug info.
1940         if (alock->box_node() == oldbox) {
1941           // Mark eliminated all related locks and unlocks.
1942 #ifdef ASSERT
1943           alock->log_lock_optimization(C, "eliminate_lock_set_non_esc4");
1944 #endif
1945           alock->set_non_esc_obj();
1946         }
1947       }
1948     }
1949     return;
1950   }
1951 
1952   // Create new "eliminated" BoxLock node and use it in monitor debug info
1953   // instead of oldbox for the same object.
1954   BoxLockNode* newbox = oldbox->clone()->as_BoxLock();
1955 
1956   // Note: BoxLock node is marked eliminated only here and it is used
1957   // to indicate that all associated lock and unlock nodes are marked
1958   // for elimination.
1959   newbox->set_eliminated();
1960   transform_later(newbox);
1961 
1962   // Replace old box node with new box for all users of the same object.
1963   for (uint i = 0; i < oldbox->outcnt();) {
1964     bool next_edge = true;
1965 
1966     Node* u = oldbox->raw_out(i);
1967     if (u->is_AbstractLock()) {
1968       AbstractLockNode* alock = u->as_AbstractLock();
1969       if (alock->box_node() == oldbox && alock->obj_node()->eqv_uncast(obj)) {
1970         // Replace Box and mark eliminated all related locks and unlocks.
1971 #ifdef ASSERT
1972         alock->log_lock_optimization(C, "eliminate_lock_set_non_esc5");
1973 #endif
1974         alock->set_non_esc_obj();
1975         _igvn.rehash_node_delayed(alock);
1976         alock->set_box_node(newbox);
1977         next_edge = false;
1978       }
1979     }
1980     if (u->is_FastLock() && u->as_FastLock()->obj_node()->eqv_uncast(obj)) {
1981       FastLockNode* flock = u->as_FastLock();
1982       assert(flock->box_node() == oldbox, "sanity");
1983       _igvn.rehash_node_delayed(flock);
1984       flock->set_box_node(newbox);
1985       next_edge = false;
1986     }
1987 
1988     // Replace old box in monitor debug info.
1989     if (u->is_SafePoint() && u->as_SafePoint()->jvms()) {
1990       SafePointNode* sfn = u->as_SafePoint();
1991       JVMState* youngest_jvms = sfn->jvms();
1992       int max_depth = youngest_jvms->depth();
1993       for (int depth = 1; depth <= max_depth; depth++) {
1994         JVMState* jvms = youngest_jvms->of_depth(depth);
1995         int num_mon  = jvms->nof_monitors();
1996         // Loop over monitors
1997         for (int idx = 0; idx < num_mon; idx++) {
1998           Node* obj_node = sfn->monitor_obj(jvms, idx);
1999           Node* box_node = sfn->monitor_box(jvms, idx);
2000           if (box_node == oldbox && obj_node->eqv_uncast(obj)) {
2001             int j = jvms->monitor_box_offset(idx);
2002             _igvn.replace_input_of(u, j, newbox);
2003             next_edge = false;
2004           }
2005         }
2006       }
2007     }
2008     if (next_edge) i++;
2009   }
2010 }
2011 
2012 //-----------------------mark_eliminated_locking_nodes-----------------------
2013 void PhaseMacroExpand::mark_eliminated_locking_nodes(AbstractLockNode *alock) {
2014   if (EliminateNestedLocks) {
2015     if (alock->is_nested()) {
2016        assert(alock->box_node()->as_BoxLock()->is_eliminated(), "sanity");
2017        return;
2018     } else if (!alock->is_non_esc_obj()) { // Not eliminated or coarsened
2019       // Only Lock node has JVMState needed here.
2020       // Not that preceding claim is documented anywhere else.
2021       if (alock->jvms() != nullptr) {
2022         if (alock->as_Lock()->is_nested_lock_region()) {
2023           // Mark eliminated related nested locks and unlocks.
2024           Node* obj = alock->obj_node();
2025           BoxLockNode* box_node = alock->box_node()->as_BoxLock();
2026           assert(!box_node->is_eliminated(), "should not be marked yet");
2027           // Note: BoxLock node is marked eliminated only here
2028           // and it is used to indicate that all associated lock
2029           // and unlock nodes are marked for elimination.
2030           box_node->set_eliminated(); // Box's hash is always NO_HASH here
2031           for (uint i = 0; i < box_node->outcnt(); i++) {
2032             Node* u = box_node->raw_out(i);
2033             if (u->is_AbstractLock()) {
2034               alock = u->as_AbstractLock();
2035               if (alock->box_node() == box_node) {
2036                 // Verify that this Box is referenced only by related locks.
2037                 assert(alock->obj_node()->eqv_uncast(obj), "");
2038                 // Mark all related locks and unlocks.
2039 #ifdef ASSERT
2040                 alock->log_lock_optimization(C, "eliminate_lock_set_nested");
2041 #endif
2042                 alock->set_nested();
2043               }
2044             }
2045           }
2046         } else {
2047 #ifdef ASSERT
2048           alock->log_lock_optimization(C, "eliminate_lock_NOT_nested_lock_region");
2049           if (C->log() != nullptr)
2050             alock->as_Lock()->is_nested_lock_region(C); // rerun for debugging output
2051 #endif
2052         }
2053       }
2054       return;
2055     }
2056     // Process locks for non escaping object
2057     assert(alock->is_non_esc_obj(), "");
2058   } // EliminateNestedLocks
2059 
2060   if (alock->is_non_esc_obj()) { // Lock is used for non escaping object
2061     // Look for all locks of this object and mark them and
2062     // corresponding BoxLock nodes as eliminated.
2063     Node* obj = alock->obj_node();
2064     for (uint j = 0; j < obj->outcnt(); j++) {
2065       Node* o = obj->raw_out(j);
2066       if (o->is_AbstractLock() &&
2067           o->as_AbstractLock()->obj_node()->eqv_uncast(obj)) {
2068         alock = o->as_AbstractLock();
2069         Node* box = alock->box_node();
2070         // Replace old box node with new eliminated box for all users
2071         // of the same object and mark related locks as eliminated.
2072         mark_eliminated_box(box, obj);
2073       }
2074     }
2075   }
2076 }
2077 
2078 // we have determined that this lock/unlock can be eliminated, we simply
2079 // eliminate the node without expanding it.
2080 //
2081 // Note:  The membar's associated with the lock/unlock are currently not
2082 //        eliminated.  This should be investigated as a future enhancement.
2083 //
2084 bool PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) {
2085 
2086   if (!alock->is_eliminated()) {
2087     return false;
2088   }
2089 #ifdef ASSERT
2090   if (!alock->is_coarsened()) {
2091     // Check that new "eliminated" BoxLock node is created.
2092     BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2093     assert(oldbox->is_eliminated(), "should be done already");
2094   }
2095 #endif
2096 
2097   alock->log_lock_optimization(C, "eliminate_lock");
2098 
2099 #ifndef PRODUCT
2100   if (PrintEliminateLocks) {
2101     tty->print_cr("++++ Eliminated: %d %s '%s'", alock->_idx, (alock->is_Lock() ? "Lock" : "Unlock"), alock->kind_as_string());
2102   }
2103 #endif
2104 
2105   Node* mem  = alock->in(TypeFunc::Memory);
2106   Node* ctrl = alock->in(TypeFunc::Control);
2107   guarantee(ctrl != nullptr, "missing control projection, cannot replace_node() with null");
2108 
2109   alock->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2110   // There are 2 projections from the lock.  The lock node will
2111   // be deleted when its last use is subsumed below.
2112   assert(alock->outcnt() == 2 &&
2113          _callprojs.fallthrough_proj != nullptr &&
2114          _callprojs.fallthrough_memproj != nullptr,
2115          "Unexpected projections from Lock/Unlock");
2116 
2117   Node* fallthroughproj = _callprojs.fallthrough_proj;
2118   Node* memproj_fallthrough = _callprojs.fallthrough_memproj;
2119 
2120   // The memory projection from a lock/unlock is RawMem
2121   // The input to a Lock is merged memory, so extract its RawMem input
2122   // (unless the MergeMem has been optimized away.)
2123   if (alock->is_Lock()) {
2124     // Seach for MemBarAcquireLock node and delete it also.
2125     MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
2126     assert(membar != nullptr && membar->Opcode() == Op_MemBarAcquireLock, "");
2127     Node* ctrlproj = membar->proj_out(TypeFunc::Control);
2128     Node* memproj = membar->proj_out(TypeFunc::Memory);
2129     _igvn.replace_node(ctrlproj, fallthroughproj);
2130     _igvn.replace_node(memproj, memproj_fallthrough);
2131 
2132     // Delete FastLock node also if this Lock node is unique user
2133     // (a loop peeling may clone a Lock node).
2134     Node* flock = alock->as_Lock()->fastlock_node();
2135     if (flock->outcnt() == 1) {
2136       assert(flock->unique_out() == alock, "sanity");
2137       _igvn.replace_node(flock, top());
2138     }
2139   }
2140 
2141   // Seach for MemBarReleaseLock node and delete it also.
2142   if (alock->is_Unlock() && ctrl->is_Proj() && ctrl->in(0)->is_MemBar()) {
2143     MemBarNode* membar = ctrl->in(0)->as_MemBar();
2144     assert(membar->Opcode() == Op_MemBarReleaseLock &&
2145            mem->is_Proj() && membar == mem->in(0), "");
2146     _igvn.replace_node(fallthroughproj, ctrl);
2147     _igvn.replace_node(memproj_fallthrough, mem);
2148     fallthroughproj = ctrl;
2149     memproj_fallthrough = mem;
2150     ctrl = membar->in(TypeFunc::Control);
2151     mem  = membar->in(TypeFunc::Memory);
2152   }
2153 
2154   _igvn.replace_node(fallthroughproj, ctrl);
2155   _igvn.replace_node(memproj_fallthrough, mem);
2156   return true;
2157 }
2158 
2159 
2160 //------------------------------expand_lock_node----------------------
2161 void PhaseMacroExpand::expand_lock_node(LockNode *lock) {
2162 
2163   Node* ctrl = lock->in(TypeFunc::Control);
2164   Node* mem = lock->in(TypeFunc::Memory);
2165   Node* obj = lock->obj_node();
2166   Node* box = lock->box_node();
2167   Node* flock = lock->fastlock_node();
2168 
2169   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2170 
2171   // Make the merge point
2172   Node *region;
2173   Node *mem_phi;
2174   Node *slow_path;
2175 
2176   if (UseOptoBiasInlining) {
2177     /*
2178      *  See the full description in MacroAssembler::biased_locking_enter().
2179      *
2180      *  if( (mark_word & biased_lock_mask) == biased_lock_pattern ) {
2181      *    // The object is biased.
2182      *    proto_node = klass->prototype_header;
2183      *    o_node = thread | proto_node;
2184      *    x_node = o_node ^ mark_word;
2185      *    if( (x_node & ~age_mask) == 0 ) { // Biased to the current thread ?
2186      *      // Done.
2187      *    } else {
2188      *      if( (x_node & biased_lock_mask) != 0 ) {
2189      *        // The klass's prototype header is no longer biased.
2190      *        cas(&mark_word, mark_word, proto_node)
2191      *        goto cas_lock;
2192      *      } else {
2193      *        // The klass's prototype header is still biased.
2194      *        if( (x_node & epoch_mask) != 0 ) { // Expired epoch?
2195      *          old = mark_word;
2196      *          new = o_node;
2197      *        } else {
2198      *          // Different thread or anonymous biased.
2199      *          old = mark_word & (epoch_mask | age_mask | biased_lock_mask);
2200      *          new = thread | old;
2201      *        }
2202      *        // Try to rebias.
2203      *        if( cas(&mark_word, old, new) == 0 ) {
2204      *          // Done.
2205      *        } else {
2206      *          goto slow_path; // Failed.
2207      *        }
2208      *      }
2209      *    }
2210      *  } else {
2211      *    // The object is not biased.
2212      *    cas_lock:
2213      *    if( FastLock(obj) == 0 ) {
2214      *      // Done.
2215      *    } else {
2216      *      slow_path:
2217      *      OptoRuntime::complete_monitor_locking_Java(obj);
2218      *    }
2219      *  }
2220      */
2221 
2222     region  = new RegionNode(5);
2223     // create a Phi for the memory state
2224     mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2225 
2226     Node* fast_lock_region  = new RegionNode(3);
2227     Node* fast_lock_mem_phi = new PhiNode( fast_lock_region, Type::MEMORY, TypeRawPtr::BOTTOM);
2228 
2229     // First, check mark word for the biased lock pattern.
2230     Node* mark_node = make_load(ctrl, mem, obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
2231 
2232     // Get fast path - mark word has the biased lock pattern.
2233     ctrl = opt_bits_test(ctrl, fast_lock_region, 1, mark_node,
2234                          markWord::biased_lock_mask_in_place,
2235                          markWord::biased_lock_pattern, true);
2236     // fast_lock_region->in(1) is set to slow path.
2237     fast_lock_mem_phi->init_req(1, mem);
2238 
2239     // Now check that the lock is biased to the current thread and has
2240     // the same epoch and bias as Klass::_prototype_header.
2241 
2242     // Special-case a fresh allocation to avoid building nodes:
2243     Node* klass_node = AllocateNode::Ideal_klass(obj, &_igvn);
2244     if (klass_node == NULL) {
2245       Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
2246       klass_node = transform_later(LoadKlassNode::make(_igvn, NULL, mem, k_adr, _igvn.type(k_adr)->is_ptr()));
2247 #ifdef _LP64
2248       if (UseCompressedClassPointers && klass_node->is_DecodeNKlass()) {
2249         assert(klass_node->in(1)->Opcode() == Op_LoadNKlass, "sanity");
2250         klass_node->in(1)->init_req(0, ctrl);
2251       } else
2252 #endif
2253       klass_node->init_req(0, ctrl);
2254     }
2255     Node *proto_node = make_load(ctrl, mem, klass_node, in_bytes(Klass::prototype_header_offset()), TypeX_X, TypeX_X->basic_type());
2256 
2257     Node* thread = transform_later(new ThreadLocalNode());
2258     Node* cast_thread = transform_later(new CastP2XNode(ctrl, thread));
2259     Node* o_node = transform_later(new OrXNode(cast_thread, proto_node));
2260     Node* x_node = transform_later(new XorXNode(o_node, mark_node));
2261 
2262     // Get slow path - mark word does NOT match the value.
2263     STATIC_ASSERT(markWord::age_mask_in_place <= INT_MAX);
2264     Node* not_biased_ctrl =  opt_bits_test(ctrl, region, 3, x_node,
2265                                       (~(int)markWord::age_mask_in_place), 0);
2266     // region->in(3) is set to fast path - the object is biased to the current thread.
2267     mem_phi->init_req(3, mem);
2268 
2269 
2270     // Mark word does NOT match the value (thread | Klass::_prototype_header).
2271 
2272 
2273     // First, check biased pattern.
2274     // Get fast path - _prototype_header has the same biased lock pattern.
2275     ctrl =  opt_bits_test(not_biased_ctrl, fast_lock_region, 2, x_node,
2276                           markWord::biased_lock_mask_in_place, 0, true);
2277 
2278     not_biased_ctrl = fast_lock_region->in(2); // Slow path
2279     // fast_lock_region->in(2) - the prototype header is no longer biased
2280     // and we have to revoke the bias on this object.
2281     // We are going to try to reset the mark of this object to the prototype
2282     // value and fall through to the CAS-based locking scheme.
2283     Node* adr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
2284     Node* cas = new StoreXConditionalNode(not_biased_ctrl, mem, adr,
2285                                           proto_node, mark_node);
2286     transform_later(cas);
2287     Node* proj = transform_later(new SCMemProjNode(cas));
2288     fast_lock_mem_phi->init_req(2, proj);
2289 
2290 
2291     // Second, check epoch bits.
2292     Node* rebiased_region  = new RegionNode(3);
2293     Node* old_phi = new PhiNode( rebiased_region, TypeX_X);
2294     Node* new_phi = new PhiNode( rebiased_region, TypeX_X);
2295 
2296     // Get slow path - mark word does NOT match epoch bits.
2297     Node* epoch_ctrl =  opt_bits_test(ctrl, rebiased_region, 1, x_node,
2298                                       markWord::epoch_mask_in_place, 0);
2299     // The epoch of the current bias is not valid, attempt to rebias the object
2300     // toward the current thread.
2301     rebiased_region->init_req(2, epoch_ctrl);
2302     old_phi->init_req(2, mark_node);
2303     new_phi->init_req(2, o_node);
2304 
2305     // rebiased_region->in(1) is set to fast path.
2306     // The epoch of the current bias is still valid but we know
2307     // nothing about the owner; it might be set or it might be clear.
2308     Node* cmask   = MakeConX(markWord::biased_lock_mask_in_place |
2309                              markWord::age_mask_in_place |
2310                              markWord::epoch_mask_in_place);
2311     Node* old = transform_later(new AndXNode(mark_node, cmask));
2312     cast_thread = transform_later(new CastP2XNode(ctrl, thread));
2313     Node* new_mark = transform_later(new OrXNode(cast_thread, old));
2314     old_phi->init_req(1, old);
2315     new_phi->init_req(1, new_mark);
2316 
2317     transform_later(rebiased_region);
2318     transform_later(old_phi);
2319     transform_later(new_phi);
2320 
2321     // Try to acquire the bias of the object using an atomic operation.
2322     // If this fails we will go in to the runtime to revoke the object's bias.
2323     cas = new StoreXConditionalNode(rebiased_region, mem, adr, new_phi, old_phi);
2324     transform_later(cas);
2325     proj = transform_later(new SCMemProjNode(cas));
2326 
2327     // Get slow path - Failed to CAS.
2328     not_biased_ctrl = opt_bits_test(rebiased_region, region, 4, cas, 0, 0);
2329     mem_phi->init_req(4, proj);
2330     // region->in(4) is set to fast path - the object is rebiased to the current thread.
2331 
2332     // Failed to CAS.
2333     slow_path  = new RegionNode(3);
2334     Node *slow_mem = new PhiNode( slow_path, Type::MEMORY, TypeRawPtr::BOTTOM);
2335 
2336     slow_path->init_req(1, not_biased_ctrl); // Capture slow-control
2337     slow_mem->init_req(1, proj);
2338 
2339     // Call CAS-based locking scheme (FastLock node).
2340 
2341     transform_later(fast_lock_region);
2342     transform_later(fast_lock_mem_phi);
2343 
2344     // Get slow path - FastLock failed to lock the object.
2345     ctrl = opt_bits_test(fast_lock_region, region, 2, flock, 0, 0);
2346     mem_phi->init_req(2, fast_lock_mem_phi);
2347     // region->in(2) is set to fast path - the object is locked to the current thread.
2348 
2349     slow_path->init_req(2, ctrl); // Capture slow-control
2350     slow_mem->init_req(2, fast_lock_mem_phi);
2351 
2352     transform_later(slow_path);
2353     transform_later(slow_mem);
2354     // Reset lock's memory edge.
2355     lock->set_req(TypeFunc::Memory, slow_mem);
2356 
2357   } else {
2358     region  = new RegionNode(3);
2359     // create a Phi for the memory state
2360     mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2361 
2362     // Optimize test; set region slot 2
2363     slow_path = opt_bits_test(ctrl, region, 2, flock, 0, 0);
2364     mem_phi->init_req(2, mem);
2365   }
2366 
2367   // Make slow path call
2368   CallNode *call = make_slow_call((CallNode *) lock, OptoRuntime::complete_monitor_enter_Type(),
2369                                   OptoRuntime::complete_monitor_locking_Java(), nullptr, slow_path,
2370                                   obj, box, nullptr);
2371 
2372   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2373 
2374   // Slow path can only throw asynchronous exceptions, which are always
2375   // de-opted.  So the compiler thinks the slow-call can never throw an
2376   // exception.  If it DOES throw an exception we would need the debug
2377   // info removed first (since if it throws there is no monitor).
2378   assert(_callprojs.fallthrough_ioproj == nullptr && _callprojs.catchall_ioproj == nullptr &&
2379          _callprojs.catchall_memproj == nullptr && _callprojs.catchall_catchproj == nullptr, "Unexpected projection from Lock");
2380 
2381   // Capture slow path
2382   // disconnect fall-through projection from call and create a new one
2383   // hook up users of fall-through projection to region
2384   Node *slow_ctrl = _callprojs.fallthrough_proj->clone();
2385   transform_later(slow_ctrl);
2386   _igvn.hash_delete(_callprojs.fallthrough_proj);
2387   _callprojs.fallthrough_proj->disconnect_inputs(C);
2388   region->init_req(1, slow_ctrl);
2389   // region inputs are now complete
2390   transform_later(region);
2391   _igvn.replace_node(_callprojs.fallthrough_proj, region);
2392 
2393   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2394   mem_phi->init_req(1, memproj );
2395   transform_later(mem_phi);
2396   _igvn.replace_node(_callprojs.fallthrough_memproj, mem_phi);
2397 }
2398 
2399 //------------------------------expand_unlock_node----------------------
2400 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
2401 
2402   Node* ctrl = unlock->in(TypeFunc::Control);
2403   Node* mem = unlock->in(TypeFunc::Memory);
2404   Node* obj = unlock->obj_node();
2405   Node* box = unlock->box_node();
2406 
2407   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2408 
2409   // No need for a null check on unlock
2410 
2411   // Make the merge point
2412   Node *region;
2413   Node *mem_phi;
2414 
2415   if (UseOptoBiasInlining) {
2416     // Check for biased locking unlock case, which is a no-op.
2417     // See the full description in MacroAssembler::biased_locking_exit().
2418     region  = new RegionNode(4);
2419     // create a Phi for the memory state
2420     mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2421     mem_phi->init_req(3, mem);
2422 
2423     Node* mark_node = make_load(ctrl, mem, obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
2424     ctrl = opt_bits_test(ctrl, region, 3, mark_node,
2425                          markWord::biased_lock_mask_in_place,
2426                          markWord::biased_lock_pattern);
2427   } else {
2428     region  = new RegionNode(3);
2429     // create a Phi for the memory state
2430     mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2431   }
2432 
2433   FastUnlockNode *funlock = new FastUnlockNode( ctrl, obj, box );
2434   funlock = transform_later( funlock )->as_FastUnlock();
2435   // Optimize test; set region slot 2
2436   Node *slow_path = opt_bits_test(ctrl, region, 2, funlock, 0, 0);
2437   Node *thread = transform_later(new ThreadLocalNode());
2438 
2439   CallNode *call = make_slow_call((CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(),
2440                                   CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C),
2441                                   "complete_monitor_unlocking_C", slow_path, obj, box, thread);
2442 
2443   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2444   assert(_callprojs.fallthrough_ioproj == nullptr && _callprojs.catchall_ioproj == nullptr &&
2445          _callprojs.catchall_memproj == nullptr && _callprojs.catchall_catchproj == nullptr, "Unexpected projection from Lock");
2446 
2447   // No exceptions for unlocking
2448   // Capture slow path
2449   // disconnect fall-through projection from call and create a new one
2450   // hook up users of fall-through projection to region
2451   Node *slow_ctrl = _callprojs.fallthrough_proj->clone();
2452   transform_later(slow_ctrl);
2453   _igvn.hash_delete(_callprojs.fallthrough_proj);
2454   _callprojs.fallthrough_proj->disconnect_inputs(C);
2455   region->init_req(1, slow_ctrl);
2456   // region inputs are now complete
2457   transform_later(region);
2458   _igvn.replace_node(_callprojs.fallthrough_proj, region);
2459 
2460   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory) );
2461   mem_phi->init_req(1, memproj );
2462   mem_phi->init_req(2, mem);
2463   transform_later(mem_phi);
2464   _igvn.replace_node(_callprojs.fallthrough_memproj, mem_phi);
2465 }
2466 
2467 void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) {
2468   assert(check->in(SubTypeCheckNode::Control) == nullptr, "should be pinned");
2469   Node* bol = check->unique_out();
2470   Node* obj_or_subklass = check->in(SubTypeCheckNode::ObjOrSubKlass);
2471   Node* superklass = check->in(SubTypeCheckNode::SuperKlass);
2472   assert(bol->is_Bool() && bol->as_Bool()->_test._test == BoolTest::ne, "unexpected bool node");
2473 
2474   for (DUIterator_Last imin, i = bol->last_outs(imin); i >= imin; --i) {
2475     Node* iff = bol->last_out(i);
2476     assert(iff->is_If(), "where's the if?");
2477 
2478     if (iff->in(0)->is_top()) {
2479       _igvn.replace_input_of(iff, 1, C->top());
2480       continue;
2481     }
2482 
2483     Node* iftrue = iff->as_If()->proj_out(1);
2484     Node* iffalse = iff->as_If()->proj_out(0);
2485     Node* ctrl = iff->in(0);
2486 
2487     Node* subklass = nullptr;
2488     if (_igvn.type(obj_or_subklass)->isa_klassptr()) {
2489       subklass = obj_or_subklass;
2490     } else {
2491       Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes());
2492       subklass = _igvn.transform(LoadKlassNode::make(_igvn, nullptr, C->immutable_memory(), k_adr, TypeInstPtr::KLASS));
2493     }
2494 
2495     Node* not_subtype_ctrl = Phase::gen_subtype_check(subklass, superklass, &ctrl, nullptr, _igvn);
2496 
2497     _igvn.replace_input_of(iff, 0, C->top());
2498     _igvn.replace_node(iftrue, not_subtype_ctrl);
2499     _igvn.replace_node(iffalse, ctrl);
2500   }
2501   _igvn.replace_node(check, C->top());
2502 }
2503 
2504 //---------------------------eliminate_macro_nodes----------------------
2505 // Eliminate scalar replaced allocations and associated locks.
2506 void PhaseMacroExpand::eliminate_macro_nodes() {
2507   if (C->macro_count() == 0)
2508     return;
2509 
2510   // Before elimination may re-mark (change to Nested or NonEscObj)
2511   // all associated (same box and obj) lock and unlock nodes.
2512   int cnt = C->macro_count();
2513   for (int i=0; i < cnt; i++) {
2514     Node *n = C->macro_node(i);
2515     if (n->is_AbstractLock()) { // Lock and Unlock nodes
2516       mark_eliminated_locking_nodes(n->as_AbstractLock());
2517     }
2518   }
2519   // Re-marking may break consistency of Coarsened locks.
2520   if (!C->coarsened_locks_consistent()) {
2521     return; // recompile without Coarsened locks if broken
2522   }
2523 
2524   // First, attempt to eliminate locks
2525   bool progress = true;
2526   while (progress) {
2527     progress = false;
2528     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
2529       Node* n = C->macro_node(i - 1);
2530       bool success = false;
2531       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2532       if (n->is_AbstractLock()) {
2533         success = eliminate_locking_node(n->as_AbstractLock());
2534       }
2535       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2536       progress = progress || success;
2537     }
2538   }
2539   // Next, attempt to eliminate allocations
2540   _has_locks = false;
2541   progress = true;
2542   while (progress) {
2543     progress = false;
2544     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
2545       Node* n = C->macro_node(i - 1);
2546       bool success = false;
2547       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2548       switch (n->class_id()) {
2549       case Node::Class_Allocate:
2550       case Node::Class_AllocateArray:
2551         success = eliminate_allocate_node(n->as_Allocate());
2552         break;
2553       case Node::Class_CallStaticJava:
2554         success = eliminate_boxing_node(n->as_CallStaticJava());
2555         break;
2556       case Node::Class_Lock:
2557       case Node::Class_Unlock:
2558         assert(!n->as_AbstractLock()->is_eliminated(), "sanity");
2559         _has_locks = true;
2560         break;
2561       case Node::Class_ArrayCopy:
2562         break;
2563       case Node::Class_OuterStripMinedLoop:
2564         break;
2565       case Node::Class_SubTypeCheck:
2566         break;
2567       case Node::Class_Opaque1:
2568         break;
2569       default:
2570         assert(n->Opcode() == Op_LoopLimit ||
2571                n->Opcode() == Op_Opaque2   ||
2572                n->Opcode() == Op_Opaque3   ||
2573                n->Opcode() == Op_Opaque4   ||
2574                BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
2575                "unknown node type in macro list");
2576       }
2577       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2578       progress = progress || success;
2579     }
2580   }
2581 }
2582 
2583 //------------------------------expand_macro_nodes----------------------
2584 //  Returns true if a failure occurred.
2585 bool PhaseMacroExpand::expand_macro_nodes() {
2586   // Last attempt to eliminate macro nodes.
2587   eliminate_macro_nodes();
2588   if (C->failing())  return true;
2589 
2590   // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
2591   bool progress = true;
2592   while (progress) {
2593     progress = false;
2594     for (int i = C->macro_count(); i > 0; i--) {
2595       Node* n = C->macro_node(i-1);
2596       bool success = false;
2597       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2598       if (n->Opcode() == Op_LoopLimit) {
2599         // Remove it from macro list and put on IGVN worklist to optimize.
2600         C->remove_macro_node(n);
2601         _igvn._worklist.push(n);
2602         success = true;
2603       } else if (n->Opcode() == Op_CallStaticJava) {
2604         // Remove it from macro list and put on IGVN worklist to optimize.
2605         C->remove_macro_node(n);
2606         _igvn._worklist.push(n);
2607         success = true;
2608       } else if (n->is_Opaque1() || n->Opcode() == Op_Opaque2) {
2609         _igvn.replace_node(n, n->in(1));
2610         success = true;
2611 #if INCLUDE_RTM_OPT
2612       } else if ((n->Opcode() == Op_Opaque3) && ((Opaque3Node*)n)->rtm_opt()) {
2613         assert(C->profile_rtm(), "should be used only in rtm deoptimization code");
2614         assert((n->outcnt() == 1) && n->unique_out()->is_Cmp(), "");
2615         Node* cmp = n->unique_out();
2616 #ifdef ASSERT
2617         // Validate graph.
2618         assert((cmp->outcnt() == 1) && cmp->unique_out()->is_Bool(), "");
2619         BoolNode* bol = cmp->unique_out()->as_Bool();
2620         assert((bol->outcnt() == 1) && bol->unique_out()->is_If() &&
2621                (bol->_test._test == BoolTest::ne), "");
2622         IfNode* ifn = bol->unique_out()->as_If();
2623         assert((ifn->outcnt() == 2) &&
2624                ifn->proj_out(1)->is_uncommon_trap_proj(Deoptimization::Reason_rtm_state_change) != nullptr, "");
2625 #endif
2626         Node* repl = n->in(1);
2627         if (!_has_locks) {
2628           // Remove RTM state check if there are no locks in the code.
2629           // Replace input to compare the same value.
2630           repl = (cmp->in(1) == n) ? cmp->in(2) : cmp->in(1);
2631         }
2632         _igvn.replace_node(n, repl);
2633         success = true;
2634 #endif
2635       } else if (n->Opcode() == Op_Opaque4) {
2636         // With Opaque4 nodes, the expectation is that the test of input 1
2637         // is always equal to the constant value of input 2. So we can
2638         // remove the Opaque4 and replace it by input 2. In debug builds,
2639         // leave the non constant test in instead to sanity check that it
2640         // never fails (if it does, that subgraph was constructed so, at
2641         // runtime, a Halt node is executed).
2642 #ifdef ASSERT
2643         _igvn.replace_node(n, n->in(1));
2644 #else
2645         _igvn.replace_node(n, n->in(2));
2646 #endif
2647         success = true;
2648       } else if (n->Opcode() == Op_OuterStripMinedLoop) {
2649         n->as_OuterStripMinedLoop()->adjust_strip_mined_loop(&_igvn);
2650         C->remove_macro_node(n);
2651         success = true;
2652       }
2653       assert(!success || (C->macro_count() == (old_macro_count - 1)), "elimination must have deleted one node from macro list");
2654       progress = progress || success;
2655     }
2656   }
2657 
2658   // Clean up the graph so we're less likely to hit the maximum node
2659   // limit
2660   _igvn.set_delay_transform(false);
2661   _igvn.optimize();
2662   if (C->failing())  return true;
2663   _igvn.set_delay_transform(true);
2664 
2665 
2666   // Because we run IGVN after each expansion, some macro nodes may go
2667   // dead and be removed from the list as we iterate over it. Move
2668   // Allocate nodes (processed in a second pass) at the beginning of
2669   // the list and then iterate from the last element of the list until
2670   // an Allocate node is seen. This is robust to random deletion in
2671   // the list due to nodes going dead.
2672   C->sort_macro_nodes();
2673 
2674   // expand arraycopy "macro" nodes first
2675   // For ReduceBulkZeroing, we must first process all arraycopy nodes
2676   // before the allocate nodes are expanded.
2677   while (C->macro_count() > 0) {
2678     int macro_count = C->macro_count();
2679     Node * n = C->macro_node(macro_count-1);
2680     assert(n->is_macro(), "only macro nodes expected here");
2681     if (_igvn.type(n) == Type::TOP || (n->in(0) != nullptr && n->in(0)->is_top())) {
2682       // node is unreachable, so don't try to expand it
2683       C->remove_macro_node(n);
2684       continue;
2685     }
2686     if (n->is_Allocate()) {
2687       break;
2688     }
2689     // Make sure expansion will not cause node limit to be exceeded.
2690     // Worst case is a macro node gets expanded into about 200 nodes.
2691     // Allow 50% more for optimization.
2692     if (C->check_node_count(300, "out of nodes before macro expansion")) {
2693       return true;
2694     }
2695 
2696     DEBUG_ONLY(int old_macro_count = C->macro_count();)
2697     switch (n->class_id()) {
2698     case Node::Class_Lock:
2699       expand_lock_node(n->as_Lock());
2700       break;
2701     case Node::Class_Unlock:
2702       expand_unlock_node(n->as_Unlock());
2703       break;
2704     case Node::Class_ArrayCopy:
2705       expand_arraycopy_node(n->as_ArrayCopy());
2706       break;
2707     case Node::Class_SubTypeCheck:
2708       expand_subtypecheck_node(n->as_SubTypeCheck());
2709       break;
2710     default:
2711       assert(false, "unknown node type in macro list");
2712     }
2713     assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2714     if (C->failing())  return true;
2715 
2716     // Clean up the graph so we're less likely to hit the maximum node
2717     // limit
2718     _igvn.set_delay_transform(false);
2719     _igvn.optimize();
2720     if (C->failing())  return true;
2721     _igvn.set_delay_transform(true);
2722   }
2723 
2724   // All nodes except Allocate nodes are expanded now. There could be
2725   // new optimization opportunities (such as folding newly created
2726   // load from a just allocated object). Run IGVN.
2727 
2728   // expand "macro" nodes
2729   // nodes are removed from the macro list as they are processed
2730   while (C->macro_count() > 0) {
2731     int macro_count = C->macro_count();
2732     Node * n = C->macro_node(macro_count-1);
2733     assert(n->is_macro(), "only macro nodes expected here");
2734     if (_igvn.type(n) == Type::TOP || (n->in(0) != nullptr && n->in(0)->is_top())) {
2735       // node is unreachable, so don't try to expand it
2736       C->remove_macro_node(n);
2737       continue;
2738     }
2739     // Make sure expansion will not cause node limit to be exceeded.
2740     // Worst case is a macro node gets expanded into about 200 nodes.
2741     // Allow 50% more for optimization.
2742     if (C->check_node_count(300, "out of nodes before macro expansion")) {
2743       return true;
2744     }
2745     switch (n->class_id()) {
2746     case Node::Class_Allocate:
2747       expand_allocate(n->as_Allocate());
2748       break;
2749     case Node::Class_AllocateArray:
2750       expand_allocate_array(n->as_AllocateArray());
2751       break;
2752     default:
2753       assert(false, "unknown node type in macro list");
2754     }
2755     assert(C->macro_count() < macro_count, "must have deleted a node from macro list");
2756     if (C->failing())  return true;
2757 
2758     // Clean up the graph so we're less likely to hit the maximum node
2759     // limit
2760     _igvn.set_delay_transform(false);
2761     _igvn.optimize();
2762     if (C->failing())  return true;
2763     _igvn.set_delay_transform(true);
2764   }
2765 
2766   _igvn.set_delay_transform(false);
2767   return false;
2768 }
--- EOF ---