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