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