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