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