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