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