1 /*
   2  * Copyright (c) 1997, 2016, 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 "classfile/systemDictionary.hpp"
  27 #include "compiler/compileLog.hpp"
  28 #include "memory/allocation.inline.hpp"
  29 #include "memory/resourceArea.hpp"
  30 #include "oops/objArrayKlass.hpp"
  31 #include "opto/addnode.hpp"
  32 #include "opto/arraycopynode.hpp"
  33 #include "opto/cfgnode.hpp"
  34 #include "opto/compile.hpp"
  35 #include "opto/connode.hpp"
  36 #include "opto/convertnode.hpp"
  37 #include "opto/loopnode.hpp"
  38 #include "opto/machnode.hpp"
  39 #include "opto/matcher.hpp"
  40 #include "opto/memnode.hpp"
  41 #include "opto/mulnode.hpp"
  42 #include "opto/narrowptrnode.hpp"
  43 #include "opto/phaseX.hpp"
  44 #include "opto/regmask.hpp"
  45 #include "utilities/copy.hpp"
  46 
  47 // Portions of code courtesy of Clifford Click
  48 
  49 // Optimization - Graph Style
  50 
  51 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem,  const TypePtr *tp, const TypePtr *adr_check, outputStream *st);
  52 
  53 //=============================================================================
  54 uint MemNode::size_of() const { return sizeof(*this); }
  55 
  56 const TypePtr *MemNode::adr_type() const {
  57   Node* adr = in(Address);
  58   if (adr == NULL)  return NULL; // node is dead
  59   const TypePtr* cross_check = NULL;
  60   DEBUG_ONLY(cross_check = _adr_type);
  61   return calculate_adr_type(adr->bottom_type(), cross_check);
  62 }
  63 
  64 #ifndef PRODUCT
  65 void MemNode::dump_spec(outputStream *st) const {
  66   if (in(Address) == NULL)  return; // node is dead
  67 #ifndef ASSERT
  68   // fake the missing field
  69   const TypePtr* _adr_type = NULL;
  70   if (in(Address) != NULL)
  71     _adr_type = in(Address)->bottom_type()->isa_ptr();
  72 #endif
  73   dump_adr_type(this, _adr_type, st);
  74 
  75   Compile* C = Compile::current();
  76   if (C->alias_type(_adr_type)->is_volatile()) {
  77     st->print(" Volatile!");
  78   }
  79   if (_unaligned_access) {
  80     st->print(" unaligned");
  81   }
  82   if (_mismatched_access) {
  83     st->print(" mismatched");
  84   }
  85 }
  86 
  87 void MemNode::dump_adr_type(const Node* mem, const TypePtr* adr_type, outputStream *st) {
  88   st->print(" @");
  89   if (adr_type == NULL) {
  90     st->print("NULL");
  91   } else {
  92     adr_type->dump_on(st);
  93     Compile* C = Compile::current();
  94     Compile::AliasType* atp = NULL;
  95     if (C->have_alias_type(adr_type))  atp = C->alias_type(adr_type);
  96     if (atp == NULL)
  97       st->print(", idx=?\?;");
  98     else if (atp->index() == Compile::AliasIdxBot)
  99       st->print(", idx=Bot;");
 100     else if (atp->index() == Compile::AliasIdxTop)
 101       st->print(", idx=Top;");
 102     else if (atp->index() == Compile::AliasIdxRaw)
 103       st->print(", idx=Raw;");
 104     else {
 105       ciField* field = atp->field();
 106       if (field) {
 107         st->print(", name=");
 108         field->print_name_on(st);
 109       }
 110       st->print(", idx=%d;", atp->index());
 111     }
 112   }
 113 }
 114 
 115 extern void print_alias_types();
 116 
 117 #endif
 118 
 119 Node *MemNode::optimize_simple_memory_chain(Node *mchain, const TypeOopPtr *t_oop, Node *load, PhaseGVN *phase) {
 120   assert((t_oop != NULL), "sanity");
 121   bool is_instance = t_oop->is_known_instance_field();
 122   bool is_boxed_value_load = t_oop->is_ptr_to_boxed_value() &&
 123                              (load != NULL) && load->is_Load() &&
 124                              (phase->is_IterGVN() != NULL);
 125   if (!(is_instance || is_boxed_value_load))
 126     return mchain;  // don't try to optimize non-instance types
 127   uint instance_id = t_oop->instance_id();
 128   Node *start_mem = phase->C->start()->proj_out(TypeFunc::Memory);
 129   Node *prev = NULL;
 130   Node *result = mchain;
 131   while (prev != result) {
 132     prev = result;
 133     if (result == start_mem)
 134       break;  // hit one of our sentinels
 135     // skip over a call which does not affect this memory slice
 136     if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
 137       Node *proj_in = result->in(0);
 138       if (proj_in->is_Allocate() && proj_in->_idx == instance_id) {
 139         break;  // hit one of our sentinels
 140       } else if (proj_in->is_Call()) {
 141         // ArrayCopyNodes processed here as well
 142         CallNode *call = proj_in->as_Call();
 143         if (!call->may_modify(t_oop, phase)) { // returns false for instances
 144           result = call->in(TypeFunc::Memory);
 145         }
 146       } else if (proj_in->is_Initialize()) {
 147         AllocateNode* alloc = proj_in->as_Initialize()->allocation();
 148         // Stop if this is the initialization for the object instance which
 149         // contains this memory slice, otherwise skip over it.
 150         if ((alloc == NULL) || (alloc->_idx == instance_id)) {
 151           break;
 152         }
 153         if (is_instance) {
 154           result = proj_in->in(TypeFunc::Memory);
 155         } else if (is_boxed_value_load) {
 156           Node* klass = alloc->in(AllocateNode::KlassNode);
 157           const TypeKlassPtr* tklass = phase->type(klass)->is_klassptr();
 158           if (tklass->klass_is_exact() && !tklass->klass()->equals(t_oop->klass())) {
 159             result = proj_in->in(TypeFunc::Memory); // not related allocation
 160           }
 161         }
 162       } else if (proj_in->is_MemBar()) {
 163         ArrayCopyNode* ac = NULL;
 164         if (ArrayCopyNode::may_modify(t_oop, proj_in->as_MemBar(), phase, ac)) {
 165           break;
 166         }
 167         result = proj_in->in(TypeFunc::Memory);
 168       } else {
 169         assert(false, "unexpected projection");
 170       }
 171     } else if (result->is_ClearArray()) {
 172       if (!is_instance || !ClearArrayNode::step_through(&result, instance_id, phase)) {
 173         // Can not bypass initialization of the instance
 174         // we are looking for.
 175         break;
 176       }
 177       // Otherwise skip it (the call updated 'result' value).
 178     } else if (result->is_MergeMem()) {
 179       result = step_through_mergemem(phase, result->as_MergeMem(), t_oop, NULL, tty);
 180     }
 181   }
 182   return result;
 183 }
 184 
 185 Node *MemNode::optimize_memory_chain(Node *mchain, const TypePtr *t_adr, Node *load, PhaseGVN *phase) {
 186   const TypeOopPtr* t_oop = t_adr->isa_oopptr();
 187   if (t_oop == NULL)
 188     return mchain;  // don't try to optimize non-oop types
 189   Node* result = optimize_simple_memory_chain(mchain, t_oop, load, phase);
 190   bool is_instance = t_oop->is_known_instance_field();
 191   PhaseIterGVN *igvn = phase->is_IterGVN();
 192   if (is_instance && igvn != NULL  && result->is_Phi()) {
 193     PhiNode *mphi = result->as_Phi();
 194     assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
 195     const TypePtr *t = mphi->adr_type();
 196     if (t == TypePtr::BOTTOM || t == TypeRawPtr::BOTTOM ||
 197         t->isa_oopptr() && !t->is_oopptr()->is_known_instance() &&
 198         t->is_oopptr()->cast_to_exactness(true)
 199          ->is_oopptr()->cast_to_ptr_type(t_oop->ptr())
 200          ->is_oopptr()->cast_to_instance_id(t_oop->instance_id()) == t_oop) {
 201       // clone the Phi with our address type
 202       result = mphi->split_out_instance(t_adr, igvn);
 203     } else {
 204       assert(phase->C->get_alias_index(t) == phase->C->get_alias_index(t_adr), "correct memory chain");
 205     }
 206   }
 207   return result;
 208 }
 209 
 210 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem,  const TypePtr *tp, const TypePtr *adr_check, outputStream *st) {
 211   uint alias_idx = phase->C->get_alias_index(tp);
 212   Node *mem = mmem;
 213 #ifdef ASSERT
 214   {
 215     // Check that current type is consistent with the alias index used during graph construction
 216     assert(alias_idx >= Compile::AliasIdxRaw, "must not be a bad alias_idx");
 217     bool consistent =  adr_check == NULL || adr_check->empty() ||
 218                        phase->C->must_alias(adr_check, alias_idx );
 219     // Sometimes dead array references collapse to a[-1], a[-2], or a[-3]
 220     if( !consistent && adr_check != NULL && !adr_check->empty() &&
 221                tp->isa_aryptr() &&        tp->offset() == Type::OffsetBot &&
 222         adr_check->isa_aryptr() && adr_check->offset() != Type::OffsetBot &&
 223         ( adr_check->offset() == arrayOopDesc::length_offset_in_bytes() ||
 224           adr_check->offset() == oopDesc::klass_offset_in_bytes() ||
 225           adr_check->offset() == oopDesc::mark_offset_in_bytes() ) ) {
 226       // don't assert if it is dead code.
 227       consistent = true;
 228     }
 229     if( !consistent ) {
 230       st->print("alias_idx==%d, adr_check==", alias_idx);
 231       if( adr_check == NULL ) {
 232         st->print("NULL");
 233       } else {
 234         adr_check->dump();
 235       }
 236       st->cr();
 237       print_alias_types();
 238       assert(consistent, "adr_check must match alias idx");
 239     }
 240   }
 241 #endif
 242   // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally
 243   // means an array I have not precisely typed yet.  Do not do any
 244   // alias stuff with it any time soon.
 245   const TypeOopPtr *toop = tp->isa_oopptr();
 246   if( tp->base() != Type::AnyPtr &&
 247       !(toop &&
 248         toop->klass() != NULL &&
 249         toop->klass()->is_java_lang_Object() &&
 250         toop->offset() == Type::OffsetBot) ) {
 251     // compress paths and change unreachable cycles to TOP
 252     // If not, we can update the input infinitely along a MergeMem cycle
 253     // Equivalent code in PhiNode::Ideal
 254     Node* m  = phase->transform(mmem);
 255     // If transformed to a MergeMem, get the desired slice
 256     // Otherwise the returned node represents memory for every slice
 257     mem = (m->is_MergeMem())? m->as_MergeMem()->memory_at(alias_idx) : m;
 258     // Update input if it is progress over what we have now
 259   }
 260   return mem;
 261 }
 262 
 263 //--------------------------Ideal_common---------------------------------------
 264 // Look for degenerate control and memory inputs.  Bypass MergeMem inputs.
 265 // Unhook non-raw memories from complete (macro-expanded) initializations.
 266 Node *MemNode::Ideal_common(PhaseGVN *phase, bool can_reshape) {
 267   // If our control input is a dead region, kill all below the region
 268   Node *ctl = in(MemNode::Control);
 269   if (ctl && remove_dead_region(phase, can_reshape))
 270     return this;
 271   ctl = in(MemNode::Control);
 272   // Don't bother trying to transform a dead node
 273   if (ctl && ctl->is_top())  return NodeSentinel;
 274 
 275   PhaseIterGVN *igvn = phase->is_IterGVN();
 276   // Wait if control on the worklist.
 277   if (ctl && can_reshape && igvn != NULL) {
 278     Node* bol = NULL;
 279     Node* cmp = NULL;
 280     if (ctl->in(0)->is_If()) {
 281       assert(ctl->is_IfTrue() || ctl->is_IfFalse(), "sanity");
 282       bol = ctl->in(0)->in(1);
 283       if (bol->is_Bool())
 284         cmp = ctl->in(0)->in(1)->in(1);
 285     }
 286     if (igvn->_worklist.member(ctl) ||
 287         (bol != NULL && igvn->_worklist.member(bol)) ||
 288         (cmp != NULL && igvn->_worklist.member(cmp)) ) {
 289       // This control path may be dead.
 290       // Delay this memory node transformation until the control is processed.
 291       phase->is_IterGVN()->_worklist.push(this);
 292       return NodeSentinel; // caller will return NULL
 293     }
 294   }
 295   // Ignore if memory is dead, or self-loop
 296   Node *mem = in(MemNode::Memory);
 297   if (phase->type( mem ) == Type::TOP) return NodeSentinel; // caller will return NULL
 298   assert(mem != this, "dead loop in MemNode::Ideal");
 299 
 300   if (can_reshape && igvn != NULL && igvn->_worklist.member(mem)) {
 301     // This memory slice may be dead.
 302     // Delay this mem node transformation until the memory is processed.
 303     phase->is_IterGVN()->_worklist.push(this);
 304     return NodeSentinel; // caller will return NULL
 305   }
 306 
 307   Node *address = in(MemNode::Address);
 308   const Type *t_adr = phase->type(address);
 309   if (t_adr == Type::TOP)              return NodeSentinel; // caller will return NULL
 310 
 311   if (can_reshape && igvn != NULL &&
 312       (igvn->_worklist.member(address) ||
 313        igvn->_worklist.size() > 0 && (t_adr != adr_type())) ) {
 314     // The address's base and type may change when the address is processed.
 315     // Delay this mem node transformation until the address is processed.
 316     phase->is_IterGVN()->_worklist.push(this);
 317     return NodeSentinel; // caller will return NULL
 318   }
 319 
 320   // Do NOT remove or optimize the next lines: ensure a new alias index
 321   // is allocated for an oop pointer type before Escape Analysis.
 322   // Note: C++ will not remove it since the call has side effect.
 323   if (t_adr->isa_oopptr()) {
 324     int alias_idx = phase->C->get_alias_index(t_adr->is_ptr());
 325   }
 326 
 327   Node* base = NULL;
 328   if (address->is_AddP()) {
 329     base = address->in(AddPNode::Base);
 330   }
 331   if (base != NULL && phase->type(base)->higher_equal(TypePtr::NULL_PTR) &&
 332       !t_adr->isa_rawptr()) {
 333     // Note: raw address has TOP base and top->higher_equal(TypePtr::NULL_PTR) is true.
 334     // Skip this node optimization if its address has TOP base.
 335     return NodeSentinel; // caller will return NULL
 336   }
 337 
 338   // Avoid independent memory operations
 339   Node* old_mem = mem;
 340 
 341   // The code which unhooks non-raw memories from complete (macro-expanded)
 342   // initializations was removed. After macro-expansion all stores catched
 343   // by Initialize node became raw stores and there is no information
 344   // which memory slices they modify. So it is unsafe to move any memory
 345   // operation above these stores. Also in most cases hooked non-raw memories
 346   // were already unhooked by using information from detect_ptr_independence()
 347   // and find_previous_store().
 348 
 349   if (mem->is_MergeMem()) {
 350     MergeMemNode* mmem = mem->as_MergeMem();
 351     const TypePtr *tp = t_adr->is_ptr();
 352 
 353     mem = step_through_mergemem(phase, mmem, tp, adr_type(), tty);
 354   }
 355 
 356   if (mem != old_mem) {
 357     set_req(MemNode::Memory, mem);
 358     if (can_reshape && old_mem->outcnt() == 0) {
 359         igvn->_worklist.push(old_mem);
 360     }
 361     if (phase->type( mem ) == Type::TOP) return NodeSentinel;
 362     return this;
 363   }
 364 
 365   // let the subclass continue analyzing...
 366   return NULL;
 367 }
 368 
 369 // Helper function for proving some simple control dominations.
 370 // Attempt to prove that all control inputs of 'dom' dominate 'sub'.
 371 // Already assumes that 'dom' is available at 'sub', and that 'sub'
 372 // is not a constant (dominated by the method's StartNode).
 373 // Used by MemNode::find_previous_store to prove that the
 374 // control input of a memory operation predates (dominates)
 375 // an allocation it wants to look past.
 376 bool MemNode::all_controls_dominate(Node* dom, Node* sub) {
 377   if (dom == NULL || dom->is_top() || sub == NULL || sub->is_top())
 378     return false; // Conservative answer for dead code
 379 
 380   // Check 'dom'. Skip Proj and CatchProj nodes.
 381   dom = dom->find_exact_control(dom);
 382   if (dom == NULL || dom->is_top())
 383     return false; // Conservative answer for dead code
 384 
 385   if (dom == sub) {
 386     // For the case when, for example, 'sub' is Initialize and the original
 387     // 'dom' is Proj node of the 'sub'.
 388     return false;
 389   }
 390 
 391   if (dom->is_Con() || dom->is_Start() || dom->is_Root() || dom == sub)
 392     return true;
 393 
 394   // 'dom' dominates 'sub' if its control edge and control edges
 395   // of all its inputs dominate or equal to sub's control edge.
 396 
 397   // Currently 'sub' is either Allocate, Initialize or Start nodes.
 398   // Or Region for the check in LoadNode::Ideal();
 399   // 'sub' should have sub->in(0) != NULL.
 400   assert(sub->is_Allocate() || sub->is_Initialize() || sub->is_Start() ||
 401          sub->is_Region() || sub->is_Call(), "expecting only these nodes");
 402 
 403   // Get control edge of 'sub'.
 404   Node* orig_sub = sub;
 405   sub = sub->find_exact_control(sub->in(0));
 406   if (sub == NULL || sub->is_top())
 407     return false; // Conservative answer for dead code
 408 
 409   assert(sub->is_CFG(), "expecting control");
 410 
 411   if (sub == dom)
 412     return true;
 413 
 414   if (sub->is_Start() || sub->is_Root())
 415     return false;
 416 
 417   {
 418     // Check all control edges of 'dom'.
 419 
 420     ResourceMark rm;
 421     Arena* arena = Thread::current()->resource_area();
 422     Node_List nlist(arena);
 423     Unique_Node_List dom_list(arena);
 424 
 425     dom_list.push(dom);
 426     bool only_dominating_controls = false;
 427 
 428     for (uint next = 0; next < dom_list.size(); next++) {
 429       Node* n = dom_list.at(next);
 430       if (n == orig_sub)
 431         return false; // One of dom's inputs dominated by sub.
 432       if (!n->is_CFG() && n->pinned()) {
 433         // Check only own control edge for pinned non-control nodes.
 434         n = n->find_exact_control(n->in(0));
 435         if (n == NULL || n->is_top())
 436           return false; // Conservative answer for dead code
 437         assert(n->is_CFG(), "expecting control");
 438         dom_list.push(n);
 439       } else if (n->is_Con() || n->is_Start() || n->is_Root()) {
 440         only_dominating_controls = true;
 441       } else if (n->is_CFG()) {
 442         if (n->dominates(sub, nlist))
 443           only_dominating_controls = true;
 444         else
 445           return false;
 446       } else {
 447         // First, own control edge.
 448         Node* m = n->find_exact_control(n->in(0));
 449         if (m != NULL) {
 450           if (m->is_top())
 451             return false; // Conservative answer for dead code
 452           dom_list.push(m);
 453         }
 454         // Now, the rest of edges.
 455         uint cnt = n->req();
 456         for (uint i = 1; i < cnt; i++) {
 457           m = n->find_exact_control(n->in(i));
 458           if (m == NULL || m->is_top())
 459             continue;
 460           dom_list.push(m);
 461         }
 462       }
 463     }
 464     return only_dominating_controls;
 465   }
 466 }
 467 
 468 //---------------------detect_ptr_independence---------------------------------
 469 // Used by MemNode::find_previous_store to prove that two base
 470 // pointers are never equal.
 471 // The pointers are accompanied by their associated allocations,
 472 // if any, which have been previously discovered by the caller.
 473 bool MemNode::detect_ptr_independence(Node* p1, AllocateNode* a1,
 474                                       Node* p2, AllocateNode* a2,
 475                                       PhaseTransform* phase) {
 476   // Attempt to prove that these two pointers cannot be aliased.
 477   // They may both manifestly be allocations, and they should differ.
 478   // Or, if they are not both allocations, they can be distinct constants.
 479   // Otherwise, one is an allocation and the other a pre-existing value.
 480   if (a1 == NULL && a2 == NULL) {           // neither an allocation
 481     return (p1 != p2) && p1->is_Con() && p2->is_Con();
 482   } else if (a1 != NULL && a2 != NULL) {    // both allocations
 483     return (a1 != a2);
 484   } else if (a1 != NULL) {                  // one allocation a1
 485     // (Note:  p2->is_Con implies p2->in(0)->is_Root, which dominates.)
 486     return all_controls_dominate(p2, a1);
 487   } else { //(a2 != NULL)                   // one allocation a2
 488     return all_controls_dominate(p1, a2);
 489   }
 490   return false;
 491 }
 492 
 493 
 494 // Find an arraycopy that must have set (can_see_stored_value=true) or
 495 // could have set (can_see_stored_value=false) the value for this load
 496 Node* LoadNode::find_previous_arraycopy(PhaseTransform* phase, Node* ld_alloc, Node*& mem, bool can_see_stored_value) const {
 497   if (mem->is_Proj() && mem->in(0) != NULL && (mem->in(0)->Opcode() == Op_MemBarStoreStore ||
 498                                                mem->in(0)->Opcode() == Op_MemBarCPUOrder)) {
 499     Node* mb = mem->in(0);
 500     if (mb->in(0) != NULL && mb->in(0)->is_Proj() &&
 501         mb->in(0)->in(0) != NULL && mb->in(0)->in(0)->is_ArrayCopy()) {
 502       ArrayCopyNode* ac = mb->in(0)->in(0)->as_ArrayCopy();
 503       if (ac->is_clonebasic()) {
 504         intptr_t offset;
 505         AllocateNode* alloc = AllocateNode::Ideal_allocation(ac->in(ArrayCopyNode::Dest), phase, offset);
 506         assert(alloc != NULL && (!ReduceBulkZeroing || alloc->initialization()->is_complete_with_arraycopy()), "broken allocation");
 507         if (alloc == ld_alloc) {
 508           return ac;
 509         }
 510       }
 511     }
 512   } else if (mem->is_Proj() && mem->in(0) != NULL && mem->in(0)->is_ArrayCopy()) {
 513     ArrayCopyNode* ac = mem->in(0)->as_ArrayCopy();
 514 
 515     if (ac->is_arraycopy_validated() ||
 516         ac->is_copyof_validated() ||
 517         ac->is_copyofrange_validated()) {
 518       Node* ld_addp = in(MemNode::Address);
 519       if (ld_addp->is_AddP()) {
 520         Node* ld_base = ld_addp->in(AddPNode::Address);
 521         Node* ld_offs = ld_addp->in(AddPNode::Offset);
 522 
 523         Node* dest = ac->in(ArrayCopyNode::Dest);
 524 
 525         if (dest == ld_base) {
 526           const TypeX *ld_offs_t = phase->type(ld_offs)->isa_intptr_t();
 527           if (ac->modifies(ld_offs_t->_lo, ld_offs_t->_hi, phase, can_see_stored_value)) {
 528             return ac;
 529           }
 530           if (!can_see_stored_value) {
 531             mem = ac->in(TypeFunc::Memory);
 532           }
 533         }
 534       }
 535     }
 536   }
 537   return NULL;
 538 }
 539 
 540 // The logic for reordering loads and stores uses four steps:
 541 // (a) Walk carefully past stores and initializations which we
 542 //     can prove are independent of this load.
 543 // (b) Observe that the next memory state makes an exact match
 544 //     with self (load or store), and locate the relevant store.
 545 // (c) Ensure that, if we were to wire self directly to the store,
 546 //     the optimizer would fold it up somehow.
 547 // (d) Do the rewiring, and return, depending on some other part of
 548 //     the optimizer to fold up the load.
 549 // This routine handles steps (a) and (b).  Steps (c) and (d) are
 550 // specific to loads and stores, so they are handled by the callers.
 551 // (Currently, only LoadNode::Ideal has steps (c), (d).  More later.)
 552 //
 553 Node* MemNode::find_previous_store(PhaseTransform* phase) {
 554   Node*         ctrl   = in(MemNode::Control);
 555   Node*         adr    = in(MemNode::Address);
 556   intptr_t      offset = 0;
 557   Node*         base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
 558   AllocateNode* alloc  = AllocateNode::Ideal_allocation(base, phase);
 559 
 560   if (offset == Type::OffsetBot)
 561     return NULL;            // cannot unalias unless there are precise offsets
 562 
 563   const TypeOopPtr *addr_t = adr->bottom_type()->isa_oopptr();
 564 
 565   intptr_t size_in_bytes = memory_size();
 566 
 567   Node* mem = in(MemNode::Memory);   // start searching here...
 568 
 569   int cnt = 50;             // Cycle limiter
 570   for (;;) {                // While we can dance past unrelated stores...
 571     if (--cnt < 0)  break;  // Caught in cycle or a complicated dance?
 572 
 573     Node* prev = mem;
 574     if (mem->is_Store()) {
 575       Node* st_adr = mem->in(MemNode::Address);
 576       intptr_t st_offset = 0;
 577       Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_offset);
 578       if (st_base == NULL)
 579         break;              // inscrutable pointer
 580       if (st_offset != offset && st_offset != Type::OffsetBot) {
 581         const int MAX_STORE = BytesPerLong;
 582         if (st_offset >= offset + size_in_bytes ||
 583             st_offset <= offset - MAX_STORE ||
 584             st_offset <= offset - mem->as_Store()->memory_size()) {
 585           // Success:  The offsets are provably independent.
 586           // (You may ask, why not just test st_offset != offset and be done?
 587           // The answer is that stores of different sizes can co-exist
 588           // in the same sequence of RawMem effects.  We sometimes initialize
 589           // a whole 'tile' of array elements with a single jint or jlong.)
 590           mem = mem->in(MemNode::Memory);
 591           continue;           // (a) advance through independent store memory
 592         }
 593       }
 594       if (st_base != base &&
 595           detect_ptr_independence(base, alloc,
 596                                   st_base,
 597                                   AllocateNode::Ideal_allocation(st_base, phase),
 598                                   phase)) {
 599         // Success:  The bases are provably independent.
 600         mem = mem->in(MemNode::Memory);
 601         continue;           // (a) advance through independent store memory
 602       }
 603 
 604       // (b) At this point, if the bases or offsets do not agree, we lose,
 605       // since we have not managed to prove 'this' and 'mem' independent.
 606       if (st_base == base && st_offset == offset) {
 607         return mem;         // let caller handle steps (c), (d)
 608       }
 609 
 610     } else if (mem->is_Proj() && mem->in(0)->is_Initialize()) {
 611       InitializeNode* st_init = mem->in(0)->as_Initialize();
 612       AllocateNode*  st_alloc = st_init->allocation();
 613       if (st_alloc == NULL)
 614         break;              // something degenerated
 615       bool known_identical = false;
 616       bool known_independent = false;
 617       if (alloc == st_alloc)
 618         known_identical = true;
 619       else if (alloc != NULL)
 620         known_independent = true;
 621       else if (all_controls_dominate(this, st_alloc))
 622         known_independent = true;
 623 
 624       if (known_independent) {
 625         // The bases are provably independent: Either they are
 626         // manifestly distinct allocations, or else the control
 627         // of this load dominates the store's allocation.
 628         int alias_idx = phase->C->get_alias_index(adr_type());
 629         if (alias_idx == Compile::AliasIdxRaw) {
 630           mem = st_alloc->in(TypeFunc::Memory);
 631         } else {
 632           mem = st_init->memory(alias_idx);
 633         }
 634         continue;           // (a) advance through independent store memory
 635       }
 636 
 637       // (b) at this point, if we are not looking at a store initializing
 638       // the same allocation we are loading from, we lose.
 639       if (known_identical) {
 640         // From caller, can_see_stored_value will consult find_captured_store.
 641         return mem;         // let caller handle steps (c), (d)
 642       }
 643 
 644     } else if (find_previous_arraycopy(phase, alloc, mem, false) != NULL) {
 645       if (prev != mem) {
 646         // Found an arraycopy but it doesn't affect that load
 647         continue;
 648       }
 649       // Found an arraycopy that may affect that load
 650       return mem;
 651     } else if (addr_t != NULL && addr_t->is_known_instance_field()) {
 652       // Can't use optimize_simple_memory_chain() since it needs PhaseGVN.
 653       if (mem->is_Proj() && mem->in(0)->is_Call()) {
 654         // ArrayCopyNodes processed here as well.
 655         CallNode *call = mem->in(0)->as_Call();
 656         if (!call->may_modify(addr_t, phase)) {
 657           mem = call->in(TypeFunc::Memory);
 658           continue;         // (a) advance through independent call memory
 659         }
 660       } else if (mem->is_Proj() && mem->in(0)->is_MemBar()) {
 661         ArrayCopyNode* ac = NULL;
 662         if (ArrayCopyNode::may_modify(addr_t, mem->in(0)->as_MemBar(), phase, ac)) {
 663           break;
 664         }
 665         mem = mem->in(0)->in(TypeFunc::Memory);
 666         continue;           // (a) advance through independent MemBar memory
 667       } else if (mem->is_ClearArray()) {
 668         if (ClearArrayNode::step_through(&mem, (uint)addr_t->instance_id(), phase)) {
 669           // (the call updated 'mem' value)
 670           continue;         // (a) advance through independent allocation memory
 671         } else {
 672           // Can not bypass initialization of the instance
 673           // we are looking for.
 674           return mem;
 675         }
 676       } else if (mem->is_MergeMem()) {
 677         int alias_idx = phase->C->get_alias_index(adr_type());
 678         mem = mem->as_MergeMem()->memory_at(alias_idx);
 679         continue;           // (a) advance through independent MergeMem memory
 680       }
 681     }
 682 
 683     // Unless there is an explicit 'continue', we must bail out here,
 684     // because 'mem' is an inscrutable memory state (e.g., a call).
 685     break;
 686   }
 687 
 688   return NULL;              // bail out
 689 }
 690 
 691 //----------------------calculate_adr_type-------------------------------------
 692 // Helper function.  Notices when the given type of address hits top or bottom.
 693 // Also, asserts a cross-check of the type against the expected address type.
 694 const TypePtr* MemNode::calculate_adr_type(const Type* t, const TypePtr* cross_check) {
 695   if (t == Type::TOP)  return NULL; // does not touch memory any more?
 696   #ifdef PRODUCT
 697   cross_check = NULL;
 698   #else
 699   if (!VerifyAliases || is_error_reported() || Node::in_dump())  cross_check = NULL;
 700   #endif
 701   const TypePtr* tp = t->isa_ptr();
 702   if (tp == NULL) {
 703     assert(cross_check == NULL || cross_check == TypePtr::BOTTOM, "expected memory type must be wide");
 704     return TypePtr::BOTTOM;           // touches lots of memory
 705   } else {
 706     #ifdef ASSERT
 707     // %%%% [phh] We don't check the alias index if cross_check is
 708     //            TypeRawPtr::BOTTOM.  Needs to be investigated.
 709     if (cross_check != NULL &&
 710         cross_check != TypePtr::BOTTOM &&
 711         cross_check != TypeRawPtr::BOTTOM) {
 712       // Recheck the alias index, to see if it has changed (due to a bug).
 713       Compile* C = Compile::current();
 714       assert(C->get_alias_index(cross_check) == C->get_alias_index(tp),
 715              "must stay in the original alias category");
 716       // The type of the address must be contained in the adr_type,
 717       // disregarding "null"-ness.
 718       // (We make an exception for TypeRawPtr::BOTTOM, which is a bit bucket.)
 719       const TypePtr* tp_notnull = tp->join(TypePtr::NOTNULL)->is_ptr();
 720       assert(cross_check->meet(tp_notnull) == cross_check->remove_speculative(),
 721              "real address must not escape from expected memory type");
 722     }
 723     #endif
 724     return tp;
 725   }
 726 }
 727 
 728 //=============================================================================
 729 // Should LoadNode::Ideal() attempt to remove control edges?
 730 bool LoadNode::can_remove_control() const {
 731   return true;
 732 }
 733 uint LoadNode::size_of() const { return sizeof(*this); }
 734 uint LoadNode::cmp( const Node &n ) const
 735 { return !Type::cmp( _type, ((LoadNode&)n)._type ); }
 736 const Type *LoadNode::bottom_type() const { return _type; }
 737 uint LoadNode::ideal_reg() const {
 738   return _type->ideal_reg();
 739 }
 740 
 741 #ifndef PRODUCT
 742 void LoadNode::dump_spec(outputStream *st) const {
 743   MemNode::dump_spec(st);
 744   if( !Verbose && !WizardMode ) {
 745     // standard dump does this in Verbose and WizardMode
 746     st->print(" #"); _type->dump_on(st);
 747   }
 748   if (!depends_only_on_test()) {
 749     st->print(" (does not depend only on test)");
 750   }
 751 }
 752 #endif
 753 
 754 #ifdef ASSERT
 755 //----------------------------is_immutable_value-------------------------------
 756 // Helper function to allow a raw load without control edge for some cases
 757 bool LoadNode::is_immutable_value(Node* adr) {
 758   return (adr->is_AddP() && adr->in(AddPNode::Base)->is_top() &&
 759           adr->in(AddPNode::Address)->Opcode() == Op_ThreadLocal &&
 760           (adr->in(AddPNode::Offset)->find_intptr_t_con(-1) ==
 761            in_bytes(JavaThread::osthread_offset())));
 762 }
 763 #endif
 764 
 765 //----------------------------LoadNode::make-----------------------------------
 766 // Polymorphic factory method:
 767 Node *LoadNode::make(PhaseGVN& gvn, Node *ctl, Node *mem, Node *adr, const TypePtr* adr_type, const Type *rt, BasicType bt, MemOrd mo,
 768                      ControlDependency control_dependency, bool unaligned, bool mismatched) {
 769   Compile* C = gvn.C;
 770 
 771   // sanity check the alias category against the created node type
 772   assert(!(adr_type->isa_oopptr() &&
 773            adr_type->offset() == oopDesc::klass_offset_in_bytes()),
 774          "use LoadKlassNode instead");
 775   assert(!(adr_type->isa_aryptr() &&
 776            adr_type->offset() == arrayOopDesc::length_offset_in_bytes()),
 777          "use LoadRangeNode instead");
 778   // Check control edge of raw loads
 779   assert( ctl != NULL || C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
 780           // oop will be recorded in oop map if load crosses safepoint
 781           rt->isa_oopptr() || is_immutable_value(adr),
 782           "raw memory operations should have control edge");
 783   LoadNode* load = NULL;
 784   switch (bt) {
 785   case T_BOOLEAN: load = new LoadUBNode(ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 786   case T_BYTE:    load = new LoadBNode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 787   case T_INT:     load = new LoadINode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 788   case T_CHAR:    load = new LoadUSNode(ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 789   case T_SHORT:   load = new LoadSNode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 790   case T_LONG:    load = new LoadLNode (ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency); break;
 791   case T_FLOAT:   load = new LoadFNode (ctl, mem, adr, adr_type, rt,            mo, control_dependency); break;
 792   case T_DOUBLE:  load = new LoadDNode (ctl, mem, adr, adr_type, rt,            mo, control_dependency); break;
 793   case T_ADDRESS: load = new LoadPNode (ctl, mem, adr, adr_type, rt->is_ptr(),  mo, control_dependency); break;
 794   case T_OBJECT:
 795 #ifdef _LP64
 796     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 797       load = new LoadNNode(ctl, mem, adr, adr_type, rt->make_narrowoop(), mo, control_dependency);
 798     } else
 799 #endif
 800     {
 801       assert(!adr->bottom_type()->is_ptr_to_narrowoop() && !adr->bottom_type()->is_ptr_to_narrowklass(), "should have got back a narrow oop");
 802       load = new LoadPNode(ctl, mem, adr, adr_type, rt->is_ptr(), mo, control_dependency);
 803     }
 804     break;
 805   }
 806   assert(load != NULL, "LoadNode should have been created");
 807   if (unaligned) {
 808     load->set_unaligned_access();
 809   }
 810   if (mismatched) {
 811     load->set_mismatched_access();
 812   }
 813   if (load->Opcode() == Op_LoadN) {
 814     Node* ld = gvn.transform(load);
 815     return new DecodeNNode(ld, ld->bottom_type()->make_ptr());
 816   }
 817 
 818   return load;
 819 }
 820 
 821 LoadLNode* LoadLNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, MemOrd mo,
 822                                   ControlDependency control_dependency, bool unaligned, bool mismatched) {
 823   bool require_atomic = true;
 824   LoadLNode* load = new LoadLNode(ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency, require_atomic);
 825   if (unaligned) {
 826     load->set_unaligned_access();
 827   }
 828   if (mismatched) {
 829     load->set_mismatched_access();
 830   }
 831   return load;
 832 }
 833 
 834 LoadDNode* LoadDNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, MemOrd mo,
 835                                   ControlDependency control_dependency, bool unaligned, bool mismatched) {
 836   bool require_atomic = true;
 837   LoadDNode* load = new LoadDNode(ctl, mem, adr, adr_type, rt, mo, control_dependency, require_atomic);
 838   if (unaligned) {
 839     load->set_unaligned_access();
 840   }
 841   if (mismatched) {
 842     load->set_mismatched_access();
 843   }
 844   return load;
 845 }
 846 
 847 
 848 
 849 //------------------------------hash-------------------------------------------
 850 uint LoadNode::hash() const {
 851   // unroll addition of interesting fields
 852   return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address);
 853 }
 854 
 855 static bool skip_through_membars(Compile::AliasType* atp, const TypeInstPtr* tp, bool eliminate_boxing) {
 856   if ((atp != NULL) && (atp->index() >= Compile::AliasIdxRaw)) {
 857     bool non_volatile = (atp->field() != NULL) && !atp->field()->is_volatile();
 858     bool is_stable_ary = FoldStableValues &&
 859                          (tp != NULL) && (tp->isa_aryptr() != NULL) &&
 860                          tp->isa_aryptr()->is_stable();
 861 
 862     return (eliminate_boxing && non_volatile) || is_stable_ary;
 863   }
 864 
 865   return false;
 866 }
 867 
 868 // Is the value loaded previously stored by an arraycopy? If so return
 869 // a load node that reads from the source array so we may be able to
 870 // optimize out the ArrayCopy node later.
 871 Node* LoadNode::can_see_arraycopy_value(Node* st, PhaseTransform* phase) const {
 872   Node* ld_adr = in(MemNode::Address);
 873   intptr_t ld_off = 0;
 874   AllocateNode* ld_alloc = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off);
 875   Node* ac = find_previous_arraycopy(phase, ld_alloc, st, true);
 876   if (ac != NULL) {
 877     assert(ac->is_ArrayCopy(), "what kind of node can this be?");
 878 
 879     Node* ld = clone();
 880     if (ac->as_ArrayCopy()->is_clonebasic()) {
 881       assert(ld_alloc != NULL, "need an alloc");
 882       Node* addp = in(MemNode::Address)->clone();
 883       assert(addp->is_AddP(), "address must be addp");
 884       assert(addp->in(AddPNode::Base) == ac->in(ArrayCopyNode::Dest)->in(AddPNode::Base), "strange pattern");
 885       assert(addp->in(AddPNode::Address) == ac->in(ArrayCopyNode::Dest)->in(AddPNode::Address), "strange pattern");
 886       addp->set_req(AddPNode::Base, ac->in(ArrayCopyNode::Src)->in(AddPNode::Base));
 887       addp->set_req(AddPNode::Address, ac->in(ArrayCopyNode::Src)->in(AddPNode::Address));
 888       ld->set_req(MemNode::Address, phase->transform(addp));
 889       if (in(0) != NULL) {
 890         assert(ld_alloc->in(0) != NULL, "alloc must have control");
 891         ld->set_req(0, ld_alloc->in(0));
 892       }
 893     } else {
 894       Node* addp = in(MemNode::Address)->clone();
 895       assert(addp->in(AddPNode::Base) == addp->in(AddPNode::Address), "should be");
 896       addp->set_req(AddPNode::Base, ac->in(ArrayCopyNode::Src));
 897       addp->set_req(AddPNode::Address, ac->in(ArrayCopyNode::Src));
 898 
 899       const TypeAryPtr* ary_t = phase->type(in(MemNode::Address))->isa_aryptr();
 900       BasicType ary_elem  = ary_t->klass()->as_array_klass()->element_type()->basic_type();
 901       uint header = arrayOopDesc::base_offset_in_bytes(ary_elem);
 902       uint shift  = exact_log2(type2aelembytes(ary_elem));
 903 
 904       Node* diff = phase->transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
 905 #ifdef _LP64
 906       diff = phase->transform(new ConvI2LNode(diff));
 907 #endif
 908       diff = phase->transform(new LShiftXNode(diff, phase->intcon(shift)));
 909 
 910       Node* offset = phase->transform(new AddXNode(addp->in(AddPNode::Offset), diff));
 911       addp->set_req(AddPNode::Offset, offset);
 912       ld->set_req(MemNode::Address, phase->transform(addp));
 913 
 914       if (in(0) != NULL) {
 915         assert(ac->in(0) != NULL, "alloc must have control");
 916         ld->set_req(0, ac->in(0));
 917       }
 918     }
 919     // load depends on the tests that validate the arraycopy
 920     ld->as_Load()->_control_dependency = Pinned;
 921     return ld;
 922   }
 923   return NULL;
 924 }
 925 
 926 
 927 //---------------------------can_see_stored_value------------------------------
 928 // This routine exists to make sure this set of tests is done the same
 929 // everywhere.  We need to make a coordinated change: first LoadNode::Ideal
 930 // will change the graph shape in a way which makes memory alive twice at the
 931 // same time (uses the Oracle model of aliasing), then some
 932 // LoadXNode::Identity will fold things back to the equivalence-class model
 933 // of aliasing.
 934 Node* MemNode::can_see_stored_value(Node* st, PhaseTransform* phase) const {
 935   Node* ld_adr = in(MemNode::Address);
 936   intptr_t ld_off = 0;
 937   AllocateNode* ld_alloc = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off);
 938   const TypeInstPtr* tp = phase->type(ld_adr)->isa_instptr();
 939   Compile::AliasType* atp = (tp != NULL) ? phase->C->alias_type(tp) : NULL;
 940   // This is more general than load from boxing objects.
 941   if (skip_through_membars(atp, tp, phase->C->eliminate_boxing())) {
 942     uint alias_idx = atp->index();
 943     bool final = !atp->is_rewritable();
 944     Node* result = NULL;
 945     Node* current = st;
 946     // Skip through chains of MemBarNodes checking the MergeMems for
 947     // new states for the slice of this load.  Stop once any other
 948     // kind of node is encountered.  Loads from final memory can skip
 949     // through any kind of MemBar but normal loads shouldn't skip
 950     // through MemBarAcquire since the could allow them to move out of
 951     // a synchronized region.
 952     while (current->is_Proj()) {
 953       int opc = current->in(0)->Opcode();
 954       if ((final && (opc == Op_MemBarAcquire ||
 955                      opc == Op_MemBarAcquireLock ||
 956                      opc == Op_LoadFence)) ||
 957           opc == Op_MemBarRelease ||
 958           opc == Op_StoreFence ||
 959           opc == Op_MemBarReleaseLock ||
 960           opc == Op_MemBarStoreStore ||
 961           opc == Op_MemBarCPUOrder) {
 962         Node* mem = current->in(0)->in(TypeFunc::Memory);
 963         if (mem->is_MergeMem()) {
 964           MergeMemNode* merge = mem->as_MergeMem();
 965           Node* new_st = merge->memory_at(alias_idx);
 966           if (new_st == merge->base_memory()) {
 967             // Keep searching
 968             current = new_st;
 969             continue;
 970           }
 971           // Save the new memory state for the slice and fall through
 972           // to exit.
 973           result = new_st;
 974         }
 975       }
 976       break;
 977     }
 978     if (result != NULL) {
 979       st = result;
 980     }
 981   }
 982 
 983   // Loop around twice in the case Load -> Initialize -> Store.
 984   // (See PhaseIterGVN::add_users_to_worklist, which knows about this case.)
 985   for (int trip = 0; trip <= 1; trip++) {
 986 
 987     if (st->is_Store()) {
 988       Node* st_adr = st->in(MemNode::Address);
 989       if (!phase->eqv(st_adr, ld_adr)) {
 990         // Try harder before giving up...  Match raw and non-raw pointers.
 991         intptr_t st_off = 0;
 992         AllocateNode* alloc = AllocateNode::Ideal_allocation(st_adr, phase, st_off);
 993         if (alloc == NULL)       return NULL;
 994         if (alloc != ld_alloc)   return NULL;
 995         if (ld_off != st_off)    return NULL;
 996         // At this point we have proven something like this setup:
 997         //  A = Allocate(...)
 998         //  L = LoadQ(,  AddP(CastPP(, A.Parm),, #Off))
 999         //  S = StoreQ(, AddP(,        A.Parm  , #Off), V)
1000         // (Actually, we haven't yet proven the Q's are the same.)
1001         // In other words, we are loading from a casted version of
1002         // the same pointer-and-offset that we stored to.
1003         // Thus, we are able to replace L by V.
1004       }
1005       // Now prove that we have a LoadQ matched to a StoreQ, for some Q.
1006       if (store_Opcode() != st->Opcode())
1007         return NULL;
1008       return st->in(MemNode::ValueIn);
1009     }
1010 
1011     // A load from a freshly-created object always returns zero.
1012     // (This can happen after LoadNode::Ideal resets the load's memory input
1013     // to find_captured_store, which returned InitializeNode::zero_memory.)
1014     if (st->is_Proj() && st->in(0)->is_Allocate() &&
1015         (st->in(0) == ld_alloc) &&
1016         (ld_off >= st->in(0)->as_Allocate()->minimum_header_size())) {
1017       // return a zero value for the load's basic type
1018       // (This is one of the few places where a generic PhaseTransform
1019       // can create new nodes.  Think of it as lazily manifesting
1020       // virtually pre-existing constants.)
1021       return phase->zerocon(memory_type());
1022     }
1023 
1024     // A load from an initialization barrier can match a captured store.
1025     if (st->is_Proj() && st->in(0)->is_Initialize()) {
1026       InitializeNode* init = st->in(0)->as_Initialize();
1027       AllocateNode* alloc = init->allocation();
1028       if ((alloc != NULL) && (alloc == ld_alloc)) {
1029         // examine a captured store value
1030         st = init->find_captured_store(ld_off, memory_size(), phase);
1031         if (st != NULL) {
1032           continue;             // take one more trip around
1033         }
1034       }
1035     }
1036 
1037     // Load boxed value from result of valueOf() call is input parameter.
1038     if (this->is_Load() && ld_adr->is_AddP() &&
1039         (tp != NULL) && tp->is_ptr_to_boxed_value()) {
1040       intptr_t ignore = 0;
1041       Node* base = AddPNode::Ideal_base_and_offset(ld_adr, phase, ignore);
1042       if (base != NULL && base->is_Proj() &&
1043           base->as_Proj()->_con == TypeFunc::Parms &&
1044           base->in(0)->is_CallStaticJava() &&
1045           base->in(0)->as_CallStaticJava()->is_boxing_method()) {
1046         return base->in(0)->in(TypeFunc::Parms);
1047       }
1048     }
1049 
1050     break;
1051   }
1052 
1053   return NULL;
1054 }
1055 
1056 //----------------------is_instance_field_load_with_local_phi------------------
1057 bool LoadNode::is_instance_field_load_with_local_phi(Node* ctrl) {
1058   if( in(Memory)->is_Phi() && in(Memory)->in(0) == ctrl &&
1059       in(Address)->is_AddP() ) {
1060     const TypeOopPtr* t_oop = in(Address)->bottom_type()->isa_oopptr();
1061     // Only instances and boxed values.
1062     if( t_oop != NULL &&
1063         (t_oop->is_ptr_to_boxed_value() ||
1064          t_oop->is_known_instance_field()) &&
1065         t_oop->offset() != Type::OffsetBot &&
1066         t_oop->offset() != Type::OffsetTop) {
1067       return true;
1068     }
1069   }
1070   return false;
1071 }
1072 
1073 //------------------------------Identity---------------------------------------
1074 // Loads are identity if previous store is to same address
1075 Node* LoadNode::Identity(PhaseGVN* phase) {
1076   // If the previous store-maker is the right kind of Store, and the store is
1077   // to the same address, then we are equal to the value stored.
1078   Node* mem = in(Memory);
1079   Node* value = can_see_stored_value(mem, phase);
1080   if( value ) {
1081     // byte, short & char stores truncate naturally.
1082     // A load has to load the truncated value which requires
1083     // some sort of masking operation and that requires an
1084     // Ideal call instead of an Identity call.
1085     if (memory_size() < BytesPerInt) {
1086       // If the input to the store does not fit with the load's result type,
1087       // it must be truncated via an Ideal call.
1088       if (!phase->type(value)->higher_equal(phase->type(this)))
1089         return this;
1090     }
1091     // (This works even when value is a Con, but LoadNode::Value
1092     // usually runs first, producing the singleton type of the Con.)
1093     return value;
1094   }
1095 
1096   // Search for an existing data phi which was generated before for the same
1097   // instance's field to avoid infinite generation of phis in a loop.
1098   Node *region = mem->in(0);
1099   if (is_instance_field_load_with_local_phi(region)) {
1100     const TypeOopPtr *addr_t = in(Address)->bottom_type()->isa_oopptr();
1101     int this_index  = phase->C->get_alias_index(addr_t);
1102     int this_offset = addr_t->offset();
1103     int this_iid    = addr_t->instance_id();
1104     if (!addr_t->is_known_instance() &&
1105          addr_t->is_ptr_to_boxed_value()) {
1106       // Use _idx of address base (could be Phi node) for boxed values.
1107       intptr_t   ignore = 0;
1108       Node*      base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore);
1109       this_iid = base->_idx;
1110     }
1111     const Type* this_type = bottom_type();
1112     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1113       Node* phi = region->fast_out(i);
1114       if (phi->is_Phi() && phi != mem &&
1115           phi->as_Phi()->is_same_inst_field(this_type, this_iid, this_index, this_offset)) {
1116         return phi;
1117       }
1118     }
1119   }
1120 
1121   return this;
1122 }
1123 
1124 // Construct an equivalent unsigned load.
1125 Node* LoadNode::convert_to_unsigned_load(PhaseGVN& gvn) {
1126   BasicType bt = T_ILLEGAL;
1127   const Type* rt = NULL;
1128   switch (Opcode()) {
1129     case Op_LoadUB: return this;
1130     case Op_LoadUS: return this;
1131     case Op_LoadB: bt = T_BOOLEAN; rt = TypeInt::UBYTE; break;
1132     case Op_LoadS: bt = T_CHAR;    rt = TypeInt::CHAR;  break;
1133     default:
1134       assert(false, "no unsigned variant: %s", Name());
1135       return NULL;
1136   }
1137   return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1138                         raw_adr_type(), rt, bt, _mo, _control_dependency,
1139                         is_unaligned_access(), is_mismatched_access());
1140 }
1141 
1142 // Construct an equivalent signed load.
1143 Node* LoadNode::convert_to_signed_load(PhaseGVN& gvn) {
1144   BasicType bt = T_ILLEGAL;
1145   const Type* rt = NULL;
1146   switch (Opcode()) {
1147     case Op_LoadUB: bt = T_BYTE;  rt = TypeInt::BYTE;  break;
1148     case Op_LoadUS: bt = T_SHORT; rt = TypeInt::SHORT; break;
1149     case Op_LoadB: // fall through
1150     case Op_LoadS: // fall through
1151     case Op_LoadI: // fall through
1152     case Op_LoadL: return this;
1153     default:
1154       assert(false, "no signed variant: %s", Name());
1155       return NULL;
1156   }
1157   return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1158                         raw_adr_type(), rt, bt, _mo, _control_dependency,
1159                         is_unaligned_access(), is_mismatched_access());
1160 }
1161 
1162 // We're loading from an object which has autobox behaviour.
1163 // If this object is result of a valueOf call we'll have a phi
1164 // merging a newly allocated object and a load from the cache.
1165 // We want to replace this load with the original incoming
1166 // argument to the valueOf call.
1167 Node* LoadNode::eliminate_autobox(PhaseGVN* phase) {
1168   assert(phase->C->eliminate_boxing(), "sanity");
1169   intptr_t ignore = 0;
1170   Node* base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore);
1171   if ((base == NULL) || base->is_Phi()) {
1172     // Push the loads from the phi that comes from valueOf up
1173     // through it to allow elimination of the loads and the recovery
1174     // of the original value. It is done in split_through_phi().
1175     return NULL;
1176   } else if (base->is_Load() ||
1177              base->is_DecodeN() && base->in(1)->is_Load()) {
1178     // Eliminate the load of boxed value for integer types from the cache
1179     // array by deriving the value from the index into the array.
1180     // Capture the offset of the load and then reverse the computation.
1181 
1182     // Get LoadN node which loads a boxing object from 'cache' array.
1183     if (base->is_DecodeN()) {
1184       base = base->in(1);
1185     }
1186     if (!base->in(Address)->is_AddP()) {
1187       return NULL; // Complex address
1188     }
1189     AddPNode* address = base->in(Address)->as_AddP();
1190     Node* cache_base = address->in(AddPNode::Base);
1191     if ((cache_base != NULL) && cache_base->is_DecodeN()) {
1192       // Get ConP node which is static 'cache' field.
1193       cache_base = cache_base->in(1);
1194     }
1195     if ((cache_base != NULL) && cache_base->is_Con()) {
1196       const TypeAryPtr* base_type = cache_base->bottom_type()->isa_aryptr();
1197       if ((base_type != NULL) && base_type->is_autobox_cache()) {
1198         Node* elements[4];
1199         int shift = exact_log2(type2aelembytes(T_OBJECT));
1200         int count = address->unpack_offsets(elements, ARRAY_SIZE(elements));
1201         if ((count >  0) && elements[0]->is_Con() &&
1202             ((count == 1) ||
1203              (count == 2) && elements[1]->Opcode() == Op_LShiftX &&
1204                              elements[1]->in(2) == phase->intcon(shift))) {
1205           ciObjArray* array = base_type->const_oop()->as_obj_array();
1206           // Fetch the box object cache[0] at the base of the array and get its value
1207           ciInstance* box = array->obj_at(0)->as_instance();
1208           ciInstanceKlass* ik = box->klass()->as_instance_klass();
1209           assert(ik->is_box_klass(), "sanity");
1210           assert(ik->nof_nonstatic_fields() == 1, "change following code");
1211           if (ik->nof_nonstatic_fields() == 1) {
1212             // This should be true nonstatic_field_at requires calling
1213             // nof_nonstatic_fields so check it anyway
1214             ciConstant c = box->field_value(ik->nonstatic_field_at(0));
1215             BasicType bt = c.basic_type();
1216             // Only integer types have boxing cache.
1217             assert(bt == T_BOOLEAN || bt == T_CHAR  ||
1218                    bt == T_BYTE    || bt == T_SHORT ||
1219                    bt == T_INT     || bt == T_LONG, "wrong type = %s", type2name(bt));
1220             jlong cache_low = (bt == T_LONG) ? c.as_long() : c.as_int();
1221             if (cache_low != (int)cache_low) {
1222               return NULL; // should not happen since cache is array indexed by value
1223             }
1224             jlong offset = arrayOopDesc::base_offset_in_bytes(T_OBJECT) - (cache_low << shift);
1225             if (offset != (int)offset) {
1226               return NULL; // should not happen since cache is array indexed by value
1227             }
1228            // Add up all the offsets making of the address of the load
1229             Node* result = elements[0];
1230             for (int i = 1; i < count; i++) {
1231               result = phase->transform(new AddXNode(result, elements[i]));
1232             }
1233             // Remove the constant offset from the address and then
1234             result = phase->transform(new AddXNode(result, phase->MakeConX(-(int)offset)));
1235             // remove the scaling of the offset to recover the original index.
1236             if (result->Opcode() == Op_LShiftX && result->in(2) == phase->intcon(shift)) {
1237               // Peel the shift off directly but wrap it in a dummy node
1238               // since Ideal can't return existing nodes
1239               result = new RShiftXNode(result->in(1), phase->intcon(0));
1240             } else if (result->is_Add() && result->in(2)->is_Con() &&
1241                        result->in(1)->Opcode() == Op_LShiftX &&
1242                        result->in(1)->in(2) == phase->intcon(shift)) {
1243               // We can't do general optimization: ((X<<Z) + Y) >> Z ==> X + (Y>>Z)
1244               // but for boxing cache access we know that X<<Z will not overflow
1245               // (there is range check) so we do this optimizatrion by hand here.
1246               Node* add_con = new RShiftXNode(result->in(2), phase->intcon(shift));
1247               result = new AddXNode(result->in(1)->in(1), phase->transform(add_con));
1248             } else {
1249               result = new RShiftXNode(result, phase->intcon(shift));
1250             }
1251 #ifdef _LP64
1252             if (bt != T_LONG) {
1253               result = new ConvL2INode(phase->transform(result));
1254             }
1255 #else
1256             if (bt == T_LONG) {
1257               result = new ConvI2LNode(phase->transform(result));
1258             }
1259 #endif
1260             // Boxing/unboxing can be done from signed & unsigned loads (e.g. LoadUB -> ... -> LoadB pair).
1261             // Need to preserve unboxing load type if it is unsigned.
1262             switch(this->Opcode()) {
1263               case Op_LoadUB:
1264                 result = new AndINode(phase->transform(result), phase->intcon(0xFF));
1265                 break;
1266               case Op_LoadUS:
1267                 result = new AndINode(phase->transform(result), phase->intcon(0xFFFF));
1268                 break;
1269             }
1270             return result;
1271           }
1272         }
1273       }
1274     }
1275   }
1276   return NULL;
1277 }
1278 
1279 static bool stable_phi(PhiNode* phi, PhaseGVN *phase) {
1280   Node* region = phi->in(0);
1281   if (region == NULL) {
1282     return false; // Wait stable graph
1283   }
1284   uint cnt = phi->req();
1285   for (uint i = 1; i < cnt; i++) {
1286     Node* rc = region->in(i);
1287     if (rc == NULL || phase->type(rc) == Type::TOP)
1288       return false; // Wait stable graph
1289     Node* in = phi->in(i);
1290     if (in == NULL || phase->type(in) == Type::TOP)
1291       return false; // Wait stable graph
1292   }
1293   return true;
1294 }
1295 //------------------------------split_through_phi------------------------------
1296 // Split instance or boxed field load through Phi.
1297 Node *LoadNode::split_through_phi(PhaseGVN *phase) {
1298   Node* mem     = in(Memory);
1299   Node* address = in(Address);
1300   const TypeOopPtr *t_oop = phase->type(address)->isa_oopptr();
1301 
1302   assert((t_oop != NULL) &&
1303          (t_oop->is_known_instance_field() ||
1304           t_oop->is_ptr_to_boxed_value()), "invalide conditions");
1305 
1306   Compile* C = phase->C;
1307   intptr_t ignore = 0;
1308   Node*    base = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1309   bool base_is_phi = (base != NULL) && base->is_Phi();
1310   bool load_boxed_values = t_oop->is_ptr_to_boxed_value() && C->aggressive_unboxing() &&
1311                            (base != NULL) && (base == address->in(AddPNode::Base)) &&
1312                            phase->type(base)->higher_equal(TypePtr::NOTNULL);
1313 
1314   if (!((mem->is_Phi() || base_is_phi) &&
1315         (load_boxed_values || t_oop->is_known_instance_field()))) {
1316     return NULL; // memory is not Phi
1317   }
1318 
1319   if (mem->is_Phi()) {
1320     if (!stable_phi(mem->as_Phi(), phase)) {
1321       return NULL; // Wait stable graph
1322     }
1323     uint cnt = mem->req();
1324     // Check for loop invariant memory.
1325     if (cnt == 3) {
1326       for (uint i = 1; i < cnt; i++) {
1327         Node* in = mem->in(i);
1328         Node*  m = optimize_memory_chain(in, t_oop, this, phase);
1329         if (m == mem) {
1330           set_req(Memory, mem->in(cnt - i));
1331           return this; // made change
1332         }
1333       }
1334     }
1335   }
1336   if (base_is_phi) {
1337     if (!stable_phi(base->as_Phi(), phase)) {
1338       return NULL; // Wait stable graph
1339     }
1340     uint cnt = base->req();
1341     // Check for loop invariant memory.
1342     if (cnt == 3) {
1343       for (uint i = 1; i < cnt; i++) {
1344         if (base->in(i) == base) {
1345           return NULL; // Wait stable graph
1346         }
1347       }
1348     }
1349   }
1350 
1351   bool load_boxed_phi = load_boxed_values && base_is_phi && (base->in(0) == mem->in(0));
1352 
1353   // Split through Phi (see original code in loopopts.cpp).
1354   assert(C->have_alias_type(t_oop), "instance should have alias type");
1355 
1356   // Do nothing here if Identity will find a value
1357   // (to avoid infinite chain of value phis generation).
1358   if (!phase->eqv(this, this->Identity(phase)))
1359     return NULL;
1360 
1361   // Select Region to split through.
1362   Node* region;
1363   if (!base_is_phi) {
1364     assert(mem->is_Phi(), "sanity");
1365     region = mem->in(0);
1366     // Skip if the region dominates some control edge of the address.
1367     if (!MemNode::all_controls_dominate(address, region))
1368       return NULL;
1369   } else if (!mem->is_Phi()) {
1370     assert(base_is_phi, "sanity");
1371     region = base->in(0);
1372     // Skip if the region dominates some control edge of the memory.
1373     if (!MemNode::all_controls_dominate(mem, region))
1374       return NULL;
1375   } else if (base->in(0) != mem->in(0)) {
1376     assert(base_is_phi && mem->is_Phi(), "sanity");
1377     if (MemNode::all_controls_dominate(mem, base->in(0))) {
1378       region = base->in(0);
1379     } else if (MemNode::all_controls_dominate(address, mem->in(0))) {
1380       region = mem->in(0);
1381     } else {
1382       return NULL; // complex graph
1383     }
1384   } else {
1385     assert(base->in(0) == mem->in(0), "sanity");
1386     region = mem->in(0);
1387   }
1388 
1389   const Type* this_type = this->bottom_type();
1390   int this_index  = C->get_alias_index(t_oop);
1391   int this_offset = t_oop->offset();
1392   int this_iid    = t_oop->instance_id();
1393   if (!t_oop->is_known_instance() && load_boxed_values) {
1394     // Use _idx of address base for boxed values.
1395     this_iid = base->_idx;
1396   }
1397   PhaseIterGVN* igvn = phase->is_IterGVN();
1398   Node* phi = new PhiNode(region, this_type, NULL, this_iid, this_index, this_offset);
1399   for (uint i = 1; i < region->req(); i++) {
1400     Node* x;
1401     Node* the_clone = NULL;
1402     if (region->in(i) == C->top()) {
1403       x = C->top();      // Dead path?  Use a dead data op
1404     } else {
1405       x = this->clone();        // Else clone up the data op
1406       the_clone = x;            // Remember for possible deletion.
1407       // Alter data node to use pre-phi inputs
1408       if (this->in(0) == region) {
1409         x->set_req(0, region->in(i));
1410       } else {
1411         x->set_req(0, NULL);
1412       }
1413       if (mem->is_Phi() && (mem->in(0) == region)) {
1414         x->set_req(Memory, mem->in(i)); // Use pre-Phi input for the clone.
1415       }
1416       if (address->is_Phi() && address->in(0) == region) {
1417         x->set_req(Address, address->in(i)); // Use pre-Phi input for the clone
1418       }
1419       if (base_is_phi && (base->in(0) == region)) {
1420         Node* base_x = base->in(i); // Clone address for loads from boxed objects.
1421         Node* adr_x = phase->transform(new AddPNode(base_x,base_x,address->in(AddPNode::Offset)));
1422         x->set_req(Address, adr_x);
1423       }
1424     }
1425     // Check for a 'win' on some paths
1426     const Type *t = x->Value(igvn);
1427 
1428     bool singleton = t->singleton();
1429 
1430     // See comments in PhaseIdealLoop::split_thru_phi().
1431     if (singleton && t == Type::TOP) {
1432       singleton &= region->is_Loop() && (i != LoopNode::EntryControl);
1433     }
1434 
1435     if (singleton) {
1436       x = igvn->makecon(t);
1437     } else {
1438       // We now call Identity to try to simplify the cloned node.
1439       // Note that some Identity methods call phase->type(this).
1440       // Make sure that the type array is big enough for
1441       // our new node, even though we may throw the node away.
1442       // (This tweaking with igvn only works because x is a new node.)
1443       igvn->set_type(x, t);
1444       // If x is a TypeNode, capture any more-precise type permanently into Node
1445       // otherwise it will be not updated during igvn->transform since
1446       // igvn->type(x) is set to x->Value() already.
1447       x->raise_bottom_type(t);
1448       Node *y = x->Identity(igvn);
1449       if (y != x) {
1450         x = y;
1451       } else {
1452         y = igvn->hash_find_insert(x);
1453         if (y) {
1454           x = y;
1455         } else {
1456           // Else x is a new node we are keeping
1457           // We do not need register_new_node_with_optimizer
1458           // because set_type has already been called.
1459           igvn->_worklist.push(x);
1460         }
1461       }
1462     }
1463     if (x != the_clone && the_clone != NULL) {
1464       igvn->remove_dead_node(the_clone);
1465     }
1466     phi->set_req(i, x);
1467   }
1468   // Record Phi
1469   igvn->register_new_node_with_optimizer(phi);
1470   return phi;
1471 }
1472 
1473 //------------------------------Ideal------------------------------------------
1474 // If the load is from Field memory and the pointer is non-null, it might be possible to
1475 // zero out the control input.
1476 // If the offset is constant and the base is an object allocation,
1477 // try to hook me up to the exact initializing store.
1478 Node *LoadNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1479   Node* p = MemNode::Ideal_common(phase, can_reshape);
1480   if (p)  return (p == NodeSentinel) ? NULL : p;
1481 
1482   Node* ctrl    = in(MemNode::Control);
1483   Node* address = in(MemNode::Address);
1484   bool progress = false;
1485 
1486   // Skip up past a SafePoint control.  Cannot do this for Stores because
1487   // pointer stores & cardmarks must stay on the same side of a SafePoint.
1488   if( ctrl != NULL && ctrl->Opcode() == Op_SafePoint &&
1489       phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw ) {
1490     ctrl = ctrl->in(0);
1491     set_req(MemNode::Control,ctrl);
1492     progress = true;
1493   }
1494 
1495   intptr_t ignore = 0;
1496   Node*    base   = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1497   if (base != NULL
1498       && phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw) {
1499     // Check for useless control edge in some common special cases
1500     if (in(MemNode::Control) != NULL
1501         && can_remove_control()
1502         && phase->type(base)->higher_equal(TypePtr::NOTNULL)
1503         && all_controls_dominate(base, phase->C->start())) {
1504       // A method-invariant, non-null address (constant or 'this' argument).
1505       set_req(MemNode::Control, NULL);
1506       progress = true;
1507     }
1508   }
1509 
1510   Node* mem = in(MemNode::Memory);
1511   const TypePtr *addr_t = phase->type(address)->isa_ptr();
1512 
1513   if (can_reshape && (addr_t != NULL)) {
1514     // try to optimize our memory input
1515     Node* opt_mem = MemNode::optimize_memory_chain(mem, addr_t, this, phase);
1516     if (opt_mem != mem) {
1517       set_req(MemNode::Memory, opt_mem);
1518       if (phase->type( opt_mem ) == Type::TOP) return NULL;
1519       return this;
1520     }
1521     const TypeOopPtr *t_oop = addr_t->isa_oopptr();
1522     if ((t_oop != NULL) &&
1523         (t_oop->is_known_instance_field() ||
1524          t_oop->is_ptr_to_boxed_value())) {
1525       PhaseIterGVN *igvn = phase->is_IterGVN();
1526       if (igvn != NULL && igvn->_worklist.member(opt_mem)) {
1527         // Delay this transformation until memory Phi is processed.
1528         phase->is_IterGVN()->_worklist.push(this);
1529         return NULL;
1530       }
1531       // Split instance field load through Phi.
1532       Node* result = split_through_phi(phase);
1533       if (result != NULL) return result;
1534 
1535       if (t_oop->is_ptr_to_boxed_value()) {
1536         Node* result = eliminate_autobox(phase);
1537         if (result != NULL) return result;
1538       }
1539     }
1540   }
1541 
1542   // Is there a dominating load that loads the same value?  Leave
1543   // anything that is not a load of a field/array element (like
1544   // barriers etc.) alone
1545   if (in(0) != NULL && adr_type() != TypeRawPtr::BOTTOM && can_reshape) {
1546     for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
1547       Node *use = mem->fast_out(i);
1548       if (use != this &&
1549           use->Opcode() == Opcode() &&
1550           use->in(0) != NULL &&
1551           use->in(0) != in(0) &&
1552           use->in(Address) == in(Address)) {
1553         Node* ctl = in(0);
1554         for (int i = 0; i < 10 && ctl != NULL; i++) {
1555           ctl = IfNode::up_one_dom(ctl);
1556           if (ctl == use->in(0)) {
1557             set_req(0, use->in(0));
1558             return this;
1559           }
1560         }
1561       }
1562     }
1563   }
1564 
1565   // Check for prior store with a different base or offset; make Load
1566   // independent.  Skip through any number of them.  Bail out if the stores
1567   // are in an endless dead cycle and report no progress.  This is a key
1568   // transform for Reflection.  However, if after skipping through the Stores
1569   // we can't then fold up against a prior store do NOT do the transform as
1570   // this amounts to using the 'Oracle' model of aliasing.  It leaves the same
1571   // array memory alive twice: once for the hoisted Load and again after the
1572   // bypassed Store.  This situation only works if EVERYBODY who does
1573   // anti-dependence work knows how to bypass.  I.e. we need all
1574   // anti-dependence checks to ask the same Oracle.  Right now, that Oracle is
1575   // the alias index stuff.  So instead, peek through Stores and IFF we can
1576   // fold up, do so.
1577   Node* prev_mem = find_previous_store(phase);
1578   if (prev_mem != NULL) {
1579     Node* value = can_see_arraycopy_value(prev_mem, phase);
1580     if (value != NULL) {
1581       return value;
1582     }
1583   }
1584   // Steps (a), (b):  Walk past independent stores to find an exact match.
1585   if (prev_mem != NULL && prev_mem != in(MemNode::Memory)) {
1586     // (c) See if we can fold up on the spot, but don't fold up here.
1587     // Fold-up might require truncation (for LoadB/LoadS/LoadUS) or
1588     // just return a prior value, which is done by Identity calls.
1589     if (can_see_stored_value(prev_mem, phase)) {
1590       // Make ready for step (d):
1591       set_req(MemNode::Memory, prev_mem);
1592       return this;
1593     }
1594   }
1595 
1596   return progress ? this : NULL;
1597 }
1598 
1599 // Helper to recognize certain Klass fields which are invariant across
1600 // some group of array types (e.g., int[] or all T[] where T < Object).
1601 const Type*
1602 LoadNode::load_array_final_field(const TypeKlassPtr *tkls,
1603                                  ciKlass* klass) const {
1604   if (tkls->offset() == in_bytes(Klass::modifier_flags_offset())) {
1605     // The field is Klass::_modifier_flags.  Return its (constant) value.
1606     // (Folds up the 2nd indirection in aClassConstant.getModifiers().)
1607     assert(this->Opcode() == Op_LoadI, "must load an int from _modifier_flags");
1608     return TypeInt::make(klass->modifier_flags());
1609   }
1610   if (tkls->offset() == in_bytes(Klass::access_flags_offset())) {
1611     // The field is Klass::_access_flags.  Return its (constant) value.
1612     // (Folds up the 2nd indirection in Reflection.getClassAccessFlags(aClassConstant).)
1613     assert(this->Opcode() == Op_LoadI, "must load an int from _access_flags");
1614     return TypeInt::make(klass->access_flags());
1615   }
1616   if (tkls->offset() == in_bytes(Klass::layout_helper_offset())) {
1617     // The field is Klass::_layout_helper.  Return its constant value if known.
1618     assert(this->Opcode() == Op_LoadI, "must load an int from _layout_helper");
1619     return TypeInt::make(klass->layout_helper());
1620   }
1621 
1622   // No match.
1623   return NULL;
1624 }
1625 
1626 //------------------------------Value-----------------------------------------
1627 const Type* LoadNode::Value(PhaseGVN* phase) const {
1628   // Either input is TOP ==> the result is TOP
1629   Node* mem = in(MemNode::Memory);
1630   const Type *t1 = phase->type(mem);
1631   if (t1 == Type::TOP)  return Type::TOP;
1632   Node* adr = in(MemNode::Address);
1633   const TypePtr* tp = phase->type(adr)->isa_ptr();
1634   if (tp == NULL || tp->empty())  return Type::TOP;
1635   int off = tp->offset();
1636   assert(off != Type::OffsetTop, "case covered by TypePtr::empty");
1637   Compile* C = phase->C;
1638 
1639   // Try to guess loaded type from pointer type
1640   if (tp->isa_aryptr()) {
1641     const TypeAryPtr* ary = tp->is_aryptr();
1642     const Type* t = ary->elem();
1643 
1644     // Determine whether the reference is beyond the header or not, by comparing
1645     // the offset against the offset of the start of the array's data.
1646     // Different array types begin at slightly different offsets (12 vs. 16).
1647     // We choose T_BYTE as an example base type that is least restrictive
1648     // as to alignment, which will therefore produce the smallest
1649     // possible base offset.
1650     const int min_base_off = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1651     const bool off_beyond_header = ((uint)off >= (uint)min_base_off);
1652 
1653     // Try to constant-fold a stable array element.
1654     if (FoldStableValues && !is_mismatched_access() && ary->is_stable()) {
1655       // Make sure the reference is not into the header and the offset is constant
1656       ciObject* aobj = ary->const_oop();
1657       if (aobj != NULL && off_beyond_header && adr->is_AddP() && off != Type::OffsetBot) {
1658         int stable_dimension = (ary->stable_dimension() > 0 ? ary->stable_dimension() - 1 : 0);
1659         const Type* con_type = Type::make_constant_from_array_element(aobj->as_array(), off,
1660                                                                       stable_dimension,
1661                                                                       memory_type(), is_unsigned());
1662         if (con_type != NULL) {
1663           return con_type;
1664         }
1665       }
1666     }
1667 
1668     // Don't do this for integer types. There is only potential profit if
1669     // the element type t is lower than _type; that is, for int types, if _type is
1670     // more restrictive than t.  This only happens here if one is short and the other
1671     // char (both 16 bits), and in those cases we've made an intentional decision
1672     // to use one kind of load over the other. See AndINode::Ideal and 4965907.
1673     // Also, do not try to narrow the type for a LoadKlass, regardless of offset.
1674     //
1675     // Yes, it is possible to encounter an expression like (LoadKlass p1:(AddP x x 8))
1676     // where the _gvn.type of the AddP is wider than 8.  This occurs when an earlier
1677     // copy p0 of (AddP x x 8) has been proven equal to p1, and the p0 has been
1678     // subsumed by p1.  If p1 is on the worklist but has not yet been re-transformed,
1679     // it is possible that p1 will have a type like Foo*[int+]:NotNull*+any.
1680     // In fact, that could have been the original type of p1, and p1 could have
1681     // had an original form like p1:(AddP x x (LShiftL quux 3)), where the
1682     // expression (LShiftL quux 3) independently optimized to the constant 8.
1683     if ((t->isa_int() == NULL) && (t->isa_long() == NULL)
1684         && (_type->isa_vect() == NULL)
1685         && Opcode() != Op_LoadKlass && Opcode() != Op_LoadNKlass) {
1686       // t might actually be lower than _type, if _type is a unique
1687       // concrete subclass of abstract class t.
1688       if (off_beyond_header) {  // is the offset beyond the header?
1689         const Type* jt = t->join_speculative(_type);
1690         // In any case, do not allow the join, per se, to empty out the type.
1691         if (jt->empty() && !t->empty()) {
1692           // This can happen if a interface-typed array narrows to a class type.
1693           jt = _type;
1694         }
1695 #ifdef ASSERT
1696         if (phase->C->eliminate_boxing() && adr->is_AddP()) {
1697           // The pointers in the autobox arrays are always non-null
1698           Node* base = adr->in(AddPNode::Base);
1699           if ((base != NULL) && base->is_DecodeN()) {
1700             // Get LoadN node which loads IntegerCache.cache field
1701             base = base->in(1);
1702           }
1703           if ((base != NULL) && base->is_Con()) {
1704             const TypeAryPtr* base_type = base->bottom_type()->isa_aryptr();
1705             if ((base_type != NULL) && base_type->is_autobox_cache()) {
1706               // It could be narrow oop
1707               assert(jt->make_ptr()->ptr() == TypePtr::NotNull,"sanity");
1708             }
1709           }
1710         }
1711 #endif
1712         return jt;
1713       }
1714     }
1715   } else if (tp->base() == Type::InstPtr) {
1716     ciEnv* env = C->env();
1717     const TypeInstPtr* tinst = tp->is_instptr();
1718     ciKlass* klass = tinst->klass();
1719     assert( off != Type::OffsetBot ||
1720             // arrays can be cast to Objects
1721             tp->is_oopptr()->klass()->is_java_lang_Object() ||
1722             // unsafe field access may not have a constant offset
1723             C->has_unsafe_access(),
1724             "Field accesses must be precise" );
1725     // For oop loads, we expect the _type to be precise.
1726     // Optimizations for constant objects


1727     ciObject* const_oop = tinst->const_oop();
1728     if (const_oop != NULL && const_oop->is_instance()) {
1729       const Type* con_type = Type::make_constant_from_field(const_oop->as_instance(), off, is_unsigned(), memory_type());
1730       if (con_type != NULL) {
1731         return con_type;
1732       }
1733     }
1734   } else if (tp->base() == Type::KlassPtr) {
1735     assert( off != Type::OffsetBot ||
1736             // arrays can be cast to Objects
1737             tp->is_klassptr()->klass()->is_java_lang_Object() ||
1738             // also allow array-loading from the primary supertype
1739             // array during subtype checks
1740             Opcode() == Op_LoadKlass,
1741             "Field accesses must be precise" );
1742     // For klass/static loads, we expect the _type to be precise
1743   }
1744 
1745   const TypeKlassPtr *tkls = tp->isa_klassptr();
1746   if (tkls != NULL && !StressReflectiveCode) {
1747     ciKlass* klass = tkls->klass();
1748     if (klass->is_loaded() && tkls->klass_is_exact()) {
1749       // We are loading a field from a Klass metaobject whose identity
1750       // is known at compile time (the type is "exact" or "precise").
1751       // Check for fields we know are maintained as constants by the VM.
1752       if (tkls->offset() == in_bytes(Klass::super_check_offset_offset())) {
1753         // The field is Klass::_super_check_offset.  Return its (constant) value.
1754         // (Folds up type checking code.)
1755         assert(Opcode() == Op_LoadI, "must load an int from _super_check_offset");
1756         return TypeInt::make(klass->super_check_offset());
1757       }
1758       // Compute index into primary_supers array
1759       juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
1760       // Check for overflowing; use unsigned compare to handle the negative case.
1761       if( depth < ciKlass::primary_super_limit() ) {
1762         // The field is an element of Klass::_primary_supers.  Return its (constant) value.
1763         // (Folds up type checking code.)
1764         assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
1765         ciKlass *ss = klass->super_of_depth(depth);
1766         return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
1767       }
1768       const Type* aift = load_array_final_field(tkls, klass);
1769       if (aift != NULL)  return aift;
1770       if (tkls->offset() == in_bytes(Klass::java_mirror_offset())) {
1771         // The field is Klass::_java_mirror.  Return its (constant) value.
1772         // (Folds up the 2nd indirection in anObjConstant.getClass().)
1773         assert(Opcode() == Op_LoadP, "must load an oop from _java_mirror");
1774         return TypeInstPtr::make(klass->java_mirror());
1775       }
1776     }
1777 
1778     // We can still check if we are loading from the primary_supers array at a
1779     // shallow enough depth.  Even though the klass is not exact, entries less
1780     // than or equal to its super depth are correct.
1781     if (klass->is_loaded() ) {
1782       ciType *inner = klass;
1783       while( inner->is_obj_array_klass() )
1784         inner = inner->as_obj_array_klass()->base_element_type();
1785       if( inner->is_instance_klass() &&
1786           !inner->as_instance_klass()->flags().is_interface() ) {
1787         // Compute index into primary_supers array
1788         juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
1789         // Check for overflowing; use unsigned compare to handle the negative case.
1790         if( depth < ciKlass::primary_super_limit() &&
1791             depth <= klass->super_depth() ) { // allow self-depth checks to handle self-check case
1792           // The field is an element of Klass::_primary_supers.  Return its (constant) value.
1793           // (Folds up type checking code.)
1794           assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
1795           ciKlass *ss = klass->super_of_depth(depth);
1796           return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
1797         }
1798       }
1799     }
1800 
1801     // If the type is enough to determine that the thing is not an array,
1802     // we can give the layout_helper a positive interval type.
1803     // This will help short-circuit some reflective code.
1804     if (tkls->offset() == in_bytes(Klass::layout_helper_offset())
1805         && !klass->is_array_klass() // not directly typed as an array
1806         && !klass->is_interface()  // specifically not Serializable & Cloneable
1807         && !klass->is_java_lang_Object()   // not the supertype of all T[]
1808         ) {
1809       // Note:  When interfaces are reliable, we can narrow the interface
1810       // test to (klass != Serializable && klass != Cloneable).
1811       assert(Opcode() == Op_LoadI, "must load an int from _layout_helper");
1812       jint min_size = Klass::instance_layout_helper(oopDesc::header_size(), false);
1813       // The key property of this type is that it folds up tests
1814       // for array-ness, since it proves that the layout_helper is positive.
1815       // Thus, a generic value like the basic object layout helper works fine.
1816       return TypeInt::make(min_size, max_jint, Type::WidenMin);
1817     }
1818   }
1819 
1820   // If we are loading from a freshly-allocated object, produce a zero,
1821   // if the load is provably beyond the header of the object.
1822   // (Also allow a variable load from a fresh array to produce zero.)
1823   const TypeOopPtr *tinst = tp->isa_oopptr();
1824   bool is_instance = (tinst != NULL) && tinst->is_known_instance_field();
1825   bool is_boxed_value = (tinst != NULL) && tinst->is_ptr_to_boxed_value();
1826   if (ReduceFieldZeroing || is_instance || is_boxed_value) {
1827     Node* value = can_see_stored_value(mem,phase);
1828     if (value != NULL && value->is_Con()) {
1829       assert(value->bottom_type()->higher_equal(_type),"sanity");
1830       return value->bottom_type();
1831     }
1832   }
1833 
1834   if (is_instance) {
1835     // If we have an instance type and our memory input is the
1836     // programs's initial memory state, there is no matching store,
1837     // so just return a zero of the appropriate type
1838     Node *mem = in(MemNode::Memory);
1839     if (mem->is_Parm() && mem->in(0)->is_Start()) {
1840       assert(mem->as_Parm()->_con == TypeFunc::Memory, "must be memory Parm");
1841       return Type::get_zero_type(_type->basic_type());
1842     }
1843   }
1844   return _type;
1845 }
1846 
1847 //------------------------------match_edge-------------------------------------
1848 // Do we Match on this edge index or not?  Match only the address.
1849 uint LoadNode::match_edge(uint idx) const {
1850   return idx == MemNode::Address;
1851 }
1852 
1853 //--------------------------LoadBNode::Ideal--------------------------------------
1854 //
1855 //  If the previous store is to the same address as this load,
1856 //  and the value stored was larger than a byte, replace this load
1857 //  with the value stored truncated to a byte.  If no truncation is
1858 //  needed, the replacement is done in LoadNode::Identity().
1859 //
1860 Node *LoadBNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1861   Node* mem = in(MemNode::Memory);
1862   Node* value = can_see_stored_value(mem,phase);
1863   if( value && !phase->type(value)->higher_equal( _type ) ) {
1864     Node *result = phase->transform( new LShiftINode(value, phase->intcon(24)) );
1865     return new RShiftINode(result, phase->intcon(24));
1866   }
1867   // Identity call will handle the case where truncation is not needed.
1868   return LoadNode::Ideal(phase, can_reshape);
1869 }
1870 
1871 const Type* LoadBNode::Value(PhaseGVN* phase) const {
1872   Node* mem = in(MemNode::Memory);
1873   Node* value = can_see_stored_value(mem,phase);
1874   if (value != NULL && value->is_Con() &&
1875       !value->bottom_type()->higher_equal(_type)) {
1876     // If the input to the store does not fit with the load's result type,
1877     // it must be truncated. We can't delay until Ideal call since
1878     // a singleton Value is needed for split_thru_phi optimization.
1879     int con = value->get_int();
1880     return TypeInt::make((con << 24) >> 24);
1881   }
1882   return LoadNode::Value(phase);
1883 }
1884 
1885 //--------------------------LoadUBNode::Ideal-------------------------------------
1886 //
1887 //  If the previous store is to the same address as this load,
1888 //  and the value stored was larger than a byte, replace this load
1889 //  with the value stored truncated to a byte.  If no truncation is
1890 //  needed, the replacement is done in LoadNode::Identity().
1891 //
1892 Node* LoadUBNode::Ideal(PhaseGVN* phase, bool can_reshape) {
1893   Node* mem = in(MemNode::Memory);
1894   Node* value = can_see_stored_value(mem, phase);
1895   if (value && !phase->type(value)->higher_equal(_type))
1896     return new AndINode(value, phase->intcon(0xFF));
1897   // Identity call will handle the case where truncation is not needed.
1898   return LoadNode::Ideal(phase, can_reshape);
1899 }
1900 
1901 const Type* LoadUBNode::Value(PhaseGVN* phase) const {
1902   Node* mem = in(MemNode::Memory);
1903   Node* value = can_see_stored_value(mem,phase);
1904   if (value != NULL && value->is_Con() &&
1905       !value->bottom_type()->higher_equal(_type)) {
1906     // If the input to the store does not fit with the load's result type,
1907     // it must be truncated. We can't delay until Ideal call since
1908     // a singleton Value is needed for split_thru_phi optimization.
1909     int con = value->get_int();
1910     return TypeInt::make(con & 0xFF);
1911   }
1912   return LoadNode::Value(phase);
1913 }
1914 
1915 //--------------------------LoadUSNode::Ideal-------------------------------------
1916 //
1917 //  If the previous store is to the same address as this load,
1918 //  and the value stored was larger than a char, replace this load
1919 //  with the value stored truncated to a char.  If no truncation is
1920 //  needed, the replacement is done in LoadNode::Identity().
1921 //
1922 Node *LoadUSNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1923   Node* mem = in(MemNode::Memory);
1924   Node* value = can_see_stored_value(mem,phase);
1925   if( value && !phase->type(value)->higher_equal( _type ) )
1926     return new AndINode(value,phase->intcon(0xFFFF));
1927   // Identity call will handle the case where truncation is not needed.
1928   return LoadNode::Ideal(phase, can_reshape);
1929 }
1930 
1931 const Type* LoadUSNode::Value(PhaseGVN* phase) const {
1932   Node* mem = in(MemNode::Memory);
1933   Node* value = can_see_stored_value(mem,phase);
1934   if (value != NULL && value->is_Con() &&
1935       !value->bottom_type()->higher_equal(_type)) {
1936     // If the input to the store does not fit with the load's result type,
1937     // it must be truncated. We can't delay until Ideal call since
1938     // a singleton Value is needed for split_thru_phi optimization.
1939     int con = value->get_int();
1940     return TypeInt::make(con & 0xFFFF);
1941   }
1942   return LoadNode::Value(phase);
1943 }
1944 
1945 //--------------------------LoadSNode::Ideal--------------------------------------
1946 //
1947 //  If the previous store is to the same address as this load,
1948 //  and the value stored was larger than a short, replace this load
1949 //  with the value stored truncated to a short.  If no truncation is
1950 //  needed, the replacement is done in LoadNode::Identity().
1951 //
1952 Node *LoadSNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1953   Node* mem = in(MemNode::Memory);
1954   Node* value = can_see_stored_value(mem,phase);
1955   if( value && !phase->type(value)->higher_equal( _type ) ) {
1956     Node *result = phase->transform( new LShiftINode(value, phase->intcon(16)) );
1957     return new RShiftINode(result, phase->intcon(16));
1958   }
1959   // Identity call will handle the case where truncation is not needed.
1960   return LoadNode::Ideal(phase, can_reshape);
1961 }
1962 
1963 const Type* LoadSNode::Value(PhaseGVN* phase) const {
1964   Node* mem = in(MemNode::Memory);
1965   Node* value = can_see_stored_value(mem,phase);
1966   if (value != NULL && value->is_Con() &&
1967       !value->bottom_type()->higher_equal(_type)) {
1968     // If the input to the store does not fit with the load's result type,
1969     // it must be truncated. We can't delay until Ideal call since
1970     // a singleton Value is needed for split_thru_phi optimization.
1971     int con = value->get_int();
1972     return TypeInt::make((con << 16) >> 16);
1973   }
1974   return LoadNode::Value(phase);
1975 }
1976 
1977 //=============================================================================
1978 //----------------------------LoadKlassNode::make------------------------------
1979 // Polymorphic factory method:
1980 Node* LoadKlassNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* at, const TypeKlassPtr* tk) {
1981   // sanity check the alias category against the created node type
1982   const TypePtr *adr_type = adr->bottom_type()->isa_ptr();
1983   assert(adr_type != NULL, "expecting TypeKlassPtr");
1984 #ifdef _LP64
1985   if (adr_type->is_ptr_to_narrowklass()) {
1986     assert(UseCompressedClassPointers, "no compressed klasses");
1987     Node* load_klass = gvn.transform(new LoadNKlassNode(ctl, mem, adr, at, tk->make_narrowklass(), MemNode::unordered));
1988     return new DecodeNKlassNode(load_klass, load_klass->bottom_type()->make_ptr());
1989   }
1990 #endif
1991   assert(!adr_type->is_ptr_to_narrowklass() && !adr_type->is_ptr_to_narrowoop(), "should have got back a narrow oop");
1992   return new LoadKlassNode(ctl, mem, adr, at, tk, MemNode::unordered);
1993 }
1994 
1995 //------------------------------Value------------------------------------------
1996 const Type* LoadKlassNode::Value(PhaseGVN* phase) const {
1997   return klass_value_common(phase);
1998 }
1999 
2000 // In most cases, LoadKlassNode does not have the control input set. If the control
2001 // input is set, it must not be removed (by LoadNode::Ideal()).
2002 bool LoadKlassNode::can_remove_control() const {
2003   return false;
2004 }
2005 
2006 const Type* LoadNode::klass_value_common(PhaseGVN* phase) const {
2007   // Either input is TOP ==> the result is TOP
2008   const Type *t1 = phase->type( in(MemNode::Memory) );
2009   if (t1 == Type::TOP)  return Type::TOP;
2010   Node *adr = in(MemNode::Address);
2011   const Type *t2 = phase->type( adr );
2012   if (t2 == Type::TOP)  return Type::TOP;
2013   const TypePtr *tp = t2->is_ptr();
2014   if (TypePtr::above_centerline(tp->ptr()) ||
2015       tp->ptr() == TypePtr::Null)  return Type::TOP;
2016 
2017   // Return a more precise klass, if possible
2018   const TypeInstPtr *tinst = tp->isa_instptr();
2019   if (tinst != NULL) {
2020     ciInstanceKlass* ik = tinst->klass()->as_instance_klass();
2021     int offset = tinst->offset();
2022     if (ik == phase->C->env()->Class_klass()
2023         && (offset == java_lang_Class::klass_offset_in_bytes() ||
2024             offset == java_lang_Class::array_klass_offset_in_bytes())) {
2025       // We are loading a special hidden field from a Class mirror object,
2026       // the field which points to the VM's Klass metaobject.
2027       ciType* t = tinst->java_mirror_type();
2028       // java_mirror_type returns non-null for compile-time Class constants.
2029       if (t != NULL) {
2030         // constant oop => constant klass
2031         if (offset == java_lang_Class::array_klass_offset_in_bytes()) {
2032           if (t->is_void()) {
2033             // We cannot create a void array.  Since void is a primitive type return null
2034             // klass.  Users of this result need to do a null check on the returned klass.
2035             return TypePtr::NULL_PTR;
2036           }
2037           return TypeKlassPtr::make(ciArrayKlass::make(t));
2038         }
2039         if (!t->is_klass()) {
2040           // a primitive Class (e.g., int.class) has NULL for a klass field
2041           return TypePtr::NULL_PTR;
2042         }
2043         // (Folds up the 1st indirection in aClassConstant.getModifiers().)
2044         return TypeKlassPtr::make(t->as_klass());
2045       }
2046       // non-constant mirror, so we can't tell what's going on
2047     }
2048     if( !ik->is_loaded() )
2049       return _type;             // Bail out if not loaded
2050     if (offset == oopDesc::klass_offset_in_bytes()) {
2051       if (tinst->klass_is_exact()) {
2052         return TypeKlassPtr::make(ik);
2053       }
2054       // See if we can become precise: no subklasses and no interface
2055       // (Note:  We need to support verified interfaces.)
2056       if (!ik->is_interface() && !ik->has_subklass()) {
2057         //assert(!UseExactTypes, "this code should be useless with exact types");
2058         // Add a dependence; if any subclass added we need to recompile
2059         if (!ik->is_final()) {
2060           // %%% should use stronger assert_unique_concrete_subtype instead
2061           phase->C->dependencies()->assert_leaf_type(ik);
2062         }
2063         // Return precise klass
2064         return TypeKlassPtr::make(ik);
2065       }
2066 
2067       // Return root of possible klass
2068       return TypeKlassPtr::make(TypePtr::NotNull, ik, 0/*offset*/);
2069     }
2070   }
2071 
2072   // Check for loading klass from an array
2073   const TypeAryPtr *tary = tp->isa_aryptr();
2074   if( tary != NULL ) {
2075     ciKlass *tary_klass = tary->klass();
2076     if (tary_klass != NULL   // can be NULL when at BOTTOM or TOP
2077         && tary->offset() == oopDesc::klass_offset_in_bytes()) {
2078       if (tary->klass_is_exact()) {
2079         return TypeKlassPtr::make(tary_klass);
2080       }
2081       ciArrayKlass *ak = tary->klass()->as_array_klass();
2082       // If the klass is an object array, we defer the question to the
2083       // array component klass.
2084       if( ak->is_obj_array_klass() ) {
2085         assert( ak->is_loaded(), "" );
2086         ciKlass *base_k = ak->as_obj_array_klass()->base_element_klass();
2087         if( base_k->is_loaded() && base_k->is_instance_klass() ) {
2088           ciInstanceKlass* ik = base_k->as_instance_klass();
2089           // See if we can become precise: no subklasses and no interface
2090           if (!ik->is_interface() && !ik->has_subklass()) {
2091             //assert(!UseExactTypes, "this code should be useless with exact types");
2092             // Add a dependence; if any subclass added we need to recompile
2093             if (!ik->is_final()) {
2094               phase->C->dependencies()->assert_leaf_type(ik);
2095             }
2096             // Return precise array klass
2097             return TypeKlassPtr::make(ak);
2098           }
2099         }
2100         return TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
2101       } else {                  // Found a type-array?
2102         //assert(!UseExactTypes, "this code should be useless with exact types");
2103         assert( ak->is_type_array_klass(), "" );
2104         return TypeKlassPtr::make(ak); // These are always precise
2105       }
2106     }
2107   }
2108 
2109   // Check for loading klass from an array klass
2110   const TypeKlassPtr *tkls = tp->isa_klassptr();
2111   if (tkls != NULL && !StressReflectiveCode) {
2112     ciKlass* klass = tkls->klass();
2113     if( !klass->is_loaded() )
2114       return _type;             // Bail out if not loaded
2115     if( klass->is_obj_array_klass() &&
2116         tkls->offset() == in_bytes(ObjArrayKlass::element_klass_offset())) {
2117       ciKlass* elem = klass->as_obj_array_klass()->element_klass();
2118       // // Always returning precise element type is incorrect,
2119       // // e.g., element type could be object and array may contain strings
2120       // return TypeKlassPtr::make(TypePtr::Constant, elem, 0);
2121 
2122       // The array's TypeKlassPtr was declared 'precise' or 'not precise'
2123       // according to the element type's subclassing.
2124       return TypeKlassPtr::make(tkls->ptr(), elem, 0/*offset*/);
2125     }
2126     if( klass->is_instance_klass() && tkls->klass_is_exact() &&
2127         tkls->offset() == in_bytes(Klass::super_offset())) {
2128       ciKlass* sup = klass->as_instance_klass()->super();
2129       // The field is Klass::_super.  Return its (constant) value.
2130       // (Folds up the 2nd indirection in aClassConstant.getSuperClass().)
2131       return sup ? TypeKlassPtr::make(sup) : TypePtr::NULL_PTR;
2132     }
2133   }
2134 
2135   // Bailout case
2136   return LoadNode::Value(phase);
2137 }
2138 
2139 //------------------------------Identity---------------------------------------
2140 // To clean up reflective code, simplify k.java_mirror.as_klass to plain k.
2141 // Also feed through the klass in Allocate(...klass...)._klass.
2142 Node* LoadKlassNode::Identity(PhaseGVN* phase) {
2143   return klass_identity_common(phase);
2144 }
2145 
2146 Node* LoadNode::klass_identity_common(PhaseGVN* phase) {
2147   Node* x = LoadNode::Identity(phase);
2148   if (x != this)  return x;
2149 
2150   // Take apart the address into an oop and and offset.
2151   // Return 'this' if we cannot.
2152   Node*    adr    = in(MemNode::Address);
2153   intptr_t offset = 0;
2154   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2155   if (base == NULL)     return this;
2156   const TypeOopPtr* toop = phase->type(adr)->isa_oopptr();
2157   if (toop == NULL)     return this;
2158 
2159   // We can fetch the klass directly through an AllocateNode.
2160   // This works even if the klass is not constant (clone or newArray).
2161   if (offset == oopDesc::klass_offset_in_bytes()) {
2162     Node* allocated_klass = AllocateNode::Ideal_klass(base, phase);
2163     if (allocated_klass != NULL) {
2164       return allocated_klass;
2165     }
2166   }
2167 
2168   // Simplify k.java_mirror.as_klass to plain k, where k is a Klass*.
2169   // See inline_native_Class_query for occurrences of these patterns.
2170   // Java Example:  x.getClass().isAssignableFrom(y)
2171   //
2172   // This improves reflective code, often making the Class
2173   // mirror go completely dead.  (Current exception:  Class
2174   // mirrors may appear in debug info, but we could clean them out by
2175   // introducing a new debug info operator for Klass*.java_mirror).
2176   if (toop->isa_instptr() && toop->klass() == phase->C->env()->Class_klass()
2177       && offset == java_lang_Class::klass_offset_in_bytes()) {
2178     // We are loading a special hidden field from a Class mirror,
2179     // the field which points to its Klass or ArrayKlass metaobject.
2180     if (base->is_Load()) {
2181       Node* adr2 = base->in(MemNode::Address);
2182       const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
2183       if (tkls != NULL && !tkls->empty()
2184           && (tkls->klass()->is_instance_klass() ||
2185               tkls->klass()->is_array_klass())
2186           && adr2->is_AddP()
2187           ) {
2188         int mirror_field = in_bytes(Klass::java_mirror_offset());
2189         if (tkls->offset() == mirror_field) {
2190           return adr2->in(AddPNode::Base);
2191         }
2192       }
2193     }
2194   }
2195 
2196   return this;
2197 }
2198 
2199 
2200 //------------------------------Value------------------------------------------
2201 const Type* LoadNKlassNode::Value(PhaseGVN* phase) const {
2202   const Type *t = klass_value_common(phase);
2203   if (t == Type::TOP)
2204     return t;
2205 
2206   return t->make_narrowklass();
2207 }
2208 
2209 //------------------------------Identity---------------------------------------
2210 // To clean up reflective code, simplify k.java_mirror.as_klass to narrow k.
2211 // Also feed through the klass in Allocate(...klass...)._klass.
2212 Node* LoadNKlassNode::Identity(PhaseGVN* phase) {
2213   Node *x = klass_identity_common(phase);
2214 
2215   const Type *t = phase->type( x );
2216   if( t == Type::TOP ) return x;
2217   if( t->isa_narrowklass()) return x;
2218   assert (!t->isa_narrowoop(), "no narrow oop here");
2219 
2220   return phase->transform(new EncodePKlassNode(x, t->make_narrowklass()));
2221 }
2222 
2223 //------------------------------Value-----------------------------------------
2224 const Type* LoadRangeNode::Value(PhaseGVN* phase) const {
2225   // Either input is TOP ==> the result is TOP
2226   const Type *t1 = phase->type( in(MemNode::Memory) );
2227   if( t1 == Type::TOP ) return Type::TOP;
2228   Node *adr = in(MemNode::Address);
2229   const Type *t2 = phase->type( adr );
2230   if( t2 == Type::TOP ) return Type::TOP;
2231   const TypePtr *tp = t2->is_ptr();
2232   if (TypePtr::above_centerline(tp->ptr()))  return Type::TOP;
2233   const TypeAryPtr *tap = tp->isa_aryptr();
2234   if( !tap ) return _type;
2235   return tap->size();
2236 }
2237 
2238 //-------------------------------Ideal---------------------------------------
2239 // Feed through the length in AllocateArray(...length...)._length.
2240 Node *LoadRangeNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2241   Node* p = MemNode::Ideal_common(phase, can_reshape);
2242   if (p)  return (p == NodeSentinel) ? NULL : p;
2243 
2244   // Take apart the address into an oop and and offset.
2245   // Return 'this' if we cannot.
2246   Node*    adr    = in(MemNode::Address);
2247   intptr_t offset = 0;
2248   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase,  offset);
2249   if (base == NULL)     return NULL;
2250   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2251   if (tary == NULL)     return NULL;
2252 
2253   // We can fetch the length directly through an AllocateArrayNode.
2254   // This works even if the length is not constant (clone or newArray).
2255   if (offset == arrayOopDesc::length_offset_in_bytes()) {
2256     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
2257     if (alloc != NULL) {
2258       Node* allocated_length = alloc->Ideal_length();
2259       Node* len = alloc->make_ideal_length(tary, phase);
2260       if (allocated_length != len) {
2261         // New CastII improves on this.
2262         return len;
2263       }
2264     }
2265   }
2266 
2267   return NULL;
2268 }
2269 
2270 //------------------------------Identity---------------------------------------
2271 // Feed through the length in AllocateArray(...length...)._length.
2272 Node* LoadRangeNode::Identity(PhaseGVN* phase) {
2273   Node* x = LoadINode::Identity(phase);
2274   if (x != this)  return x;
2275 
2276   // Take apart the address into an oop and and offset.
2277   // Return 'this' if we cannot.
2278   Node*    adr    = in(MemNode::Address);
2279   intptr_t offset = 0;
2280   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2281   if (base == NULL)     return this;
2282   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2283   if (tary == NULL)     return this;
2284 
2285   // We can fetch the length directly through an AllocateArrayNode.
2286   // This works even if the length is not constant (clone or newArray).
2287   if (offset == arrayOopDesc::length_offset_in_bytes()) {
2288     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
2289     if (alloc != NULL) {
2290       Node* allocated_length = alloc->Ideal_length();
2291       // Do not allow make_ideal_length to allocate a CastII node.
2292       Node* len = alloc->make_ideal_length(tary, phase, false);
2293       if (allocated_length == len) {
2294         // Return allocated_length only if it would not be improved by a CastII.
2295         return allocated_length;
2296       }
2297     }
2298   }
2299 
2300   return this;
2301 
2302 }
2303 
2304 //=============================================================================
2305 //---------------------------StoreNode::make-----------------------------------
2306 // Polymorphic factory method:
2307 StoreNode* StoreNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, BasicType bt, MemOrd mo) {
2308   assert((mo == unordered || mo == release), "unexpected");
2309   Compile* C = gvn.C;
2310   assert(C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
2311          ctl != NULL, "raw memory operations should have control edge");
2312 
2313   switch (bt) {
2314   case T_BOOLEAN: val = gvn.transform(new AndINode(val, gvn.intcon(0x1))); // Fall through to T_BYTE case
2315   case T_BYTE:    return new StoreBNode(ctl, mem, adr, adr_type, val, mo);
2316   case T_INT:     return new StoreINode(ctl, mem, adr, adr_type, val, mo);
2317   case T_CHAR:
2318   case T_SHORT:   return new StoreCNode(ctl, mem, adr, adr_type, val, mo);
2319   case T_LONG:    return new StoreLNode(ctl, mem, adr, adr_type, val, mo);
2320   case T_FLOAT:   return new StoreFNode(ctl, mem, adr, adr_type, val, mo);
2321   case T_DOUBLE:  return new StoreDNode(ctl, mem, adr, adr_type, val, mo);
2322   case T_METADATA:
2323   case T_ADDRESS:
2324   case T_OBJECT:
2325 #ifdef _LP64
2326     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
2327       val = gvn.transform(new EncodePNode(val, val->bottom_type()->make_narrowoop()));
2328       return new StoreNNode(ctl, mem, adr, adr_type, val, mo);
2329     } else if (adr->bottom_type()->is_ptr_to_narrowklass() ||
2330                (UseCompressedClassPointers && val->bottom_type()->isa_klassptr() &&
2331                 adr->bottom_type()->isa_rawptr())) {
2332       val = gvn.transform(new EncodePKlassNode(val, val->bottom_type()->make_narrowklass()));
2333       return new StoreNKlassNode(ctl, mem, adr, adr_type, val, mo);
2334     }
2335 #endif
2336     {
2337       return new StorePNode(ctl, mem, adr, adr_type, val, mo);
2338     }
2339   }
2340   ShouldNotReachHere();
2341   return (StoreNode*)NULL;
2342 }
2343 
2344 StoreLNode* StoreLNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, MemOrd mo) {
2345   bool require_atomic = true;
2346   return new StoreLNode(ctl, mem, adr, adr_type, val, mo, require_atomic);
2347 }
2348 
2349 StoreDNode* StoreDNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, MemOrd mo) {
2350   bool require_atomic = true;
2351   return new StoreDNode(ctl, mem, adr, adr_type, val, mo, require_atomic);
2352 }
2353 
2354 
2355 //--------------------------bottom_type----------------------------------------
2356 const Type *StoreNode::bottom_type() const {
2357   return Type::MEMORY;
2358 }
2359 
2360 //------------------------------hash-------------------------------------------
2361 uint StoreNode::hash() const {
2362   // unroll addition of interesting fields
2363   //return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address) + (uintptr_t)in(ValueIn);
2364 
2365   // Since they are not commoned, do not hash them:
2366   return NO_HASH;
2367 }
2368 
2369 //------------------------------Ideal------------------------------------------
2370 // Change back-to-back Store(, p, x) -> Store(m, p, y) to Store(m, p, x).
2371 // When a store immediately follows a relevant allocation/initialization,
2372 // try to capture it into the initialization, or hoist it above.
2373 Node *StoreNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2374   Node* p = MemNode::Ideal_common(phase, can_reshape);
2375   if (p)  return (p == NodeSentinel) ? NULL : p;
2376 
2377   Node* mem     = in(MemNode::Memory);
2378   Node* address = in(MemNode::Address);
2379   // Back-to-back stores to same address?  Fold em up.  Generally
2380   // unsafe if I have intervening uses...  Also disallowed for StoreCM
2381   // since they must follow each StoreP operation.  Redundant StoreCMs
2382   // are eliminated just before matching in final_graph_reshape.
2383   {
2384     Node* st = mem;
2385     // If Store 'st' has more than one use, we cannot fold 'st' away.
2386     // For example, 'st' might be the final state at a conditional
2387     // return.  Or, 'st' might be used by some node which is live at
2388     // the same time 'st' is live, which might be unschedulable.  So,
2389     // require exactly ONE user until such time as we clone 'mem' for
2390     // each of 'mem's uses (thus making the exactly-1-user-rule hold
2391     // true).
2392     while (st->is_Store() && st->outcnt() == 1 && st->Opcode() != Op_StoreCM) {
2393       // Looking at a dead closed cycle of memory?
2394       assert(st != st->in(MemNode::Memory), "dead loop in StoreNode::Ideal");
2395       assert(Opcode() == st->Opcode() ||
2396              st->Opcode() == Op_StoreVector ||
2397              Opcode() == Op_StoreVector ||
2398              phase->C->get_alias_index(adr_type()) == Compile::AliasIdxRaw ||
2399              (Opcode() == Op_StoreL && st->Opcode() == Op_StoreI) || // expanded ClearArrayNode
2400              (is_mismatched_access() || st->as_Store()->is_mismatched_access()),
2401              "no mismatched stores, except on raw memory: %s %s", NodeClassNames[Opcode()], NodeClassNames[st->Opcode()]);
2402 
2403       if (st->in(MemNode::Address)->eqv_uncast(address) &&
2404           st->as_Store()->memory_size() <= this->memory_size()) {
2405         Node* use = st->raw_out(0);
2406         phase->igvn_rehash_node_delayed(use);
2407         if (can_reshape) {
2408           use->set_req_X(MemNode::Memory, st->in(MemNode::Memory), phase->is_IterGVN());
2409         } else {
2410           // It's OK to do this in the parser, since DU info is always accurate,
2411           // and the parser always refers to nodes via SafePointNode maps.
2412           use->set_req(MemNode::Memory, st->in(MemNode::Memory));
2413         }
2414         return this;
2415       }
2416       st = st->in(MemNode::Memory);
2417     }
2418   }
2419 
2420 
2421   // Capture an unaliased, unconditional, simple store into an initializer.
2422   // Or, if it is independent of the allocation, hoist it above the allocation.
2423   if (ReduceFieldZeroing && /*can_reshape &&*/
2424       mem->is_Proj() && mem->in(0)->is_Initialize()) {
2425     InitializeNode* init = mem->in(0)->as_Initialize();
2426     intptr_t offset = init->can_capture_store(this, phase, can_reshape);
2427     if (offset > 0) {
2428       Node* moved = init->capture_store(this, offset, phase, can_reshape);
2429       // If the InitializeNode captured me, it made a raw copy of me,
2430       // and I need to disappear.
2431       if (moved != NULL) {
2432         // %%% hack to ensure that Ideal returns a new node:
2433         mem = MergeMemNode::make(mem);
2434         return mem;             // fold me away
2435       }
2436     }
2437   }
2438 
2439   return NULL;                  // No further progress
2440 }
2441 
2442 //------------------------------Value-----------------------------------------
2443 const Type* StoreNode::Value(PhaseGVN* phase) const {
2444   // Either input is TOP ==> the result is TOP
2445   const Type *t1 = phase->type( in(MemNode::Memory) );
2446   if( t1 == Type::TOP ) return Type::TOP;
2447   const Type *t2 = phase->type( in(MemNode::Address) );
2448   if( t2 == Type::TOP ) return Type::TOP;
2449   const Type *t3 = phase->type( in(MemNode::ValueIn) );
2450   if( t3 == Type::TOP ) return Type::TOP;
2451   return Type::MEMORY;
2452 }
2453 
2454 //------------------------------Identity---------------------------------------
2455 // Remove redundant stores:
2456 //   Store(m, p, Load(m, p)) changes to m.
2457 //   Store(, p, x) -> Store(m, p, x) changes to Store(m, p, x).
2458 Node* StoreNode::Identity(PhaseGVN* phase) {
2459   Node* mem = in(MemNode::Memory);
2460   Node* adr = in(MemNode::Address);
2461   Node* val = in(MemNode::ValueIn);
2462 
2463   // Load then Store?  Then the Store is useless
2464   if (val->is_Load() &&
2465       val->in(MemNode::Address)->eqv_uncast(adr) &&
2466       val->in(MemNode::Memory )->eqv_uncast(mem) &&
2467       val->as_Load()->store_Opcode() == Opcode()) {
2468     return mem;
2469   }
2470 
2471   // Two stores in a row of the same value?
2472   if (mem->is_Store() &&
2473       mem->in(MemNode::Address)->eqv_uncast(adr) &&
2474       mem->in(MemNode::ValueIn)->eqv_uncast(val) &&
2475       mem->Opcode() == Opcode()) {
2476     return mem;
2477   }
2478 
2479   // Store of zero anywhere into a freshly-allocated object?
2480   // Then the store is useless.
2481   // (It must already have been captured by the InitializeNode.)
2482   if (ReduceFieldZeroing && phase->type(val)->is_zero_type()) {
2483     // a newly allocated object is already all-zeroes everywhere
2484     if (mem->is_Proj() && mem->in(0)->is_Allocate()) {
2485       return mem;
2486     }
2487 
2488     // the store may also apply to zero-bits in an earlier object
2489     Node* prev_mem = find_previous_store(phase);
2490     // Steps (a), (b):  Walk past independent stores to find an exact match.
2491     if (prev_mem != NULL) {
2492       Node* prev_val = can_see_stored_value(prev_mem, phase);
2493       if (prev_val != NULL && phase->eqv(prev_val, val)) {
2494         // prev_val and val might differ by a cast; it would be good
2495         // to keep the more informative of the two.
2496         return mem;
2497       }
2498     }
2499   }
2500 
2501   return this;
2502 }
2503 
2504 //------------------------------match_edge-------------------------------------
2505 // Do we Match on this edge index or not?  Match only memory & value
2506 uint StoreNode::match_edge(uint idx) const {
2507   return idx == MemNode::Address || idx == MemNode::ValueIn;
2508 }
2509 
2510 //------------------------------cmp--------------------------------------------
2511 // Do not common stores up together.  They generally have to be split
2512 // back up anyways, so do not bother.
2513 uint StoreNode::cmp( const Node &n ) const {
2514   return (&n == this);          // Always fail except on self
2515 }
2516 
2517 //------------------------------Ideal_masked_input-----------------------------
2518 // Check for a useless mask before a partial-word store
2519 // (StoreB ... (AndI valIn conIa) )
2520 // If (conIa & mask == mask) this simplifies to
2521 // (StoreB ... (valIn) )
2522 Node *StoreNode::Ideal_masked_input(PhaseGVN *phase, uint mask) {
2523   Node *val = in(MemNode::ValueIn);
2524   if( val->Opcode() == Op_AndI ) {
2525     const TypeInt *t = phase->type( val->in(2) )->isa_int();
2526     if( t && t->is_con() && (t->get_con() & mask) == mask ) {
2527       set_req(MemNode::ValueIn, val->in(1));
2528       return this;
2529     }
2530   }
2531   return NULL;
2532 }
2533 
2534 
2535 //------------------------------Ideal_sign_extended_input----------------------
2536 // Check for useless sign-extension before a partial-word store
2537 // (StoreB ... (RShiftI _ (LShiftI _ valIn conIL ) conIR) )
2538 // If (conIL == conIR && conIR <= num_bits)  this simplifies to
2539 // (StoreB ... (valIn) )
2540 Node *StoreNode::Ideal_sign_extended_input(PhaseGVN *phase, int num_bits) {
2541   Node *val = in(MemNode::ValueIn);
2542   if( val->Opcode() == Op_RShiftI ) {
2543     const TypeInt *t = phase->type( val->in(2) )->isa_int();
2544     if( t && t->is_con() && (t->get_con() <= num_bits) ) {
2545       Node *shl = val->in(1);
2546       if( shl->Opcode() == Op_LShiftI ) {
2547         const TypeInt *t2 = phase->type( shl->in(2) )->isa_int();
2548         if( t2 && t2->is_con() && (t2->get_con() == t->get_con()) ) {
2549           set_req(MemNode::ValueIn, shl->in(1));
2550           return this;
2551         }
2552       }
2553     }
2554   }
2555   return NULL;
2556 }
2557 
2558 //------------------------------value_never_loaded-----------------------------------
2559 // Determine whether there are any possible loads of the value stored.
2560 // For simplicity, we actually check if there are any loads from the
2561 // address stored to, not just for loads of the value stored by this node.
2562 //
2563 bool StoreNode::value_never_loaded( PhaseTransform *phase) const {
2564   Node *adr = in(Address);
2565   const TypeOopPtr *adr_oop = phase->type(adr)->isa_oopptr();
2566   if (adr_oop == NULL)
2567     return false;
2568   if (!adr_oop->is_known_instance_field())
2569     return false; // if not a distinct instance, there may be aliases of the address
2570   for (DUIterator_Fast imax, i = adr->fast_outs(imax); i < imax; i++) {
2571     Node *use = adr->fast_out(i);
2572     if (use->is_Load() || use->is_LoadStore()) {
2573       return false;
2574     }
2575   }
2576   return true;
2577 }
2578 
2579 //=============================================================================
2580 //------------------------------Ideal------------------------------------------
2581 // If the store is from an AND mask that leaves the low bits untouched, then
2582 // we can skip the AND operation.  If the store is from a sign-extension
2583 // (a left shift, then right shift) we can skip both.
2584 Node *StoreBNode::Ideal(PhaseGVN *phase, bool can_reshape){
2585   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFF);
2586   if( progress != NULL ) return progress;
2587 
2588   progress = StoreNode::Ideal_sign_extended_input(phase, 24);
2589   if( progress != NULL ) return progress;
2590 
2591   // Finally check the default case
2592   return StoreNode::Ideal(phase, can_reshape);
2593 }
2594 
2595 //=============================================================================
2596 //------------------------------Ideal------------------------------------------
2597 // If the store is from an AND mask that leaves the low bits untouched, then
2598 // we can skip the AND operation
2599 Node *StoreCNode::Ideal(PhaseGVN *phase, bool can_reshape){
2600   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFFFF);
2601   if( progress != NULL ) return progress;
2602 
2603   progress = StoreNode::Ideal_sign_extended_input(phase, 16);
2604   if( progress != NULL ) return progress;
2605 
2606   // Finally check the default case
2607   return StoreNode::Ideal(phase, can_reshape);
2608 }
2609 
2610 //=============================================================================
2611 //------------------------------Identity---------------------------------------
2612 Node* StoreCMNode::Identity(PhaseGVN* phase) {
2613   // No need to card mark when storing a null ptr
2614   Node* my_store = in(MemNode::OopStore);
2615   if (my_store->is_Store()) {
2616     const Type *t1 = phase->type( my_store->in(MemNode::ValueIn) );
2617     if( t1 == TypePtr::NULL_PTR ) {
2618       return in(MemNode::Memory);
2619     }
2620   }
2621   return this;
2622 }
2623 
2624 //=============================================================================
2625 //------------------------------Ideal---------------------------------------
2626 Node *StoreCMNode::Ideal(PhaseGVN *phase, bool can_reshape){
2627   Node* progress = StoreNode::Ideal(phase, can_reshape);
2628   if (progress != NULL) return progress;
2629 
2630   Node* my_store = in(MemNode::OopStore);
2631   if (my_store->is_MergeMem()) {
2632     Node* mem = my_store->as_MergeMem()->memory_at(oop_alias_idx());
2633     set_req(MemNode::OopStore, mem);
2634     return this;
2635   }
2636 
2637   return NULL;
2638 }
2639 
2640 //------------------------------Value-----------------------------------------
2641 const Type* StoreCMNode::Value(PhaseGVN* phase) const {
2642   // Either input is TOP ==> the result is TOP
2643   const Type *t = phase->type( in(MemNode::Memory) );
2644   if( t == Type::TOP ) return Type::TOP;
2645   t = phase->type( in(MemNode::Address) );
2646   if( t == Type::TOP ) return Type::TOP;
2647   t = phase->type( in(MemNode::ValueIn) );
2648   if( t == Type::TOP ) return Type::TOP;
2649   // If extra input is TOP ==> the result is TOP
2650   t = phase->type( in(MemNode::OopStore) );
2651   if( t == Type::TOP ) return Type::TOP;
2652 
2653   return StoreNode::Value( phase );
2654 }
2655 
2656 
2657 //=============================================================================
2658 //----------------------------------SCMemProjNode------------------------------
2659 const Type* SCMemProjNode::Value(PhaseGVN* phase) const
2660 {
2661   return bottom_type();
2662 }
2663 
2664 //=============================================================================
2665 //----------------------------------LoadStoreNode------------------------------
2666 LoadStoreNode::LoadStoreNode( Node *c, Node *mem, Node *adr, Node *val, const TypePtr* at, const Type* rt, uint required )
2667   : Node(required),
2668     _type(rt),
2669     _adr_type(at)
2670 {
2671   init_req(MemNode::Control, c  );
2672   init_req(MemNode::Memory , mem);
2673   init_req(MemNode::Address, adr);
2674   init_req(MemNode::ValueIn, val);
2675   init_class_id(Class_LoadStore);
2676 }
2677 
2678 uint LoadStoreNode::ideal_reg() const {
2679   return _type->ideal_reg();
2680 }
2681 
2682 bool LoadStoreNode::result_not_used() const {
2683   for( DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++ ) {
2684     Node *x = fast_out(i);
2685     if (x->Opcode() == Op_SCMemProj) continue;
2686     return false;
2687   }
2688   return true;
2689 }
2690 
2691 uint LoadStoreNode::size_of() const { return sizeof(*this); }
2692 
2693 //=============================================================================
2694 //----------------------------------LoadStoreConditionalNode--------------------
2695 LoadStoreConditionalNode::LoadStoreConditionalNode( Node *c, Node *mem, Node *adr, Node *val, Node *ex ) : LoadStoreNode(c, mem, adr, val, NULL, TypeInt::BOOL, 5) {
2696   init_req(ExpectedIn, ex );
2697 }
2698 
2699 //=============================================================================
2700 //-------------------------------adr_type--------------------------------------
2701 const TypePtr* ClearArrayNode::adr_type() const {
2702   Node *adr = in(3);
2703   if (adr == NULL)  return NULL; // node is dead
2704   return MemNode::calculate_adr_type(adr->bottom_type());
2705 }
2706 
2707 //------------------------------match_edge-------------------------------------
2708 // Do we Match on this edge index or not?  Do not match memory
2709 uint ClearArrayNode::match_edge(uint idx) const {
2710   return idx > 1;
2711 }
2712 
2713 //------------------------------Identity---------------------------------------
2714 // Clearing a zero length array does nothing
2715 Node* ClearArrayNode::Identity(PhaseGVN* phase) {
2716   return phase->type(in(2))->higher_equal(TypeX::ZERO)  ? in(1) : this;
2717 }
2718 
2719 //------------------------------Idealize---------------------------------------
2720 // Clearing a short array is faster with stores
2721 Node *ClearArrayNode::Ideal(PhaseGVN *phase, bool can_reshape){
2722   // Already know this is a large node, do not try to ideal it
2723   if (_is_large) return NULL;
2724 
2725   const int unit = BytesPerLong;
2726   const TypeX* t = phase->type(in(2))->isa_intptr_t();
2727   if (!t)  return NULL;
2728   if (!t->is_con())  return NULL;
2729   intptr_t raw_count = t->get_con();
2730   intptr_t size = raw_count;
2731   if (!Matcher::init_array_count_is_in_bytes) size *= unit;
2732   // Clearing nothing uses the Identity call.
2733   // Negative clears are possible on dead ClearArrays
2734   // (see jck test stmt114.stmt11402.val).
2735   if (size <= 0 || size % unit != 0)  return NULL;
2736   intptr_t count = size / unit;
2737   // Length too long; communicate this to matchers and assemblers.
2738   // Assemblers are responsible to produce fast hardware clears for it.
2739   if (size > InitArrayShortSize) {
2740     return new ClearArrayNode(in(0), in(1), in(2), in(3), true);
2741   }
2742   Node *mem = in(1);
2743   if( phase->type(mem)==Type::TOP ) return NULL;
2744   Node *adr = in(3);
2745   const Type* at = phase->type(adr);
2746   if( at==Type::TOP ) return NULL;
2747   const TypePtr* atp = at->isa_ptr();
2748   // adjust atp to be the correct array element address type
2749   if (atp == NULL)  atp = TypePtr::BOTTOM;
2750   else              atp = atp->add_offset(Type::OffsetBot);
2751   // Get base for derived pointer purposes
2752   if( adr->Opcode() != Op_AddP ) Unimplemented();
2753   Node *base = adr->in(1);
2754 
2755   Node *zero = phase->makecon(TypeLong::ZERO);
2756   Node *off  = phase->MakeConX(BytesPerLong);
2757   mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
2758   count--;
2759   while( count-- ) {
2760     mem = phase->transform(mem);
2761     adr = phase->transform(new AddPNode(base,adr,off));
2762     mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
2763   }
2764   return mem;
2765 }
2766 
2767 //----------------------------step_through----------------------------------
2768 // Return allocation input memory edge if it is different instance
2769 // or itself if it is the one we are looking for.
2770 bool ClearArrayNode::step_through(Node** np, uint instance_id, PhaseTransform* phase) {
2771   Node* n = *np;
2772   assert(n->is_ClearArray(), "sanity");
2773   intptr_t offset;
2774   AllocateNode* alloc = AllocateNode::Ideal_allocation(n->in(3), phase, offset);
2775   // This method is called only before Allocate nodes are expanded
2776   // during macro nodes expansion. Before that ClearArray nodes are
2777   // only generated in PhaseMacroExpand::generate_arraycopy() (before
2778   // Allocate nodes are expanded) which follows allocations.
2779   assert(alloc != NULL, "should have allocation");
2780   if (alloc->_idx == instance_id) {
2781     // Can not bypass initialization of the instance we are looking for.
2782     return false;
2783   }
2784   // Otherwise skip it.
2785   InitializeNode* init = alloc->initialization();
2786   if (init != NULL)
2787     *np = init->in(TypeFunc::Memory);
2788   else
2789     *np = alloc->in(TypeFunc::Memory);
2790   return true;
2791 }
2792 
2793 //----------------------------clear_memory-------------------------------------
2794 // Generate code to initialize object storage to zero.
2795 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2796                                    intptr_t start_offset,
2797                                    Node* end_offset,
2798                                    PhaseGVN* phase) {
2799   intptr_t offset = start_offset;
2800 
2801   int unit = BytesPerLong;
2802   if ((offset % unit) != 0) {
2803     Node* adr = new AddPNode(dest, dest, phase->MakeConX(offset));
2804     adr = phase->transform(adr);
2805     const TypePtr* atp = TypeRawPtr::BOTTOM;
2806     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
2807     mem = phase->transform(mem);
2808     offset += BytesPerInt;
2809   }
2810   assert((offset % unit) == 0, "");
2811 
2812   // Initialize the remaining stuff, if any, with a ClearArray.
2813   return clear_memory(ctl, mem, dest, phase->MakeConX(offset), end_offset, phase);
2814 }
2815 
2816 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2817                                    Node* start_offset,
2818                                    Node* end_offset,
2819                                    PhaseGVN* phase) {
2820   if (start_offset == end_offset) {
2821     // nothing to do
2822     return mem;
2823   }
2824 
2825   int unit = BytesPerLong;
2826   Node* zbase = start_offset;
2827   Node* zend  = end_offset;
2828 
2829   // Scale to the unit required by the CPU:
2830   if (!Matcher::init_array_count_is_in_bytes) {
2831     Node* shift = phase->intcon(exact_log2(unit));
2832     zbase = phase->transform(new URShiftXNode(zbase, shift) );
2833     zend  = phase->transform(new URShiftXNode(zend,  shift) );
2834   }
2835 
2836   // Bulk clear double-words
2837   Node* zsize = phase->transform(new SubXNode(zend, zbase) );
2838   Node* adr = phase->transform(new AddPNode(dest, dest, start_offset) );
2839   mem = new ClearArrayNode(ctl, mem, zsize, adr, false);
2840   return phase->transform(mem);
2841 }
2842 
2843 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2844                                    intptr_t start_offset,
2845                                    intptr_t end_offset,
2846                                    PhaseGVN* phase) {
2847   if (start_offset == end_offset) {
2848     // nothing to do
2849     return mem;
2850   }
2851 
2852   assert((end_offset % BytesPerInt) == 0, "odd end offset");
2853   intptr_t done_offset = end_offset;
2854   if ((done_offset % BytesPerLong) != 0) {
2855     done_offset -= BytesPerInt;
2856   }
2857   if (done_offset > start_offset) {
2858     mem = clear_memory(ctl, mem, dest,
2859                        start_offset, phase->MakeConX(done_offset), phase);
2860   }
2861   if (done_offset < end_offset) { // emit the final 32-bit store
2862     Node* adr = new AddPNode(dest, dest, phase->MakeConX(done_offset));
2863     adr = phase->transform(adr);
2864     const TypePtr* atp = TypeRawPtr::BOTTOM;
2865     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
2866     mem = phase->transform(mem);
2867     done_offset += BytesPerInt;
2868   }
2869   assert(done_offset == end_offset, "");
2870   return mem;
2871 }
2872 
2873 //=============================================================================
2874 MemBarNode::MemBarNode(Compile* C, int alias_idx, Node* precedent)
2875   : MultiNode(TypeFunc::Parms + (precedent == NULL? 0: 1)),
2876     _adr_type(C->get_adr_type(alias_idx))
2877 {
2878   init_class_id(Class_MemBar);
2879   Node* top = C->top();
2880   init_req(TypeFunc::I_O,top);
2881   init_req(TypeFunc::FramePtr,top);
2882   init_req(TypeFunc::ReturnAdr,top);
2883   if (precedent != NULL)
2884     init_req(TypeFunc::Parms, precedent);
2885 }
2886 
2887 //------------------------------cmp--------------------------------------------
2888 uint MemBarNode::hash() const { return NO_HASH; }
2889 uint MemBarNode::cmp( const Node &n ) const {
2890   return (&n == this);          // Always fail except on self
2891 }
2892 
2893 //------------------------------make-------------------------------------------
2894 MemBarNode* MemBarNode::make(Compile* C, int opcode, int atp, Node* pn) {
2895   switch (opcode) {
2896   case Op_MemBarAcquire:     return new MemBarAcquireNode(C, atp, pn);
2897   case Op_LoadFence:         return new LoadFenceNode(C, atp, pn);
2898   case Op_MemBarRelease:     return new MemBarReleaseNode(C, atp, pn);
2899   case Op_StoreFence:        return new StoreFenceNode(C, atp, pn);
2900   case Op_MemBarAcquireLock: return new MemBarAcquireLockNode(C, atp, pn);
2901   case Op_MemBarReleaseLock: return new MemBarReleaseLockNode(C, atp, pn);
2902   case Op_MemBarVolatile:    return new MemBarVolatileNode(C, atp, pn);
2903   case Op_MemBarCPUOrder:    return new MemBarCPUOrderNode(C, atp, pn);
2904   case Op_OnSpinWait:        return new OnSpinWaitNode(C, atp, pn);
2905   case Op_Initialize:        return new InitializeNode(C, atp, pn);
2906   case Op_MemBarStoreStore:  return new MemBarStoreStoreNode(C, atp, pn);
2907   default: ShouldNotReachHere(); return NULL;
2908   }
2909 }
2910 
2911 //------------------------------Ideal------------------------------------------
2912 // Return a node which is more "ideal" than the current node.  Strip out
2913 // control copies
2914 Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2915   if (remove_dead_region(phase, can_reshape)) return this;
2916   // Don't bother trying to transform a dead node
2917   if (in(0) && in(0)->is_top()) {
2918     return NULL;
2919   }
2920 
2921   bool progress = false;
2922   // Eliminate volatile MemBars for scalar replaced objects.
2923   if (can_reshape && req() == (Precedent+1)) {
2924     bool eliminate = false;
2925     int opc = Opcode();
2926     if ((opc == Op_MemBarAcquire || opc == Op_MemBarVolatile)) {
2927       // Volatile field loads and stores.
2928       Node* my_mem = in(MemBarNode::Precedent);
2929       // The MembarAquire may keep an unused LoadNode alive through the Precedent edge
2930       if ((my_mem != NULL) && (opc == Op_MemBarAcquire) && (my_mem->outcnt() == 1)) {
2931         // if the Precedent is a decodeN and its input (a Load) is used at more than one place,
2932         // replace this Precedent (decodeN) with the Load instead.
2933         if ((my_mem->Opcode() == Op_DecodeN) && (my_mem->in(1)->outcnt() > 1))  {
2934           Node* load_node = my_mem->in(1);
2935           set_req(MemBarNode::Precedent, load_node);
2936           phase->is_IterGVN()->_worklist.push(my_mem);
2937           my_mem = load_node;
2938         } else {
2939           assert(my_mem->unique_out() == this, "sanity");
2940           del_req(Precedent);
2941           phase->is_IterGVN()->_worklist.push(my_mem); // remove dead node later
2942           my_mem = NULL;
2943         }
2944         progress = true;
2945       }
2946       if (my_mem != NULL && my_mem->is_Mem()) {
2947         const TypeOopPtr* t_oop = my_mem->in(MemNode::Address)->bottom_type()->isa_oopptr();
2948         // Check for scalar replaced object reference.
2949         if( t_oop != NULL && t_oop->is_known_instance_field() &&
2950             t_oop->offset() != Type::OffsetBot &&
2951             t_oop->offset() != Type::OffsetTop) {
2952           eliminate = true;
2953         }
2954       }
2955     } else if (opc == Op_MemBarRelease) {
2956       // Final field stores.
2957       Node* alloc = AllocateNode::Ideal_allocation(in(MemBarNode::Precedent), phase);
2958       if ((alloc != NULL) && alloc->is_Allocate() &&
2959           alloc->as_Allocate()->does_not_escape_thread()) {
2960         // The allocated object does not escape.
2961         eliminate = true;
2962       }
2963     }
2964     if (eliminate) {
2965       // Replace MemBar projections by its inputs.
2966       PhaseIterGVN* igvn = phase->is_IterGVN();
2967       igvn->replace_node(proj_out(TypeFunc::Memory), in(TypeFunc::Memory));
2968       igvn->replace_node(proj_out(TypeFunc::Control), in(TypeFunc::Control));
2969       // Must return either the original node (now dead) or a new node
2970       // (Do not return a top here, since that would break the uniqueness of top.)
2971       return new ConINode(TypeInt::ZERO);
2972     }
2973   }
2974   return progress ? this : NULL;
2975 }
2976 
2977 //------------------------------Value------------------------------------------
2978 const Type* MemBarNode::Value(PhaseGVN* phase) const {
2979   if( !in(0) ) return Type::TOP;
2980   if( phase->type(in(0)) == Type::TOP )
2981     return Type::TOP;
2982   return TypeTuple::MEMBAR;
2983 }
2984 
2985 //------------------------------match------------------------------------------
2986 // Construct projections for memory.
2987 Node *MemBarNode::match( const ProjNode *proj, const Matcher *m ) {
2988   switch (proj->_con) {
2989   case TypeFunc::Control:
2990   case TypeFunc::Memory:
2991     return new MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
2992   }
2993   ShouldNotReachHere();
2994   return NULL;
2995 }
2996 
2997 //===========================InitializeNode====================================
2998 // SUMMARY:
2999 // This node acts as a memory barrier on raw memory, after some raw stores.
3000 // The 'cooked' oop value feeds from the Initialize, not the Allocation.
3001 // The Initialize can 'capture' suitably constrained stores as raw inits.
3002 // It can coalesce related raw stores into larger units (called 'tiles').
3003 // It can avoid zeroing new storage for memory units which have raw inits.
3004 // At macro-expansion, it is marked 'complete', and does not optimize further.
3005 //
3006 // EXAMPLE:
3007 // The object 'new short[2]' occupies 16 bytes in a 32-bit machine.
3008 //   ctl = incoming control; mem* = incoming memory
3009 // (Note:  A star * on a memory edge denotes I/O and other standard edges.)
3010 // First allocate uninitialized memory and fill in the header:
3011 //   alloc = (Allocate ctl mem* 16 #short[].klass ...)
3012 //   ctl := alloc.Control; mem* := alloc.Memory*
3013 //   rawmem = alloc.Memory; rawoop = alloc.RawAddress
3014 // Then initialize to zero the non-header parts of the raw memory block:
3015 //   init = (Initialize alloc.Control alloc.Memory* alloc.RawAddress)
3016 //   ctl := init.Control; mem.SLICE(#short[*]) := init.Memory
3017 // After the initialize node executes, the object is ready for service:
3018 //   oop := (CheckCastPP init.Control alloc.RawAddress #short[])
3019 // Suppose its body is immediately initialized as {1,2}:
3020 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
3021 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
3022 //   mem.SLICE(#short[*]) := store2
3023 //
3024 // DETAILS:
3025 // An InitializeNode collects and isolates object initialization after
3026 // an AllocateNode and before the next possible safepoint.  As a
3027 // memory barrier (MemBarNode), it keeps critical stores from drifting
3028 // down past any safepoint or any publication of the allocation.
3029 // Before this barrier, a newly-allocated object may have uninitialized bits.
3030 // After this barrier, it may be treated as a real oop, and GC is allowed.
3031 //
3032 // The semantics of the InitializeNode include an implicit zeroing of
3033 // the new object from object header to the end of the object.
3034 // (The object header and end are determined by the AllocateNode.)
3035 //
3036 // Certain stores may be added as direct inputs to the InitializeNode.
3037 // These stores must update raw memory, and they must be to addresses
3038 // derived from the raw address produced by AllocateNode, and with
3039 // a constant offset.  They must be ordered by increasing offset.
3040 // The first one is at in(RawStores), the last at in(req()-1).
3041 // Unlike most memory operations, they are not linked in a chain,
3042 // but are displayed in parallel as users of the rawmem output of
3043 // the allocation.
3044 //
3045 // (See comments in InitializeNode::capture_store, which continue
3046 // the example given above.)
3047 //
3048 // When the associated Allocate is macro-expanded, the InitializeNode
3049 // may be rewritten to optimize collected stores.  A ClearArrayNode
3050 // may also be created at that point to represent any required zeroing.
3051 // The InitializeNode is then marked 'complete', prohibiting further
3052 // capturing of nearby memory operations.
3053 //
3054 // During macro-expansion, all captured initializations which store
3055 // constant values of 32 bits or smaller are coalesced (if advantageous)
3056 // into larger 'tiles' 32 or 64 bits.  This allows an object to be
3057 // initialized in fewer memory operations.  Memory words which are
3058 // covered by neither tiles nor non-constant stores are pre-zeroed
3059 // by explicit stores of zero.  (The code shape happens to do all
3060 // zeroing first, then all other stores, with both sequences occurring
3061 // in order of ascending offsets.)
3062 //
3063 // Alternatively, code may be inserted between an AllocateNode and its
3064 // InitializeNode, to perform arbitrary initialization of the new object.
3065 // E.g., the object copying intrinsics insert complex data transfers here.
3066 // The initialization must then be marked as 'complete' disable the
3067 // built-in zeroing semantics and the collection of initializing stores.
3068 //
3069 // While an InitializeNode is incomplete, reads from the memory state
3070 // produced by it are optimizable if they match the control edge and
3071 // new oop address associated with the allocation/initialization.
3072 // They return a stored value (if the offset matches) or else zero.
3073 // A write to the memory state, if it matches control and address,
3074 // and if it is to a constant offset, may be 'captured' by the
3075 // InitializeNode.  It is cloned as a raw memory operation and rewired
3076 // inside the initialization, to the raw oop produced by the allocation.
3077 // Operations on addresses which are provably distinct (e.g., to
3078 // other AllocateNodes) are allowed to bypass the initialization.
3079 //
3080 // The effect of all this is to consolidate object initialization
3081 // (both arrays and non-arrays, both piecewise and bulk) into a
3082 // single location, where it can be optimized as a unit.
3083 //
3084 // Only stores with an offset less than TrackedInitializationLimit words
3085 // will be considered for capture by an InitializeNode.  This puts a
3086 // reasonable limit on the complexity of optimized initializations.
3087 
3088 //---------------------------InitializeNode------------------------------------
3089 InitializeNode::InitializeNode(Compile* C, int adr_type, Node* rawoop)
3090   : _is_complete(Incomplete), _does_not_escape(false),
3091     MemBarNode(C, adr_type, rawoop)
3092 {
3093   init_class_id(Class_Initialize);
3094 
3095   assert(adr_type == Compile::AliasIdxRaw, "only valid atp");
3096   assert(in(RawAddress) == rawoop, "proper init");
3097   // Note:  allocation() can be NULL, for secondary initialization barriers
3098 }
3099 
3100 // Since this node is not matched, it will be processed by the
3101 // register allocator.  Declare that there are no constraints
3102 // on the allocation of the RawAddress edge.
3103 const RegMask &InitializeNode::in_RegMask(uint idx) const {
3104   // This edge should be set to top, by the set_complete.  But be conservative.
3105   if (idx == InitializeNode::RawAddress)
3106     return *(Compile::current()->matcher()->idealreg2spillmask[in(idx)->ideal_reg()]);
3107   return RegMask::Empty;
3108 }
3109 
3110 Node* InitializeNode::memory(uint alias_idx) {
3111   Node* mem = in(Memory);
3112   if (mem->is_MergeMem()) {
3113     return mem->as_MergeMem()->memory_at(alias_idx);
3114   } else {
3115     // incoming raw memory is not split
3116     return mem;
3117   }
3118 }
3119 
3120 bool InitializeNode::is_non_zero() {
3121   if (is_complete())  return false;
3122   remove_extra_zeroes();
3123   return (req() > RawStores);
3124 }
3125 
3126 void InitializeNode::set_complete(PhaseGVN* phase) {
3127   assert(!is_complete(), "caller responsibility");
3128   _is_complete = Complete;
3129 
3130   // After this node is complete, it contains a bunch of
3131   // raw-memory initializations.  There is no need for
3132   // it to have anything to do with non-raw memory effects.
3133   // Therefore, tell all non-raw users to re-optimize themselves,
3134   // after skipping the memory effects of this initialization.
3135   PhaseIterGVN* igvn = phase->is_IterGVN();
3136   if (igvn)  igvn->add_users_to_worklist(this);
3137 }
3138 
3139 // convenience function
3140 // return false if the init contains any stores already
3141 bool AllocateNode::maybe_set_complete(PhaseGVN* phase) {
3142   InitializeNode* init = initialization();
3143   if (init == NULL || init->is_complete())  return false;
3144   init->remove_extra_zeroes();
3145   // for now, if this allocation has already collected any inits, bail:
3146   if (init->is_non_zero())  return false;
3147   init->set_complete(phase);
3148   return true;
3149 }
3150 
3151 void InitializeNode::remove_extra_zeroes() {
3152   if (req() == RawStores)  return;
3153   Node* zmem = zero_memory();
3154   uint fill = RawStores;
3155   for (uint i = fill; i < req(); i++) {
3156     Node* n = in(i);
3157     if (n->is_top() || n == zmem)  continue;  // skip
3158     if (fill < i)  set_req(fill, n);          // compact
3159     ++fill;
3160   }
3161   // delete any empty spaces created:
3162   while (fill < req()) {
3163     del_req(fill);
3164   }
3165 }
3166 
3167 // Helper for remembering which stores go with which offsets.
3168 intptr_t InitializeNode::get_store_offset(Node* st, PhaseTransform* phase) {
3169   if (!st->is_Store())  return -1;  // can happen to dead code via subsume_node
3170   intptr_t offset = -1;
3171   Node* base = AddPNode::Ideal_base_and_offset(st->in(MemNode::Address),
3172                                                phase, offset);
3173   if (base == NULL)     return -1;  // something is dead,
3174   if (offset < 0)       return -1;  //        dead, dead
3175   return offset;
3176 }
3177 
3178 // Helper for proving that an initialization expression is
3179 // "simple enough" to be folded into an object initialization.
3180 // Attempts to prove that a store's initial value 'n' can be captured
3181 // within the initialization without creating a vicious cycle, such as:
3182 //     { Foo p = new Foo(); p.next = p; }
3183 // True for constants and parameters and small combinations thereof.
3184 bool InitializeNode::detect_init_independence(Node* n, int& count) {
3185   if (n == NULL)      return true;   // (can this really happen?)
3186   if (n->is_Proj())   n = n->in(0);
3187   if (n == this)      return false;  // found a cycle
3188   if (n->is_Con())    return true;
3189   if (n->is_Start())  return true;   // params, etc., are OK
3190   if (n->is_Root())   return true;   // even better
3191 
3192   Node* ctl = n->in(0);
3193   if (ctl != NULL && !ctl->is_top()) {
3194     if (ctl->is_Proj())  ctl = ctl->in(0);
3195     if (ctl == this)  return false;
3196 
3197     // If we already know that the enclosing memory op is pinned right after
3198     // the init, then any control flow that the store has picked up
3199     // must have preceded the init, or else be equal to the init.
3200     // Even after loop optimizations (which might change control edges)
3201     // a store is never pinned *before* the availability of its inputs.
3202     if (!MemNode::all_controls_dominate(n, this))
3203       return false;                  // failed to prove a good control
3204   }
3205 
3206   // Check data edges for possible dependencies on 'this'.
3207   if ((count += 1) > 20)  return false;  // complexity limit
3208   for (uint i = 1; i < n->req(); i++) {
3209     Node* m = n->in(i);
3210     if (m == NULL || m == n || m->is_top())  continue;
3211     uint first_i = n->find_edge(m);
3212     if (i != first_i)  continue;  // process duplicate edge just once
3213     if (!detect_init_independence(m, count)) {
3214       return false;
3215     }
3216   }
3217 
3218   return true;
3219 }
3220 
3221 // Here are all the checks a Store must pass before it can be moved into
3222 // an initialization.  Returns zero if a check fails.
3223 // On success, returns the (constant) offset to which the store applies,
3224 // within the initialized memory.
3225 intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseTransform* phase, bool can_reshape) {
3226   const int FAIL = 0;
3227   if (st->is_unaligned_access()) {
3228     return FAIL;
3229   }
3230   if (st->req() != MemNode::ValueIn + 1)
3231     return FAIL;                // an inscrutable StoreNode (card mark?)
3232   Node* ctl = st->in(MemNode::Control);
3233   if (!(ctl != NULL && ctl->is_Proj() && ctl->in(0) == this))
3234     return FAIL;                // must be unconditional after the initialization
3235   Node* mem = st->in(MemNode::Memory);
3236   if (!(mem->is_Proj() && mem->in(0) == this))
3237     return FAIL;                // must not be preceded by other stores
3238   Node* adr = st->in(MemNode::Address);
3239   intptr_t offset;
3240   AllocateNode* alloc = AllocateNode::Ideal_allocation(adr, phase, offset);
3241   if (alloc == NULL)
3242     return FAIL;                // inscrutable address
3243   if (alloc != allocation())
3244     return FAIL;                // wrong allocation!  (store needs to float up)
3245   Node* val = st->in(MemNode::ValueIn);
3246   int complexity_count = 0;
3247   if (!detect_init_independence(val, complexity_count))
3248     return FAIL;                // stored value must be 'simple enough'
3249 
3250   // The Store can be captured only if nothing after the allocation
3251   // and before the Store is using the memory location that the store
3252   // overwrites.
3253   bool failed = false;
3254   // If is_complete_with_arraycopy() is true the shape of the graph is
3255   // well defined and is safe so no need for extra checks.
3256   if (!is_complete_with_arraycopy()) {
3257     // We are going to look at each use of the memory state following
3258     // the allocation to make sure nothing reads the memory that the
3259     // Store writes.
3260     const TypePtr* t_adr = phase->type(adr)->isa_ptr();
3261     int alias_idx = phase->C->get_alias_index(t_adr);
3262     ResourceMark rm;
3263     Unique_Node_List mems;
3264     mems.push(mem);
3265     Node* unique_merge = NULL;
3266     for (uint next = 0; next < mems.size(); ++next) {
3267       Node *m  = mems.at(next);
3268       for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
3269         Node *n = m->fast_out(j);
3270         if (n->outcnt() == 0) {
3271           continue;
3272         }
3273         if (n == st) {
3274           continue;
3275         } else if (n->in(0) != NULL && n->in(0) != ctl) {
3276           // If the control of this use is different from the control
3277           // of the Store which is right after the InitializeNode then
3278           // this node cannot be between the InitializeNode and the
3279           // Store.
3280           continue;
3281         } else if (n->is_MergeMem()) {
3282           if (n->as_MergeMem()->memory_at(alias_idx) == m) {
3283             // We can hit a MergeMemNode (that will likely go away
3284             // later) that is a direct use of the memory state
3285             // following the InitializeNode on the same slice as the
3286             // store node that we'd like to capture. We need to check
3287             // the uses of the MergeMemNode.
3288             mems.push(n);
3289           }
3290         } else if (n->is_Mem()) {
3291           Node* other_adr = n->in(MemNode::Address);
3292           if (other_adr == adr) {
3293             failed = true;
3294             break;
3295           } else {
3296             const TypePtr* other_t_adr = phase->type(other_adr)->isa_ptr();
3297             if (other_t_adr != NULL) {
3298               int other_alias_idx = phase->C->get_alias_index(other_t_adr);
3299               if (other_alias_idx == alias_idx) {
3300                 // A load from the same memory slice as the store right
3301                 // after the InitializeNode. We check the control of the
3302                 // object/array that is loaded from. If it's the same as
3303                 // the store control then we cannot capture the store.
3304                 assert(!n->is_Store(), "2 stores to same slice on same control?");
3305                 Node* base = other_adr;
3306                 assert(base->is_AddP(), "should be addp but is %s", base->Name());
3307                 base = base->in(AddPNode::Base);
3308                 if (base != NULL) {
3309                   base = base->uncast();
3310                   if (base->is_Proj() && base->in(0) == alloc) {
3311                     failed = true;
3312                     break;
3313                   }
3314                 }
3315               }
3316             }
3317           }
3318         } else {
3319           failed = true;
3320           break;
3321         }
3322       }
3323     }
3324   }
3325   if (failed) {
3326     if (!can_reshape) {
3327       // We decided we couldn't capture the store during parsing. We
3328       // should try again during the next IGVN once the graph is
3329       // cleaner.
3330       phase->C->record_for_igvn(st);
3331     }
3332     return FAIL;
3333   }
3334 
3335   return offset;                // success
3336 }
3337 
3338 // Find the captured store in(i) which corresponds to the range
3339 // [start..start+size) in the initialized object.
3340 // If there is one, return its index i.  If there isn't, return the
3341 // negative of the index where it should be inserted.
3342 // Return 0 if the queried range overlaps an initialization boundary
3343 // or if dead code is encountered.
3344 // If size_in_bytes is zero, do not bother with overlap checks.
3345 int InitializeNode::captured_store_insertion_point(intptr_t start,
3346                                                    int size_in_bytes,
3347                                                    PhaseTransform* phase) {
3348   const int FAIL = 0, MAX_STORE = BytesPerLong;
3349 
3350   if (is_complete())
3351     return FAIL;                // arraycopy got here first; punt
3352 
3353   assert(allocation() != NULL, "must be present");
3354 
3355   // no negatives, no header fields:
3356   if (start < (intptr_t) allocation()->minimum_header_size())  return FAIL;
3357 
3358   // after a certain size, we bail out on tracking all the stores:
3359   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
3360   if (start >= ti_limit)  return FAIL;
3361 
3362   for (uint i = InitializeNode::RawStores, limit = req(); ; ) {
3363     if (i >= limit)  return -(int)i; // not found; here is where to put it
3364 
3365     Node*    st     = in(i);
3366     intptr_t st_off = get_store_offset(st, phase);
3367     if (st_off < 0) {
3368       if (st != zero_memory()) {
3369         return FAIL;            // bail out if there is dead garbage
3370       }
3371     } else if (st_off > start) {
3372       // ...we are done, since stores are ordered
3373       if (st_off < start + size_in_bytes) {
3374         return FAIL;            // the next store overlaps
3375       }
3376       return -(int)i;           // not found; here is where to put it
3377     } else if (st_off < start) {
3378       if (size_in_bytes != 0 &&
3379           start < st_off + MAX_STORE &&
3380           start < st_off + st->as_Store()->memory_size()) {
3381         return FAIL;            // the previous store overlaps
3382       }
3383     } else {
3384       if (size_in_bytes != 0 &&
3385           st->as_Store()->memory_size() != size_in_bytes) {
3386         return FAIL;            // mismatched store size
3387       }
3388       return i;
3389     }
3390 
3391     ++i;
3392   }
3393 }
3394 
3395 // Look for a captured store which initializes at the offset 'start'
3396 // with the given size.  If there is no such store, and no other
3397 // initialization interferes, then return zero_memory (the memory
3398 // projection of the AllocateNode).
3399 Node* InitializeNode::find_captured_store(intptr_t start, int size_in_bytes,
3400                                           PhaseTransform* phase) {
3401   assert(stores_are_sane(phase), "");
3402   int i = captured_store_insertion_point(start, size_in_bytes, phase);
3403   if (i == 0) {
3404     return NULL;                // something is dead
3405   } else if (i < 0) {
3406     return zero_memory();       // just primordial zero bits here
3407   } else {
3408     Node* st = in(i);           // here is the store at this position
3409     assert(get_store_offset(st->as_Store(), phase) == start, "sanity");
3410     return st;
3411   }
3412 }
3413 
3414 // Create, as a raw pointer, an address within my new object at 'offset'.
3415 Node* InitializeNode::make_raw_address(intptr_t offset,
3416                                        PhaseTransform* phase) {
3417   Node* addr = in(RawAddress);
3418   if (offset != 0) {
3419     Compile* C = phase->C;
3420     addr = phase->transform( new AddPNode(C->top(), addr,
3421                                                  phase->MakeConX(offset)) );
3422   }
3423   return addr;
3424 }
3425 
3426 // Clone the given store, converting it into a raw store
3427 // initializing a field or element of my new object.
3428 // Caller is responsible for retiring the original store,
3429 // with subsume_node or the like.
3430 //
3431 // From the example above InitializeNode::InitializeNode,
3432 // here are the old stores to be captured:
3433 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
3434 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
3435 //
3436 // Here is the changed code; note the extra edges on init:
3437 //   alloc = (Allocate ...)
3438 //   rawoop = alloc.RawAddress
3439 //   rawstore1 = (StoreC alloc.Control alloc.Memory (+ rawoop 12) 1)
3440 //   rawstore2 = (StoreC alloc.Control alloc.Memory (+ rawoop 14) 2)
3441 //   init = (Initialize alloc.Control alloc.Memory rawoop
3442 //                      rawstore1 rawstore2)
3443 //
3444 Node* InitializeNode::capture_store(StoreNode* st, intptr_t start,
3445                                     PhaseTransform* phase, bool can_reshape) {
3446   assert(stores_are_sane(phase), "");
3447 
3448   if (start < 0)  return NULL;
3449   assert(can_capture_store(st, phase, can_reshape) == start, "sanity");
3450 
3451   Compile* C = phase->C;
3452   int size_in_bytes = st->memory_size();
3453   int i = captured_store_insertion_point(start, size_in_bytes, phase);
3454   if (i == 0)  return NULL;     // bail out
3455   Node* prev_mem = NULL;        // raw memory for the captured store
3456   if (i > 0) {
3457     prev_mem = in(i);           // there is a pre-existing store under this one
3458     set_req(i, C->top());       // temporarily disconnect it
3459     // See StoreNode::Ideal 'st->outcnt() == 1' for the reason to disconnect.
3460   } else {
3461     i = -i;                     // no pre-existing store
3462     prev_mem = zero_memory();   // a slice of the newly allocated object
3463     if (i > InitializeNode::RawStores && in(i-1) == prev_mem)
3464       set_req(--i, C->top());   // reuse this edge; it has been folded away
3465     else
3466       ins_req(i, C->top());     // build a new edge
3467   }
3468   Node* new_st = st->clone();
3469   new_st->set_req(MemNode::Control, in(Control));
3470   new_st->set_req(MemNode::Memory,  prev_mem);
3471   new_st->set_req(MemNode::Address, make_raw_address(start, phase));
3472   new_st = phase->transform(new_st);
3473 
3474   // At this point, new_st might have swallowed a pre-existing store
3475   // at the same offset, or perhaps new_st might have disappeared,
3476   // if it redundantly stored the same value (or zero to fresh memory).
3477 
3478   // In any case, wire it in:
3479   phase->igvn_rehash_node_delayed(this);
3480   set_req(i, new_st);
3481 
3482   // The caller may now kill the old guy.
3483   DEBUG_ONLY(Node* check_st = find_captured_store(start, size_in_bytes, phase));
3484   assert(check_st == new_st || check_st == NULL, "must be findable");
3485   assert(!is_complete(), "");
3486   return new_st;
3487 }
3488 
3489 static bool store_constant(jlong* tiles, int num_tiles,
3490                            intptr_t st_off, int st_size,
3491                            jlong con) {
3492   if ((st_off & (st_size-1)) != 0)
3493     return false;               // strange store offset (assume size==2**N)
3494   address addr = (address)tiles + st_off;
3495   assert(st_off >= 0 && addr+st_size <= (address)&tiles[num_tiles], "oob");
3496   switch (st_size) {
3497   case sizeof(jbyte):  *(jbyte*) addr = (jbyte) con; break;
3498   case sizeof(jchar):  *(jchar*) addr = (jchar) con; break;
3499   case sizeof(jint):   *(jint*)  addr = (jint)  con; break;
3500   case sizeof(jlong):  *(jlong*) addr = (jlong) con; break;
3501   default: return false;        // strange store size (detect size!=2**N here)
3502   }
3503   return true;                  // return success to caller
3504 }
3505 
3506 // Coalesce subword constants into int constants and possibly
3507 // into long constants.  The goal, if the CPU permits,
3508 // is to initialize the object with a small number of 64-bit tiles.
3509 // Also, convert floating-point constants to bit patterns.
3510 // Non-constants are not relevant to this pass.
3511 //
3512 // In terms of the running example on InitializeNode::InitializeNode
3513 // and InitializeNode::capture_store, here is the transformation
3514 // of rawstore1 and rawstore2 into rawstore12:
3515 //   alloc = (Allocate ...)
3516 //   rawoop = alloc.RawAddress
3517 //   tile12 = 0x00010002
3518 //   rawstore12 = (StoreI alloc.Control alloc.Memory (+ rawoop 12) tile12)
3519 //   init = (Initialize alloc.Control alloc.Memory rawoop rawstore12)
3520 //
3521 void
3522 InitializeNode::coalesce_subword_stores(intptr_t header_size,
3523                                         Node* size_in_bytes,
3524                                         PhaseGVN* phase) {
3525   Compile* C = phase->C;
3526 
3527   assert(stores_are_sane(phase), "");
3528   // Note:  After this pass, they are not completely sane,
3529   // since there may be some overlaps.
3530 
3531   int old_subword = 0, old_long = 0, new_int = 0, new_long = 0;
3532 
3533   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
3534   intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, ti_limit);
3535   size_limit = MIN2(size_limit, ti_limit);
3536   size_limit = align_size_up(size_limit, BytesPerLong);
3537   int num_tiles = size_limit / BytesPerLong;
3538 
3539   // allocate space for the tile map:
3540   const int small_len = DEBUG_ONLY(true ? 3 :) 30; // keep stack frames small
3541   jlong  tiles_buf[small_len];
3542   Node*  nodes_buf[small_len];
3543   jlong  inits_buf[small_len];
3544   jlong* tiles = ((num_tiles <= small_len) ? &tiles_buf[0]
3545                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
3546   Node** nodes = ((num_tiles <= small_len) ? &nodes_buf[0]
3547                   : NEW_RESOURCE_ARRAY(Node*, num_tiles));
3548   jlong* inits = ((num_tiles <= small_len) ? &inits_buf[0]
3549                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
3550   // tiles: exact bitwise model of all primitive constants
3551   // nodes: last constant-storing node subsumed into the tiles model
3552   // inits: which bytes (in each tile) are touched by any initializations
3553 
3554   //// Pass A: Fill in the tile model with any relevant stores.
3555 
3556   Copy::zero_to_bytes(tiles, sizeof(tiles[0]) * num_tiles);
3557   Copy::zero_to_bytes(nodes, sizeof(nodes[0]) * num_tiles);
3558   Copy::zero_to_bytes(inits, sizeof(inits[0]) * num_tiles);
3559   Node* zmem = zero_memory(); // initially zero memory state
3560   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
3561     Node* st = in(i);
3562     intptr_t st_off = get_store_offset(st, phase);
3563 
3564     // Figure out the store's offset and constant value:
3565     if (st_off < header_size)             continue; //skip (ignore header)
3566     if (st->in(MemNode::Memory) != zmem)  continue; //skip (odd store chain)
3567     int st_size = st->as_Store()->memory_size();
3568     if (st_off + st_size > size_limit)    break;
3569 
3570     // Record which bytes are touched, whether by constant or not.
3571     if (!store_constant(inits, num_tiles, st_off, st_size, (jlong) -1))
3572       continue;                 // skip (strange store size)
3573 
3574     const Type* val = phase->type(st->in(MemNode::ValueIn));
3575     if (!val->singleton())                continue; //skip (non-con store)
3576     BasicType type = val->basic_type();
3577 
3578     jlong con = 0;
3579     switch (type) {
3580     case T_INT:    con = val->is_int()->get_con();  break;
3581     case T_LONG:   con = val->is_long()->get_con(); break;
3582     case T_FLOAT:  con = jint_cast(val->getf());    break;
3583     case T_DOUBLE: con = jlong_cast(val->getd());   break;
3584     default:                              continue; //skip (odd store type)
3585     }
3586 
3587     if (type == T_LONG && Matcher::isSimpleConstant64(con) &&
3588         st->Opcode() == Op_StoreL) {
3589       continue;                 // This StoreL is already optimal.
3590     }
3591 
3592     // Store down the constant.
3593     store_constant(tiles, num_tiles, st_off, st_size, con);
3594 
3595     intptr_t j = st_off >> LogBytesPerLong;
3596 
3597     if (type == T_INT && st_size == BytesPerInt
3598         && (st_off & BytesPerInt) == BytesPerInt) {
3599       jlong lcon = tiles[j];
3600       if (!Matcher::isSimpleConstant64(lcon) &&
3601           st->Opcode() == Op_StoreI) {
3602         // This StoreI is already optimal by itself.
3603         jint* intcon = (jint*) &tiles[j];
3604         intcon[1] = 0;  // undo the store_constant()
3605 
3606         // If the previous store is also optimal by itself, back up and
3607         // undo the action of the previous loop iteration... if we can.
3608         // But if we can't, just let the previous half take care of itself.
3609         st = nodes[j];
3610         st_off -= BytesPerInt;
3611         con = intcon[0];
3612         if (con != 0 && st != NULL && st->Opcode() == Op_StoreI) {
3613           assert(st_off >= header_size, "still ignoring header");
3614           assert(get_store_offset(st, phase) == st_off, "must be");
3615           assert(in(i-1) == zmem, "must be");
3616           DEBUG_ONLY(const Type* tcon = phase->type(st->in(MemNode::ValueIn)));
3617           assert(con == tcon->is_int()->get_con(), "must be");
3618           // Undo the effects of the previous loop trip, which swallowed st:
3619           intcon[0] = 0;        // undo store_constant()
3620           set_req(i-1, st);     // undo set_req(i, zmem)
3621           nodes[j] = NULL;      // undo nodes[j] = st
3622           --old_subword;        // undo ++old_subword
3623         }
3624         continue;               // This StoreI is already optimal.
3625       }
3626     }
3627 
3628     // This store is not needed.
3629     set_req(i, zmem);
3630     nodes[j] = st;              // record for the moment
3631     if (st_size < BytesPerLong) // something has changed
3632           ++old_subword;        // includes int/float, but who's counting...
3633     else  ++old_long;
3634   }
3635 
3636   if ((old_subword + old_long) == 0)
3637     return;                     // nothing more to do
3638 
3639   //// Pass B: Convert any non-zero tiles into optimal constant stores.
3640   // Be sure to insert them before overlapping non-constant stores.
3641   // (E.g., byte[] x = { 1,2,y,4 }  =>  x[int 0] = 0x01020004, x[2]=y.)
3642   for (int j = 0; j < num_tiles; j++) {
3643     jlong con  = tiles[j];
3644     jlong init = inits[j];
3645     if (con == 0)  continue;
3646     jint con0,  con1;           // split the constant, address-wise
3647     jint init0, init1;          // split the init map, address-wise
3648     { union { jlong con; jint intcon[2]; } u;
3649       u.con = con;
3650       con0  = u.intcon[0];
3651       con1  = u.intcon[1];
3652       u.con = init;
3653       init0 = u.intcon[0];
3654       init1 = u.intcon[1];
3655     }
3656 
3657     Node* old = nodes[j];
3658     assert(old != NULL, "need the prior store");
3659     intptr_t offset = (j * BytesPerLong);
3660 
3661     bool split = !Matcher::isSimpleConstant64(con);
3662 
3663     if (offset < header_size) {
3664       assert(offset + BytesPerInt >= header_size, "second int counts");
3665       assert(*(jint*)&tiles[j] == 0, "junk in header");
3666       split = true;             // only the second word counts
3667       // Example:  int a[] = { 42 ... }
3668     } else if (con0 == 0 && init0 == -1) {
3669       split = true;             // first word is covered by full inits
3670       // Example:  int a[] = { ... foo(), 42 ... }
3671     } else if (con1 == 0 && init1 == -1) {
3672       split = true;             // second word is covered by full inits
3673       // Example:  int a[] = { ... 42, foo() ... }
3674     }
3675 
3676     // Here's a case where init0 is neither 0 nor -1:
3677     //   byte a[] = { ... 0,0,foo(),0,  0,0,0,42 ... }
3678     // Assuming big-endian memory, init0, init1 are 0x0000FF00, 0x000000FF.
3679     // In this case the tile is not split; it is (jlong)42.
3680     // The big tile is stored down, and then the foo() value is inserted.
3681     // (If there were foo(),foo() instead of foo(),0, init0 would be -1.)
3682 
3683     Node* ctl = old->in(MemNode::Control);
3684     Node* adr = make_raw_address(offset, phase);
3685     const TypePtr* atp = TypeRawPtr::BOTTOM;
3686 
3687     // One or two coalesced stores to plop down.
3688     Node*    st[2];
3689     intptr_t off[2];
3690     int  nst = 0;
3691     if (!split) {
3692       ++new_long;
3693       off[nst] = offset;
3694       st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
3695                                   phase->longcon(con), T_LONG, MemNode::unordered);
3696     } else {
3697       // Omit either if it is a zero.
3698       if (con0 != 0) {
3699         ++new_int;
3700         off[nst]  = offset;
3701         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
3702                                     phase->intcon(con0), T_INT, MemNode::unordered);
3703       }
3704       if (con1 != 0) {
3705         ++new_int;
3706         offset += BytesPerInt;
3707         adr = make_raw_address(offset, phase);
3708         off[nst]  = offset;
3709         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
3710                                     phase->intcon(con1), T_INT, MemNode::unordered);
3711       }
3712     }
3713 
3714     // Insert second store first, then the first before the second.
3715     // Insert each one just before any overlapping non-constant stores.
3716     while (nst > 0) {
3717       Node* st1 = st[--nst];
3718       C->copy_node_notes_to(st1, old);
3719       st1 = phase->transform(st1);
3720       offset = off[nst];
3721       assert(offset >= header_size, "do not smash header");
3722       int ins_idx = captured_store_insertion_point(offset, /*size:*/0, phase);
3723       guarantee(ins_idx != 0, "must re-insert constant store");
3724       if (ins_idx < 0)  ins_idx = -ins_idx;  // never overlap
3725       if (ins_idx > InitializeNode::RawStores && in(ins_idx-1) == zmem)
3726         set_req(--ins_idx, st1);
3727       else
3728         ins_req(ins_idx, st1);
3729     }
3730   }
3731 
3732   if (PrintCompilation && WizardMode)
3733     tty->print_cr("Changed %d/%d subword/long constants into %d/%d int/long",
3734                   old_subword, old_long, new_int, new_long);
3735   if (C->log() != NULL)
3736     C->log()->elem("comment that='%d/%d subword/long to %d/%d int/long'",
3737                    old_subword, old_long, new_int, new_long);
3738 
3739   // Clean up any remaining occurrences of zmem:
3740   remove_extra_zeroes();
3741 }
3742 
3743 // Explore forward from in(start) to find the first fully initialized
3744 // word, and return its offset.  Skip groups of subword stores which
3745 // together initialize full words.  If in(start) is itself part of a
3746 // fully initialized word, return the offset of in(start).  If there
3747 // are no following full-word stores, or if something is fishy, return
3748 // a negative value.
3749 intptr_t InitializeNode::find_next_fullword_store(uint start, PhaseGVN* phase) {
3750   int       int_map = 0;
3751   intptr_t  int_map_off = 0;
3752   const int FULL_MAP = right_n_bits(BytesPerInt);  // the int_map we hope for
3753 
3754   for (uint i = start, limit = req(); i < limit; i++) {
3755     Node* st = in(i);
3756 
3757     intptr_t st_off = get_store_offset(st, phase);
3758     if (st_off < 0)  break;  // return conservative answer
3759 
3760     int st_size = st->as_Store()->memory_size();
3761     if (st_size >= BytesPerInt && (st_off % BytesPerInt) == 0) {
3762       return st_off;            // we found a complete word init
3763     }
3764 
3765     // update the map:
3766 
3767     intptr_t this_int_off = align_size_down(st_off, BytesPerInt);
3768     if (this_int_off != int_map_off) {
3769       // reset the map:
3770       int_map = 0;
3771       int_map_off = this_int_off;
3772     }
3773 
3774     int subword_off = st_off - this_int_off;
3775     int_map |= right_n_bits(st_size) << subword_off;
3776     if ((int_map & FULL_MAP) == FULL_MAP) {
3777       return this_int_off;      // we found a complete word init
3778     }
3779 
3780     // Did this store hit or cross the word boundary?
3781     intptr_t next_int_off = align_size_down(st_off + st_size, BytesPerInt);
3782     if (next_int_off == this_int_off + BytesPerInt) {
3783       // We passed the current int, without fully initializing it.
3784       int_map_off = next_int_off;
3785       int_map >>= BytesPerInt;
3786     } else if (next_int_off > this_int_off + BytesPerInt) {
3787       // We passed the current and next int.
3788       return this_int_off + BytesPerInt;
3789     }
3790   }
3791 
3792   return -1;
3793 }
3794 
3795 
3796 // Called when the associated AllocateNode is expanded into CFG.
3797 // At this point, we may perform additional optimizations.
3798 // Linearize the stores by ascending offset, to make memory
3799 // activity as coherent as possible.
3800 Node* InitializeNode::complete_stores(Node* rawctl, Node* rawmem, Node* rawptr,
3801                                       intptr_t header_size,
3802                                       Node* size_in_bytes,
3803                                       PhaseGVN* phase) {
3804   assert(!is_complete(), "not already complete");
3805   assert(stores_are_sane(phase), "");
3806   assert(allocation() != NULL, "must be present");
3807 
3808   remove_extra_zeroes();
3809 
3810   if (ReduceFieldZeroing || ReduceBulkZeroing)
3811     // reduce instruction count for common initialization patterns
3812     coalesce_subword_stores(header_size, size_in_bytes, phase);
3813 
3814   Node* zmem = zero_memory();   // initially zero memory state
3815   Node* inits = zmem;           // accumulating a linearized chain of inits
3816   #ifdef ASSERT
3817   intptr_t first_offset = allocation()->minimum_header_size();
3818   intptr_t last_init_off = first_offset;  // previous init offset
3819   intptr_t last_init_end = first_offset;  // previous init offset+size
3820   intptr_t last_tile_end = first_offset;  // previous tile offset+size
3821   #endif
3822   intptr_t zeroes_done = header_size;
3823 
3824   bool do_zeroing = true;       // we might give up if inits are very sparse
3825   int  big_init_gaps = 0;       // how many large gaps have we seen?
3826 
3827   if (UseTLAB && ZeroTLAB)  do_zeroing = false;
3828   if (!ReduceFieldZeroing && !ReduceBulkZeroing)  do_zeroing = false;
3829 
3830   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
3831     Node* st = in(i);
3832     intptr_t st_off = get_store_offset(st, phase);
3833     if (st_off < 0)
3834       break;                    // unknown junk in the inits
3835     if (st->in(MemNode::Memory) != zmem)
3836       break;                    // complicated store chains somehow in list
3837 
3838     int st_size = st->as_Store()->memory_size();
3839     intptr_t next_init_off = st_off + st_size;
3840 
3841     if (do_zeroing && zeroes_done < next_init_off) {
3842       // See if this store needs a zero before it or under it.
3843       intptr_t zeroes_needed = st_off;
3844 
3845       if (st_size < BytesPerInt) {
3846         // Look for subword stores which only partially initialize words.
3847         // If we find some, we must lay down some word-level zeroes first,
3848         // underneath the subword stores.
3849         //
3850         // Examples:
3851         //   byte[] a = { p,q,r,s }  =>  a[0]=p,a[1]=q,a[2]=r,a[3]=s
3852         //   byte[] a = { x,y,0,0 }  =>  a[0..3] = 0, a[0]=x,a[1]=y
3853         //   byte[] a = { 0,0,z,0 }  =>  a[0..3] = 0, a[2]=z
3854         //
3855         // Note:  coalesce_subword_stores may have already done this,
3856         // if it was prompted by constant non-zero subword initializers.
3857         // But this case can still arise with non-constant stores.
3858 
3859         intptr_t next_full_store = find_next_fullword_store(i, phase);
3860 
3861         // In the examples above:
3862         //   in(i)          p   q   r   s     x   y     z
3863         //   st_off        12  13  14  15    12  13    14
3864         //   st_size        1   1   1   1     1   1     1
3865         //   next_full_s.  12  16  16  16    16  16    16
3866         //   z's_done      12  16  16  16    12  16    12
3867         //   z's_needed    12  16  16  16    16  16    16
3868         //   zsize          0   0   0   0     4   0     4
3869         if (next_full_store < 0) {
3870           // Conservative tack:  Zero to end of current word.
3871           zeroes_needed = align_size_up(zeroes_needed, BytesPerInt);
3872         } else {
3873           // Zero to beginning of next fully initialized word.
3874           // Or, don't zero at all, if we are already in that word.
3875           assert(next_full_store >= zeroes_needed, "must go forward");
3876           assert((next_full_store & (BytesPerInt-1)) == 0, "even boundary");
3877           zeroes_needed = next_full_store;
3878         }
3879       }
3880 
3881       if (zeroes_needed > zeroes_done) {
3882         intptr_t zsize = zeroes_needed - zeroes_done;
3883         // Do some incremental zeroing on rawmem, in parallel with inits.
3884         zeroes_done = align_size_down(zeroes_done, BytesPerInt);
3885         rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
3886                                               zeroes_done, zeroes_needed,
3887                                               phase);
3888         zeroes_done = zeroes_needed;
3889         if (zsize > InitArrayShortSize && ++big_init_gaps > 2)
3890           do_zeroing = false;   // leave the hole, next time
3891       }
3892     }
3893 
3894     // Collect the store and move on:
3895     st->set_req(MemNode::Memory, inits);
3896     inits = st;                 // put it on the linearized chain
3897     set_req(i, zmem);           // unhook from previous position
3898 
3899     if (zeroes_done == st_off)
3900       zeroes_done = next_init_off;
3901 
3902     assert(!do_zeroing || zeroes_done >= next_init_off, "don't miss any");
3903 
3904     #ifdef ASSERT
3905     // Various order invariants.  Weaker than stores_are_sane because
3906     // a large constant tile can be filled in by smaller non-constant stores.
3907     assert(st_off >= last_init_off, "inits do not reverse");
3908     last_init_off = st_off;
3909     const Type* val = NULL;
3910     if (st_size >= BytesPerInt &&
3911         (val = phase->type(st->in(MemNode::ValueIn)))->singleton() &&
3912         (int)val->basic_type() < (int)T_OBJECT) {
3913       assert(st_off >= last_tile_end, "tiles do not overlap");
3914       assert(st_off >= last_init_end, "tiles do not overwrite inits");
3915       last_tile_end = MAX2(last_tile_end, next_init_off);
3916     } else {
3917       intptr_t st_tile_end = align_size_up(next_init_off, BytesPerLong);
3918       assert(st_tile_end >= last_tile_end, "inits stay with tiles");
3919       assert(st_off      >= last_init_end, "inits do not overlap");
3920       last_init_end = next_init_off;  // it's a non-tile
3921     }
3922     #endif //ASSERT
3923   }
3924 
3925   remove_extra_zeroes();        // clear out all the zmems left over
3926   add_req(inits);
3927 
3928   if (!(UseTLAB && ZeroTLAB)) {
3929     // If anything remains to be zeroed, zero it all now.
3930     zeroes_done = align_size_down(zeroes_done, BytesPerInt);
3931     // if it is the last unused 4 bytes of an instance, forget about it
3932     intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, max_jint);
3933     if (zeroes_done + BytesPerLong >= size_limit) {
3934       assert(allocation() != NULL, "");
3935       if (allocation()->Opcode() == Op_Allocate) {
3936         Node* klass_node = allocation()->in(AllocateNode::KlassNode);
3937         ciKlass* k = phase->type(klass_node)->is_klassptr()->klass();
3938         if (zeroes_done == k->layout_helper())
3939           zeroes_done = size_limit;
3940       }
3941     }
3942     if (zeroes_done < size_limit) {
3943       rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
3944                                             zeroes_done, size_in_bytes, phase);
3945     }
3946   }
3947 
3948   set_complete(phase);
3949   return rawmem;
3950 }
3951 
3952 
3953 #ifdef ASSERT
3954 bool InitializeNode::stores_are_sane(PhaseTransform* phase) {
3955   if (is_complete())
3956     return true;                // stores could be anything at this point
3957   assert(allocation() != NULL, "must be present");
3958   intptr_t last_off = allocation()->minimum_header_size();
3959   for (uint i = InitializeNode::RawStores; i < req(); i++) {
3960     Node* st = in(i);
3961     intptr_t st_off = get_store_offset(st, phase);
3962     if (st_off < 0)  continue;  // ignore dead garbage
3963     if (last_off > st_off) {
3964       tty->print_cr("*** bad store offset at %d: " INTX_FORMAT " > " INTX_FORMAT, i, last_off, st_off);
3965       this->dump(2);
3966       assert(false, "ascending store offsets");
3967       return false;
3968     }
3969     last_off = st_off + st->as_Store()->memory_size();
3970   }
3971   return true;
3972 }
3973 #endif //ASSERT
3974 
3975 
3976 
3977 
3978 //============================MergeMemNode=====================================
3979 //
3980 // SEMANTICS OF MEMORY MERGES:  A MergeMem is a memory state assembled from several
3981 // contributing store or call operations.  Each contributor provides the memory
3982 // state for a particular "alias type" (see Compile::alias_type).  For example,
3983 // if a MergeMem has an input X for alias category #6, then any memory reference
3984 // to alias category #6 may use X as its memory state input, as an exact equivalent
3985 // to using the MergeMem as a whole.
3986 //   Load<6>( MergeMem(<6>: X, ...), p ) <==> Load<6>(X,p)
3987 //
3988 // (Here, the <N> notation gives the index of the relevant adr_type.)
3989 //
3990 // In one special case (and more cases in the future), alias categories overlap.
3991 // The special alias category "Bot" (Compile::AliasIdxBot) includes all memory
3992 // states.  Therefore, if a MergeMem has only one contributing input W for Bot,
3993 // it is exactly equivalent to that state W:
3994 //   MergeMem(<Bot>: W) <==> W
3995 //
3996 // Usually, the merge has more than one input.  In that case, where inputs
3997 // overlap (i.e., one is Bot), the narrower alias type determines the memory
3998 // state for that type, and the wider alias type (Bot) fills in everywhere else:
3999 //   Load<5>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<5>(W,p)
4000 //   Load<6>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<6>(X,p)
4001 //
4002 // A merge can take a "wide" memory state as one of its narrow inputs.
4003 // This simply means that the merge observes out only the relevant parts of
4004 // the wide input.  That is, wide memory states arriving at narrow merge inputs
4005 // are implicitly "filtered" or "sliced" as necessary.  (This is rare.)
4006 //
4007 // These rules imply that MergeMem nodes may cascade (via their <Bot> links),
4008 // and that memory slices "leak through":
4009 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y)) <==> MergeMem(<Bot>: W, <7>: Y)
4010 //
4011 // But, in such a cascade, repeated memory slices can "block the leak":
4012 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y), <7>: Y') <==> MergeMem(<Bot>: W, <7>: Y')
4013 //
4014 // In the last example, Y is not part of the combined memory state of the
4015 // outermost MergeMem.  The system must, of course, prevent unschedulable
4016 // memory states from arising, so you can be sure that the state Y is somehow
4017 // a precursor to state Y'.
4018 //
4019 //
4020 // REPRESENTATION OF MEMORY MERGES: The indexes used to address the Node::in array
4021 // of each MergeMemNode array are exactly the numerical alias indexes, including
4022 // but not limited to AliasIdxTop, AliasIdxBot, and AliasIdxRaw.  The functions
4023 // Compile::alias_type (and kin) produce and manage these indexes.
4024 //
4025 // By convention, the value of in(AliasIdxTop) (i.e., in(1)) is always the top node.
4026 // (Note that this provides quick access to the top node inside MergeMem methods,
4027 // without the need to reach out via TLS to Compile::current.)
4028 //
4029 // As a consequence of what was just described, a MergeMem that represents a full
4030 // memory state has an edge in(AliasIdxBot) which is a "wide" memory state,
4031 // containing all alias categories.
4032 //
4033 // MergeMem nodes never (?) have control inputs, so in(0) is NULL.
4034 //
4035 // All other edges in(N) (including in(AliasIdxRaw), which is in(3)) are either
4036 // a memory state for the alias type <N>, or else the top node, meaning that
4037 // there is no particular input for that alias type.  Note that the length of
4038 // a MergeMem is variable, and may be extended at any time to accommodate new
4039 // memory states at larger alias indexes.  When merges grow, they are of course
4040 // filled with "top" in the unused in() positions.
4041 //
4042 // This use of top is named "empty_memory()", or "empty_mem" (no-memory) as a variable.
4043 // (Top was chosen because it works smoothly with passes like GCM.)
4044 //
4045 // For convenience, we hardwire the alias index for TypeRawPtr::BOTTOM.  (It is
4046 // the type of random VM bits like TLS references.)  Since it is always the
4047 // first non-Bot memory slice, some low-level loops use it to initialize an
4048 // index variable:  for (i = AliasIdxRaw; i < req(); i++).
4049 //
4050 //
4051 // ACCESSORS:  There is a special accessor MergeMemNode::base_memory which returns
4052 // the distinguished "wide" state.  The accessor MergeMemNode::memory_at(N) returns
4053 // the memory state for alias type <N>, or (if there is no particular slice at <N>,
4054 // it returns the base memory.  To prevent bugs, memory_at does not accept <Top>
4055 // or <Bot> indexes.  The iterator MergeMemStream provides robust iteration over
4056 // MergeMem nodes or pairs of such nodes, ensuring that the non-top edges are visited.
4057 //
4058 // %%%% We may get rid of base_memory as a separate accessor at some point; it isn't
4059 // really that different from the other memory inputs.  An abbreviation called
4060 // "bot_memory()" for "memory_at(AliasIdxBot)" would keep code tidy.
4061 //
4062 //
4063 // PARTIAL MEMORY STATES:  During optimization, MergeMem nodes may arise that represent
4064 // partial memory states.  When a Phi splits through a MergeMem, the copy of the Phi
4065 // that "emerges though" the base memory will be marked as excluding the alias types
4066 // of the other (narrow-memory) copies which "emerged through" the narrow edges:
4067 //
4068 //   Phi<Bot>(U, MergeMem(<Bot>: W, <8>: Y))
4069 //     ==Ideal=>  MergeMem(<Bot>: Phi<Bot-8>(U, W), Phi<8>(U, Y))
4070 //
4071 // This strange "subtraction" effect is necessary to ensure IGVN convergence.
4072 // (It is currently unimplemented.)  As you can see, the resulting merge is
4073 // actually a disjoint union of memory states, rather than an overlay.
4074 //
4075 
4076 //------------------------------MergeMemNode-----------------------------------
4077 Node* MergeMemNode::make_empty_memory() {
4078   Node* empty_memory = (Node*) Compile::current()->top();
4079   assert(empty_memory->is_top(), "correct sentinel identity");
4080   return empty_memory;
4081 }
4082 
4083 MergeMemNode::MergeMemNode(Node *new_base) : Node(1+Compile::AliasIdxRaw) {
4084   init_class_id(Class_MergeMem);
4085   // all inputs are nullified in Node::Node(int)
4086   // set_input(0, NULL);  // no control input
4087 
4088   // Initialize the edges uniformly to top, for starters.
4089   Node* empty_mem = make_empty_memory();
4090   for (uint i = Compile::AliasIdxTop; i < req(); i++) {
4091     init_req(i,empty_mem);
4092   }
4093   assert(empty_memory() == empty_mem, "");
4094 
4095   if( new_base != NULL && new_base->is_MergeMem() ) {
4096     MergeMemNode* mdef = new_base->as_MergeMem();
4097     assert(mdef->empty_memory() == empty_mem, "consistent sentinels");
4098     for (MergeMemStream mms(this, mdef); mms.next_non_empty2(); ) {
4099       mms.set_memory(mms.memory2());
4100     }
4101     assert(base_memory() == mdef->base_memory(), "");
4102   } else {
4103     set_base_memory(new_base);
4104   }
4105 }
4106 
4107 // Make a new, untransformed MergeMem with the same base as 'mem'.
4108 // If mem is itself a MergeMem, populate the result with the same edges.
4109 MergeMemNode* MergeMemNode::make(Node* mem) {
4110   return new MergeMemNode(mem);
4111 }
4112 
4113 //------------------------------cmp--------------------------------------------
4114 uint MergeMemNode::hash() const { return NO_HASH; }
4115 uint MergeMemNode::cmp( const Node &n ) const {
4116   return (&n == this);          // Always fail except on self
4117 }
4118 
4119 //------------------------------Identity---------------------------------------
4120 Node* MergeMemNode::Identity(PhaseGVN* phase) {
4121   // Identity if this merge point does not record any interesting memory
4122   // disambiguations.
4123   Node* base_mem = base_memory();
4124   Node* empty_mem = empty_memory();
4125   if (base_mem != empty_mem) {  // Memory path is not dead?
4126     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4127       Node* mem = in(i);
4128       if (mem != empty_mem && mem != base_mem) {
4129         return this;            // Many memory splits; no change
4130       }
4131     }
4132   }
4133   return base_mem;              // No memory splits; ID on the one true input
4134 }
4135 
4136 //------------------------------Ideal------------------------------------------
4137 // This method is invoked recursively on chains of MergeMem nodes
4138 Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) {
4139   // Remove chain'd MergeMems
4140   //
4141   // This is delicate, because the each "in(i)" (i >= Raw) is interpreted
4142   // relative to the "in(Bot)".  Since we are patching both at the same time,
4143   // we have to be careful to read each "in(i)" relative to the old "in(Bot)",
4144   // but rewrite each "in(i)" relative to the new "in(Bot)".
4145   Node *progress = NULL;
4146 
4147 
4148   Node* old_base = base_memory();
4149   Node* empty_mem = empty_memory();
4150   if (old_base == empty_mem)
4151     return NULL; // Dead memory path.
4152 
4153   MergeMemNode* old_mbase;
4154   if (old_base != NULL && old_base->is_MergeMem())
4155     old_mbase = old_base->as_MergeMem();
4156   else
4157     old_mbase = NULL;
4158   Node* new_base = old_base;
4159 
4160   // simplify stacked MergeMems in base memory
4161   if (old_mbase)  new_base = old_mbase->base_memory();
4162 
4163   // the base memory might contribute new slices beyond my req()
4164   if (old_mbase)  grow_to_match(old_mbase);
4165 
4166   // Look carefully at the base node if it is a phi.
4167   PhiNode* phi_base;
4168   if (new_base != NULL && new_base->is_Phi())
4169     phi_base = new_base->as_Phi();
4170   else
4171     phi_base = NULL;
4172 
4173   Node*    phi_reg = NULL;
4174   uint     phi_len = (uint)-1;
4175   if (phi_base != NULL && !phi_base->is_copy()) {
4176     // do not examine phi if degraded to a copy
4177     phi_reg = phi_base->region();
4178     phi_len = phi_base->req();
4179     // see if the phi is unfinished
4180     for (uint i = 1; i < phi_len; i++) {
4181       if (phi_base->in(i) == NULL) {
4182         // incomplete phi; do not look at it yet!
4183         phi_reg = NULL;
4184         phi_len = (uint)-1;
4185         break;
4186       }
4187     }
4188   }
4189 
4190   // Note:  We do not call verify_sparse on entry, because inputs
4191   // can normalize to the base_memory via subsume_node or similar
4192   // mechanisms.  This method repairs that damage.
4193 
4194   assert(!old_mbase || old_mbase->is_empty_memory(empty_mem), "consistent sentinels");
4195 
4196   // Look at each slice.
4197   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4198     Node* old_in = in(i);
4199     // calculate the old memory value
4200     Node* old_mem = old_in;
4201     if (old_mem == empty_mem)  old_mem = old_base;
4202     assert(old_mem == memory_at(i), "");
4203 
4204     // maybe update (reslice) the old memory value
4205 
4206     // simplify stacked MergeMems
4207     Node* new_mem = old_mem;
4208     MergeMemNode* old_mmem;
4209     if (old_mem != NULL && old_mem->is_MergeMem())
4210       old_mmem = old_mem->as_MergeMem();
4211     else
4212       old_mmem = NULL;
4213     if (old_mmem == this) {
4214       // This can happen if loops break up and safepoints disappear.
4215       // A merge of BotPtr (default) with a RawPtr memory derived from a
4216       // safepoint can be rewritten to a merge of the same BotPtr with
4217       // the BotPtr phi coming into the loop.  If that phi disappears
4218       // also, we can end up with a self-loop of the mergemem.
4219       // In general, if loops degenerate and memory effects disappear,
4220       // a mergemem can be left looking at itself.  This simply means
4221       // that the mergemem's default should be used, since there is
4222       // no longer any apparent effect on this slice.
4223       // Note: If a memory slice is a MergeMem cycle, it is unreachable
4224       //       from start.  Update the input to TOP.
4225       new_mem = (new_base == this || new_base == empty_mem)? empty_mem : new_base;
4226     }
4227     else if (old_mmem != NULL) {
4228       new_mem = old_mmem->memory_at(i);
4229     }
4230     // else preceding memory was not a MergeMem
4231 
4232     // replace equivalent phis (unfortunately, they do not GVN together)
4233     if (new_mem != NULL && new_mem != new_base &&
4234         new_mem->req() == phi_len && new_mem->in(0) == phi_reg) {
4235       if (new_mem->is_Phi()) {
4236         PhiNode* phi_mem = new_mem->as_Phi();
4237         for (uint i = 1; i < phi_len; i++) {
4238           if (phi_base->in(i) != phi_mem->in(i)) {
4239             phi_mem = NULL;
4240             break;
4241           }
4242         }
4243         if (phi_mem != NULL) {
4244           // equivalent phi nodes; revert to the def
4245           new_mem = new_base;
4246         }
4247       }
4248     }
4249 
4250     // maybe store down a new value
4251     Node* new_in = new_mem;
4252     if (new_in == new_base)  new_in = empty_mem;
4253 
4254     if (new_in != old_in) {
4255       // Warning:  Do not combine this "if" with the previous "if"
4256       // A memory slice might have be be rewritten even if it is semantically
4257       // unchanged, if the base_memory value has changed.
4258       set_req(i, new_in);
4259       progress = this;          // Report progress
4260     }
4261   }
4262 
4263   if (new_base != old_base) {
4264     set_req(Compile::AliasIdxBot, new_base);
4265     // Don't use set_base_memory(new_base), because we need to update du.
4266     assert(base_memory() == new_base, "");
4267     progress = this;
4268   }
4269 
4270   if( base_memory() == this ) {
4271     // a self cycle indicates this memory path is dead
4272     set_req(Compile::AliasIdxBot, empty_mem);
4273   }
4274 
4275   // Resolve external cycles by calling Ideal on a MergeMem base_memory
4276   // Recursion must occur after the self cycle check above
4277   if( base_memory()->is_MergeMem() ) {
4278     MergeMemNode *new_mbase = base_memory()->as_MergeMem();
4279     Node *m = phase->transform(new_mbase);  // Rollup any cycles
4280     if( m != NULL && (m->is_top() ||
4281         m->is_MergeMem() && m->as_MergeMem()->base_memory() == empty_mem) ) {
4282       // propagate rollup of dead cycle to self
4283       set_req(Compile::AliasIdxBot, empty_mem);
4284     }
4285   }
4286 
4287   if( base_memory() == empty_mem ) {
4288     progress = this;
4289     // Cut inputs during Parse phase only.
4290     // During Optimize phase a dead MergeMem node will be subsumed by Top.
4291     if( !can_reshape ) {
4292       for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4293         if( in(i) != empty_mem ) { set_req(i, empty_mem); }
4294       }
4295     }
4296   }
4297 
4298   if( !progress && base_memory()->is_Phi() && can_reshape ) {
4299     // Check if PhiNode::Ideal's "Split phis through memory merges"
4300     // transform should be attempted. Look for this->phi->this cycle.
4301     uint merge_width = req();
4302     if (merge_width > Compile::AliasIdxRaw) {
4303       PhiNode* phi = base_memory()->as_Phi();
4304       for( uint i = 1; i < phi->req(); ++i ) {// For all paths in
4305         if (phi->in(i) == this) {
4306           phase->is_IterGVN()->_worklist.push(phi);
4307           break;
4308         }
4309       }
4310     }
4311   }
4312 
4313   assert(progress || verify_sparse(), "please, no dups of base");
4314   return progress;
4315 }
4316 
4317 //-------------------------set_base_memory-------------------------------------
4318 void MergeMemNode::set_base_memory(Node *new_base) {
4319   Node* empty_mem = empty_memory();
4320   set_req(Compile::AliasIdxBot, new_base);
4321   assert(memory_at(req()) == new_base, "must set default memory");
4322   // Clear out other occurrences of new_base:
4323   if (new_base != empty_mem) {
4324     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4325       if (in(i) == new_base)  set_req(i, empty_mem);
4326     }
4327   }
4328 }
4329 
4330 //------------------------------out_RegMask------------------------------------
4331 const RegMask &MergeMemNode::out_RegMask() const {
4332   return RegMask::Empty;
4333 }
4334 
4335 //------------------------------dump_spec--------------------------------------
4336 #ifndef PRODUCT
4337 void MergeMemNode::dump_spec(outputStream *st) const {
4338   st->print(" {");
4339   Node* base_mem = base_memory();
4340   for( uint i = Compile::AliasIdxRaw; i < req(); i++ ) {
4341     Node* mem = (in(i) != NULL) ? memory_at(i) : base_mem;
4342     if (mem == base_mem) { st->print(" -"); continue; }
4343     st->print( " N%d:", mem->_idx );
4344     Compile::current()->get_adr_type(i)->dump_on(st);
4345   }
4346   st->print(" }");
4347 }
4348 #endif // !PRODUCT
4349 
4350 
4351 #ifdef ASSERT
4352 static bool might_be_same(Node* a, Node* b) {
4353   if (a == b)  return true;
4354   if (!(a->is_Phi() || b->is_Phi()))  return false;
4355   // phis shift around during optimization
4356   return true;  // pretty stupid...
4357 }
4358 
4359 // verify a narrow slice (either incoming or outgoing)
4360 static void verify_memory_slice(const MergeMemNode* m, int alias_idx, Node* n) {
4361   if (!VerifyAliases)       return;  // don't bother to verify unless requested
4362   if (is_error_reported())  return;  // muzzle asserts when debugging an error
4363   if (Node::in_dump())      return;  // muzzle asserts when printing
4364   assert(alias_idx >= Compile::AliasIdxRaw, "must not disturb base_memory or sentinel");
4365   assert(n != NULL, "");
4366   // Elide intervening MergeMem's
4367   while (n->is_MergeMem()) {
4368     n = n->as_MergeMem()->memory_at(alias_idx);
4369   }
4370   Compile* C = Compile::current();
4371   const TypePtr* n_adr_type = n->adr_type();
4372   if (n == m->empty_memory()) {
4373     // Implicit copy of base_memory()
4374   } else if (n_adr_type != TypePtr::BOTTOM) {
4375     assert(n_adr_type != NULL, "new memory must have a well-defined adr_type");
4376     assert(C->must_alias(n_adr_type, alias_idx), "new memory must match selected slice");
4377   } else {
4378     // A few places like make_runtime_call "know" that VM calls are narrow,
4379     // and can be used to update only the VM bits stored as TypeRawPtr::BOTTOM.
4380     bool expected_wide_mem = false;
4381     if (n == m->base_memory()) {
4382       expected_wide_mem = true;
4383     } else if (alias_idx == Compile::AliasIdxRaw ||
4384                n == m->memory_at(Compile::AliasIdxRaw)) {
4385       expected_wide_mem = true;
4386     } else if (!C->alias_type(alias_idx)->is_rewritable()) {
4387       // memory can "leak through" calls on channels that
4388       // are write-once.  Allow this also.
4389       expected_wide_mem = true;
4390     }
4391     assert(expected_wide_mem, "expected narrow slice replacement");
4392   }
4393 }
4394 #else // !ASSERT
4395 #define verify_memory_slice(m,i,n) (void)(0)  // PRODUCT version is no-op
4396 #endif
4397 
4398 
4399 //-----------------------------memory_at---------------------------------------
4400 Node* MergeMemNode::memory_at(uint alias_idx) const {
4401   assert(alias_idx >= Compile::AliasIdxRaw ||
4402          alias_idx == Compile::AliasIdxBot && Compile::current()->AliasLevel() == 0,
4403          "must avoid base_memory and AliasIdxTop");
4404 
4405   // Otherwise, it is a narrow slice.
4406   Node* n = alias_idx < req() ? in(alias_idx) : empty_memory();
4407   Compile *C = Compile::current();
4408   if (is_empty_memory(n)) {
4409     // the array is sparse; empty slots are the "top" node
4410     n = base_memory();
4411     assert(Node::in_dump()
4412            || n == NULL || n->bottom_type() == Type::TOP
4413            || n->adr_type() == NULL // address is TOP
4414            || n->adr_type() == TypePtr::BOTTOM
4415            || n->adr_type() == TypeRawPtr::BOTTOM
4416            || Compile::current()->AliasLevel() == 0,
4417            "must be a wide memory");
4418     // AliasLevel == 0 if we are organizing the memory states manually.
4419     // See verify_memory_slice for comments on TypeRawPtr::BOTTOM.
4420   } else {
4421     // make sure the stored slice is sane
4422     #ifdef ASSERT
4423     if (is_error_reported() || Node::in_dump()) {
4424     } else if (might_be_same(n, base_memory())) {
4425       // Give it a pass:  It is a mostly harmless repetition of the base.
4426       // This can arise normally from node subsumption during optimization.
4427     } else {
4428       verify_memory_slice(this, alias_idx, n);
4429     }
4430     #endif
4431   }
4432   return n;
4433 }
4434 
4435 //---------------------------set_memory_at-------------------------------------
4436 void MergeMemNode::set_memory_at(uint alias_idx, Node *n) {
4437   verify_memory_slice(this, alias_idx, n);
4438   Node* empty_mem = empty_memory();
4439   if (n == base_memory())  n = empty_mem;  // collapse default
4440   uint need_req = alias_idx+1;
4441   if (req() < need_req) {
4442     if (n == empty_mem)  return;  // already the default, so do not grow me
4443     // grow the sparse array
4444     do {
4445       add_req(empty_mem);
4446     } while (req() < need_req);
4447   }
4448   set_req( alias_idx, n );
4449 }
4450 
4451 
4452 
4453 //--------------------------iteration_setup------------------------------------
4454 void MergeMemNode::iteration_setup(const MergeMemNode* other) {
4455   if (other != NULL) {
4456     grow_to_match(other);
4457     // invariant:  the finite support of mm2 is within mm->req()
4458     #ifdef ASSERT
4459     for (uint i = req(); i < other->req(); i++) {
4460       assert(other->is_empty_memory(other->in(i)), "slice left uncovered");
4461     }
4462     #endif
4463   }
4464   // Replace spurious copies of base_memory by top.
4465   Node* base_mem = base_memory();
4466   if (base_mem != NULL && !base_mem->is_top()) {
4467     for (uint i = Compile::AliasIdxBot+1, imax = req(); i < imax; i++) {
4468       if (in(i) == base_mem)
4469         set_req(i, empty_memory());
4470     }
4471   }
4472 }
4473 
4474 //---------------------------grow_to_match-------------------------------------
4475 void MergeMemNode::grow_to_match(const MergeMemNode* other) {
4476   Node* empty_mem = empty_memory();
4477   assert(other->is_empty_memory(empty_mem), "consistent sentinels");
4478   // look for the finite support of the other memory
4479   for (uint i = other->req(); --i >= req(); ) {
4480     if (other->in(i) != empty_mem) {
4481       uint new_len = i+1;
4482       while (req() < new_len)  add_req(empty_mem);
4483       break;
4484     }
4485   }
4486 }
4487 
4488 //---------------------------verify_sparse-------------------------------------
4489 #ifndef PRODUCT
4490 bool MergeMemNode::verify_sparse() const {
4491   assert(is_empty_memory(make_empty_memory()), "sane sentinel");
4492   Node* base_mem = base_memory();
4493   // The following can happen in degenerate cases, since empty==top.
4494   if (is_empty_memory(base_mem))  return true;
4495   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4496     assert(in(i) != NULL, "sane slice");
4497     if (in(i) == base_mem)  return false;  // should have been the sentinel value!
4498   }
4499   return true;
4500 }
4501 
4502 bool MergeMemStream::match_memory(Node* mem, const MergeMemNode* mm, int idx) {
4503   Node* n;
4504   n = mm->in(idx);
4505   if (mem == n)  return true;  // might be empty_memory()
4506   n = (idx == Compile::AliasIdxBot)? mm->base_memory(): mm->memory_at(idx);
4507   if (mem == n)  return true;
4508   while (n->is_Phi() && (n = n->as_Phi()->is_copy()) != NULL) {
4509     if (mem == n)  return true;
4510     if (n == NULL)  break;
4511   }
4512   return false;
4513 }
4514 #endif // !PRODUCT
--- EOF ---