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