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