< prev index next >

src/hotspot/share/opto/macro.cpp

Print this page

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

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

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

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

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

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

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

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




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

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





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

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






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






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

 436     }
 437   }
 438   // Set Phi's inputs
 439   for (uint j = 1; j < length; j++) {
 440     if (values.at(j) == mem) {
 441       phi->init_req(j, phi);
 442     } else {
 443       phi->init_req(j, values.at(j));
 444     }
 445   }
 446   return phi;
 447 }
 448 
 449 // Search the last value stored into the object's field.
 450 Node *PhaseMacroExpand::value_from_mem(Node *sfpt_mem, Node *sfpt_ctl, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, AllocateNode *alloc) {
 451   assert(adr_t->is_known_instance_field(), "instance required");
 452   int instance_id = adr_t->instance_id();
 453   assert((uint)instance_id == alloc->_idx, "wrong allocation");
 454 
 455   int alias_idx = C->get_alias_index(adr_t);
 456   int offset = adr_t->offset();
 457   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
 458   Node *alloc_ctrl = alloc->in(TypeFunc::Control);
 459   Node *alloc_mem = alloc->in(TypeFunc::Memory);
 460   VectorSet visited;
 461 
 462   bool done = sfpt_mem == alloc_mem;
 463   Node *mem = sfpt_mem;
 464   while (!done) {
 465     if (visited.test_set(mem->_idx)) {
 466       return NULL;  // found a loop, give up
 467     }
 468     mem = scan_mem_chain(mem, alias_idx, offset, start_mem, alloc, &_igvn);
 469     if (mem == start_mem || mem == alloc_mem) {
 470       done = true;  // hit a sentinel, return appropriate 0 value
 471     } else if (mem->is_Initialize()) {
 472       mem = mem->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 473       if (mem == NULL) {
 474         done = true; // Something go wrong.
 475       } else if (mem->is_Store()) {
 476         const TypePtr* atype = mem->as_Store()->adr_type();
 477         assert(C->get_alias_index(atype) == Compile::AliasIdxRaw, "store is correct memory slice");
 478         done = true;
 479       }
 480     } else if (mem->is_Store()) {
 481       const TypeOopPtr* atype = mem->as_Store()->adr_type()->isa_oopptr();
 482       assert(atype != NULL, "address type must be oopptr");
 483       assert(C->get_alias_index(atype) == alias_idx &&
 484              atype->is_known_instance_field() && atype->offset() == offset &&
 485              atype->instance_id() == instance_id, "store is correct memory slice");
 486       done = true;
 487     } else if (mem->is_Phi()) {
 488       // try to find a phi's unique input
 489       Node *unique_input = NULL;
 490       Node *top = C->top();
 491       for (uint i = 1; i < mem->req(); i++) {
 492         Node *n = scan_mem_chain(mem->in(i), alias_idx, offset, start_mem, alloc, &_igvn);
 493         if (n == NULL || n == top || n == mem) {
 494           continue;
 495         } else if (unique_input == NULL) {
 496           unique_input = n;
 497         } else if (unique_input != n) {
 498           unique_input = top;
 499           break;
 500         }
 501       }
 502       if (unique_input != NULL && unique_input != top) {
 503         mem = unique_input;
 504       } else {
 505         done = true;
 506       }
 507     } else if (mem->is_ArrayCopy()) {
 508       done = true;
 509     } else {
 510       DEBUG_ONLY( mem->dump(); )
 511       assert(false, "unexpected node");
 512     }
 513   }
 514   if (mem != NULL) {
 515     if (mem == start_mem || mem == alloc_mem) {
 516       // hit a sentinel, return appropriate 0 value





 517       return _igvn.zerocon(ft);
 518     } else if (mem->is_Store()) {
 519       Node* n = mem->in(MemNode::ValueIn);
 520       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 521       n = bs->step_over_gc_barrier(n);
 522       return n;
 523     } else if (mem->is_Phi()) {
 524       // attempt to produce a Phi reflecting the values on the input paths of the Phi
 525       Node_Stack value_phis(8);
 526       Node* phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, &value_phis, ValueSearchLimit);
 527       if (phi != NULL) {
 528         return phi;
 529       } else {
 530         // Kill all new Phis
 531         while(value_phis.is_nonempty()) {
 532           Node* n = value_phis.node();
 533           _igvn.replace_node(n, C->top());
 534           value_phis.pop();
 535         }
 536       }
 537     } else if (mem->is_ArrayCopy()) {
 538       Node* ctl = mem->in(0);
 539       Node* m = mem->in(TypeFunc::Memory);
 540       if (sfpt_ctl->is_Proj() && sfpt_ctl->as_Proj()->is_uncommon_trap_proj(Deoptimization::Reason_none)) {
 541         // pin the loads in the uncommon trap path
 542         ctl = sfpt_ctl;
 543         m = sfpt_mem;
 544       }
 545       return make_arraycopy_load(mem->as_ArrayCopy(), offset, ctl, m, ft, ftype, alloc);
 546     }
 547   }
 548   // Something go wrong.
 549   return NULL;
 550 }
 551 










































 552 // Check the possibility of scalar replacement.
 553 bool PhaseMacroExpand::can_eliminate_allocation(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
 554   //  Scan the uses of the allocation to check for anything that would
 555   //  prevent us from eliminating it.
 556   NOT_PRODUCT( const char* fail_eliminate = NULL; )
 557   DEBUG_ONLY( Node* disq_node = NULL; )
 558   bool  can_eliminate = true;
 559 

 560   Node* res = alloc->result_cast();
 561   const TypeOopPtr* res_type = NULL;
 562   if (res == NULL) {
 563     // All users were eliminated.
 564   } else if (!res->is_CheckCastPP()) {
 565     NOT_PRODUCT(fail_eliminate = "Allocation does not have unique CheckCastPP";)
 566     can_eliminate = false;
 567   } else {

 568     res_type = _igvn.type(res)->isa_oopptr();
 569     if (res_type == NULL) {
 570       NOT_PRODUCT(fail_eliminate = "Neither instance or array allocation";)
 571       can_eliminate = false;
 572     } else if (res_type->isa_aryptr()) {
 573       int length = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 574       if (length < 0) {
 575         NOT_PRODUCT(fail_eliminate = "Array's size is not constant";)
 576         can_eliminate = false;
 577       }
 578     }
 579   }
 580 
 581   if (can_eliminate && res != NULL) {
 582     BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
 583     for (DUIterator_Fast jmax, j = res->fast_outs(jmax);
 584                                j < jmax && can_eliminate; j++) {
 585       Node* use = res->fast_out(j);
 586 
 587       if (use->is_AddP()) {
 588         const TypePtr* addp_type = _igvn.type(use)->is_ptr();
 589         int offset = addp_type->offset();
 590 
 591         if (offset == Type::OffsetTop || offset == Type::OffsetBot) {
 592           NOT_PRODUCT(fail_eliminate = "Undefined field reference";)
 593           can_eliminate = false;
 594           break;
 595         }
 596         for (DUIterator_Fast kmax, k = use->fast_outs(kmax);
 597                                    k < kmax && can_eliminate; k++) {
 598           Node* n = use->fast_out(k);
 599           if (!n->is_Store() && n->Opcode() != Op_CastP2X && !bs->is_gc_pre_barrier_node(n)) {
 600             DEBUG_ONLY(disq_node = n;)
 601             if (n->is_Load() || n->is_LoadStore()) {
 602               NOT_PRODUCT(fail_eliminate = "Field load";)
 603             } else {
 604               NOT_PRODUCT(fail_eliminate = "Not store field reference";)

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





















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



 649       }
 650     }
 651   }
 652 
 653 #ifndef PRODUCT
 654   if (PrintEliminateAllocations) {
 655     if (can_eliminate) {
 656       tty->print("Scalar ");
 657       if (res == NULL)
 658         alloc->dump();
 659       else
 660         res->dump();
 661     } else if (alloc->_is_scalar_replaceable) {
 662       tty->print("NotScalar (%s)", fail_eliminate);
 663       if (res == NULL)
 664         alloc->dump();
 665       else
 666         res->dump();
 667 #ifdef ASSERT
 668       if (disq_node != NULL) {
 669           tty->print("  >>>> ");
 670           disq_node->dump();
 671       }
 672 #endif /*ASSERT*/
 673     }
 674   }
 675 #endif
 676   return can_eliminate;
 677 }
 678 
 679 // Do scalar replacement.
 680 bool PhaseMacroExpand::scalar_replacement(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
 681   GrowableArray <SafePointNode *> safepoints_done;

 690   Node* res = alloc->result_cast();
 691   assert(res == NULL || res->is_CheckCastPP(), "unexpected AllocateNode result");
 692   const TypeOopPtr* res_type = NULL;
 693   if (res != NULL) { // Could be NULL when there are no users
 694     res_type = _igvn.type(res)->isa_oopptr();
 695   }
 696 
 697   if (res != NULL) {
 698     if (res_type->isa_instptr()) {
 699       // find the fields of the class which will be needed for safepoint debug information
 700       iklass = res_type->is_instptr()->instance_klass();
 701       nfields = iklass->nof_nonstatic_fields();
 702     } else {
 703       // find the array's elements which will be needed for safepoint debug information
 704       nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 705       assert(nfields >= 0, "must be an array klass.");
 706       basic_elem_type = res_type->is_aryptr()->elem()->array_element_basic_type();
 707       array_base = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
 708       element_size = type2aelembytes(basic_elem_type);
 709       field_type = res_type->is_aryptr()->elem();




 710     }
 711   }
 712   //
 713   // Process the safepoint uses
 714   //


 715   while (safepoints.length() > 0) {
 716     SafePointNode* sfpt = safepoints.pop();
 717     Node* mem = sfpt->memory();
 718     Node* ctl = sfpt->control();
 719     assert(sfpt->jvms() != NULL, "missed JVMS");
 720     // Fields of scalar objs are referenced only at the end
 721     // of regular debuginfo at the last (youngest) JVMS.
 722     // Record relative start index.
 723     uint first_ind = (sfpt->req() - sfpt->jvms()->scloff());
 724     SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(res_type,
 725 #ifdef ASSERT
 726                                                  alloc,
 727 #endif
 728                                                  first_ind, nfields);
 729     sobj->init_req(0, C->root());
 730     transform_later(sobj);
 731 
 732     // Scan object's fields adding an input to the safepoint for each field.
 733     for (int j = 0; j < nfields; j++) {
 734       intptr_t offset;
 735       ciField* field = NULL;
 736       if (iklass != NULL) {
 737         field = iklass->nonstatic_field_at(j);
 738         offset = field->offset();
 739         ciType* elem_type = field->type();
 740         basic_elem_type = field->layout_type();

 741 
 742         // The next code is taken from Parse::do_get_xxx().
 743         if (is_reference_type(basic_elem_type)) {
 744           if (!elem_type->is_loaded()) {
 745             field_type = TypeInstPtr::BOTTOM;
 746           } else if (field != NULL && field->is_static_constant()) {
 747             ciObject* con = field->constant_value().as_object();
 748             // Do not "join" in the previous type; it doesn't add value,
 749             // and may yield a vacuous result if the field is of interface type.
 750             field_type = TypeOopPtr::make_from_constant(con)->isa_oopptr();
 751             assert(field_type != NULL, "field singleton type must be consistent");
 752           } else {
 753             field_type = TypeOopPtr::make_from_klass(elem_type->as_klass());
 754           }
 755           if (UseCompressedOops) {
 756             field_type = field_type->make_narrowoop();
 757             basic_elem_type = T_NARROWOOP;
 758           }
 759         } else {
 760           field_type = Type::get_const_basic_type(basic_elem_type);
 761         }
 762       } else {
 763         offset = array_base + j * (intptr_t)element_size;
 764       }
 765 
 766       const TypeOopPtr *field_addr_type = res_type->add_offset(offset)->isa_oopptr();
 767 
 768       Node *field_val = value_from_mem(mem, ctl, basic_elem_type, field_type, field_addr_type, alloc);






 769       if (field_val == NULL) {
 770         // We weren't able to find a value for this field,
 771         // give up on eliminating this allocation.
 772 
 773         // Remove any extra entries we added to the safepoint.
 774         uint last = sfpt->req() - 1;
 775         for (int k = 0;  k < j; k++) {
 776           sfpt->del_req(last--);
 777         }
 778         _igvn._worklist.push(sfpt);
 779         // rollback processed safepoints
 780         while (safepoints_done.length() > 0) {
 781           SafePointNode* sfpt_done = safepoints_done.pop();
 782           // remove any extra entries we added to the safepoint
 783           last = sfpt_done->req() - 1;
 784           for (int k = 0;  k < nfields; k++) {
 785             sfpt_done->del_req(last--);
 786           }
 787           JVMState *jvms = sfpt_done->jvms();
 788           jvms->set_endoff(sfpt_done->req());

 811             int field_idx = C->get_alias_index(field_addr_type);
 812             tty->print(" (alias_idx=%d)", field_idx);
 813           } else { // Array's element
 814             tty->print("=== At SafePoint node %d can't find value of array element [%d]",
 815                        sfpt->_idx, j);
 816           }
 817           tty->print(", which prevents elimination of: ");
 818           if (res == NULL)
 819             alloc->dump();
 820           else
 821             res->dump();
 822         }
 823 #endif
 824         return false;
 825       }
 826       if (UseCompressedOops && field_type->isa_narrowoop()) {
 827         // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation
 828         // to be able scalar replace the allocation.
 829         if (field_val->is_EncodeP()) {
 830           field_val = field_val->in(1);
 831         } else {
 832           field_val = transform_later(new DecodeNNode(field_val, field_val->get_ptr_type()));
 833         }
 834       }




 835       sfpt->add_req(field_val);
 836     }
 837     JVMState *jvms = sfpt->jvms();
 838     jvms->set_endoff(sfpt->req());
 839     // Now make a pass over the debug information replacing any references
 840     // to the allocated object with "sobj"
 841     int start = jvms->debug_start();
 842     int end   = jvms->debug_end();
 843     sfpt->replace_edges_in_range(res, sobj, start, end, &_igvn);
 844     _igvn._worklist.push(sfpt);
 845     safepoints_done.append_if_missing(sfpt); // keep it for rollback
 846   }








 847   return true;
 848 }
 849 
 850 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) {
 851   Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control);
 852   Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory);
 853   if (ctl_proj != NULL) {
 854     igvn.replace_node(ctl_proj, n->in(0));
 855   }
 856   if (mem_proj != NULL) {
 857     igvn.replace_node(mem_proj, n->in(TypeFunc::Memory));
 858   }
 859 }
 860 
 861 // Process users of eliminated allocation.
 862 void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc) {

 863   Node* res = alloc->result_cast();
 864   if (res != NULL) {




 865     for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
 866       Node *use = res->last_out(j);
 867       uint oc1 = res->outcnt();
 868 
 869       if (use->is_AddP()) {
 870         for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
 871           Node *n = use->last_out(k);
 872           uint oc2 = use->outcnt();
 873           if (n->is_Store()) {
 874 #ifdef ASSERT
 875             // Verify that there is no dependent MemBarVolatile nodes,
 876             // they should be removed during IGVN, see MemBarNode::Ideal().
 877             for (DUIterator_Fast pmax, p = n->fast_outs(pmax);
 878                                        p < pmax; p++) {
 879               Node* mb = n->fast_out(p);
 880               assert(mb->is_Initialize() || !mb->is_MemBar() ||
 881                      mb->req() <= MemBarNode::Precedent ||
 882                      mb->in(MemBarNode::Precedent) != n,
 883                      "MemBarVolatile should be eliminated for non-escaping object");
 884             }
 885 #endif
 886             _igvn.replace_node(n, n->in(MemNode::Memory));
 887           } else {
 888             eliminate_gc_barrier(n);
 889           }
 890           k -= (oc2 - use->outcnt());
 891         }
 892         _igvn.remove_dead_node(use);
 893       } else if (use->is_ArrayCopy()) {
 894         // Disconnect ArrayCopy node
 895         ArrayCopyNode* ac = use->as_ArrayCopy();
 896         if (ac->is_clonebasic()) {
 897           Node* membar_after = ac->proj_out(TypeFunc::Control)->unique_ctrl_out();
 898           disconnect_projections(ac, _igvn);
 899           assert(alloc->in(TypeFunc::Memory)->is_Proj() && alloc->in(TypeFunc::Memory)->in(0)->Opcode() == Op_MemBarCPUOrder, "mem barrier expected before allocation");
 900           Node* membar_before = alloc->in(TypeFunc::Memory)->in(0);
 901           disconnect_projections(membar_before->as_MemBar(), _igvn);
 902           if (membar_after->is_MemBar()) {
 903             disconnect_projections(membar_after->as_MemBar(), _igvn);
 904           }
 905         } else {
 906           assert(ac->is_arraycopy_validated() ||
 907                  ac->is_copyof_validated() ||
 908                  ac->is_copyofrange_validated(), "unsupported");
 909           CallProjections callprojs;
 910           ac->extract_projections(&callprojs, true);
 911 
 912           _igvn.replace_node(callprojs.fallthrough_ioproj, ac->in(TypeFunc::I_O));
 913           _igvn.replace_node(callprojs.fallthrough_memproj, ac->in(TypeFunc::Memory));
 914           _igvn.replace_node(callprojs.fallthrough_catchproj, ac->in(TypeFunc::Control));
 915 
 916           // Set control to top. IGVN will remove the remaining projections
 917           ac->set_req(0, top());
 918           ac->replace_edge(res, top(), &_igvn);
 919 
 920           // Disconnect src right away: it can help find new
 921           // opportunities for allocation elimination
 922           Node* src = ac->in(ArrayCopyNode::Src);
 923           ac->replace_edge(src, top(), &_igvn);
 924           // src can be top at this point if src and dest of the
 925           // arraycopy were the same
 926           if (src->outcnt() == 0 && !src->is_top()) {
 927             _igvn.remove_dead_node(src);
 928           }
 929         }
 930         _igvn._worklist.push(ac);



















 931       } else {
 932         eliminate_gc_barrier(use);
 933       }
 934       j -= (oc1 - res->outcnt());
 935     }
 936     assert(res->outcnt() == 0, "all uses of allocated objects must be deleted");
 937     _igvn.remove_dead_node(res);
 938   }
 939 
 940   //
 941   // Process other users of allocation's projections
 942   //
 943   if (_callprojs.resproj != NULL && _callprojs.resproj->outcnt() != 0) {
 944     // First disconnect stores captured by Initialize node.
 945     // If Initialize node is eliminated first in the following code,
 946     // it will kill such stores and DUIterator_Last will assert.
 947     for (DUIterator_Fast jmax, j = _callprojs.resproj->fast_outs(jmax);  j < jmax; j++) {
 948       Node* use = _callprojs.resproj->fast_out(j);
 949       if (use->is_AddP()) {
 950         // raw memory addresses used only by the initialization
 951         _igvn.replace_node(use, C->top());
 952         --j; --jmax;
 953       }
 954     }
 955     for (DUIterator_Last jmin, j = _callprojs.resproj->last_outs(jmin); j >= jmin; ) {
 956       Node* use = _callprojs.resproj->last_out(j);
 957       uint oc1 = _callprojs.resproj->outcnt();
 958       if (use->is_Initialize()) {
 959         // Eliminate Initialize node.
 960         InitializeNode *init = use->as_Initialize();
 961         assert(init->outcnt() <= 2, "only a control and memory projection expected");
 962         Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
 963         if (ctrl_proj != NULL) {
 964           _igvn.replace_node(ctrl_proj, init->in(TypeFunc::Control));
 965 #ifdef ASSERT
 966           // If the InitializeNode has no memory out, it will die, and tmp will become NULL
 967           Node* tmp = init->in(TypeFunc::Control);
 968           assert(tmp == NULL || tmp == _callprojs.fallthrough_catchproj, "allocation control projection");
 969 #endif
 970         }
 971         Node *mem_proj = init->proj_out_or_null(TypeFunc::Memory);
 972         if (mem_proj != NULL) {
 973           Node *mem = init->in(TypeFunc::Memory);
 974 #ifdef ASSERT
 975           if (mem->is_MergeMem()) {
 976             assert(mem->in(TypeFunc::Memory) == _callprojs.fallthrough_memproj, "allocation memory projection");
 977           } else {
 978             assert(mem == _callprojs.fallthrough_memproj, "allocation memory projection");
 979           }
 980 #endif
 981           _igvn.replace_node(mem_proj, mem);
 982         }




 983       } else  {
 984         assert(false, "only Initialize or AddP expected");
 985       }
 986       j -= (oc1 - _callprojs.resproj->outcnt());
 987     }
 988   }
 989   if (_callprojs.fallthrough_catchproj != NULL) {
 990     _igvn.replace_node(_callprojs.fallthrough_catchproj, alloc->in(TypeFunc::Control));
 991   }
 992   if (_callprojs.fallthrough_memproj != NULL) {
 993     _igvn.replace_node(_callprojs.fallthrough_memproj, alloc->in(TypeFunc::Memory));
 994   }
 995   if (_callprojs.catchall_memproj != NULL) {
 996     _igvn.replace_node(_callprojs.catchall_memproj, C->top());
 997   }
 998   if (_callprojs.fallthrough_ioproj != NULL) {
 999     _igvn.replace_node(_callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
1000   }
1001   if (_callprojs.catchall_ioproj != NULL) {
1002     _igvn.replace_node(_callprojs.catchall_ioproj, C->top());
1003   }
1004   if (_callprojs.catchall_catchproj != NULL) {
1005     _igvn.replace_node(_callprojs.catchall_catchproj, C->top());
1006   }
1007 }
1008 
1009 bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) {
1010   // If reallocation fails during deoptimization we'll pop all
1011   // interpreter frames for this compiled frame and that won't play
1012   // nice with JVMTI popframe.
1013   // We avoid this issue by eager reallocation when the popframe request
1014   // is received.
1015   if (!EliminateAllocations || !alloc->_is_non_escaping) {
1016     return false;
1017   }
1018   Node* klass = alloc->in(AllocateNode::KlassNode);
1019   const TypeKlassPtr* tklass = _igvn.type(klass)->is_klassptr();
1020   Node* res = alloc->result_cast();







1021   // Eliminate boxing allocations which are not used
1022   // regardless scalar replaceable status.
1023   bool boxing_alloc = C->eliminate_boxing() &&

1024                       tklass->isa_instklassptr() &&
1025                       tklass->is_instklassptr()->instance_klass()->is_box_klass();
1026   if (!alloc->_is_scalar_replaceable && (!boxing_alloc || (res != NULL))) {
1027     return false;
1028   }
1029 
1030   alloc->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1031 
1032   GrowableArray <SafePointNode *> safepoints;
1033   if (!can_eliminate_allocation(alloc, safepoints)) {
1034     return false;
1035   }
1036 
1037   if (!alloc->_is_scalar_replaceable) {
1038     assert(res == NULL, "sanity");
1039     // We can only eliminate allocation if all debug info references
1040     // are already replaced with SafePointScalarObject because
1041     // we can't search for a fields value without instance_id.
1042     if (safepoints.length() > 0) {

1043       return false;
1044     }
1045   }
1046 
1047   if (!scalar_replacement(alloc, safepoints)) {
1048     return false;
1049   }
1050 
1051   CompileLog* log = C->log();
1052   if (log != NULL) {
1053     log->head("eliminate_allocation type='%d'",
1054               log->identify(tklass->exact_klass()));
1055     JVMState* p = alloc->jvms();
1056     while (p != NULL) {
1057       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1058       p = p->caller();
1059     }
1060     log->tail("eliminate_allocation");
1061   }
1062 
1063   process_users_of_allocation(alloc);
1064 
1065 #ifndef PRODUCT
1066   if (PrintEliminateAllocations) {
1067     if (alloc->is_AllocateArray())
1068       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1069     else
1070       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1071   }
1072 #endif
1073 
1074   return true;
1075 }
1076 
1077 bool PhaseMacroExpand::eliminate_boxing_node(CallStaticJavaNode *boxing) {
1078   // EA should remove all uses of non-escaping boxing node.
1079   if (!C->eliminate_boxing() || boxing->proj_out_or_null(TypeFunc::Parms) != NULL) {
1080     return false;
1081   }
1082 
1083   assert(boxing->result_cast() == NULL, "unexpected boxing node result");
1084 
1085   boxing->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1086 
1087   const TypeTuple* r = boxing->tf()->range();
1088   assert(r->cnt() > TypeFunc::Parms, "sanity");
1089   const TypeInstPtr* t = r->field_at(TypeFunc::Parms)->isa_instptr();
1090   assert(t != NULL, "sanity");
1091 
1092   CompileLog* log = C->log();
1093   if (log != NULL) {
1094     log->head("eliminate_boxing type='%d'",
1095               log->identify(t->instance_klass()));
1096     JVMState* p = boxing->jvms();
1097     while (p != NULL) {
1098       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1099       p = p->caller();
1100     }
1101     log->tail("eliminate_boxing");
1102   }
1103 
1104   process_users_of_allocation(boxing);
1105 
1106 #ifndef PRODUCT
1107   if (PrintEliminateAllocations) {

1251         }
1252       }
1253 #endif
1254       yank_alloc_node(alloc);
1255       return;
1256     }
1257   }
1258 
1259   enum { too_big_or_final_path = 1, need_gc_path = 2 };
1260   Node *slow_region = NULL;
1261   Node *toobig_false = ctrl;
1262 
1263   // generate the initial test if necessary
1264   if (initial_slow_test != NULL ) {
1265     assert (expand_fast_path, "Only need test if there is a fast path");
1266     slow_region = new RegionNode(3);
1267 
1268     // Now make the initial failure test.  Usually a too-big test but
1269     // might be a TRUE for finalizers or a fancy class check for
1270     // newInstance0.
1271     IfNode *toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1272     transform_later(toobig_iff);
1273     // Plug the failing-too-big test into the slow-path region
1274     Node *toobig_true = new IfTrueNode( toobig_iff );
1275     transform_later(toobig_true);
1276     slow_region    ->init_req( too_big_or_final_path, toobig_true );
1277     toobig_false = new IfFalseNode( toobig_iff );
1278     transform_later(toobig_false);
1279   } else {
1280     // No initial test, just fall into next case
1281     assert(allocation_has_use || !expand_fast_path, "Should already have been handled");
1282     toobig_false = ctrl;
1283     debug_only(slow_region = NodeSentinel);
1284   }
1285 
1286   // If we are here there are several possibilities
1287   // - expand_fast_path is false - then only a slow path is expanded. That's it.
1288   // no_initial_check means a constant allocation.
1289   // - If check always evaluates to false -> expand_fast_path is false (see above)
1290   // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath)
1291   // if !allocation_has_use the fast path is empty
1292   // if !allocation_has_use && no_initial_check
1293   // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all.
1294   //   removed by yank_alloc_node above.
1295 
1296   Node *slow_mem = mem;  // save the current memory state for slow path
1297   // generate the fast allocation code unless we know that the initial test will always go slow
1298   if (expand_fast_path) {
1299     // Fast path modifies only raw memory.
1300     if (mem->is_MergeMem()) {
1301       mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1302     }
1303 
1304     // allocate the Region and Phi nodes for the result
1305     result_region = new RegionNode(3);
1306     result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1307     result_phi_i_o    = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1308 
1309     // Grab regular I/O before optional prefetch may change it.
1310     // Slow-path does no I/O so just set it to the original I/O.
1311     result_phi_i_o->init_req(slow_result_path, i_o);
1312 
1313     // Name successful fast-path variables
1314     Node* fast_oop_ctrl;
1315     Node* fast_oop_rawmem;

1316     if (allocation_has_use) {
1317       Node* needgc_ctrl = NULL;
1318       result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1319 
1320       intx prefetch_lines = length != NULL ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1321       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1322       Node* fast_oop = bs->obj_allocate(this, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1323                                         fast_oop_ctrl, fast_oop_rawmem,
1324                                         prefetch_lines);
1325 
1326       if (initial_slow_test != NULL) {
1327         // This completes all paths into the slow merge point
1328         slow_region->init_req(need_gc_path, needgc_ctrl);
1329         transform_later(slow_region);
1330       } else {
1331         // No initial slow path needed!
1332         // Just fall from the need-GC path straight into the VM call.
1333         slow_region = needgc_ctrl;
1334       }
1335 

1353     result_phi_i_o   ->init_req(fast_result_path, i_o);
1354     result_phi_rawmem->init_req(fast_result_path, fast_oop_rawmem);
1355   } else {
1356     slow_region = ctrl;
1357     result_phi_i_o = i_o; // Rename it to use in the following code.
1358   }
1359 
1360   // Generate slow-path call
1361   CallNode *call = new CallStaticJavaNode(slow_call_type, slow_call_address,
1362                                OptoRuntime::stub_name(slow_call_address),
1363                                TypePtr::BOTTOM);
1364   call->init_req(TypeFunc::Control,   slow_region);
1365   call->init_req(TypeFunc::I_O,       top());    // does no i/o
1366   call->init_req(TypeFunc::Memory,    slow_mem); // may gc ptrs
1367   call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1368   call->init_req(TypeFunc::FramePtr,  alloc->in(TypeFunc::FramePtr));
1369 
1370   call->init_req(TypeFunc::Parms+0, klass_node);
1371   if (length != NULL) {
1372     call->init_req(TypeFunc::Parms+1, length);



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

1631     Node* thread = new ThreadLocalNode();
1632     transform_later(thread);
1633 
1634     call->init_req(TypeFunc::Parms + 0, thread);
1635     call->init_req(TypeFunc::Parms + 1, oop);
1636     call->init_req(TypeFunc::Control, ctrl);
1637     call->init_req(TypeFunc::I_O    , top()); // does no i/o
1638     call->init_req(TypeFunc::Memory , rawmem);
1639     call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1640     call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1641     transform_later(call);
1642     ctrl = new ProjNode(call, TypeFunc::Control);
1643     transform_later(ctrl);
1644     rawmem = new ProjNode(call, TypeFunc::Memory);
1645     transform_later(rawmem);
1646   }
1647 }
1648 
1649 // Helper for PhaseMacroExpand::expand_allocate_common.
1650 // Initializes the newly-allocated storage.
1651 Node*
1652 PhaseMacroExpand::initialize_object(AllocateNode* alloc,
1653                                     Node* control, Node* rawmem, Node* object,
1654                                     Node* klass_node, Node* length,
1655                                     Node* size_in_bytes) {
1656   InitializeNode* init = alloc->initialization();
1657   // Store the klass & mark bits
1658   Node* mark_node = alloc->make_ideal_mark(&_igvn, object, control, rawmem);
1659   if (!mark_node->is_Con()) {
1660     transform_later(mark_node);
1661   }
1662   rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
1663 
1664   rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
1665   int header_size = alloc->minimum_header_size();  // conservatively small
1666 
1667   // Array length
1668   if (length != NULL) {         // Arrays need length field
1669     rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1670     // conservatively small header size:
1671     header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1672     if (_igvn.type(klass_node)->isa_aryklassptr()) {   // we know the exact header size in most cases:
1673       BasicType elem = _igvn.type(klass_node)->is_klassptr()->as_instance_type()->isa_aryptr()->elem()->array_element_basic_type();
1674       if (is_reference_type(elem, true)) {
1675         elem = T_OBJECT;
1676       }
1677       header_size = Klass::layout_helper_header_size(Klass::array_layout_helper(elem));
1678     }
1679   }
1680 
1681   // Clear the object body, if necessary.
1682   if (init == NULL) {
1683     // The init has somehow disappeared; be cautious and clear everything.
1684     //
1685     // This can happen if a node is allocated but an uncommon trap occurs
1686     // immediately.  In this case, the Initialize gets associated with the
1687     // trap, and may be placed in a different (outer) loop, if the Allocate
1688     // is in a loop.  If (this is rare) the inner loop gets unrolled, then
1689     // there can be two Allocates to one Initialize.  The answer in all these
1690     // edge cases is safety first.  It is always safe to clear immediately
1691     // within an Allocate, and then (maybe or maybe not) clear some more later.
1692     if (!(UseTLAB && ZeroTLAB)) {
1693       rawmem = ClearArrayNode::clear_memory(control, rawmem, object,


1694                                             header_size, size_in_bytes,
1695                                             &_igvn);
1696     }
1697   } else {
1698     if (!init->is_complete()) {
1699       // Try to win by zeroing only what the init does not store.
1700       // We can also try to do some peephole optimizations,
1701       // such as combining some adjacent subword stores.
1702       rawmem = init->complete_stores(control, rawmem, object,
1703                                      header_size, size_in_bytes, &_igvn);
1704     }
1705     // We have no more use for this link, since the AllocateNode goes away:
1706     init->set_req(InitializeNode::RawAddress, top());
1707     // (If we keep the link, it just confuses the register allocator,
1708     // who thinks he sees a real use of the address by the membar.)
1709   }
1710 
1711   return rawmem;
1712 }
1713 

2043   } // EliminateNestedLocks
2044 
2045   if (alock->is_non_esc_obj()) { // Lock is used for non escaping object
2046     // Look for all locks of this object and mark them and
2047     // corresponding BoxLock nodes as eliminated.
2048     Node* obj = alock->obj_node();
2049     for (uint j = 0; j < obj->outcnt(); j++) {
2050       Node* o = obj->raw_out(j);
2051       if (o->is_AbstractLock() &&
2052           o->as_AbstractLock()->obj_node()->eqv_uncast(obj)) {
2053         alock = o->as_AbstractLock();
2054         Node* box = alock->box_node();
2055         // Replace old box node with new eliminated box for all users
2056         // of the same object and mark related locks as eliminated.
2057         mark_eliminated_box(box, obj);
2058       }
2059     }
2060   }
2061 }
2062 











































2063 // we have determined that this lock/unlock can be eliminated, we simply
2064 // eliminate the node without expanding it.
2065 //
2066 // Note:  The membar's associated with the lock/unlock are currently not
2067 //        eliminated.  This should be investigated as a future enhancement.
2068 //
2069 bool PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) {
2070 
2071   if (!alock->is_eliminated()) {
2072     return false;
2073   }
2074 #ifdef ASSERT
2075   if (!alock->is_coarsened()) {
2076     // Check that new "eliminated" BoxLock node is created.
2077     BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2078     assert(oldbox->is_eliminated(), "should be done already");
2079   }
2080 #endif
2081 
2082   alock->log_lock_optimization(C, "eliminate_lock");
2083 
2084 #ifndef PRODUCT
2085   if (PrintEliminateLocks) {
2086     tty->print_cr("++++ Eliminated: %d %s '%s'", alock->_idx, (alock->is_Lock() ? "Lock" : "Unlock"), alock->kind_as_string());
2087   }
2088 #endif
2089 
2090   Node* mem  = alock->in(TypeFunc::Memory);
2091   Node* ctrl = alock->in(TypeFunc::Control);
2092   guarantee(ctrl != NULL, "missing control projection, cannot replace_node() with NULL");
2093 
2094   alock->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2095   // There are 2 projections from the lock.  The lock node will
2096   // be deleted when its last use is subsumed below.
2097   assert(alock->outcnt() == 2 &&
2098          _callprojs.fallthrough_proj != NULL &&
2099          _callprojs.fallthrough_memproj != NULL,
2100          "Unexpected projections from Lock/Unlock");
2101 
2102   Node* fallthroughproj = _callprojs.fallthrough_proj;
2103   Node* memproj_fallthrough = _callprojs.fallthrough_memproj;
2104 
2105   // The memory projection from a lock/unlock is RawMem
2106   // The input to a Lock is merged memory, so extract its RawMem input
2107   // (unless the MergeMem has been optimized away.)
2108   if (alock->is_Lock()) {



2109     // Search for MemBarAcquireLock node and delete it also.
2110     MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
2111     assert(membar != NULL && membar->Opcode() == Op_MemBarAcquireLock, "");
2112     Node* ctrlproj = membar->proj_out(TypeFunc::Control);
2113     Node* memproj = membar->proj_out(TypeFunc::Memory);
2114     _igvn.replace_node(ctrlproj, fallthroughproj);
2115     _igvn.replace_node(memproj, memproj_fallthrough);
2116 
2117     // Delete FastLock node also if this Lock node is unique user
2118     // (a loop peeling may clone a Lock node).
2119     Node* flock = alock->as_Lock()->fastlock_node();
2120     if (flock->outcnt() == 1) {
2121       assert(flock->unique_out() == alock, "sanity");
2122       _igvn.replace_node(flock, top());
2123     }
2124   }
2125 
2126   // Search for MemBarReleaseLock node and delete it also.
2127   if (alock->is_Unlock() && ctrl->is_Proj() && ctrl->in(0)->is_MemBar()) {
2128     MemBarNode* membar = ctrl->in(0)->as_MemBar();

2149   Node* mem = lock->in(TypeFunc::Memory);
2150   Node* obj = lock->obj_node();
2151   Node* box = lock->box_node();
2152   Node* flock = lock->fastlock_node();
2153 
2154   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2155 
2156   // Make the merge point
2157   Node *region;
2158   Node *mem_phi;
2159   Node *slow_path;
2160 
2161   region  = new RegionNode(3);
2162   // create a Phi for the memory state
2163   mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2164 
2165   // Optimize test; set region slot 2
2166   slow_path = opt_bits_test(ctrl, region, 2, flock, 0, 0);
2167   mem_phi->init_req(2, mem);
2168 



2169   // Make slow path call
2170   CallNode *call = make_slow_call((CallNode *) lock, OptoRuntime::complete_monitor_enter_Type(),
2171                                   OptoRuntime::complete_monitor_locking_Java(), NULL, slow_path,
2172                                   obj, box, NULL);
2173 
2174   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2175 
2176   // Slow path can only throw asynchronous exceptions, which are always
2177   // de-opted.  So the compiler thinks the slow-call can never throw an
2178   // exception.  If it DOES throw an exception we would need the debug
2179   // info removed first (since if it throws there is no monitor).
2180   assert(_callprojs.fallthrough_ioproj == NULL && _callprojs.catchall_ioproj == NULL &&
2181          _callprojs.catchall_memproj == NULL && _callprojs.catchall_catchproj == NULL, "Unexpected projection from Lock");
2182 
2183   // Capture slow path
2184   // disconnect fall-through projection from call and create a new one
2185   // hook up users of fall-through projection to region
2186   Node *slow_ctrl = _callprojs.fallthrough_proj->clone();
2187   transform_later(slow_ctrl);
2188   _igvn.hash_delete(_callprojs.fallthrough_proj);
2189   _callprojs.fallthrough_proj->disconnect_inputs(C);
2190   region->init_req(1, slow_ctrl);
2191   // region inputs are now complete
2192   transform_later(region);
2193   _igvn.replace_node(_callprojs.fallthrough_proj, region);
2194 
2195   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2196 
2197   mem_phi->init_req(1, memproj);
2198 
2199   transform_later(mem_phi);
2200 
2201   _igvn.replace_node(_callprojs.fallthrough_memproj, mem_phi);
2202 }
2203 
2204 //------------------------------expand_unlock_node----------------------
2205 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
2206 
2207   Node* ctrl = unlock->in(TypeFunc::Control);
2208   Node* mem = unlock->in(TypeFunc::Memory);
2209   Node* obj = unlock->obj_node();
2210   Node* box = unlock->box_node();
2211 
2212   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2213 
2214   // No need for a null check on unlock
2215 
2216   // Make the merge point
2217   Node *region;
2218   Node *mem_phi;
2219 
2220   region  = new RegionNode(3);
2221   // create a Phi for the memory state
2222   mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2223 
2224   FastUnlockNode *funlock = new FastUnlockNode( ctrl, obj, box );
2225   funlock = transform_later( funlock )->as_FastUnlock();
2226   // Optimize test; set region slot 2
2227   Node *slow_path = opt_bits_test(ctrl, region, 2, funlock, 0, 0);
2228   Node *thread = transform_later(new ThreadLocalNode());
2229 
2230   CallNode *call = make_slow_call((CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(),
2231                                   CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C),
2232                                   "complete_monitor_unlocking_C", slow_path, obj, box, thread);
2233 
2234   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2235   assert(_callprojs.fallthrough_ioproj == NULL && _callprojs.catchall_ioproj == NULL &&
2236          _callprojs.catchall_memproj == NULL && _callprojs.catchall_catchproj == NULL, "Unexpected projection from Lock");
2237 
2238   // No exceptions for unlocking
2239   // Capture slow path
2240   // disconnect fall-through projection from call and create a new one
2241   // hook up users of fall-through projection to region
2242   Node *slow_ctrl = _callprojs.fallthrough_proj->clone();
2243   transform_later(slow_ctrl);
2244   _igvn.hash_delete(_callprojs.fallthrough_proj);
2245   _callprojs.fallthrough_proj->disconnect_inputs(C);
2246   region->init_req(1, slow_ctrl);
2247   // region inputs are now complete
2248   transform_later(region);
2249   _igvn.replace_node(_callprojs.fallthrough_proj, region);
2250 
2251   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory) );
2252   mem_phi->init_req(1, memproj );
2253   mem_phi->init_req(2, mem);
2254   transform_later(mem_phi);
2255 
2256   _igvn.replace_node(_callprojs.fallthrough_memproj, mem_phi);
2257 }
2258 



















































































































































































































2259 void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) {
2260   assert(check->in(SubTypeCheckNode::Control) == NULL, "should be pinned");
2261   Node* bol = check->unique_out();
2262   Node* obj_or_subklass = check->in(SubTypeCheckNode::ObjOrSubKlass);
2263   Node* superklass = check->in(SubTypeCheckNode::SuperKlass);
2264   assert(bol->is_Bool() && bol->as_Bool()->_test._test == BoolTest::ne, "unexpected bool node");
2265 
2266   for (DUIterator_Last imin, i = bol->last_outs(imin); i >= imin; --i) {
2267     Node* iff = bol->last_out(i);
2268     assert(iff->is_If(), "where's the if?");
2269 
2270     if (iff->in(0)->is_top()) {
2271       _igvn.replace_input_of(iff, 1, C->top());
2272       continue;
2273     }
2274 
2275     Node* iftrue = iff->as_If()->proj_out(1);
2276     Node* iffalse = iff->as_If()->proj_out(0);
2277     Node* ctrl = iff->in(0);
2278 
2279     Node* subklass = NULL;
2280     if (_igvn.type(obj_or_subklass)->isa_klassptr()) {
2281       subklass = obj_or_subklass;
2282     } else {
2283       Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes());
2284       subklass = _igvn.transform(LoadKlassNode::make(_igvn, NULL, C->immutable_memory(), k_adr, TypeInstPtr::KLASS));
2285     }
2286 
2287     Node* not_subtype_ctrl = Phase::gen_subtype_check(subklass, superklass, &ctrl, NULL, _igvn);
2288 
2289     _igvn.replace_input_of(iff, 0, C->top());
2290     _igvn.replace_node(iftrue, not_subtype_ctrl);
2291     _igvn.replace_node(iffalse, ctrl);
2292   }
2293   _igvn.replace_node(check, C->top());
2294 }
2295 





































































































2296 //---------------------------eliminate_macro_nodes----------------------
2297 // Eliminate scalar replaced allocations and associated locks.
2298 void PhaseMacroExpand::eliminate_macro_nodes() {
2299   if (C->macro_count() == 0)
2300     return;
2301   NOT_PRODUCT(int membar_before = count_MemBar(C);)
2302 
2303   // Before elimination may re-mark (change to Nested or NonEscObj)
2304   // all associated (same box and obj) lock and unlock nodes.
2305   int cnt = C->macro_count();
2306   for (int i=0; i < cnt; i++) {
2307     Node *n = C->macro_node(i);
2308     if (n->is_AbstractLock()) { // Lock and Unlock nodes
2309       mark_eliminated_locking_nodes(n->as_AbstractLock());
2310     }
2311   }
2312   // Re-marking may break consistency of Coarsened locks.
2313   if (!C->coarsened_locks_consistent()) {
2314     return; // recompile without Coarsened locks if broken
2315   }

2336   }
2337   // Next, attempt to eliminate allocations
2338   _has_locks = false;
2339   progress = true;
2340   while (progress) {
2341     progress = false;
2342     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
2343       Node* n = C->macro_node(i - 1);
2344       bool success = false;
2345       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2346       switch (n->class_id()) {
2347       case Node::Class_Allocate:
2348       case Node::Class_AllocateArray:
2349         success = eliminate_allocate_node(n->as_Allocate());
2350 #ifndef PRODUCT
2351         if (success && PrintOptoStatistics) {
2352           Atomic::inc(&PhaseMacroExpand::_objs_scalar_replaced_counter);
2353         }
2354 #endif
2355         break;
2356       case Node::Class_CallStaticJava:
2357         success = eliminate_boxing_node(n->as_CallStaticJava());



2358         break;

2359       case Node::Class_Lock:
2360       case Node::Class_Unlock:
2361         assert(!n->as_AbstractLock()->is_eliminated(), "sanity");
2362         _has_locks = true;
2363         break;
2364       case Node::Class_ArrayCopy:
2365         break;
2366       case Node::Class_OuterStripMinedLoop:
2367         break;
2368       case Node::Class_SubTypeCheck:
2369         break;
2370       case Node::Class_Opaque1:
2371         break;


2372       default:
2373         assert(n->Opcode() == Op_LoopLimit ||
2374                n->Opcode() == Op_Opaque3   ||
2375                n->Opcode() == Op_Opaque4   ||
2376                BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
2377                "unknown node type in macro list");
2378       }
2379       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2380       progress = progress || success;
2381     }
2382   }
2383 #ifndef PRODUCT
2384   if (PrintOptoStatistics) {
2385     int membar_after = count_MemBar(C);
2386     Atomic::add(&PhaseMacroExpand::_memory_barriers_removed_counter, membar_before - membar_after);
2387   }
2388 #endif
2389 }
2390 
2391 //------------------------------expand_macro_nodes----------------------
2392 //  Returns true if a failure occurred.
2393 bool PhaseMacroExpand::expand_macro_nodes() {
2394   // Last attempt to eliminate macro nodes.
2395   eliminate_macro_nodes();
2396   if (C->failing())  return true;
2397 
2398   // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
2399   bool progress = true;
2400   while (progress) {
2401     progress = false;
2402     for (int i = C->macro_count(); i > 0; i--) {
2403       Node* n = C->macro_node(i-1);
2404       bool success = false;
2405       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2406       if (n->Opcode() == Op_LoopLimit) {
2407         // Remove it from macro list and put on IGVN worklist to optimize.
2408         C->remove_macro_node(n);
2409         _igvn._worklist.push(n);
2410         success = true;
2411       } else if (n->Opcode() == Op_CallStaticJava) {
2412         // Remove it from macro list and put on IGVN worklist to optimize.
2413         C->remove_macro_node(n);
2414         _igvn._worklist.push(n);
2415         success = true;



2416       } else if (n->is_Opaque1()) {
2417         _igvn.replace_node(n, n->in(1));
2418         success = true;
2419 #if INCLUDE_RTM_OPT
2420       } else if ((n->Opcode() == Op_Opaque3) && ((Opaque3Node*)n)->rtm_opt()) {
2421         assert(C->profile_rtm(), "should be used only in rtm deoptimization code");
2422         assert((n->outcnt() == 1) && n->unique_out()->is_Cmp(), "");
2423         Node* cmp = n->unique_out();
2424 #ifdef ASSERT
2425         // Validate graph.
2426         assert((cmp->outcnt() == 1) && cmp->unique_out()->is_Bool(), "");
2427         BoolNode* bol = cmp->unique_out()->as_Bool();
2428         assert((bol->outcnt() == 1) && bol->unique_out()->is_If() &&
2429                (bol->_test._test == BoolTest::ne), "");
2430         IfNode* ifn = bol->unique_out()->as_If();
2431         assert((ifn->outcnt() == 2) &&
2432                ifn->proj_out(1)->is_uncommon_trap_proj(Deoptimization::Reason_rtm_state_change) != NULL, "");
2433 #endif
2434         Node* repl = n->in(1);
2435         if (!_has_locks) {

2498     // Worst case is a macro node gets expanded into about 200 nodes.
2499     // Allow 50% more for optimization.
2500     if (C->check_node_count(300, "out of nodes before macro expansion")) {
2501       return true;
2502     }
2503 
2504     DEBUG_ONLY(int old_macro_count = C->macro_count();)
2505     switch (n->class_id()) {
2506     case Node::Class_Lock:
2507       expand_lock_node(n->as_Lock());
2508       break;
2509     case Node::Class_Unlock:
2510       expand_unlock_node(n->as_Unlock());
2511       break;
2512     case Node::Class_ArrayCopy:
2513       expand_arraycopy_node(n->as_ArrayCopy());
2514       break;
2515     case Node::Class_SubTypeCheck:
2516       expand_subtypecheck_node(n->as_SubTypeCheck());
2517       break;







2518     default:
2519       assert(false, "unknown node type in macro list");
2520     }
2521     assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2522     if (C->failing())  return true;
2523 
2524     // Clean up the graph so we're less likely to hit the maximum node
2525     // limit
2526     _igvn.set_delay_transform(false);
2527     _igvn.optimize();
2528     if (C->failing())  return true;
2529     _igvn.set_delay_transform(true);
2530   }
2531 
2532   // All nodes except Allocate nodes are expanded now. There could be
2533   // new optimization opportunities (such as folding newly created
2534   // load from a just allocated object). Run IGVN.
2535 
2536   // expand "macro" nodes
2537   // nodes are removed from the macro list as they are processed

   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "ci/ciFlatArrayKlass.hpp"
  27 #include "compiler/compileLog.hpp"
  28 #include "gc/shared/collectedHeap.inline.hpp"
  29 #include "gc/shared/tlab_globals.hpp"
  30 #include "libadt/vectset.hpp"
  31 #include "memory/universe.hpp"
  32 #include "opto/addnode.hpp"
  33 #include "opto/arraycopynode.hpp"
  34 #include "opto/callnode.hpp"
  35 #include "opto/castnode.hpp"
  36 #include "opto/cfgnode.hpp"
  37 #include "opto/compile.hpp"
  38 #include "opto/convertnode.hpp"
  39 #include "opto/graphKit.hpp"
  40 #include "opto/inlinetypenode.hpp"
  41 #include "opto/intrinsicnode.hpp"
  42 #include "opto/locknode.hpp"
  43 #include "opto/loopnode.hpp"
  44 #include "opto/macro.hpp"
  45 #include "opto/memnode.hpp"
  46 #include "opto/narrowptrnode.hpp"
  47 #include "opto/node.hpp"
  48 #include "opto/opaquenode.hpp"
  49 #include "opto/phaseX.hpp"
  50 #include "opto/rootnode.hpp"
  51 #include "opto/runtime.hpp"
  52 #include "opto/subnode.hpp"
  53 #include "opto/subtypenode.hpp"
  54 #include "opto/type.hpp"
  55 #include "prims/jvmtiExport.hpp"
  56 #include "runtime/continuation.hpp"
  57 #include "runtime/sharedRuntime.hpp"
  58 #include "runtime/stubRoutines.hpp"
  59 #include "utilities/macros.hpp"
  60 #include "utilities/powerOfTwo.hpp"
  61 #if INCLUDE_G1GC
  62 #include "gc/g1/g1ThreadLocalData.hpp"
  63 #endif // INCLUDE_G1GC
  64 
  65 
  66 //
  67 // Replace any references to "oldref" in inputs to "use" with "newref".
  68 // Returns the number of replacements made.
  69 //
  70 int PhaseMacroExpand::replace_input(Node *use, Node *oldref, Node *newref) {
  71   int nreplacements = 0;
  72   uint req = use->req();
  73   for (uint j = 0; j < use->len(); j++) {
  74     Node *uin = use->in(j);
  75     if (uin == oldref) {
  76       if (j < req)
  77         use->set_req(j, newref);
  78       else
  79         use->set_prec(j, newref);
  80       nreplacements++;
  81     } else if (j >= req && uin == NULL) {
  82       break;
  83     }
  84   }
  85   return nreplacements;
  86 }
  87 












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

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

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

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

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

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

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

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

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

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

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

 773   Node* res = alloc->result_cast();
 774   assert(res == NULL || res->is_CheckCastPP(), "unexpected AllocateNode result");
 775   const TypeOopPtr* res_type = NULL;
 776   if (res != NULL) { // Could be NULL when there are no users
 777     res_type = _igvn.type(res)->isa_oopptr();
 778   }
 779 
 780   if (res != NULL) {
 781     if (res_type->isa_instptr()) {
 782       // find the fields of the class which will be needed for safepoint debug information
 783       iklass = res_type->is_instptr()->instance_klass();
 784       nfields = iklass->nof_nonstatic_fields();
 785     } else {
 786       // find the array's elements which will be needed for safepoint debug information
 787       nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 788       assert(nfields >= 0, "must be an array klass.");
 789       basic_elem_type = res_type->is_aryptr()->elem()->array_element_basic_type();
 790       array_base = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
 791       element_size = type2aelembytes(basic_elem_type);
 792       field_type = res_type->is_aryptr()->elem();
 793       if (res_type->is_flat()) {
 794         // Flattened inline type array
 795         element_size = res_type->is_aryptr()->flat_elem_size();
 796       }
 797     }
 798   }
 799   //
 800   // Process the safepoint uses
 801   //
 802   assert(safepoints.length() == 0 || !res_type->is_inlinetypeptr(), "Inline type allocations should not have safepoint uses");
 803   Unique_Node_List value_worklist;
 804   while (safepoints.length() > 0) {
 805     SafePointNode* sfpt = safepoints.pop();
 806     Node* mem = sfpt->memory();
 807     Node* ctl = sfpt->control();
 808     assert(sfpt->jvms() != NULL, "missed JVMS");
 809     // Fields of scalar objs are referenced only at the end
 810     // of regular debuginfo at the last (youngest) JVMS.
 811     // Record relative start index.
 812     uint first_ind = (sfpt->req() - sfpt->jvms()->scloff());
 813     SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(res_type,
 814 #ifdef ASSERT
 815                                                  alloc,
 816 #endif
 817                                                  first_ind, nfields);
 818     sobj->init_req(0, C->root());
 819     transform_later(sobj);
 820 
 821     // Scan object's fields adding an input to the safepoint for each field.
 822     for (int j = 0; j < nfields; j++) {
 823       intptr_t offset;
 824       ciField* field = NULL;
 825       if (iklass != NULL) {
 826         field = iklass->nonstatic_field_at(j);
 827         offset = field->offset();
 828         ciType* elem_type = field->type();
 829         basic_elem_type = field->layout_type();
 830         assert(!field->is_flattened(), "flattened inline type fields should not have safepoint uses");
 831 
 832         // The next code is taken from Parse::do_get_xxx().
 833         if (is_reference_type(basic_elem_type)) {
 834           if (!elem_type->is_loaded()) {
 835             field_type = TypeInstPtr::BOTTOM;
 836           } else if (field != NULL && field->is_static_constant()) {
 837             ciObject* con = field->constant_value().as_object();
 838             // Do not "join" in the previous type; it doesn't add value,
 839             // and may yield a vacuous result if the field is of interface type.
 840             field_type = TypeOopPtr::make_from_constant(con)->isa_oopptr();
 841             assert(field_type != NULL, "field singleton type must be consistent");
 842           } else {
 843             field_type = TypeOopPtr::make_from_klass(elem_type->as_klass());
 844           }
 845           if (UseCompressedOops) {
 846             field_type = field_type->make_narrowoop();
 847             basic_elem_type = T_NARROWOOP;
 848           }
 849         } else {
 850           field_type = Type::get_const_basic_type(basic_elem_type);
 851         }
 852       } else {
 853         offset = array_base + j * (intptr_t)element_size;
 854       }
 855 
 856       Node* field_val = NULL;
 857       const TypeOopPtr* field_addr_type = res_type->add_offset(offset)->isa_oopptr();
 858       if (res_type->is_flat()) {
 859         ciInlineKlass* vk = res_type->is_aryptr()->elem()->inline_klass();
 860         assert(vk->flatten_array(), "must be flattened");
 861         field_val = inline_type_from_mem(mem, ctl, vk, field_addr_type->isa_aryptr(), 0, alloc);
 862       } else {
 863         field_val = value_from_mem(mem, ctl, basic_elem_type, field_type, field_addr_type, alloc);
 864       }
 865       if (field_val == NULL) {
 866         // We weren't able to find a value for this field,
 867         // give up on eliminating this allocation.
 868 
 869         // Remove any extra entries we added to the safepoint.
 870         uint last = sfpt->req() - 1;
 871         for (int k = 0;  k < j; k++) {
 872           sfpt->del_req(last--);
 873         }
 874         _igvn._worklist.push(sfpt);
 875         // rollback processed safepoints
 876         while (safepoints_done.length() > 0) {
 877           SafePointNode* sfpt_done = safepoints_done.pop();
 878           // remove any extra entries we added to the safepoint
 879           last = sfpt_done->req() - 1;
 880           for (int k = 0;  k < nfields; k++) {
 881             sfpt_done->del_req(last--);
 882           }
 883           JVMState *jvms = sfpt_done->jvms();
 884           jvms->set_endoff(sfpt_done->req());

 907             int field_idx = C->get_alias_index(field_addr_type);
 908             tty->print(" (alias_idx=%d)", field_idx);
 909           } else { // Array's element
 910             tty->print("=== At SafePoint node %d can't find value of array element [%d]",
 911                        sfpt->_idx, j);
 912           }
 913           tty->print(", which prevents elimination of: ");
 914           if (res == NULL)
 915             alloc->dump();
 916           else
 917             res->dump();
 918         }
 919 #endif
 920         return false;
 921       }
 922       if (UseCompressedOops && field_type->isa_narrowoop()) {
 923         // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation
 924         // to be able scalar replace the allocation.
 925         if (field_val->is_EncodeP()) {
 926           field_val = field_val->in(1);
 927         } else if (!field_val->is_InlineType()) {
 928           field_val = transform_later(new DecodeNNode(field_val, field_val->get_ptr_type()));
 929         }
 930       }
 931       if (field_val->is_InlineType()) {
 932         // Keep track of inline types to scalarize them later
 933         value_worklist.push(field_val);
 934       }
 935       sfpt->add_req(field_val);
 936     }
 937     JVMState *jvms = sfpt->jvms();
 938     jvms->set_endoff(sfpt->req());
 939     // Now make a pass over the debug information replacing any references
 940     // to the allocated object with "sobj"
 941     int start = jvms->debug_start();
 942     int end   = jvms->debug_end();
 943     sfpt->replace_edges_in_range(res, sobj, start, end, &_igvn);
 944     _igvn._worklist.push(sfpt);
 945     safepoints_done.append_if_missing(sfpt); // keep it for rollback
 946   }
 947   // Scalarize inline types that were added to the safepoint.
 948   // Don't allow linking a constant oop (if available) for flat array elements
 949   // because Deoptimization::reassign_flat_array_elements needs field values.
 950   bool allow_oop = (res_type != NULL) && !res_type->is_flat();
 951   for (uint i = 0; i < value_worklist.size(); ++i) {
 952     InlineTypeNode* vt = value_worklist.at(i)->as_InlineType();
 953     vt->make_scalar_in_safepoints(&_igvn, allow_oop);
 954   }
 955   return true;
 956 }
 957 
 958 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) {
 959   Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control);
 960   Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory);
 961   if (ctl_proj != NULL) {
 962     igvn.replace_node(ctl_proj, n->in(0));
 963   }
 964   if (mem_proj != NULL) {
 965     igvn.replace_node(mem_proj, n->in(TypeFunc::Memory));
 966   }
 967 }
 968 
 969 // Process users of eliminated allocation.
 970 void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc, bool inline_alloc) {
 971   Unique_Node_List worklist;
 972   Node* res = alloc->result_cast();
 973   if (res != NULL) {
 974     worklist.push(res);
 975   }
 976   while (worklist.size() > 0) {
 977     res = worklist.pop();
 978     for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
 979       Node *use = res->last_out(j);
 980       uint oc1 = res->outcnt();
 981 
 982       if (use->is_AddP()) {
 983         for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
 984           Node *n = use->last_out(k);
 985           uint oc2 = use->outcnt();
 986           if (n->is_Store()) {
 987             for (DUIterator_Fast pmax, p = n->fast_outs(pmax); p < pmax; p++) {
 988               MemBarNode* mb = n->fast_out(p)->isa_MemBar();
 989               if (mb != NULL && mb->req() <= MemBarNode::Precedent && mb->in(MemBarNode::Precedent) == n) {
 990                 // MemBarVolatiles should have been removed by MemBarNode::Ideal() for non-inline allocations
 991                 assert(inline_alloc, "MemBarVolatile should be eliminated for non-escaping object");
 992                 mb->remove(&_igvn);
 993               }



 994             }

 995             _igvn.replace_node(n, n->in(MemNode::Memory));
 996           } else {
 997             eliminate_gc_barrier(n);
 998           }
 999           k -= (oc2 - use->outcnt());
1000         }
1001         _igvn.remove_dead_node(use);
1002       } else if (use->is_ArrayCopy()) {
1003         // Disconnect ArrayCopy node
1004         ArrayCopyNode* ac = use->as_ArrayCopy();
1005         if (ac->is_clonebasic()) {
1006           Node* membar_after = ac->proj_out(TypeFunc::Control)->unique_ctrl_out();
1007           disconnect_projections(ac, _igvn);
1008           assert(alloc->in(TypeFunc::Memory)->is_Proj() && alloc->in(TypeFunc::Memory)->in(0)->Opcode() == Op_MemBarCPUOrder, "mem barrier expected before allocation");
1009           Node* membar_before = alloc->in(TypeFunc::Memory)->in(0);
1010           disconnect_projections(membar_before->as_MemBar(), _igvn);
1011           if (membar_after->is_MemBar()) {
1012             disconnect_projections(membar_after->as_MemBar(), _igvn);
1013           }
1014         } else {
1015           assert(ac->is_arraycopy_validated() ||
1016                  ac->is_copyof_validated() ||
1017                  ac->is_copyofrange_validated(), "unsupported");
1018           CallProjections* callprojs = ac->extract_projections(true);

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

1391         }
1392       }
1393 #endif
1394       yank_alloc_node(alloc);
1395       return;
1396     }
1397   }
1398 
1399   enum { too_big_or_final_path = 1, need_gc_path = 2 };
1400   Node *slow_region = NULL;
1401   Node *toobig_false = ctrl;
1402 
1403   // generate the initial test if necessary
1404   if (initial_slow_test != NULL ) {
1405     assert (expand_fast_path, "Only need test if there is a fast path");
1406     slow_region = new RegionNode(3);
1407 
1408     // Now make the initial failure test.  Usually a too-big test but
1409     // might be a TRUE for finalizers or a fancy class check for
1410     // newInstance0.
1411     IfNode* toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1412     transform_later(toobig_iff);
1413     // Plug the failing-too-big test into the slow-path region
1414     Node* toobig_true = new IfTrueNode(toobig_iff);
1415     transform_later(toobig_true);
1416     slow_region    ->init_req( too_big_or_final_path, toobig_true );
1417     toobig_false = new IfFalseNode(toobig_iff);
1418     transform_later(toobig_false);
1419   } else {
1420     // No initial test, just fall into next case
1421     assert(allocation_has_use || !expand_fast_path, "Should already have been handled");
1422     toobig_false = ctrl;
1423     debug_only(slow_region = NodeSentinel);
1424   }
1425 
1426   // If we are here there are several possibilities
1427   // - expand_fast_path is false - then only a slow path is expanded. That's it.
1428   // no_initial_check means a constant allocation.
1429   // - If check always evaluates to false -> expand_fast_path is false (see above)
1430   // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath)
1431   // if !allocation_has_use the fast path is empty
1432   // if !allocation_has_use && no_initial_check
1433   // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all.
1434   //   removed by yank_alloc_node above.
1435 
1436   Node *slow_mem = mem;  // save the current memory state for slow path
1437   // generate the fast allocation code unless we know that the initial test will always go slow
1438   if (expand_fast_path) {
1439     // Fast path modifies only raw memory.
1440     if (mem->is_MergeMem()) {
1441       mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1442     }
1443 
1444     // allocate the Region and Phi nodes for the result
1445     result_region = new RegionNode(3);
1446     result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1447     result_phi_i_o    = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1448 
1449     // Grab regular I/O before optional prefetch may change it.
1450     // Slow-path does no I/O so just set it to the original I/O.
1451     result_phi_i_o->init_req(slow_result_path, i_o);
1452 
1453     // Name successful fast-path variables
1454     Node* fast_oop_ctrl;
1455     Node* fast_oop_rawmem;
1456 
1457     if (allocation_has_use) {
1458       Node* needgc_ctrl = NULL;
1459       result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1460 
1461       intx prefetch_lines = length != NULL ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1462       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1463       Node* fast_oop = bs->obj_allocate(this, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1464                                         fast_oop_ctrl, fast_oop_rawmem,
1465                                         prefetch_lines);
1466 
1467       if (initial_slow_test != NULL) {
1468         // This completes all paths into the slow merge point
1469         slow_region->init_req(need_gc_path, needgc_ctrl);
1470         transform_later(slow_region);
1471       } else {
1472         // No initial slow path needed!
1473         // Just fall from the need-GC path straight into the VM call.
1474         slow_region = needgc_ctrl;
1475       }
1476 

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

1775     Node* thread = new ThreadLocalNode();
1776     transform_later(thread);
1777 
1778     call->init_req(TypeFunc::Parms + 0, thread);
1779     call->init_req(TypeFunc::Parms + 1, oop);
1780     call->init_req(TypeFunc::Control, ctrl);
1781     call->init_req(TypeFunc::I_O    , top()); // does no i/o
1782     call->init_req(TypeFunc::Memory , rawmem);
1783     call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1784     call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1785     transform_later(call);
1786     ctrl = new ProjNode(call, TypeFunc::Control);
1787     transform_later(ctrl);
1788     rawmem = new ProjNode(call, TypeFunc::Memory);
1789     transform_later(rawmem);
1790   }
1791 }
1792 
1793 // Helper for PhaseMacroExpand::expand_allocate_common.
1794 // Initializes the newly-allocated storage.
1795 Node* PhaseMacroExpand::initialize_object(AllocateNode* alloc,
1796                                           Node* control, Node* rawmem, Node* object,
1797                                           Node* klass_node, Node* length,
1798                                           Node* size_in_bytes) {

1799   InitializeNode* init = alloc->initialization();
1800   // Store the klass & mark bits
1801   Node* mark_node = alloc->make_ideal_mark(&_igvn, control, rawmem);
1802   if (!mark_node->is_Con()) {
1803     transform_later(mark_node);
1804   }
1805   rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
1806 
1807   rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
1808   int header_size = alloc->minimum_header_size();  // conservatively small
1809 
1810   // Array length
1811   if (length != NULL) {         // Arrays need length field
1812     rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1813     // conservatively small header size:
1814     header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1815     if (_igvn.type(klass_node)->isa_aryklassptr()) {   // we know the exact header size in most cases:
1816       BasicType elem = _igvn.type(klass_node)->is_klassptr()->as_instance_type()->isa_aryptr()->elem()->array_element_basic_type();
1817       if (is_reference_type(elem, true)) {
1818         elem = T_OBJECT;
1819       }
1820       header_size = Klass::layout_helper_header_size(Klass::array_layout_helper(elem));
1821     }
1822   }
1823 
1824   // Clear the object body, if necessary.
1825   if (init == NULL) {
1826     // The init has somehow disappeared; be cautious and clear everything.
1827     //
1828     // This can happen if a node is allocated but an uncommon trap occurs
1829     // immediately.  In this case, the Initialize gets associated with the
1830     // trap, and may be placed in a different (outer) loop, if the Allocate
1831     // is in a loop.  If (this is rare) the inner loop gets unrolled, then
1832     // there can be two Allocates to one Initialize.  The answer in all these
1833     // edge cases is safety first.  It is always safe to clear immediately
1834     // within an Allocate, and then (maybe or maybe not) clear some more later.
1835     if (!(UseTLAB && ZeroTLAB)) {
1836       rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
1837                                             alloc->in(AllocateNode::DefaultValue),
1838                                             alloc->in(AllocateNode::RawDefaultValue),
1839                                             header_size, size_in_bytes,
1840                                             &_igvn);
1841     }
1842   } else {
1843     if (!init->is_complete()) {
1844       // Try to win by zeroing only what the init does not store.
1845       // We can also try to do some peephole optimizations,
1846       // such as combining some adjacent subword stores.
1847       rawmem = init->complete_stores(control, rawmem, object,
1848                                      header_size, size_in_bytes, &_igvn);
1849     }
1850     // We have no more use for this link, since the AllocateNode goes away:
1851     init->set_req(InitializeNode::RawAddress, top());
1852     // (If we keep the link, it just confuses the register allocator,
1853     // who thinks he sees a real use of the address by the membar.)
1854   }
1855 
1856   return rawmem;
1857 }
1858 

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

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

2842   }
2843   // Next, attempt to eliminate allocations
2844   _has_locks = false;
2845   progress = true;
2846   while (progress) {
2847     progress = false;
2848     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
2849       Node* n = C->macro_node(i - 1);
2850       bool success = false;
2851       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2852       switch (n->class_id()) {
2853       case Node::Class_Allocate:
2854       case Node::Class_AllocateArray:
2855         success = eliminate_allocate_node(n->as_Allocate());
2856 #ifndef PRODUCT
2857         if (success && PrintOptoStatistics) {
2858           Atomic::inc(&PhaseMacroExpand::_objs_scalar_replaced_counter);
2859         }
2860 #endif
2861         break;
2862       case Node::Class_CallStaticJava: {
2863         CallStaticJavaNode* call = n->as_CallStaticJava();
2864         if (!call->method()->is_method_handle_intrinsic()) {
2865           success = eliminate_boxing_node(n->as_CallStaticJava());
2866         }
2867         break;
2868       }
2869       case Node::Class_Lock:
2870       case Node::Class_Unlock:
2871         assert(!n->as_AbstractLock()->is_eliminated(), "sanity");
2872         _has_locks = true;
2873         break;
2874       case Node::Class_ArrayCopy:
2875         break;
2876       case Node::Class_OuterStripMinedLoop:
2877         break;
2878       case Node::Class_SubTypeCheck:
2879         break;
2880       case Node::Class_Opaque1:
2881         break;
2882       case Node::Class_FlatArrayCheck:
2883         break;
2884       default:
2885         assert(n->Opcode() == Op_LoopLimit ||
2886                n->Opcode() == Op_Opaque3   ||
2887                n->Opcode() == Op_Opaque4   ||
2888                BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
2889                "unknown node type in macro list");
2890       }
2891       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2892       progress = progress || success;
2893     }
2894   }
2895 #ifndef PRODUCT
2896   if (PrintOptoStatistics) {
2897     int membar_after = count_MemBar(C);
2898     Atomic::add(&PhaseMacroExpand::_memory_barriers_removed_counter, membar_before - membar_after);
2899   }
2900 #endif
2901 }
2902 
2903 //------------------------------expand_macro_nodes----------------------
2904 //  Returns true if a failure occurred.
2905 bool PhaseMacroExpand::expand_macro_nodes() {
2906   // Last attempt to eliminate macro nodes.
2907   eliminate_macro_nodes();
2908   if (C->failing())  return true;
2909 
2910   // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
2911   bool progress = true;
2912   while (progress) {
2913     progress = false;
2914     for (int i = C->macro_count(); i > 0; i--) {
2915       Node* n = C->macro_node(i-1);
2916       bool success = false;
2917       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2918       if (n->Opcode() == Op_LoopLimit) {
2919         // Remove it from macro list and put on IGVN worklist to optimize.
2920         C->remove_macro_node(n);
2921         _igvn._worklist.push(n);
2922         success = true;
2923       } else if (n->Opcode() == Op_CallStaticJava) {
2924         CallStaticJavaNode* call = n->as_CallStaticJava();
2925         if (!call->method()->is_method_handle_intrinsic()) {
2926           // Remove it from macro list and put on IGVN worklist to optimize.
2927           C->remove_macro_node(n);
2928           _igvn._worklist.push(n);
2929           success = true;
2930         }
2931       } else if (n->is_Opaque1()) {
2932         _igvn.replace_node(n, n->in(1));
2933         success = true;
2934 #if INCLUDE_RTM_OPT
2935       } else if ((n->Opcode() == Op_Opaque3) && ((Opaque3Node*)n)->rtm_opt()) {
2936         assert(C->profile_rtm(), "should be used only in rtm deoptimization code");
2937         assert((n->outcnt() == 1) && n->unique_out()->is_Cmp(), "");
2938         Node* cmp = n->unique_out();
2939 #ifdef ASSERT
2940         // Validate graph.
2941         assert((cmp->outcnt() == 1) && cmp->unique_out()->is_Bool(), "");
2942         BoolNode* bol = cmp->unique_out()->as_Bool();
2943         assert((bol->outcnt() == 1) && bol->unique_out()->is_If() &&
2944                (bol->_test._test == BoolTest::ne), "");
2945         IfNode* ifn = bol->unique_out()->as_If();
2946         assert((ifn->outcnt() == 2) &&
2947                ifn->proj_out(1)->is_uncommon_trap_proj(Deoptimization::Reason_rtm_state_change) != NULL, "");
2948 #endif
2949         Node* repl = n->in(1);
2950         if (!_has_locks) {

3013     // Worst case is a macro node gets expanded into about 200 nodes.
3014     // Allow 50% more for optimization.
3015     if (C->check_node_count(300, "out of nodes before macro expansion")) {
3016       return true;
3017     }
3018 
3019     DEBUG_ONLY(int old_macro_count = C->macro_count();)
3020     switch (n->class_id()) {
3021     case Node::Class_Lock:
3022       expand_lock_node(n->as_Lock());
3023       break;
3024     case Node::Class_Unlock:
3025       expand_unlock_node(n->as_Unlock());
3026       break;
3027     case Node::Class_ArrayCopy:
3028       expand_arraycopy_node(n->as_ArrayCopy());
3029       break;
3030     case Node::Class_SubTypeCheck:
3031       expand_subtypecheck_node(n->as_SubTypeCheck());
3032       break;
3033     case Node::Class_CallStaticJava:
3034       expand_mh_intrinsic_return(n->as_CallStaticJava());
3035       C->remove_macro_node(n);
3036       break;
3037     case Node::Class_FlatArrayCheck:
3038       expand_flatarraycheck_node(n->as_FlatArrayCheck());
3039       break;
3040     default:
3041       assert(false, "unknown node type in macro list");
3042     }
3043     assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
3044     if (C->failing())  return true;
3045 
3046     // Clean up the graph so we're less likely to hit the maximum node
3047     // limit
3048     _igvn.set_delay_transform(false);
3049     _igvn.optimize();
3050     if (C->failing())  return true;
3051     _igvn.set_delay_transform(true);
3052   }
3053 
3054   // All nodes except Allocate nodes are expanded now. There could be
3055   // new optimization opportunities (such as folding newly created
3056   // load from a just allocated object). Run IGVN.
3057 
3058   // expand "macro" nodes
3059   // nodes are removed from the macro list as they are processed
< prev index next >