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