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