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