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