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