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