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