1 /*
   2  * Copyright (c) 1997, 2015, 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 "oops/objArrayKlass.hpp"
  30 #include "opto/addnode.hpp"
  31 #include "opto/arraycopynode.hpp"
  32 #include "opto/cfgnode.hpp"
  33 #include "opto/compile.hpp"
  34 #include "opto/connode.hpp"
  35 #include "opto/convertnode.hpp"
  36 #include "opto/loopnode.hpp"
  37 #include "opto/machnode.hpp"
  38 #include "opto/matcher.hpp"
  39 #include "opto/memnode.hpp"
  40 #include "opto/mulnode.hpp"
  41 #include "opto/narrowptrnode.hpp"
  42 #include "opto/phaseX.hpp"
  43 #include "opto/regmask.hpp"
  44 #include "opto/shenandoahSupport.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 
  80 void MemNode::dump_adr_type(const Node* mem, const TypePtr* adr_type, outputStream *st) {
  81   st->print(" @");
  82   if (adr_type == NULL) {
  83     st->print("NULL");
  84   } else {
  85     adr_type->dump_on(st);
  86     Compile* C = Compile::current();
  87     Compile::AliasType* atp = NULL;
  88     if (C->have_alias_type(adr_type))  atp = C->alias_type(adr_type);
  89     if (atp == NULL)
  90       st->print(", idx=?\?;");
  91     else if (atp->index() == Compile::AliasIdxBot)
  92       st->print(", idx=Bot;");
  93     else if (atp->index() == Compile::AliasIdxTop)
  94       st->print(", idx=Top;");
  95     else if (atp->index() == Compile::AliasIdxRaw)
  96       st->print(", idx=Raw;");
  97     else {
  98       ciField* field = atp->field();
  99       if (field) {
 100         st->print(", name=");
 101         field->print_name_on(st);
 102       }
 103       st->print(", idx=%d;", atp->index());
 104     }
 105   }
 106 }
 107 
 108 extern void print_alias_types();
 109 
 110 #endif
 111 
 112 Node *MemNode::optimize_simple_memory_chain(Node *mchain, const TypeOopPtr *t_oop, Node *load, PhaseGVN *phase) {
 113   assert((t_oop != NULL), "sanity");
 114   bool is_instance = t_oop->is_known_instance_field();
 115   bool is_boxed_value_load = t_oop->is_ptr_to_boxed_value() &&
 116                              (load != NULL) && load->is_Load() &&
 117                              (phase->is_IterGVN() != NULL);
 118   if (!(is_instance || is_boxed_value_load))
 119     return mchain;  // don't try to optimize non-instance types
 120   uint instance_id = t_oop->instance_id();
 121   Node *start_mem = phase->C->start()->proj_out(TypeFunc::Memory);
 122   Node *prev = NULL;
 123   Node *result = mchain;
 124   while (prev != result) {
 125     prev = result;
 126     if (result == start_mem)
 127       break;  // hit one of our sentinels
 128     // skip over a call which does not affect this memory slice
 129     if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
 130       Node *proj_in = result->in(0);
 131       if (proj_in->is_Allocate() && proj_in->_idx == instance_id) {
 132         break;  // hit one of our sentinels
 133       } else if (proj_in->is_Call()) {
 134         // ArrayCopyNodes processed here as well
 135         CallNode *call = proj_in->as_Call();
 136         if (!call->may_modify(t_oop, phase)) { // returns false for instances
 137           result = call->in(TypeFunc::Memory);
 138         }
 139       } else if (proj_in->is_Initialize()) {
 140         AllocateNode* alloc = proj_in->as_Initialize()->allocation();
 141         // Stop if this is the initialization for the object instance which
 142         // contains this memory slice, otherwise skip over it.
 143         if ((alloc == NULL) || (alloc->_idx == instance_id)) {
 144           break;
 145         }
 146         if (is_instance) {
 147           result = proj_in->in(TypeFunc::Memory);
 148         } else if (is_boxed_value_load) {
 149           Node* klass = alloc->in(AllocateNode::KlassNode);
 150           const TypeKlassPtr* tklass = phase->type(klass)->is_klassptr();
 151           if (tklass->klass_is_exact() && !tklass->klass()->equals(t_oop->klass())) {
 152             result = proj_in->in(TypeFunc::Memory); // not related allocation
 153           }
 154         }
 155       } else if (proj_in->is_MemBar()) {
 156         if (ArrayCopyNode::may_modify(t_oop, proj_in->as_MemBar(), phase)) {
 157           break;
 158         }
 159         result = proj_in->in(TypeFunc::Memory);
 160       } else {
 161         assert(false, "unexpected projection");
 162       }
 163     } else if (result->is_ClearArray()) {
 164       if (!is_instance || !ClearArrayNode::step_through(&result, instance_id, phase)) {
 165         // Can not bypass initialization of the instance
 166         // we are looking for.
 167         break;
 168       }
 169       // Otherwise skip it (the call updated 'result' value).
 170     } else if (result->is_MergeMem()) {
 171       result = step_through_mergemem(phase, result->as_MergeMem(), t_oop, NULL, tty);
 172     }
 173   }
 174   return result;
 175 }
 176 
 177 Node *MemNode::optimize_memory_chain(Node *mchain, const TypePtr *t_adr, Node *load, PhaseGVN *phase) {
 178   const TypeOopPtr* t_oop = t_adr->isa_oopptr();
 179   if (t_oop == NULL)
 180     return mchain;  // don't try to optimize non-oop types
 181   Node* result = optimize_simple_memory_chain(mchain, t_oop, load, phase);
 182   bool is_instance = t_oop->is_known_instance_field();
 183   PhaseIterGVN *igvn = phase->is_IterGVN();
 184   if (is_instance && igvn != NULL  && result->is_Phi()) {
 185     PhiNode *mphi = result->as_Phi();
 186     assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
 187     const TypePtr *t = mphi->adr_type();
 188     if (t == TypePtr::BOTTOM || t == TypeRawPtr::BOTTOM ||
 189         t->isa_oopptr() && !t->is_oopptr()->is_known_instance() &&
 190         t->is_oopptr()->cast_to_exactness(true)
 191          ->is_oopptr()->cast_to_ptr_type(t_oop->ptr())
 192          ->is_oopptr()->cast_to_instance_id(t_oop->instance_id()) == t_oop) {
 193       // clone the Phi with our address type
 194       result = mphi->split_out_instance(t_adr, igvn);
 195     } else {
 196       assert(phase->C->get_alias_index(t) == phase->C->get_alias_index(t_adr), "correct memory chain");
 197     }
 198   }
 199   return result;
 200 }
 201 
 202 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem,  const TypePtr *tp, const TypePtr *adr_check, outputStream *st) {
 203   uint alias_idx = phase->C->get_alias_index(tp);
 204   Node *mem = mmem;
 205 #ifdef ASSERT
 206   {
 207     // Check that current type is consistent with the alias index used during graph construction
 208     assert(alias_idx >= Compile::AliasIdxRaw, "must not be a bad alias_idx");
 209     bool consistent =  adr_check == NULL || adr_check->empty() ||
 210                        phase->C->must_alias(adr_check, alias_idx );
 211     // Sometimes dead array references collapse to a[-1], a[-2], or a[-3]
 212     if( !consistent && adr_check != NULL && !adr_check->empty() &&
 213                tp->isa_aryptr() &&        tp->offset() == Type::OffsetBot &&
 214         adr_check->isa_aryptr() && adr_check->offset() != Type::OffsetBot &&
 215         ( adr_check->offset() == arrayOopDesc::length_offset_in_bytes() ||
 216           adr_check->offset() == oopDesc::klass_offset_in_bytes() ||
 217           adr_check->offset() == oopDesc::mark_offset_in_bytes() ) ) {
 218       // don't assert if it is dead code.
 219       consistent = true;
 220     }
 221     if( !consistent ) {
 222       st->print("alias_idx==%d, adr_check==", alias_idx);
 223       if( adr_check == NULL ) {
 224         st->print("NULL");
 225       } else {
 226         adr_check->dump();
 227       }
 228       st->cr();
 229       print_alias_types();
 230       assert(consistent, "adr_check must match alias idx");
 231     }
 232   }
 233 #endif
 234   // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally
 235   // means an array I have not precisely typed yet.  Do not do any
 236   // alias stuff with it any time soon.
 237   const TypeOopPtr *toop = tp->isa_oopptr();
 238   if( tp->base() != Type::AnyPtr &&
 239       !(toop &&
 240         toop->klass() != NULL &&
 241         toop->klass()->is_java_lang_Object() &&
 242         toop->offset() == Type::OffsetBot) ) {
 243     // compress paths and change unreachable cycles to TOP
 244     // If not, we can update the input infinitely along a MergeMem cycle
 245     // Equivalent code in PhiNode::Ideal
 246     Node* m  = phase->transform(mmem);
 247     // If transformed to a MergeMem, get the desired slice
 248     // Otherwise the returned node represents memory for every slice
 249     mem = (m->is_MergeMem())? m->as_MergeMem()->memory_at(alias_idx) : m;
 250     // Update input if it is progress over what we have now
 251   }
 252   return mem;
 253 }
 254 
 255 //--------------------------Ideal_common---------------------------------------
 256 // Look for degenerate control and memory inputs.  Bypass MergeMem inputs.
 257 // Unhook non-raw memories from complete (macro-expanded) initializations.
 258 Node *MemNode::Ideal_common(PhaseGVN *phase, bool can_reshape) {
 259   // If our control input is a dead region, kill all below the region
 260   Node *ctl = in(MemNode::Control);
 261   if (ctl && remove_dead_region(phase, can_reshape))
 262     return this;
 263   ctl = in(MemNode::Control);
 264   // Don't bother trying to transform a dead node
 265   if (ctl && ctl->is_top())  return NodeSentinel;
 266 
 267   PhaseIterGVN *igvn = phase->is_IterGVN();
 268   // Wait if control on the worklist.
 269   if (ctl && can_reshape && igvn != NULL) {
 270     Node* bol = NULL;
 271     Node* cmp = NULL;
 272     if (ctl->in(0)->is_If()) {
 273       assert(ctl->is_IfTrue() || ctl->is_IfFalse(), "sanity");
 274       bol = ctl->in(0)->in(1);
 275       if (bol->is_Bool())
 276         cmp = ctl->in(0)->in(1)->in(1);
 277     }
 278     if (igvn->_worklist.member(ctl) ||
 279         (bol != NULL && igvn->_worklist.member(bol)) ||
 280         (cmp != NULL && igvn->_worklist.member(cmp)) ) {
 281       // This control path may be dead.
 282       // Delay this memory node transformation until the control is processed.
 283       phase->is_IterGVN()->_worklist.push(this);
 284       return NodeSentinel; // caller will return NULL
 285     }
 286   }
 287   // Ignore if memory is dead, or self-loop
 288   Node *mem = in(MemNode::Memory);
 289   if (phase->type( mem ) == Type::TOP) return NodeSentinel; // caller will return NULL
 290   assert(mem != this, "dead loop in MemNode::Ideal");
 291 
 292   if (can_reshape && igvn != NULL && igvn->_worklist.member(mem)) {
 293     // This memory slice may be dead.
 294     // Delay this mem node transformation until the memory is processed.
 295     phase->is_IterGVN()->_worklist.push(this);
 296     return NodeSentinel; // caller will return NULL
 297   }
 298 
 299   Node *address = in(MemNode::Address);
 300   const Type *t_adr = phase->type(address);
 301   if (t_adr == Type::TOP)              return NodeSentinel; // caller will return NULL
 302 
 303   if (can_reshape && igvn != NULL &&
 304       (igvn->_worklist.member(address) ||
 305        igvn->_worklist.size() > 0 && (t_adr != adr_type())) ) {
 306     // The address's base and type may change when the address is processed.
 307     // Delay this mem node transformation until the address is processed.
 308     phase->is_IterGVN()->_worklist.push(this);
 309     return NodeSentinel; // caller will return NULL
 310   }
 311 
 312   // Do NOT remove or optimize the next lines: ensure a new alias index
 313   // is allocated for an oop pointer type before Escape Analysis.
 314   // Note: C++ will not remove it since the call has side effect.
 315   if (t_adr->isa_oopptr()) {
 316     int alias_idx = phase->C->get_alias_index(t_adr->is_ptr());
 317   }
 318 
 319   Node* base = NULL;
 320   if (address->is_AddP()) {
 321     base = address->in(AddPNode::Base);
 322   }
 323   if (base != NULL && phase->type(base)->higher_equal(TypePtr::NULL_PTR) &&
 324       !t_adr->isa_rawptr()) {
 325     // Note: raw address has TOP base and top->higher_equal(TypePtr::NULL_PTR) is true.
 326     // Skip this node optimization if its address has TOP base.
 327     return NodeSentinel; // caller will return NULL
 328   }
 329 
 330   // Avoid independent memory operations
 331   Node* old_mem = mem;
 332 
 333   // The code which unhooks non-raw memories from complete (macro-expanded)
 334   // initializations was removed. After macro-expansion all stores catched
 335   // by Initialize node became raw stores and there is no information
 336   // which memory slices they modify. So it is unsafe to move any memory
 337   // operation above these stores. Also in most cases hooked non-raw memories
 338   // were already unhooked by using information from detect_ptr_independence()
 339   // and find_previous_store().
 340 
 341   if (mem->is_MergeMem()) {
 342     MergeMemNode* mmem = mem->as_MergeMem();
 343     const TypePtr *tp = t_adr->is_ptr();
 344 
 345     mem = step_through_mergemem(phase, mmem, tp, adr_type(), tty);
 346   }
 347 
 348   if (mem != old_mem) {
 349     set_req(MemNode::Memory, mem);
 350     if (can_reshape && old_mem->outcnt() == 0) {
 351         igvn->_worklist.push(old_mem);
 352     }
 353     if (phase->type( mem ) == Type::TOP) return NodeSentinel;
 354     return this;
 355   }
 356 
 357   // let the subclass continue analyzing...
 358   return NULL;
 359 }
 360 
 361 // Helper function for proving some simple control dominations.
 362 // Attempt to prove that all control inputs of 'dom' dominate 'sub'.
 363 // Already assumes that 'dom' is available at 'sub', and that 'sub'
 364 // is not a constant (dominated by the method's StartNode).
 365 // Used by MemNode::find_previous_store to prove that the
 366 // control input of a memory operation predates (dominates)
 367 // an allocation it wants to look past.
 368 bool MemNode::all_controls_dominate(Node* dom, Node* sub) {
 369   if (dom == NULL || dom->is_top() || sub == NULL || sub->is_top())
 370     return false; // Conservative answer for dead code
 371 
 372   // Check 'dom'. Skip Proj and CatchProj nodes.
 373   dom = dom->find_exact_control(dom);
 374   if (dom == NULL || dom->is_top())
 375     return false; // Conservative answer for dead code
 376 
 377   if (dom == sub) {
 378     // For the case when, for example, 'sub' is Initialize and the original
 379     // 'dom' is Proj node of the 'sub'.
 380     return false;
 381   }
 382 
 383   if (dom->is_Con() || dom->is_Start() || dom->is_Root() || dom == sub)
 384     return true;
 385 
 386   // 'dom' dominates 'sub' if its control edge and control edges
 387   // of all its inputs dominate or equal to sub's control edge.
 388 
 389   // Currently 'sub' is either Allocate, Initialize or Start nodes.
 390   // Or Region for the check in LoadNode::Ideal();
 391   // 'sub' should have sub->in(0) != NULL.
 392   assert(sub->is_Allocate() || sub->is_Initialize() || sub->is_Start() ||
 393          sub->is_Region() || sub->is_Call(), "expecting only these nodes");
 394 
 395   // Get control edge of 'sub'.
 396   Node* orig_sub = sub;
 397   sub = sub->find_exact_control(sub->in(0));
 398   if (sub == NULL || sub->is_top())
 399     return false; // Conservative answer for dead code
 400 
 401   assert(sub->is_CFG(), "expecting control");
 402 
 403   if (sub == dom)
 404     return true;
 405 
 406   if (sub->is_Start() || sub->is_Root())
 407     return false;
 408 
 409   {
 410     // Check all control edges of 'dom'.
 411 
 412     ResourceMark rm;
 413     Arena* arena = Thread::current()->resource_area();
 414     Node_List nlist(arena);
 415     Unique_Node_List dom_list(arena);
 416 
 417     dom_list.push(dom);
 418     bool only_dominating_controls = false;
 419 
 420     for (uint next = 0; next < dom_list.size(); next++) {
 421       Node* n = dom_list.at(next);
 422       if (n == orig_sub)
 423         return false; // One of dom's inputs dominated by sub.
 424       if (!n->is_CFG() && n->pinned()) {
 425         // Check only own control edge for pinned non-control nodes.
 426         n = n->find_exact_control(n->in(0));
 427         if (n == NULL || n->is_top())
 428           return false; // Conservative answer for dead code
 429         assert(n->is_CFG(), "expecting control");
 430         dom_list.push(n);
 431       } else if (n->is_Con() || n->is_Start() || n->is_Root()) {
 432         only_dominating_controls = true;
 433       } else if (n->is_CFG()) {
 434         if (n->dominates(sub, nlist))
 435           only_dominating_controls = true;
 436         else
 437           return false;
 438       } else {
 439         // First, own control edge.
 440         Node* m = n->find_exact_control(n->in(0));
 441         if (m != NULL) {
 442           if (m->is_top())
 443             return false; // Conservative answer for dead code
 444           dom_list.push(m);
 445         }
 446         // Now, the rest of edges.
 447         uint cnt = n->req();
 448         for (uint i = 1; i < cnt; i++) {
 449           m = n->find_exact_control(n->in(i));
 450           if (m == NULL || m->is_top())
 451             continue;
 452           dom_list.push(m);
 453         }
 454       }
 455     }
 456     return only_dominating_controls;
 457   }
 458 }
 459 
 460 //---------------------detect_ptr_independence---------------------------------
 461 // Used by MemNode::find_previous_store to prove that two base
 462 // pointers are never equal.
 463 // The pointers are accompanied by their associated allocations,
 464 // if any, which have been previously discovered by the caller.
 465 bool MemNode::detect_ptr_independence(Node* p1, AllocateNode* a1,
 466                                       Node* p2, AllocateNode* a2,
 467                                       PhaseTransform* phase) {
 468   // Attempt to prove that these two pointers cannot be aliased.
 469   // They may both manifestly be allocations, and they should differ.
 470   // Or, if they are not both allocations, they can be distinct constants.
 471   // Otherwise, one is an allocation and the other a pre-existing value.
 472   if (a1 == NULL && a2 == NULL) {           // neither an allocation
 473     return (p1 != p2) && p1->is_Con() && p2->is_Con();
 474   } else if (a1 != NULL && a2 != NULL) {    // both allocations
 475     return (a1 != a2);
 476   } else if (a1 != NULL) {                  // one allocation a1
 477     // (Note:  p2->is_Con implies p2->in(0)->is_Root, which dominates.)
 478     return all_controls_dominate(p2, a1);
 479   } else { //(a2 != NULL)                   // one allocation a2
 480     return all_controls_dominate(p1, a2);
 481   }
 482   return false;
 483 }
 484 
 485 
 486 // Find an arraycopy that must have set (can_see_stored_value=true) or
 487 // could have set (can_see_stored_value=false) the value for this load
 488 Node* LoadNode::find_previous_arraycopy(PhaseTransform* phase, Node* ld_alloc, Node*& mem, bool can_see_stored_value) const {
 489   if (mem->is_Proj() && mem->in(0) != NULL && (mem->in(0)->Opcode() == Op_MemBarStoreStore ||
 490                                                mem->in(0)->Opcode() == Op_MemBarCPUOrder)) {
 491     Node* mb = mem->in(0);
 492     if (mb->in(0) != NULL && mb->in(0)->is_Proj() &&
 493         mb->in(0)->in(0) != NULL && mb->in(0)->in(0)->is_ArrayCopy()) {
 494       ArrayCopyNode* ac = mb->in(0)->in(0)->as_ArrayCopy();
 495       if (ac->is_clonebasic()) {
 496         intptr_t offset;
 497         AllocateNode* alloc = AllocateNode::Ideal_allocation(ac->in(ArrayCopyNode::Dest), phase, offset);
 498         assert(alloc != NULL && alloc->initialization()->is_complete_with_arraycopy(), "broken allocation");
 499         if (alloc == ld_alloc) {
 500           return ac;
 501         }
 502       }
 503     }
 504   } else if (mem->is_Proj() && mem->in(0) != NULL && mem->in(0)->is_ArrayCopy()) {
 505     ArrayCopyNode* ac = mem->in(0)->as_ArrayCopy();
 506 
 507     if (ac->is_arraycopy_validated() ||
 508         ac->is_copyof_validated() ||
 509         ac->is_copyofrange_validated()) {
 510       Node* ld_addp = in(MemNode::Address);
 511       if (ld_addp->is_AddP()) {
 512         Node* ld_base = ld_addp->in(AddPNode::Address);
 513         Node* ld_offs = ld_addp->in(AddPNode::Offset);
 514 
 515         Node* dest = ac->in(ArrayCopyNode::Dest);
 516 
 517         if (dest == ld_base) {
 518           const TypeX *ld_offs_t = phase->type(ld_offs)->isa_intptr_t();
 519           if (ac->modifies(ld_offs_t->_lo, ld_offs_t->_hi, phase, can_see_stored_value)) {
 520             return ac;
 521           }
 522           if (!can_see_stored_value) {
 523             mem = ac->in(TypeFunc::Memory);
 524           }
 525         }
 526       }
 527     }
 528   }
 529   return NULL;
 530 }
 531 
 532 // The logic for reordering loads and stores uses four steps:
 533 // (a) Walk carefully past stores and initializations which we
 534 //     can prove are independent of this load.
 535 // (b) Observe that the next memory state makes an exact match
 536 //     with self (load or store), and locate the relevant store.
 537 // (c) Ensure that, if we were to wire self directly to the store,
 538 //     the optimizer would fold it up somehow.
 539 // (d) Do the rewiring, and return, depending on some other part of
 540 //     the optimizer to fold up the load.
 541 // This routine handles steps (a) and (b).  Steps (c) and (d) are
 542 // specific to loads and stores, so they are handled by the callers.
 543 // (Currently, only LoadNode::Ideal has steps (c), (d).  More later.)
 544 //
 545 Node* MemNode::find_previous_store(PhaseTransform* phase) {
 546   Node*         ctrl   = in(MemNode::Control);
 547   Node*         adr    = in(MemNode::Address);
 548   intptr_t      offset = 0;
 549   Node*         base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
 550   AllocateNode* alloc  = AllocateNode::Ideal_allocation(base, phase);
 551 
 552   if (offset == Type::OffsetBot)
 553     return NULL;            // cannot unalias unless there are precise offsets
 554 
 555   const TypeOopPtr *addr_t = adr->bottom_type()->isa_oopptr();
 556 
 557   intptr_t size_in_bytes = memory_size();
 558 
 559   Node* mem = in(MemNode::Memory);   // start searching here...
 560 
 561   int cnt = 50;             // Cycle limiter
 562   for (;;) {                // While we can dance past unrelated stores...
 563     if (--cnt < 0)  break;  // Caught in cycle or a complicated dance?
 564 
 565     Node* prev = mem;
 566     if (mem->is_Store()) {
 567       Node* st_adr = mem->in(MemNode::Address);
 568       intptr_t st_offset = 0;
 569       Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_offset);
 570       if (st_base == NULL)
 571         break;              // inscrutable pointer
 572       if (st_offset != offset && st_offset != Type::OffsetBot) {
 573         const int MAX_STORE = BytesPerLong;
 574         if (st_offset >= offset + size_in_bytes ||
 575             st_offset <= offset - MAX_STORE ||
 576             st_offset <= offset - mem->as_Store()->memory_size()) {
 577           // Success:  The offsets are provably independent.
 578           // (You may ask, why not just test st_offset != offset and be done?
 579           // The answer is that stores of different sizes can co-exist
 580           // in the same sequence of RawMem effects.  We sometimes initialize
 581           // a whole 'tile' of array elements with a single jint or jlong.)
 582           mem = mem->in(MemNode::Memory);
 583           continue;           // (a) advance through independent store memory
 584         }
 585       }
 586       if (st_base != base &&
 587           detect_ptr_independence(base, alloc,
 588                                   st_base,
 589                                   AllocateNode::Ideal_allocation(st_base, phase),
 590                                   phase)) {
 591         // Success:  The bases are provably independent.
 592         mem = mem->in(MemNode::Memory);
 593         continue;           // (a) advance through independent store memory
 594       }
 595 
 596       // (b) At this point, if the bases or offsets do not agree, we lose,
 597       // since we have not managed to prove 'this' and 'mem' independent.
 598       if (st_base == base && st_offset == offset) {
 599         return mem;         // let caller handle steps (c), (d)
 600       }
 601 
 602     } else if (mem->is_Proj() && mem->in(0)->is_Initialize()) {
 603       InitializeNode* st_init = mem->in(0)->as_Initialize();
 604       AllocateNode*  st_alloc = st_init->allocation();
 605       if (st_alloc == NULL)
 606         break;              // something degenerated
 607       bool known_identical = false;
 608       bool known_independent = false;
 609       if (alloc == st_alloc)
 610         known_identical = true;
 611       else if (alloc != NULL)
 612         known_independent = true;
 613       else if (all_controls_dominate(this, st_alloc))
 614         known_independent = true;
 615 
 616       if (known_independent) {
 617         // The bases are provably independent: Either they are
 618         // manifestly distinct allocations, or else the control
 619         // of this load dominates the store's allocation.
 620         int alias_idx = phase->C->get_alias_index(adr_type());
 621         if (alias_idx == Compile::AliasIdxRaw) {
 622           mem = st_alloc->in(TypeFunc::Memory);
 623         } else {
 624           mem = st_init->memory(alias_idx);
 625         }
 626         continue;           // (a) advance through independent store memory
 627       }
 628 
 629       // (b) at this point, if we are not looking at a store initializing
 630       // the same allocation we are loading from, we lose.
 631       if (known_identical) {
 632         // From caller, can_see_stored_value will consult find_captured_store.
 633         return mem;         // let caller handle steps (c), (d)
 634       }
 635 
 636     } else if (find_previous_arraycopy(phase, alloc, mem, false) != NULL) {
 637       if (prev != mem) {
 638         // Found an arraycopy but it doesn't affect that load
 639         continue;
 640       }
 641       // Found an arraycopy that may affect that load
 642       return mem;
 643     } else if (addr_t != NULL && addr_t->is_known_instance_field()) {
 644       // Can't use optimize_simple_memory_chain() since it needs PhaseGVN.
 645       if (mem->is_Proj() && mem->in(0)->is_Call()) {
 646         // ArrayCopyNodes processed here as well.
 647         CallNode *call = mem->in(0)->as_Call();
 648         if (!call->may_modify(addr_t, phase)) {
 649           mem = call->in(TypeFunc::Memory);
 650           continue;         // (a) advance through independent call memory
 651         }
 652       } else if (mem->is_Proj() && mem->in(0)->is_MemBar()) {
 653         if (ArrayCopyNode::may_modify(addr_t, mem->in(0)->as_MemBar(), phase)) {
 654           break;
 655         }
 656         mem = mem->in(0)->in(TypeFunc::Memory);
 657         continue;           // (a) advance through independent MemBar memory
 658       } else if (mem->is_ClearArray()) {
 659         if (ClearArrayNode::step_through(&mem, (uint)addr_t->instance_id(), phase)) {
 660           // (the call updated 'mem' value)
 661           continue;         // (a) advance through independent allocation memory
 662         } else {
 663           // Can not bypass initialization of the instance
 664           // we are looking for.
 665           return mem;
 666         }
 667       } else if (mem->is_MergeMem()) {
 668         int alias_idx = phase->C->get_alias_index(adr_type());
 669         mem = mem->as_MergeMem()->memory_at(alias_idx);
 670         continue;           // (a) advance through independent MergeMem memory
 671       }
 672     }
 673 
 674     // Unless there is an explicit 'continue', we must bail out here,
 675     // because 'mem' is an inscrutable memory state (e.g., a call).
 676     break;
 677   }
 678 
 679   return NULL;              // bail out
 680 }
 681 
 682 //----------------------calculate_adr_type-------------------------------------
 683 // Helper function.  Notices when the given type of address hits top or bottom.
 684 // Also, asserts a cross-check of the type against the expected address type.
 685 const TypePtr* MemNode::calculate_adr_type(const Type* t, const TypePtr* cross_check) {
 686   if (t == Type::TOP)  return NULL; // does not touch memory any more?
 687   #ifdef PRODUCT
 688   cross_check = NULL;
 689   #else
 690   if (!VerifyAliases || is_error_reported() || Node::in_dump())  cross_check = NULL;
 691   #endif
 692   const TypePtr* tp = t->isa_ptr();
 693   if (tp == NULL) {
 694     assert(cross_check == NULL || cross_check == TypePtr::BOTTOM, "expected memory type must be wide");
 695     return TypePtr::BOTTOM;           // touches lots of memory
 696   } else {
 697     #ifdef ASSERT
 698     // %%%% [phh] We don't check the alias index if cross_check is
 699     //            TypeRawPtr::BOTTOM.  Needs to be investigated.
 700     if (cross_check != NULL &&
 701         cross_check != TypePtr::BOTTOM &&
 702         cross_check != TypeRawPtr::BOTTOM) {
 703       // Recheck the alias index, to see if it has changed (due to a bug).
 704       Compile* C = Compile::current();
 705       assert(C->get_alias_index(cross_check) == C->get_alias_index(tp),
 706              "must stay in the original alias category");
 707       // The type of the address must be contained in the adr_type,
 708       // disregarding "null"-ness.
 709       // (We make an exception for TypeRawPtr::BOTTOM, which is a bit bucket.)
 710       const TypePtr* tp_notnull = tp->join(TypePtr::NOTNULL)->is_ptr();
 711       assert(cross_check->meet(tp_notnull) == cross_check->remove_speculative(),
 712              "real address must not escape from expected memory type");
 713     }
 714     #endif
 715     return tp;
 716   }
 717 }
 718 
 719 //=============================================================================
 720 // Should LoadNode::Ideal() attempt to remove control edges?
 721 bool LoadNode::can_remove_control() const {
 722   return true;
 723 }
 724 uint LoadNode::size_of() const { return sizeof(*this); }
 725 uint LoadNode::cmp( const Node &n ) const
 726 { return !Type::cmp( _type, ((LoadNode&)n)._type ); }
 727 const Type *LoadNode::bottom_type() const { return _type; }
 728 uint LoadNode::ideal_reg() const {
 729   return _type->ideal_reg();
 730 }
 731 
 732 #ifndef PRODUCT
 733 void LoadNode::dump_spec(outputStream *st) const {
 734   MemNode::dump_spec(st);
 735   if( !Verbose && !WizardMode ) {
 736     // standard dump does this in Verbose and WizardMode
 737     st->print(" #"); _type->dump_on(st);
 738   }
 739   if (!_depends_only_on_test) {
 740     st->print(" (does not depend only on test)");
 741   }
 742 }
 743 #endif
 744 
 745 #ifdef ASSERT
 746 //----------------------------is_immutable_value-------------------------------
 747 // Helper function to allow a raw load without control edge for some cases
 748 bool LoadNode::is_immutable_value(Node* adr) {
 749   return (adr->is_AddP() && adr->in(AddPNode::Base)->is_top() &&
 750           adr->in(AddPNode::Address)->Opcode() == Op_ThreadLocal &&
 751           (adr->in(AddPNode::Offset)->find_intptr_t_con(-1) ==
 752            in_bytes(JavaThread::osthread_offset())));
 753 }
 754 #endif
 755 
 756 //----------------------------LoadNode::make-----------------------------------
 757 // Polymorphic factory method:
 758 Node *LoadNode::make(PhaseGVN& gvn, Node *ctl, Node *mem, Node *adr, const TypePtr* adr_type, const Type *rt, BasicType bt, MemOrd mo, ControlDependency control_dependency) {
 759   Compile* C = gvn.C;
 760 
 761   // sanity check the alias category against the created node type
 762   assert(!(adr_type->isa_oopptr() &&
 763            adr_type->offset() == oopDesc::klass_offset_in_bytes()),
 764          "use LoadKlassNode instead");
 765   assert(!(adr_type->isa_aryptr() &&
 766            adr_type->offset() == arrayOopDesc::length_offset_in_bytes()),
 767          "use LoadRangeNode instead");
 768   // Check control edge of raw loads
 769   assert( ctl != NULL || C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
 770           // oop will be recorded in oop map if load crosses safepoint
 771           rt->isa_oopptr() || is_immutable_value(adr),
 772           "raw memory operations should have control edge");
 773   switch (bt) {
 774   case T_BOOLEAN: return new LoadUBNode(ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency);
 775   case T_BYTE:    return new LoadBNode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency);
 776   case T_INT:     return new LoadINode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency);
 777   case T_CHAR:    return new LoadUSNode(ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency);
 778   case T_SHORT:   return new LoadSNode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency);
 779   case T_LONG:    return new LoadLNode (ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency);
 780   case T_FLOAT:   return new LoadFNode (ctl, mem, adr, adr_type, rt,            mo, control_dependency);
 781   case T_DOUBLE:  return new LoadDNode (ctl, mem, adr, adr_type, rt,            mo, control_dependency);
 782   case T_ADDRESS: return new LoadPNode (ctl, mem, adr, adr_type, rt->is_ptr(),  mo, control_dependency);
 783   case T_OBJECT:
 784 #ifdef _LP64
 785     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 786       Node* load  = gvn.transform(new LoadNNode(ctl, mem, adr, adr_type, rt->make_narrowoop(), mo, control_dependency));
 787       return new DecodeNNode(load, load->bottom_type()->make_ptr());
 788     } else
 789 #endif
 790     {
 791       assert(!adr->bottom_type()->is_ptr_to_narrowoop() && !adr->bottom_type()->is_ptr_to_narrowklass(), "should have got back a narrow oop");
 792       return new LoadPNode(ctl, mem, adr, adr_type, rt->is_oopptr(), mo, control_dependency);
 793     }
 794   }
 795   ShouldNotReachHere();
 796   return (LoadNode*)NULL;
 797 }
 798 
 799 LoadLNode* LoadLNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, MemOrd mo, ControlDependency control_dependency) {
 800   bool require_atomic = true;
 801   return new LoadLNode(ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency, require_atomic);
 802 }
 803 
 804 LoadDNode* LoadDNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, MemOrd mo, ControlDependency control_dependency) {
 805   bool require_atomic = true;
 806   return new LoadDNode(ctl, mem, adr, adr_type, rt, mo, control_dependency, require_atomic);
 807 }
 808 
 809 
 810 
 811 //------------------------------hash-------------------------------------------
 812 uint LoadNode::hash() const {
 813   // unroll addition of interesting fields
 814   return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address);
 815 }
 816 
 817 static bool skip_through_membars(Compile::AliasType* atp, const TypeInstPtr* tp, bool eliminate_boxing) {
 818   if ((atp != NULL) && (atp->index() >= Compile::AliasIdxRaw)) {
 819     bool non_volatile = (atp->field() != NULL) && !atp->field()->is_volatile();
 820     bool is_stable_ary = FoldStableValues &&
 821                          (tp != NULL) && (tp->isa_aryptr() != NULL) &&
 822                          tp->isa_aryptr()->is_stable();
 823 
 824     return (eliminate_boxing && non_volatile) || is_stable_ary;
 825   }
 826 
 827   return false;
 828 }
 829 
 830 // Is the value loaded previously stored by an arraycopy? If so return
 831 // a load node that reads from the source array so we may be able to
 832 // optimize out the ArrayCopy node later.
 833 Node* LoadNode::can_see_arraycopy_value(Node* st, PhaseTransform* phase) const {
 834   Node* ld_adr = in(MemNode::Address);
 835   intptr_t ld_off = 0;
 836   AllocateNode* ld_alloc = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off);
 837   Node* ac = find_previous_arraycopy(phase, ld_alloc, st, true);
 838   if (ac != NULL) {
 839     assert(ac->is_ArrayCopy(), "what kind of node can this be?");
 840 
 841     Node* ld = clone();
 842     if (ac->as_ArrayCopy()->is_clonebasic()) {
 843       assert(ld_alloc != NULL, "need an alloc");
 844       Node* addp = in(MemNode::Address)->clone();
 845       assert(addp->is_AddP(), "address must be addp");
 846       assert(addp->in(AddPNode::Base) == ac->in(ArrayCopyNode::Dest)->in(AddPNode::Base), "strange pattern");
 847       assert(addp->in(AddPNode::Address) == ac->in(ArrayCopyNode::Dest)->in(AddPNode::Address), "strange pattern");
 848       addp->set_req(AddPNode::Base, ac->in(ArrayCopyNode::Src)->in(AddPNode::Base));
 849       addp->set_req(AddPNode::Address, ac->in(ArrayCopyNode::Src)->in(AddPNode::Address));
 850       ld->set_req(MemNode::Address, phase->transform(addp));
 851       if (in(0) != NULL) {
 852         assert(ld_alloc->in(0) != NULL, "alloc must have control");
 853         ld->set_req(0, ld_alloc->in(0));
 854       }
 855     } else {
 856       Node* addp = in(MemNode::Address)->clone();
 857       assert(addp->in(AddPNode::Base) == addp->in(AddPNode::Address), "should be");
 858       addp->set_req(AddPNode::Base, ac->in(ArrayCopyNode::Src));
 859       addp->set_req(AddPNode::Address, ac->in(ArrayCopyNode::Src));
 860 
 861       const TypeAryPtr* ary_t = phase->type(in(MemNode::Address))->isa_aryptr();
 862       BasicType ary_elem  = ary_t->klass()->as_array_klass()->element_type()->basic_type();
 863       uint header = arrayOopDesc::base_offset_in_bytes(ary_elem);
 864       uint shift  = exact_log2(type2aelembytes(ary_elem));
 865 
 866       Node* diff = phase->transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
 867 #ifdef _LP64
 868       diff = phase->transform(new ConvI2LNode(diff));
 869 #endif
 870       diff = phase->transform(new LShiftXNode(diff, phase->intcon(shift)));
 871 
 872       Node* offset = phase->transform(new AddXNode(addp->in(AddPNode::Offset), diff));
 873       addp->set_req(AddPNode::Offset, offset);
 874       ld->set_req(MemNode::Address, phase->transform(addp));
 875 
 876       if (in(0) != NULL) {
 877         assert(ac->in(0) != NULL, "alloc must have control");
 878         ld->set_req(0, ac->in(0));
 879       }
 880     }
 881     // load depends on the tests that validate the arraycopy
 882     ld->as_Load()->_depends_only_on_test = Pinned;
 883     return ld;
 884   }
 885   return NULL;
 886 }
 887 
 888 
 889 //---------------------------can_see_stored_value------------------------------
 890 // This routine exists to make sure this set of tests is done the same
 891 // everywhere.  We need to make a coordinated change: first LoadNode::Ideal
 892 // will change the graph shape in a way which makes memory alive twice at the
 893 // same time (uses the Oracle model of aliasing), then some
 894 // LoadXNode::Identity will fold things back to the equivalence-class model
 895 // of aliasing.
 896 Node* MemNode::can_see_stored_value(Node* st, PhaseTransform* phase) const {
 897   Node* ld_adr = in(MemNode::Address);
 898   intptr_t ld_off = 0;
 899   AllocateNode* ld_alloc = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off);
 900   const TypeInstPtr* tp = phase->type(ld_adr)->isa_instptr();
 901   Compile::AliasType* atp = (tp != NULL) ? phase->C->alias_type(tp) : NULL;
 902   // This is more general than load from boxing objects.
 903   if (skip_through_membars(atp, tp, phase->C->eliminate_boxing())) {
 904     uint alias_idx = atp->index();
 905     bool final = !atp->is_rewritable();
 906     Node* result = NULL;
 907     Node* current = st;
 908     // Skip through chains of MemBarNodes checking the MergeMems for
 909     // new states for the slice of this load.  Stop once any other
 910     // kind of node is encountered.  Loads from final memory can skip
 911     // through any kind of MemBar but normal loads shouldn't skip
 912     // through MemBarAcquire since the could allow them to move out of
 913     // a synchronized region.
 914     while (current->is_Proj()) {
 915       int opc = current->in(0)->Opcode();
 916       if ((final && (opc == Op_MemBarAcquire ||
 917                      opc == Op_MemBarAcquireLock ||
 918                      opc == Op_LoadFence)) ||
 919           opc == Op_MemBarRelease ||
 920           opc == Op_StoreFence ||
 921           opc == Op_MemBarReleaseLock ||
 922           opc == Op_MemBarStoreStore ||
 923           opc == Op_MemBarCPUOrder) {
 924         Node* mem = current->in(0)->in(TypeFunc::Memory);
 925         if (mem->is_MergeMem()) {
 926           MergeMemNode* merge = mem->as_MergeMem();
 927           Node* new_st = merge->memory_at(alias_idx);
 928           if (new_st == merge->base_memory()) {
 929             // Keep searching
 930             current = new_st;
 931             continue;
 932           }
 933           // Save the new memory state for the slice and fall through
 934           // to exit.
 935           result = new_st;
 936         }
 937       }
 938       break;
 939     }
 940     if (result != NULL) {
 941       st = result;
 942     }
 943   }
 944 
 945   // Loop around twice in the case Load -> Initialize -> Store.
 946   // (See PhaseIterGVN::add_users_to_worklist, which knows about this case.)
 947   for (int trip = 0; trip <= 1; trip++) {
 948 
 949     if (st->is_Store()) {
 950       Node* st_adr = st->in(MemNode::Address);
 951       if (!phase->eqv(st_adr, ld_adr)) {
 952         // Try harder before giving up...  Match raw and non-raw pointers.
 953         intptr_t st_off = 0;
 954         AllocateNode* alloc = AllocateNode::Ideal_allocation(st_adr, phase, st_off);
 955         if (alloc == NULL)       return NULL;
 956         if (alloc != ld_alloc)   return NULL;
 957         if (ld_off != st_off)    return NULL;
 958         // At this point we have proven something like this setup:
 959         //  A = Allocate(...)
 960         //  L = LoadQ(,  AddP(CastPP(, A.Parm),, #Off))
 961         //  S = StoreQ(, AddP(,        A.Parm  , #Off), V)
 962         // (Actually, we haven't yet proven the Q's are the same.)
 963         // In other words, we are loading from a casted version of
 964         // the same pointer-and-offset that we stored to.
 965         // Thus, we are able to replace L by V.
 966       }
 967       // Now prove that we have a LoadQ matched to a StoreQ, for some Q.
 968       if (store_Opcode() != st->Opcode())
 969         return NULL;
 970       return st->in(MemNode::ValueIn);
 971     }
 972 
 973     // A load from a freshly-created object always returns zero.
 974     // (This can happen after LoadNode::Ideal resets the load's memory input
 975     // to find_captured_store, which returned InitializeNode::zero_memory.)
 976     if (st->is_Proj() && st->in(0)->is_Allocate() &&
 977         (st->in(0) == ld_alloc) &&
 978         (ld_off >= st->in(0)->as_Allocate()->minimum_header_size())) {
 979       // return a zero value for the load's basic type
 980       // (This is one of the few places where a generic PhaseTransform
 981       // can create new nodes.  Think of it as lazily manifesting
 982       // virtually pre-existing constants.)
 983       return phase->zerocon(memory_type());
 984     }
 985 
 986     // A load from an initialization barrier can match a captured store.
 987     if (st->is_Proj() && st->in(0)->is_Initialize()) {
 988       InitializeNode* init = st->in(0)->as_Initialize();
 989       AllocateNode* alloc = init->allocation();
 990       if ((alloc != NULL) && (alloc == ld_alloc)) {
 991         // examine a captured store value
 992         st = init->find_captured_store(ld_off, memory_size(), phase);
 993         if (st != NULL) {
 994           continue;             // take one more trip around
 995         }
 996       }
 997     }
 998 
 999     // Load boxed value from result of valueOf() call is input parameter.
1000     if (this->is_Load() && ld_adr->is_AddP() &&
1001         (tp != NULL) && tp->is_ptr_to_boxed_value()) {
1002       intptr_t ignore = 0;
1003       Node* base = AddPNode::Ideal_base_and_offset(ld_adr, phase, ignore);
1004       base = ShenandoahBarrierNode::skip_through_barrier(base);
1005       if (base != NULL && base->is_Proj() &&
1006           base->as_Proj()->_con == TypeFunc::Parms &&
1007           base->in(0)->is_CallStaticJava() &&
1008           base->in(0)->as_CallStaticJava()->is_boxing_method()) {
1009         return base->in(0)->in(TypeFunc::Parms);
1010       }
1011     }
1012 
1013     break;
1014   }
1015 
1016   return NULL;
1017 }
1018 
1019 //----------------------is_instance_field_load_with_local_phi------------------
1020 bool LoadNode::is_instance_field_load_with_local_phi(Node* ctrl) {
1021   if( in(Memory)->is_Phi() && in(Memory)->in(0) == ctrl &&
1022       in(Address)->is_AddP() ) {
1023     const TypeOopPtr* t_oop = in(Address)->bottom_type()->isa_oopptr();
1024     // Only instances and boxed values.
1025     if( t_oop != NULL &&
1026         (t_oop->is_ptr_to_boxed_value() ||
1027          t_oop->is_known_instance_field()) &&
1028         t_oop->offset() != Type::OffsetBot &&
1029         t_oop->offset() != Type::OffsetTop) {
1030       return true;
1031     }
1032   }
1033   return false;
1034 }
1035 
1036 //------------------------------Identity---------------------------------------
1037 // Loads are identity if previous store is to same address
1038 Node *LoadNode::Identity( PhaseTransform *phase ) {
1039   // If the previous store-maker is the right kind of Store, and the store is
1040   // to the same address, then we are equal to the value stored.
1041   Node* mem = in(Memory);
1042   Node* value = can_see_stored_value(mem, phase);
1043   if( value ) {
1044     // byte, short & char stores truncate naturally.
1045     // A load has to load the truncated value which requires
1046     // some sort of masking operation and that requires an
1047     // Ideal call instead of an Identity call.
1048     if (memory_size() < BytesPerInt) {
1049       // If the input to the store does not fit with the load's result type,
1050       // it must be truncated via an Ideal call.
1051       if (!phase->type(value)->higher_equal(phase->type(this)))
1052         return this;
1053     }
1054     // (This works even when value is a Con, but LoadNode::Value
1055     // usually runs first, producing the singleton type of the Con.)
1056     return value;
1057   }
1058 
1059   // Search for an existing data phi which was generated before for the same
1060   // instance's field to avoid infinite generation of phis in a loop.
1061   Node *region = mem->in(0);
1062   if (is_instance_field_load_with_local_phi(region)) {
1063     const TypeOopPtr *addr_t = in(Address)->bottom_type()->isa_oopptr();
1064     int this_index  = phase->C->get_alias_index(addr_t);
1065     int this_offset = addr_t->offset();
1066     int this_iid    = addr_t->instance_id();
1067     if (!addr_t->is_known_instance() &&
1068          addr_t->is_ptr_to_boxed_value()) {
1069       // Use _idx of address base (could be Phi node) for boxed values.
1070       intptr_t   ignore = 0;
1071       Node*      base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore);
1072       this_iid = base->_idx;
1073     }
1074     const Type* this_type = bottom_type();
1075     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1076       Node* phi = region->fast_out(i);
1077       if (phi->is_Phi() && phi != mem &&
1078           phi->as_Phi()->is_same_inst_field(this_type, this_iid, this_index, this_offset)) {
1079         return phi;
1080       }
1081     }
1082   }
1083 
1084   return this;
1085 }
1086 
1087 // We're loading from an object which has autobox behaviour.
1088 // If this object is result of a valueOf call we'll have a phi
1089 // merging a newly allocated object and a load from the cache.
1090 // We want to replace this load with the original incoming
1091 // argument to the valueOf call.
1092 Node* LoadNode::eliminate_autobox(PhaseGVN* phase) {
1093   assert(phase->C->eliminate_boxing(), "sanity");
1094   intptr_t ignore = 0;
1095   Node* base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore);
1096   if ((base == NULL) || base->is_Phi()) {
1097     // Push the loads from the phi that comes from valueOf up
1098     // through it to allow elimination of the loads and the recovery
1099     // of the original value. It is done in split_through_phi().
1100     return NULL;
1101   } else if (base->is_Load() ||
1102              base->is_DecodeN() && base->in(1)->is_Load()) {
1103     // Eliminate the load of boxed value for integer types from the cache
1104     // array by deriving the value from the index into the array.
1105     // Capture the offset of the load and then reverse the computation.
1106 
1107     // Get LoadN node which loads a boxing object from 'cache' array.
1108     if (base->is_DecodeN()) {
1109       base = base->in(1);
1110     }
1111     if (!base->in(Address)->is_AddP()) {
1112       return NULL; // Complex address
1113     }
1114     AddPNode* address = base->in(Address)->as_AddP();
1115     Node* cache_base = address->in(AddPNode::Base);
1116     if ((cache_base != NULL) && cache_base->is_DecodeN()) {
1117       // Get ConP node which is static 'cache' field.
1118       cache_base = cache_base->in(1);
1119     }
1120     if ((cache_base != NULL) && cache_base->is_Con()) {
1121       const TypeAryPtr* base_type = cache_base->bottom_type()->isa_aryptr();
1122       if ((base_type != NULL) && base_type->is_autobox_cache()) {
1123         Node* elements[4];
1124         int shift = exact_log2(type2aelembytes(T_OBJECT));
1125         int count = address->unpack_offsets(elements, ARRAY_SIZE(elements));
1126         if ((count >  0) && elements[0]->is_Con() &&
1127             ((count == 1) ||
1128              (count == 2) && elements[1]->Opcode() == Op_LShiftX &&
1129                              elements[1]->in(2) == phase->intcon(shift))) {
1130           ciObjArray* array = base_type->const_oop()->as_obj_array();
1131           // Fetch the box object cache[0] at the base of the array and get its value
1132           ciInstance* box = array->obj_at(0)->as_instance();
1133           ciInstanceKlass* ik = box->klass()->as_instance_klass();
1134           assert(ik->is_box_klass(), "sanity");
1135           assert(ik->nof_nonstatic_fields() == 1, "change following code");
1136           if (ik->nof_nonstatic_fields() == 1) {
1137             // This should be true nonstatic_field_at requires calling
1138             // nof_nonstatic_fields so check it anyway
1139             ciConstant c = box->field_value(ik->nonstatic_field_at(0));
1140             BasicType bt = c.basic_type();
1141             // Only integer types have boxing cache.
1142             assert(bt == T_BOOLEAN || bt == T_CHAR  ||
1143                    bt == T_BYTE    || bt == T_SHORT ||
1144                    bt == T_INT     || bt == T_LONG, err_msg_res("wrong type = %s", type2name(bt)));
1145             jlong cache_low = (bt == T_LONG) ? c.as_long() : c.as_int();
1146             if (cache_low != (int)cache_low) {
1147               return NULL; // should not happen since cache is array indexed by value
1148             }
1149             jlong offset = arrayOopDesc::base_offset_in_bytes(T_OBJECT) - (cache_low << shift);
1150             if (offset != (int)offset) {
1151               return NULL; // should not happen since cache is array indexed by value
1152             }
1153            // Add up all the offsets making of the address of the load
1154             Node* result = elements[0];
1155             for (int i = 1; i < count; i++) {
1156               result = phase->transform(new AddXNode(result, elements[i]));
1157             }
1158             // Remove the constant offset from the address and then
1159             result = phase->transform(new AddXNode(result, phase->MakeConX(-(int)offset)));
1160             // remove the scaling of the offset to recover the original index.
1161             if (result->Opcode() == Op_LShiftX && result->in(2) == phase->intcon(shift)) {
1162               // Peel the shift off directly but wrap it in a dummy node
1163               // since Ideal can't return existing nodes
1164               result = new RShiftXNode(result->in(1), phase->intcon(0));
1165             } else if (result->is_Add() && result->in(2)->is_Con() &&
1166                        result->in(1)->Opcode() == Op_LShiftX &&
1167                        result->in(1)->in(2) == phase->intcon(shift)) {
1168               // We can't do general optimization: ((X<<Z) + Y) >> Z ==> X + (Y>>Z)
1169               // but for boxing cache access we know that X<<Z will not overflow
1170               // (there is range check) so we do this optimizatrion by hand here.
1171               Node* add_con = new RShiftXNode(result->in(2), phase->intcon(shift));
1172               result = new AddXNode(result->in(1)->in(1), phase->transform(add_con));
1173             } else {
1174               result = new RShiftXNode(result, phase->intcon(shift));
1175             }
1176 #ifdef _LP64
1177             if (bt != T_LONG) {
1178               result = new ConvL2INode(phase->transform(result));
1179             }
1180 #else
1181             if (bt == T_LONG) {
1182               result = new ConvI2LNode(phase->transform(result));
1183             }
1184 #endif
1185             // Boxing/unboxing can be done from signed & unsigned loads (e.g. LoadUB -> ... -> LoadB pair).
1186             // Need to preserve unboxing load type if it is unsigned.
1187             switch(this->Opcode()) {
1188               case Op_LoadUB:
1189                 result = new AndINode(phase->transform(result), phase->intcon(0xFF));
1190                 break;
1191               case Op_LoadUS:
1192                 result = new AndINode(phase->transform(result), phase->intcon(0xFFFF));
1193                 break;
1194             }
1195             return result;
1196           }
1197         }
1198       }
1199     }
1200   }
1201   return NULL;
1202 }
1203 
1204 static bool stable_phi(PhiNode* phi, PhaseGVN *phase) {
1205   Node* region = phi->in(0);
1206   if (region == NULL) {
1207     return false; // Wait stable graph
1208   }
1209   uint cnt = phi->req();
1210   for (uint i = 1; i < cnt; i++) {
1211     Node* rc = region->in(i);
1212     if (rc == NULL || phase->type(rc) == Type::TOP)
1213       return false; // Wait stable graph
1214     Node* in = phi->in(i);
1215     if (in == NULL || phase->type(in) == Type::TOP)
1216       return false; // Wait stable graph
1217   }
1218   return true;
1219 }
1220 //------------------------------split_through_phi------------------------------
1221 // Split instance or boxed field load through Phi.
1222 Node *LoadNode::split_through_phi(PhaseGVN *phase) {
1223   Node* mem     = in(Memory);
1224   Node* address = in(Address);
1225   const TypeOopPtr *t_oop = phase->type(address)->isa_oopptr();
1226 
1227   assert((t_oop != NULL) &&
1228          (t_oop->is_known_instance_field() ||
1229           t_oop->is_ptr_to_boxed_value()), "invalide conditions");
1230 
1231   Compile* C = phase->C;
1232   intptr_t ignore = 0;
1233   Node*    base = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1234   bool base_is_phi = (base != NULL) && base->is_Phi();
1235   bool load_boxed_values = t_oop->is_ptr_to_boxed_value() && C->aggressive_unboxing() &&
1236                            (base != NULL) && (base == address->in(AddPNode::Base)) &&
1237                            phase->type(base)->higher_equal(TypePtr::NOTNULL);
1238 
1239   if (!((mem->is_Phi() || base_is_phi) &&
1240         (load_boxed_values || t_oop->is_known_instance_field()))) {
1241     return NULL; // memory is not Phi
1242   }
1243 
1244   if (mem->is_Phi()) {
1245     if (!stable_phi(mem->as_Phi(), phase)) {
1246       return NULL; // Wait stable graph
1247     }
1248     uint cnt = mem->req();
1249     // Check for loop invariant memory.
1250     if (cnt == 3) {
1251       for (uint i = 1; i < cnt; i++) {
1252         Node* in = mem->in(i);
1253         Node*  m = optimize_memory_chain(in, t_oop, this, phase);
1254         if (m == mem) {
1255           set_req(Memory, mem->in(cnt - i));
1256           return this; // made change
1257         }
1258       }
1259     }
1260   }
1261   if (base_is_phi) {
1262     if (!stable_phi(base->as_Phi(), phase)) {
1263       return NULL; // Wait stable graph
1264     }
1265     uint cnt = base->req();
1266     // Check for loop invariant memory.
1267     if (cnt == 3) {
1268       for (uint i = 1; i < cnt; i++) {
1269         if (base->in(i) == base) {
1270           return NULL; // Wait stable graph
1271         }
1272       }
1273     }
1274   }
1275 
1276   bool load_boxed_phi = load_boxed_values && base_is_phi && (base->in(0) == mem->in(0));
1277 
1278   // Split through Phi (see original code in loopopts.cpp).
1279   assert(C->have_alias_type(t_oop), "instance should have alias type");
1280 
1281   // Do nothing here if Identity will find a value
1282   // (to avoid infinite chain of value phis generation).
1283   if (!phase->eqv(this, this->Identity(phase)))
1284     return NULL;
1285 
1286   // Select Region to split through.
1287   Node* region;
1288   if (!base_is_phi) {
1289     assert(mem->is_Phi(), "sanity");
1290     region = mem->in(0);
1291     // Skip if the region dominates some control edge of the address.
1292     if (!MemNode::all_controls_dominate(address, region))
1293       return NULL;
1294   } else if (!mem->is_Phi()) {
1295     assert(base_is_phi, "sanity");
1296     region = base->in(0);
1297     // Skip if the region dominates some control edge of the memory.
1298     if (!MemNode::all_controls_dominate(mem, region))
1299       return NULL;
1300   } else if (base->in(0) != mem->in(0)) {
1301     assert(base_is_phi && mem->is_Phi(), "sanity");
1302     if (MemNode::all_controls_dominate(mem, base->in(0))) {
1303       region = base->in(0);
1304     } else if (MemNode::all_controls_dominate(address, mem->in(0))) {
1305       region = mem->in(0);
1306     } else {
1307       return NULL; // complex graph
1308     }
1309   } else {
1310     assert(base->in(0) == mem->in(0), "sanity");
1311     region = mem->in(0);
1312   }
1313 
1314   const Type* this_type = this->bottom_type();
1315   int this_index  = C->get_alias_index(t_oop);
1316   int this_offset = t_oop->offset();
1317   int this_iid    = t_oop->instance_id();
1318   if (!t_oop->is_known_instance() && load_boxed_values) {
1319     // Use _idx of address base for boxed values.
1320     this_iid = base->_idx;
1321   }
1322   PhaseIterGVN* igvn = phase->is_IterGVN();
1323   Node* phi = new PhiNode(region, this_type, NULL, this_iid, this_index, this_offset);
1324   for (uint i = 1; i < region->req(); i++) {
1325     Node* x;
1326     Node* the_clone = NULL;
1327     if (region->in(i) == C->top()) {
1328       x = C->top();      // Dead path?  Use a dead data op
1329     } else {
1330       x = this->clone();        // Else clone up the data op
1331       the_clone = x;            // Remember for possible deletion.
1332       // Alter data node to use pre-phi inputs
1333       if (this->in(0) == region) {
1334         x->set_req(0, region->in(i));
1335       } else {
1336         x->set_req(0, NULL);
1337       }
1338       if (mem->is_Phi() && (mem->in(0) == region)) {
1339         x->set_req(Memory, mem->in(i)); // Use pre-Phi input for the clone.
1340       }
1341       if (address->is_Phi() && address->in(0) == region) {
1342         x->set_req(Address, address->in(i)); // Use pre-Phi input for the clone
1343       }
1344       if (base_is_phi && (base->in(0) == region)) {
1345         Node* base_x = base->in(i); // Clone address for loads from boxed objects.
1346         Node* adr_x = phase->transform(new AddPNode(base_x,base_x,address->in(AddPNode::Offset)));
1347         x->set_req(Address, adr_x);
1348       }
1349     }
1350     // Check for a 'win' on some paths
1351     const Type *t = x->Value(igvn);
1352 
1353     bool singleton = t->singleton();
1354 
1355     // See comments in PhaseIdealLoop::split_thru_phi().
1356     if (singleton && t == Type::TOP) {
1357       singleton &= region->is_Loop() && (i != LoopNode::EntryControl);
1358     }
1359 
1360     if (singleton) {
1361       x = igvn->makecon(t);
1362     } else {
1363       // We now call Identity to try to simplify the cloned node.
1364       // Note that some Identity methods call phase->type(this).
1365       // Make sure that the type array is big enough for
1366       // our new node, even though we may throw the node away.
1367       // (This tweaking with igvn only works because x is a new node.)
1368       igvn->set_type(x, t);
1369       // If x is a TypeNode, capture any more-precise type permanently into Node
1370       // otherwise it will be not updated during igvn->transform since
1371       // igvn->type(x) is set to x->Value() already.
1372       x->raise_bottom_type(t);
1373       Node *y = x->Identity(igvn);
1374       if (y != x) {
1375         x = y;
1376       } else {
1377         y = igvn->hash_find_insert(x);
1378         if (y) {
1379           x = y;
1380         } else {
1381           // Else x is a new node we are keeping
1382           // We do not need register_new_node_with_optimizer
1383           // because set_type has already been called.
1384           igvn->_worklist.push(x);
1385         }
1386       }
1387     }
1388     if (x != the_clone && the_clone != NULL) {
1389       igvn->remove_dead_node(the_clone);
1390     }
1391     phi->set_req(i, x);
1392   }
1393   // Record Phi
1394   igvn->register_new_node_with_optimizer(phi);
1395   return phi;
1396 }
1397 
1398 //------------------------------Ideal------------------------------------------
1399 // If the load is from Field memory and the pointer is non-null, it might be possible to
1400 // zero out the control input.
1401 // If the offset is constant and the base is an object allocation,
1402 // try to hook me up to the exact initializing store.
1403 Node *LoadNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1404   Node* p = MemNode::Ideal_common(phase, can_reshape);
1405   if (p)  return (p == NodeSentinel) ? NULL : p;
1406 
1407   Node* ctrl    = in(MemNode::Control);
1408   Node* address = in(MemNode::Address);
1409   bool progress = false;
1410 
1411   // Skip up past a SafePoint control.  Cannot do this for Stores because
1412   // pointer stores & cardmarks must stay on the same side of a SafePoint.
1413   if( ctrl != NULL && ctrl->Opcode() == Op_SafePoint &&
1414       phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw ) {
1415     ctrl = ctrl->in(0);
1416     set_req(MemNode::Control,ctrl);
1417     progress = true;
1418   }
1419 
1420   intptr_t ignore = 0;
1421   Node*    base   = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1422   if (base != NULL
1423       && phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw) {
1424     // Check for useless control edge in some common special cases
1425     if (in(MemNode::Control) != NULL
1426         && can_remove_control()
1427         && phase->type(base)->higher_equal(TypePtr::NOTNULL)
1428         && all_controls_dominate(base, phase->C->start())) {
1429       // A method-invariant, non-null address (constant or 'this' argument).
1430       set_req(MemNode::Control, NULL);
1431       progress = true;
1432     }
1433   }
1434 
1435   Node* mem = in(MemNode::Memory);
1436   const TypePtr *addr_t = phase->type(address)->isa_ptr();
1437 
1438   if (can_reshape && (addr_t != NULL)) {
1439     // try to optimize our memory input
1440     Node* opt_mem = MemNode::optimize_memory_chain(mem, addr_t, this, phase);
1441     if (opt_mem != mem) {
1442       set_req(MemNode::Memory, opt_mem);
1443       if (phase->type( opt_mem ) == Type::TOP) return NULL;
1444       return this;
1445     }
1446     const TypeOopPtr *t_oop = addr_t->isa_oopptr();
1447     if ((t_oop != NULL) &&
1448         (t_oop->is_known_instance_field() ||
1449          t_oop->is_ptr_to_boxed_value())) {
1450       PhaseIterGVN *igvn = phase->is_IterGVN();
1451       if (igvn != NULL && igvn->_worklist.member(opt_mem)) {
1452         // Delay this transformation until memory Phi is processed.
1453         phase->is_IterGVN()->_worklist.push(this);
1454         return NULL;
1455       }
1456       // Split instance field load through Phi.
1457       Node* result = split_through_phi(phase);
1458       if (result != NULL) return result;
1459 
1460       if (t_oop->is_ptr_to_boxed_value()) {
1461         Node* result = eliminate_autobox(phase);
1462         if (result != NULL) return result;
1463       }
1464     }
1465   }
1466 
1467   // Is there a dominating load that loads the same value?  Leave
1468   // anything that is not a load of a field/array element (like
1469   // barriers etc.) alone
1470   if (in(0) != NULL && adr_type() != TypeRawPtr::BOTTOM && can_reshape) {
1471     for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
1472       Node *use = mem->fast_out(i);
1473       if (use != this &&
1474           use->Opcode() == Opcode() &&
1475           use->in(0) != NULL &&
1476           use->in(0) != in(0) &&
1477           use->in(Address) == in(Address)) {
1478         Node* ctl = in(0);
1479         for (int i = 0; i < 10 && ctl != NULL; i++) {
1480           ctl = IfNode::up_one_dom(ctl);
1481           if (ctl == use->in(0)) {
1482             set_req(0, use->in(0));
1483             return this;
1484           }
1485         }
1486       }
1487     }
1488   }
1489 
1490   // Check for prior store with a different base or offset; make Load
1491   // independent.  Skip through any number of them.  Bail out if the stores
1492   // are in an endless dead cycle and report no progress.  This is a key
1493   // transform for Reflection.  However, if after skipping through the Stores
1494   // we can't then fold up against a prior store do NOT do the transform as
1495   // this amounts to using the 'Oracle' model of aliasing.  It leaves the same
1496   // array memory alive twice: once for the hoisted Load and again after the
1497   // bypassed Store.  This situation only works if EVERYBODY who does
1498   // anti-dependence work knows how to bypass.  I.e. we need all
1499   // anti-dependence checks to ask the same Oracle.  Right now, that Oracle is
1500   // the alias index stuff.  So instead, peek through Stores and IFF we can
1501   // fold up, do so.
1502   Node* prev_mem = find_previous_store(phase);
1503   if (prev_mem != NULL) {
1504     Node* value = can_see_arraycopy_value(prev_mem, phase);
1505     if (value != NULL) {
1506       return value;
1507     }
1508   }
1509   // Steps (a), (b):  Walk past independent stores to find an exact match.
1510   if (prev_mem != NULL && prev_mem != in(MemNode::Memory)) {
1511     // (c) See if we can fold up on the spot, but don't fold up here.
1512     // Fold-up might require truncation (for LoadB/LoadS/LoadUS) or
1513     // just return a prior value, which is done by Identity calls.
1514     if (can_see_stored_value(prev_mem, phase)) {
1515       // Make ready for step (d):
1516       set_req(MemNode::Memory, prev_mem);
1517       return this;
1518     }
1519   }
1520 
1521   return progress ? this : NULL;
1522 }
1523 
1524 // Helper to recognize certain Klass fields which are invariant across
1525 // some group of array types (e.g., int[] or all T[] where T < Object).
1526 const Type*
1527 LoadNode::load_array_final_field(const TypeKlassPtr *tkls,
1528                                  ciKlass* klass) const {
1529   if (tkls->offset() == in_bytes(Klass::modifier_flags_offset())) {
1530     // The field is Klass::_modifier_flags.  Return its (constant) value.
1531     // (Folds up the 2nd indirection in aClassConstant.getModifiers().)
1532     assert(this->Opcode() == Op_LoadI, "must load an int from _modifier_flags");
1533     return TypeInt::make(klass->modifier_flags());
1534   }
1535   if (tkls->offset() == in_bytes(Klass::access_flags_offset())) {
1536     // The field is Klass::_access_flags.  Return its (constant) value.
1537     // (Folds up the 2nd indirection in Reflection.getClassAccessFlags(aClassConstant).)
1538     assert(this->Opcode() == Op_LoadI, "must load an int from _access_flags");
1539     return TypeInt::make(klass->access_flags());
1540   }
1541   if (tkls->offset() == in_bytes(Klass::layout_helper_offset())) {
1542     // The field is Klass::_layout_helper.  Return its constant value if known.
1543     assert(this->Opcode() == Op_LoadI, "must load an int from _layout_helper");
1544     return TypeInt::make(klass->layout_helper());
1545   }
1546 
1547   // No match.
1548   return NULL;
1549 }
1550 
1551 // Try to constant-fold a stable array element.
1552 static const Type* fold_stable_ary_elem(const TypeAryPtr* ary, int off, BasicType loadbt) {
1553   assert(ary->const_oop(), "array should be constant");
1554   assert(ary->is_stable(), "array should be stable");
1555 
1556   // Decode the results of GraphKit::array_element_address.
1557   ciArray* aobj = ary->const_oop()->as_array();
1558   ciConstant con = aobj->element_value_by_offset(off);
1559 
1560   if (con.basic_type() != T_ILLEGAL && !con.is_null_or_zero()) {
1561     const Type* con_type = Type::make_from_constant(con);
1562     if (con_type != NULL) {
1563       if (con_type->isa_aryptr()) {
1564         // Join with the array element type, in case it is also stable.
1565         int dim = ary->stable_dimension();
1566         con_type = con_type->is_aryptr()->cast_to_stable(true, dim-1);
1567       }
1568       if (loadbt == T_NARROWOOP && con_type->isa_oopptr()) {
1569         con_type = con_type->make_narrowoop();
1570       }
1571 #ifndef PRODUCT
1572       if (TraceIterativeGVN) {
1573         tty->print("FoldStableValues: array element [off=%d]: con_type=", off);
1574         con_type->dump(); tty->cr();
1575       }
1576 #endif //PRODUCT
1577       return con_type;
1578     }
1579   }
1580   return NULL;
1581 }
1582 
1583 //------------------------------Value-----------------------------------------
1584 const Type *LoadNode::Value( PhaseTransform *phase ) const {
1585   // Either input is TOP ==> the result is TOP
1586   Node* mem = in(MemNode::Memory);
1587   const Type *t1 = phase->type(mem);
1588   if (t1 == Type::TOP)  return Type::TOP;
1589   Node* adr = in(MemNode::Address);
1590   const TypePtr* tp = phase->type(adr)->isa_ptr();
1591   if (tp == NULL || tp->empty())  return Type::TOP;
1592   int off = tp->offset();
1593   assert(off != Type::OffsetTop, "case covered by TypePtr::empty");
1594   Compile* C = phase->C;
1595 
1596   // Try to guess loaded type from pointer type
1597   if (tp->isa_aryptr()) {
1598     const TypeAryPtr* ary = tp->is_aryptr();
1599     const Type* t = ary->elem();
1600 
1601     // Determine whether the reference is beyond the header or not, by comparing
1602     // the offset against the offset of the start of the array's data.
1603     // Different array types begin at slightly different offsets (12 vs. 16).
1604     // We choose T_BYTE as an example base type that is least restrictive
1605     // as to alignment, which will therefore produce the smallest
1606     // possible base offset.
1607     const int min_base_off = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1608     const bool off_beyond_header = (off != -8 || !UseShenandoahGC) && ((uint)off >= (uint)min_base_off);
1609 
1610     // Try to constant-fold a stable array element.
1611     if (FoldStableValues && ary->is_stable() && ary->const_oop() != NULL) {
1612       // Make sure the reference is not into the header and the offset is constant
1613       if (off_beyond_header && adr->is_AddP() && off != Type::OffsetBot) {
1614         const Type* con_type = fold_stable_ary_elem(ary, off, memory_type());
1615         if (con_type != NULL) {
1616           return con_type;
1617         }
1618       }
1619     }
1620 
1621     // Don't do this for integer types. There is only potential profit if
1622     // the element type t is lower than _type; that is, for int types, if _type is
1623     // more restrictive than t.  This only happens here if one is short and the other
1624     // char (both 16 bits), and in those cases we've made an intentional decision
1625     // to use one kind of load over the other. See AndINode::Ideal and 4965907.
1626     // Also, do not try to narrow the type for a LoadKlass, regardless of offset.
1627     //
1628     // Yes, it is possible to encounter an expression like (LoadKlass p1:(AddP x x 8))
1629     // where the _gvn.type of the AddP is wider than 8.  This occurs when an earlier
1630     // copy p0 of (AddP x x 8) has been proven equal to p1, and the p0 has been
1631     // subsumed by p1.  If p1 is on the worklist but has not yet been re-transformed,
1632     // it is possible that p1 will have a type like Foo*[int+]:NotNull*+any.
1633     // In fact, that could have been the original type of p1, and p1 could have
1634     // had an original form like p1:(AddP x x (LShiftL quux 3)), where the
1635     // expression (LShiftL quux 3) independently optimized to the constant 8.
1636     if ((t->isa_int() == NULL) && (t->isa_long() == NULL)
1637         && (_type->isa_vect() == NULL)
1638         && Opcode() != Op_LoadKlass && Opcode() != Op_LoadNKlass) {
1639       // t might actually be lower than _type, if _type is a unique
1640       // concrete subclass of abstract class t.
1641       if (off_beyond_header) {  // is the offset beyond the header?
1642         const Type* jt = t->join_speculative(_type);
1643         // In any case, do not allow the join, per se, to empty out the type.
1644         if (jt->empty() && !t->empty()) {
1645           // This can happen if a interface-typed array narrows to a class type.
1646           jt = _type;
1647         }
1648 #ifdef ASSERT
1649         if (phase->C->eliminate_boxing() && adr->is_AddP()) {
1650           // The pointers in the autobox arrays are always non-null
1651           Node* base = adr->in(AddPNode::Base);
1652           if ((base != NULL) && base->is_DecodeN()) {
1653             // Get LoadN node which loads IntegerCache.cache field
1654             base = base->in(1);
1655           }
1656           if ((base != NULL) && base->is_Con()) {
1657             const TypeAryPtr* base_type = base->bottom_type()->isa_aryptr();
1658             if ((base_type != NULL) && base_type->is_autobox_cache()) {
1659               // It could be narrow oop
1660               assert(jt->make_ptr()->ptr() == TypePtr::NotNull,"sanity");
1661             }
1662           }
1663         }
1664 #endif
1665         return jt;
1666       }
1667     }
1668   } else if (tp->base() == Type::InstPtr) {
1669     ciEnv* env = C->env();
1670     const TypeInstPtr* tinst = tp->is_instptr();
1671     ciKlass* klass = tinst->klass();
1672     assert( off != Type::OffsetBot ||
1673             // arrays can be cast to Objects
1674             tp->is_oopptr()->klass()->is_java_lang_Object() ||
1675             // unsafe field access may not have a constant offset
1676             C->has_unsafe_access(),
1677             "Field accesses must be precise" );
1678     // For oop loads, we expect the _type to be precise
1679     if (klass == env->String_klass() &&
1680         adr->is_AddP() && off != Type::OffsetBot) {
1681       // For constant Strings treat the final fields as compile time constants.
1682       // While we can list what field types java.lang.String has, it is more
1683       // future-proof to handle all possible field types, anticipating future
1684       // changes and experiments in String code.
1685       Node* base = adr->in(AddPNode::Base);
1686       const TypeOopPtr* t = phase->type(base)->isa_oopptr();
1687       if (t != NULL && t->singleton()) {
1688         ciField* field = env->String_klass()->get_field_by_offset(off, false);
1689         if (field != NULL && field->is_final()) {
1690           ciObject* string = t->const_oop();
1691           ciConstant constant = string->as_instance()->field_value(field);
1692           // Type::make_from_constant does not handle narrow oops, so handle it here.
1693           // Everything else can use the factory method.
1694           if ((constant.basic_type() == T_ARRAY || constant.basic_type() == T_OBJECT)
1695                   && adr->bottom_type()->is_ptr_to_narrowoop()) {
1696             return TypeNarrowOop::make_from_constant(constant.as_object(), true);
1697           } else {
1698             return Type::make_from_constant(constant, true);
1699           }
1700         }
1701       }
1702     }
1703     // Optimizations for constant objects
1704     ciObject* const_oop = tinst->const_oop();
1705     if (const_oop != NULL) {
1706       // For constant Boxed value treat the target field as a compile time constant.
1707       if (tinst->is_ptr_to_boxed_value()) {
1708         return tinst->get_const_boxed_value();
1709       } else
1710       // For constant CallSites treat the target field as a compile time constant.
1711       if (const_oop->is_call_site()) {
1712         ciCallSite* call_site = const_oop->as_call_site();
1713         ciField* field = call_site->klass()->as_instance_klass()->get_field_by_offset(off, /*is_static=*/ false);
1714         if (field != NULL && field->is_call_site_target()) {
1715           ciMethodHandle* target = call_site->get_target();
1716           if (target != NULL) {  // just in case
1717             ciConstant constant(T_OBJECT, target);
1718             const Type* t;
1719             if (adr->bottom_type()->is_ptr_to_narrowoop()) {
1720               t = TypeNarrowOop::make_from_constant(constant.as_object(), true);
1721             } else {
1722               t = TypeOopPtr::make_from_constant(constant.as_object(), true);
1723             }
1724             // Add a dependence for invalidation of the optimization.
1725             if (!call_site->is_constant_call_site()) {
1726               C->dependencies()->assert_call_site_target_value(call_site, target);
1727             }
1728             return t;
1729           }
1730         }
1731       }
1732     }
1733   } else if (tp->base() == Type::KlassPtr) {
1734     assert( off != Type::OffsetBot ||
1735             // arrays can be cast to Objects
1736             tp->is_klassptr()->klass()->is_java_lang_Object() ||
1737             // also allow array-loading from the primary supertype
1738             // array during subtype checks
1739             Opcode() == Op_LoadKlass,
1740             "Field accesses must be precise" );
1741     // For klass/static loads, we expect the _type to be precise
1742   }
1743 
1744   const TypeKlassPtr *tkls = tp->isa_klassptr();
1745   if (tkls != NULL && !StressReflectiveCode) {
1746     ciKlass* klass = tkls->klass();
1747     if (klass->is_loaded() && tkls->klass_is_exact()) {
1748       // We are loading a field from a Klass metaobject whose identity
1749       // is known at compile time (the type is "exact" or "precise").
1750       // Check for fields we know are maintained as constants by the VM.
1751       if (tkls->offset() == in_bytes(Klass::super_check_offset_offset())) {
1752         // The field is Klass::_super_check_offset.  Return its (constant) value.
1753         // (Folds up type checking code.)
1754         assert(Opcode() == Op_LoadI, "must load an int from _super_check_offset");
1755         return TypeInt::make(klass->super_check_offset());
1756       }
1757       // Compute index into primary_supers array
1758       juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
1759       // Check for overflowing; use unsigned compare to handle the negative case.
1760       if( depth < ciKlass::primary_super_limit() ) {
1761         // The field is an element of Klass::_primary_supers.  Return its (constant) value.
1762         // (Folds up type checking code.)
1763         assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
1764         ciKlass *ss = klass->super_of_depth(depth);
1765         return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
1766       }
1767       const Type* aift = load_array_final_field(tkls, klass);
1768       if (aift != NULL)  return aift;
1769       if (tkls->offset() == in_bytes(Klass::java_mirror_offset())) {
1770         // The field is Klass::_java_mirror.  Return its (constant) value.
1771         // (Folds up the 2nd indirection in anObjConstant.getClass().)
1772         assert(Opcode() == Op_LoadP, "must load an oop from _java_mirror");
1773         return TypeInstPtr::make(klass->java_mirror());
1774       }
1775     }
1776 
1777     // We can still check if we are loading from the primary_supers array at a
1778     // shallow enough depth.  Even though the klass is not exact, entries less
1779     // than or equal to its super depth are correct.
1780     if (klass->is_loaded() ) {
1781       ciType *inner = klass;
1782       while( inner->is_obj_array_klass() )
1783         inner = inner->as_obj_array_klass()->base_element_type();
1784       if( inner->is_instance_klass() &&
1785           !inner->as_instance_klass()->flags().is_interface() ) {
1786         // Compute index into primary_supers array
1787         juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
1788         // Check for overflowing; use unsigned compare to handle the negative case.
1789         if( depth < ciKlass::primary_super_limit() &&
1790             depth <= klass->super_depth() ) { // allow self-depth checks to handle self-check case
1791           // The field is an element of Klass::_primary_supers.  Return its (constant) value.
1792           // (Folds up type checking code.)
1793           assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
1794           ciKlass *ss = klass->super_of_depth(depth);
1795           return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
1796         }
1797       }
1798     }
1799 
1800     // If the type is enough to determine that the thing is not an array,
1801     // we can give the layout_helper a positive interval type.
1802     // This will help short-circuit some reflective code.
1803     if (tkls->offset() == in_bytes(Klass::layout_helper_offset())
1804         && !klass->is_array_klass() // not directly typed as an array
1805         && !klass->is_interface()  // specifically not Serializable & Cloneable
1806         && !klass->is_java_lang_Object()   // not the supertype of all T[]
1807         ) {
1808       // Note:  When interfaces are reliable, we can narrow the interface
1809       // test to (klass != Serializable && klass != Cloneable).
1810       assert(Opcode() == Op_LoadI, "must load an int from _layout_helper");
1811       jint min_size = Klass::instance_layout_helper(oopDesc::header_size(), false);
1812       // The key property of this type is that it folds up tests
1813       // for array-ness, since it proves that the layout_helper is positive.
1814       // Thus, a generic value like the basic object layout helper works fine.
1815       return TypeInt::make(min_size, max_jint, Type::WidenMin);
1816     }
1817   }
1818 
1819   // If we are loading from a freshly-allocated object, produce a zero,
1820   // if the load is provably beyond the header of the object.
1821   // (Also allow a variable load from a fresh array to produce zero.)
1822   const TypeOopPtr *tinst = tp->isa_oopptr();
1823   bool is_instance = (tinst != NULL) && tinst->is_known_instance_field();
1824   bool is_boxed_value = (tinst != NULL) && tinst->is_ptr_to_boxed_value();
1825   if (ReduceFieldZeroing || is_instance || is_boxed_value) {
1826     Node* value = can_see_stored_value(mem,phase);
1827     if (value != NULL && value->is_Con()) {
1828       assert(value->bottom_type()->higher_equal(_type),"sanity");
1829       return value->bottom_type();
1830     }
1831   }
1832 
1833   if (is_instance) {
1834     // If we have an instance type and our memory input is the
1835     // programs's initial memory state, there is no matching store,
1836     // so just return a zero of the appropriate type
1837     Node *mem = in(MemNode::Memory);
1838     if (mem->is_Parm() && mem->in(0)->is_Start()) {
1839       assert(mem->as_Parm()->_con == TypeFunc::Memory, "must be memory Parm");
1840       return Type::get_zero_type(_type->basic_type());
1841     }
1842   }
1843   return _type;
1844 }
1845 
1846 //------------------------------match_edge-------------------------------------
1847 // Do we Match on this edge index or not?  Match only the address.
1848 uint LoadNode::match_edge(uint idx) const {
1849   return idx == MemNode::Address;
1850 }
1851 
1852 //--------------------------LoadBNode::Ideal--------------------------------------
1853 //
1854 //  If the previous store is to the same address as this load,
1855 //  and the value stored was larger than a byte, replace this load
1856 //  with the value stored truncated to a byte.  If no truncation is
1857 //  needed, the replacement is done in LoadNode::Identity().
1858 //
1859 Node *LoadBNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1860   Node* mem = in(MemNode::Memory);
1861   Node* value = can_see_stored_value(mem,phase);
1862   if( value && !phase->type(value)->higher_equal( _type ) ) {
1863     Node *result = phase->transform( new LShiftINode(value, phase->intcon(24)) );
1864     return new RShiftINode(result, phase->intcon(24));
1865   }
1866   // Identity call will handle the case where truncation is not needed.
1867   return LoadNode::Ideal(phase, can_reshape);
1868 }
1869 
1870 const Type* LoadBNode::Value(PhaseTransform *phase) const {
1871   Node* mem = in(MemNode::Memory);
1872   Node* value = can_see_stored_value(mem,phase);
1873   if (value != NULL && value->is_Con() &&
1874       !value->bottom_type()->higher_equal(_type)) {
1875     // If the input to the store does not fit with the load's result type,
1876     // it must be truncated. We can't delay until Ideal call since
1877     // a singleton Value is needed for split_thru_phi optimization.
1878     int con = value->get_int();
1879     return TypeInt::make((con << 24) >> 24);
1880   }
1881   return LoadNode::Value(phase);
1882 }
1883 
1884 //--------------------------LoadUBNode::Ideal-------------------------------------
1885 //
1886 //  If the previous store is to the same address as this load,
1887 //  and the value stored was larger than a byte, replace this load
1888 //  with the value stored truncated to a byte.  If no truncation is
1889 //  needed, the replacement is done in LoadNode::Identity().
1890 //
1891 Node* LoadUBNode::Ideal(PhaseGVN* phase, bool can_reshape) {
1892   Node* mem = in(MemNode::Memory);
1893   Node* value = can_see_stored_value(mem, phase);
1894   if (value && !phase->type(value)->higher_equal(_type))
1895     return new AndINode(value, phase->intcon(0xFF));
1896   // Identity call will handle the case where truncation is not needed.
1897   return LoadNode::Ideal(phase, can_reshape);
1898 }
1899 
1900 const Type* LoadUBNode::Value(PhaseTransform *phase) const {
1901   Node* mem = in(MemNode::Memory);
1902   Node* value = can_see_stored_value(mem,phase);
1903   if (value != NULL && value->is_Con() &&
1904       !value->bottom_type()->higher_equal(_type)) {
1905     // If the input to the store does not fit with the load's result type,
1906     // it must be truncated. We can't delay until Ideal call since
1907     // a singleton Value is needed for split_thru_phi optimization.
1908     int con = value->get_int();
1909     return TypeInt::make(con & 0xFF);
1910   }
1911   return LoadNode::Value(phase);
1912 }
1913 
1914 //--------------------------LoadUSNode::Ideal-------------------------------------
1915 //
1916 //  If the previous store is to the same address as this load,
1917 //  and the value stored was larger than a char, replace this load
1918 //  with the value stored truncated to a char.  If no truncation is
1919 //  needed, the replacement is done in LoadNode::Identity().
1920 //
1921 Node *LoadUSNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1922   Node* mem = in(MemNode::Memory);
1923   Node* value = can_see_stored_value(mem,phase);
1924   if( value && !phase->type(value)->higher_equal( _type ) )
1925     return new AndINode(value,phase->intcon(0xFFFF));
1926   // Identity call will handle the case where truncation is not needed.
1927   return LoadNode::Ideal(phase, can_reshape);
1928 }
1929 
1930 const Type* LoadUSNode::Value(PhaseTransform *phase) const {
1931   Node* mem = in(MemNode::Memory);
1932   Node* value = can_see_stored_value(mem,phase);
1933   if (value != NULL && value->is_Con() &&
1934       !value->bottom_type()->higher_equal(_type)) {
1935     // If the input to the store does not fit with the load's result type,
1936     // it must be truncated. We can't delay until Ideal call since
1937     // a singleton Value is needed for split_thru_phi optimization.
1938     int con = value->get_int();
1939     return TypeInt::make(con & 0xFFFF);
1940   }
1941   return LoadNode::Value(phase);
1942 }
1943 
1944 //--------------------------LoadSNode::Ideal--------------------------------------
1945 //
1946 //  If the previous store is to the same address as this load,
1947 //  and the value stored was larger than a short, replace this load
1948 //  with the value stored truncated to a short.  If no truncation is
1949 //  needed, the replacement is done in LoadNode::Identity().
1950 //
1951 Node *LoadSNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1952   Node* mem = in(MemNode::Memory);
1953   Node* value = can_see_stored_value(mem,phase);
1954   if( value && !phase->type(value)->higher_equal( _type ) ) {
1955     Node *result = phase->transform( new LShiftINode(value, phase->intcon(16)) );
1956     return new RShiftINode(result, phase->intcon(16));
1957   }
1958   // Identity call will handle the case where truncation is not needed.
1959   return LoadNode::Ideal(phase, can_reshape);
1960 }
1961 
1962 const Type* LoadSNode::Value(PhaseTransform *phase) const {
1963   Node* mem = in(MemNode::Memory);
1964   Node* value = can_see_stored_value(mem,phase);
1965   if (value != NULL && value->is_Con() &&
1966       !value->bottom_type()->higher_equal(_type)) {
1967     // If the input to the store does not fit with the load's result type,
1968     // it must be truncated. We can't delay until Ideal call since
1969     // a singleton Value is needed for split_thru_phi optimization.
1970     int con = value->get_int();
1971     return TypeInt::make((con << 16) >> 16);
1972   }
1973   return LoadNode::Value(phase);
1974 }
1975 
1976 //=============================================================================
1977 //----------------------------LoadKlassNode::make------------------------------
1978 // Polymorphic factory method:
1979 Node* LoadKlassNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* at, const TypeKlassPtr* tk) {
1980   // sanity check the alias category against the created node type
1981   const TypePtr *adr_type = adr->bottom_type()->isa_ptr();
1982   assert(adr_type != NULL, "expecting TypeKlassPtr");
1983 #ifdef _LP64
1984   if (adr_type->is_ptr_to_narrowklass()) {
1985     assert(UseCompressedClassPointers, "no compressed klasses");
1986     Node* load_klass = gvn.transform(new LoadNKlassNode(ctl, mem, adr, at, tk->make_narrowklass(), MemNode::unordered));
1987     return new DecodeNKlassNode(load_klass, load_klass->bottom_type()->make_ptr());
1988   }
1989 #endif
1990   assert(!adr_type->is_ptr_to_narrowklass() && !adr_type->is_ptr_to_narrowoop(), "should have got back a narrow oop");
1991   return new LoadKlassNode(ctl, mem, adr, at, tk, MemNode::unordered);
1992 }
1993 
1994 //------------------------------Value------------------------------------------
1995 const Type *LoadKlassNode::Value( PhaseTransform *phase ) const {
1996   return klass_value_common(phase);
1997 }
1998 
1999 // In most cases, LoadKlassNode does not have the control input set. If the control
2000 // input is set, it must not be removed (by LoadNode::Ideal()).
2001 bool LoadKlassNode::can_remove_control() const {
2002   return false;
2003 }
2004 
2005 const Type *LoadNode::klass_value_common( PhaseTransform *phase ) const {
2006   // Either input is TOP ==> the result is TOP
2007   const Type *t1 = phase->type( in(MemNode::Memory) );
2008   if (t1 == Type::TOP)  return Type::TOP;
2009   Node *adr = in(MemNode::Address);
2010   const Type *t2 = phase->type( adr );
2011   if (t2 == Type::TOP)  return Type::TOP;
2012   const TypePtr *tp = t2->is_ptr();
2013   if (TypePtr::above_centerline(tp->ptr()) ||
2014       tp->ptr() == TypePtr::Null)  return Type::TOP;
2015 
2016   // Return a more precise klass, if possible
2017   const TypeInstPtr *tinst = tp->isa_instptr();
2018   if (tinst != NULL) {
2019     ciInstanceKlass* ik = tinst->klass()->as_instance_klass();
2020     int offset = tinst->offset();
2021     if (ik == phase->C->env()->Class_klass()
2022         && (offset == java_lang_Class::klass_offset_in_bytes() ||
2023             offset == java_lang_Class::array_klass_offset_in_bytes())) {
2024       // We are loading a special hidden field from a Class mirror object,
2025       // the field which points to the VM's Klass metaobject.
2026       ciType* t = tinst->java_mirror_type();
2027       // java_mirror_type returns non-null for compile-time Class constants.
2028       if (t != NULL) {
2029         // constant oop => constant klass
2030         if (offset == java_lang_Class::array_klass_offset_in_bytes()) {
2031           if (t->is_void()) {
2032             // We cannot create a void array.  Since void is a primitive type return null
2033             // klass.  Users of this result need to do a null check on the returned klass.
2034             return TypePtr::NULL_PTR;
2035           }
2036           return TypeKlassPtr::make(ciArrayKlass::make(t));
2037         }
2038         if (!t->is_klass()) {
2039           // a primitive Class (e.g., int.class) has NULL for a klass field
2040           return TypePtr::NULL_PTR;
2041         }
2042         // (Folds up the 1st indirection in aClassConstant.getModifiers().)
2043         return TypeKlassPtr::make(t->as_klass());
2044       }
2045       // non-constant mirror, so we can't tell what's going on
2046     }
2047     if( !ik->is_loaded() )
2048       return _type;             // Bail out if not loaded
2049     if (offset == oopDesc::klass_offset_in_bytes()) {
2050       if (tinst->klass_is_exact()) {
2051         return TypeKlassPtr::make(ik);
2052       }
2053       // See if we can become precise: no subklasses and no interface
2054       // (Note:  We need to support verified interfaces.)
2055       if (!ik->is_interface() && !ik->has_subklass()) {
2056         //assert(!UseExactTypes, "this code should be useless with exact types");
2057         // Add a dependence; if any subclass added we need to recompile
2058         if (!ik->is_final()) {
2059           // %%% should use stronger assert_unique_concrete_subtype instead
2060           phase->C->dependencies()->assert_leaf_type(ik);
2061         }
2062         // Return precise klass
2063         return TypeKlassPtr::make(ik);
2064       }
2065 
2066       // Return root of possible klass
2067       return TypeKlassPtr::make(TypePtr::NotNull, ik, 0/*offset*/);
2068     }
2069   }
2070 
2071   // Check for loading klass from an array
2072   const TypeAryPtr *tary = tp->isa_aryptr();
2073   if( tary != NULL ) {
2074     ciKlass *tary_klass = tary->klass();
2075     if (tary_klass != NULL   // can be NULL when at BOTTOM or TOP
2076         && tary->offset() == oopDesc::klass_offset_in_bytes()) {
2077       if (tary->klass_is_exact()) {
2078         return TypeKlassPtr::make(tary_klass);
2079       }
2080       ciArrayKlass *ak = tary->klass()->as_array_klass();
2081       // If the klass is an object array, we defer the question to the
2082       // array component klass.
2083       if( ak->is_obj_array_klass() ) {
2084         assert( ak->is_loaded(), "" );
2085         ciKlass *base_k = ak->as_obj_array_klass()->base_element_klass();
2086         if( base_k->is_loaded() && base_k->is_instance_klass() ) {
2087           ciInstanceKlass* ik = base_k->as_instance_klass();
2088           // See if we can become precise: no subklasses and no interface
2089           if (!ik->is_interface() && !ik->has_subklass()) {
2090             //assert(!UseExactTypes, "this code should be useless with exact types");
2091             // Add a dependence; if any subclass added we need to recompile
2092             if (!ik->is_final()) {
2093               phase->C->dependencies()->assert_leaf_type(ik);
2094             }
2095             // Return precise array klass
2096             return TypeKlassPtr::make(ak);
2097           }
2098         }
2099         return TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
2100       } else {                  // Found a type-array?
2101         //assert(!UseExactTypes, "this code should be useless with exact types");
2102         assert( ak->is_type_array_klass(), "" );
2103         return TypeKlassPtr::make(ak); // These are always precise
2104       }
2105     }
2106   }
2107 
2108   // Check for loading klass from an array klass
2109   const TypeKlassPtr *tkls = tp->isa_klassptr();
2110   if (tkls != NULL && !StressReflectiveCode) {
2111     ciKlass* klass = tkls->klass();
2112     if( !klass->is_loaded() )
2113       return _type;             // Bail out if not loaded
2114     if( klass->is_obj_array_klass() &&
2115         tkls->offset() == in_bytes(ObjArrayKlass::element_klass_offset())) {
2116       ciKlass* elem = klass->as_obj_array_klass()->element_klass();
2117       // // Always returning precise element type is incorrect,
2118       // // e.g., element type could be object and array may contain strings
2119       // return TypeKlassPtr::make(TypePtr::Constant, elem, 0);
2120 
2121       // The array's TypeKlassPtr was declared 'precise' or 'not precise'
2122       // according to the element type's subclassing.
2123       return TypeKlassPtr::make(tkls->ptr(), elem, 0/*offset*/);
2124     }
2125     if( klass->is_instance_klass() && tkls->klass_is_exact() &&
2126         tkls->offset() == in_bytes(Klass::super_offset())) {
2127       ciKlass* sup = klass->as_instance_klass()->super();
2128       // The field is Klass::_super.  Return its (constant) value.
2129       // (Folds up the 2nd indirection in aClassConstant.getSuperClass().)
2130       return sup ? TypeKlassPtr::make(sup) : TypePtr::NULL_PTR;
2131     }
2132   }
2133 
2134   // Bailout case
2135   return LoadNode::Value(phase);
2136 }
2137 
2138 //------------------------------Identity---------------------------------------
2139 // To clean up reflective code, simplify k.java_mirror.as_klass to plain k.
2140 // Also feed through the klass in Allocate(...klass...)._klass.
2141 Node* LoadKlassNode::Identity( PhaseTransform *phase ) {
2142   return klass_identity_common(phase);
2143 }
2144 
2145 Node* LoadNode::klass_identity_common(PhaseTransform *phase ) {
2146   Node* x = LoadNode::Identity(phase);
2147   if (x != this)  return x;
2148 
2149   // Take apart the address into an oop and and offset.
2150   // Return 'this' if we cannot.
2151   Node*    adr    = in(MemNode::Address);
2152   intptr_t offset = 0;
2153   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2154   if (base == NULL)     return this;
2155   const TypeOopPtr* toop = phase->type(adr)->isa_oopptr();
2156   if (toop == NULL)     return this;
2157 
2158   // We can fetch the klass directly through an AllocateNode.
2159   // This works even if the klass is not constant (clone or newArray).
2160   if (offset == oopDesc::klass_offset_in_bytes()) {
2161     Node* allocated_klass = AllocateNode::Ideal_klass(base, phase);
2162     if (allocated_klass != NULL) {
2163       return allocated_klass;
2164     }
2165   }
2166 
2167   // Simplify k.java_mirror.as_klass to plain k, where k is a Klass*.
2168   // See inline_native_Class_query for occurrences of these patterns.
2169   // Java Example:  x.getClass().isAssignableFrom(y)
2170   //
2171   // This improves reflective code, often making the Class
2172   // mirror go completely dead.  (Current exception:  Class
2173   // mirrors may appear in debug info, but we could clean them out by
2174   // introducing a new debug info operator for Klass*.java_mirror).
2175   if (toop->isa_instptr() && toop->klass() == phase->C->env()->Class_klass()
2176       && offset == java_lang_Class::klass_offset_in_bytes()) {
2177     // We are loading a special hidden field from a Class mirror,
2178     // the field which points to its Klass or ArrayKlass metaobject.
2179     if (base->is_Load()) {
2180       Node* adr2 = base->in(MemNode::Address);
2181       const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
2182       if (tkls != NULL && !tkls->empty()
2183           && (tkls->klass()->is_instance_klass() ||
2184               tkls->klass()->is_array_klass())
2185           && adr2->is_AddP()
2186           ) {
2187         int mirror_field = in_bytes(Klass::java_mirror_offset());
2188         if (tkls->offset() == mirror_field) {
2189           return adr2->in(AddPNode::Base);
2190         }
2191       }
2192     }
2193   }
2194 
2195   return this;
2196 }
2197 
2198 
2199 //------------------------------Value------------------------------------------
2200 const Type *LoadNKlassNode::Value( PhaseTransform *phase ) const {
2201   const Type *t = klass_value_common(phase);
2202   if (t == Type::TOP)
2203     return t;
2204 
2205   return t->make_narrowklass();
2206 }
2207 
2208 //------------------------------Identity---------------------------------------
2209 // To clean up reflective code, simplify k.java_mirror.as_klass to narrow k.
2210 // Also feed through the klass in Allocate(...klass...)._klass.
2211 Node* LoadNKlassNode::Identity( PhaseTransform *phase ) {
2212   Node *x = klass_identity_common(phase);
2213 
2214   const Type *t = phase->type( x );
2215   if( t == Type::TOP ) return x;
2216   if( t->isa_narrowklass()) return x;
2217   assert (!t->isa_narrowoop(), "no narrow oop here");
2218 
2219   return phase->transform(new EncodePKlassNode(x, t->make_narrowklass()));
2220 }
2221 
2222 //------------------------------Value-----------------------------------------
2223 const Type *LoadRangeNode::Value( PhaseTransform *phase ) const {
2224   // Either input is TOP ==> the result is TOP
2225   const Type *t1 = phase->type( in(MemNode::Memory) );
2226   if( t1 == Type::TOP ) return Type::TOP;
2227   Node *adr = in(MemNode::Address);
2228   const Type *t2 = phase->type( adr );
2229   if( t2 == Type::TOP ) return Type::TOP;
2230   const TypePtr *tp = t2->is_ptr();
2231   if (TypePtr::above_centerline(tp->ptr()))  return Type::TOP;
2232   const TypeAryPtr *tap = tp->isa_aryptr();
2233   if( !tap ) return _type;
2234   return tap->size();
2235 }
2236 
2237 //-------------------------------Ideal---------------------------------------
2238 // Feed through the length in AllocateArray(...length...)._length.
2239 Node *LoadRangeNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2240   Node* p = MemNode::Ideal_common(phase, can_reshape);
2241   if (p)  return (p == NodeSentinel) ? NULL : p;
2242 
2243   // Take apart the address into an oop and and offset.
2244   // Return 'this' if we cannot.
2245   Node*    adr    = in(MemNode::Address);
2246   intptr_t offset = 0;
2247   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase,  offset);
2248   if (base == NULL)     return NULL;
2249   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2250   if (tary == NULL)     return NULL;
2251 
2252   // We can fetch the length directly through an AllocateArrayNode.
2253   // This works even if the length is not constant (clone or newArray).
2254   if (offset == arrayOopDesc::length_offset_in_bytes()) {
2255     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
2256     if (alloc != NULL) {
2257       Node* allocated_length = alloc->Ideal_length();
2258       Node* len = alloc->make_ideal_length(tary, phase);
2259       if (allocated_length != len) {
2260         // New CastII improves on this.
2261         return len;
2262       }
2263     }
2264   }
2265 
2266   return NULL;
2267 }
2268 
2269 //------------------------------Identity---------------------------------------
2270 // Feed through the length in AllocateArray(...length...)._length.
2271 Node* LoadRangeNode::Identity( PhaseTransform *phase ) {
2272   Node* x = LoadINode::Identity(phase);
2273   if (x != this)  return x;
2274 
2275   // Take apart the address into an oop and and offset.
2276   // Return 'this' if we cannot.
2277   Node*    adr    = in(MemNode::Address);
2278   intptr_t offset = 0;
2279   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2280   if (base == NULL)     return this;
2281   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2282   if (tary == NULL)     return this;
2283 
2284   // We can fetch the length directly through an AllocateArrayNode.
2285   // This works even if the length is not constant (clone or newArray).
2286   if (offset == arrayOopDesc::length_offset_in_bytes()) {
2287     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
2288     if (alloc != NULL) {
2289       Node* allocated_length = alloc->Ideal_length();
2290       // Do not allow make_ideal_length to allocate a CastII node.
2291       Node* len = alloc->make_ideal_length(tary, phase, false);
2292       if (allocated_length == len) {
2293         // Return allocated_length only if it would not be improved by a CastII.
2294         return allocated_length;
2295       }
2296     }
2297   }
2298 
2299   return this;
2300 
2301 }
2302 
2303 //=============================================================================
2304 //---------------------------StoreNode::make-----------------------------------
2305 // Polymorphic factory method:
2306 StoreNode* StoreNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, BasicType bt, MemOrd mo) {
2307   assert((mo == unordered || mo == release), "unexpected");
2308   Compile* C = gvn.C;
2309   assert(C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
2310          ctl != NULL, "raw memory operations should have control edge");
2311 
2312   switch (bt) {
2313   case T_BOOLEAN:
2314   case T_BYTE:    return new StoreBNode(ctl, mem, adr, adr_type, val, mo);
2315   case T_INT:     return new StoreINode(ctl, mem, adr, adr_type, val, mo);
2316   case T_CHAR:
2317   case T_SHORT:   return new StoreCNode(ctl, mem, adr, adr_type, val, mo);
2318   case T_LONG:    return new StoreLNode(ctl, mem, adr, adr_type, val, mo);
2319   case T_FLOAT:   return new StoreFNode(ctl, mem, adr, adr_type, val, mo);
2320   case T_DOUBLE:  return new StoreDNode(ctl, mem, adr, adr_type, val, mo);
2321   case T_METADATA:
2322   case T_ADDRESS:
2323   case T_OBJECT:
2324 #ifdef _LP64
2325     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
2326       val = gvn.transform(new EncodePNode(val, val->bottom_type()->make_narrowoop()));
2327       return new StoreNNode(ctl, mem, adr, adr_type, val, mo);
2328     } else if (adr->bottom_type()->is_ptr_to_narrowklass() ||
2329                (UseCompressedClassPointers && val->bottom_type()->isa_klassptr() &&
2330                 adr->bottom_type()->isa_rawptr())) {
2331       val = gvn.transform(new EncodePKlassNode(val, val->bottom_type()->make_narrowklass()));
2332       return new StoreNKlassNode(ctl, mem, adr, adr_type, val, mo);
2333     }
2334 #endif
2335     {
2336       return new StorePNode(ctl, mem, adr, adr_type, val, mo);
2337     }
2338   }
2339   ShouldNotReachHere();
2340   return (StoreNode*)NULL;
2341 }
2342 
2343 StoreLNode* StoreLNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, MemOrd mo) {
2344   bool require_atomic = true;
2345   return new StoreLNode(ctl, mem, adr, adr_type, val, mo, require_atomic);
2346 }
2347 
2348 StoreDNode* StoreDNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, MemOrd mo) {
2349   bool require_atomic = true;
2350   return new StoreDNode(ctl, mem, adr, adr_type, val, mo, require_atomic);
2351 }
2352 
2353 
2354 //--------------------------bottom_type----------------------------------------
2355 const Type *StoreNode::bottom_type() const {
2356   return Type::MEMORY;
2357 }
2358 
2359 //------------------------------hash-------------------------------------------
2360 uint StoreNode::hash() const {
2361   // unroll addition of interesting fields
2362   //return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address) + (uintptr_t)in(ValueIn);
2363 
2364   // Since they are not commoned, do not hash them:
2365   return NO_HASH;
2366 }
2367 
2368 //------------------------------Ideal------------------------------------------
2369 // Change back-to-back Store(, p, x) -> Store(m, p, y) to Store(m, p, x).
2370 // When a store immediately follows a relevant allocation/initialization,
2371 // try to capture it into the initialization, or hoist it above.
2372 Node *StoreNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2373   Node* p = MemNode::Ideal_common(phase, can_reshape);
2374   if (p)  return (p == NodeSentinel) ? NULL : p;
2375 
2376   Node* mem     = in(MemNode::Memory);
2377   Node* address = in(MemNode::Address);
2378   // Back-to-back stores to same address?  Fold em up.  Generally
2379   // unsafe if I have intervening uses...  Also disallowed for StoreCM
2380   // since they must follow each StoreP operation.  Redundant StoreCMs
2381   // are eliminated just before matching in final_graph_reshape.
2382   {
2383     Node* st = mem;
2384     // If Store 'st' has more than one use, we cannot fold 'st' away.
2385     // For example, 'st' might be the final state at a conditional
2386     // return.  Or, 'st' might be used by some node which is live at
2387     // the same time 'st' is live, which might be unschedulable.  So,
2388     // require exactly ONE user until such time as we clone 'mem' for
2389     // each of 'mem's uses (thus making the exactly-1-user-rule hold
2390     // true).
2391     while (st->is_Store() && st->outcnt() == 1 && st->Opcode() != Op_StoreCM) {
2392       // Looking at a dead closed cycle of memory?
2393       assert(st != st->in(MemNode::Memory), "dead loop in StoreNode::Ideal");
2394       assert(Opcode() == st->Opcode() ||
2395              st->Opcode() == Op_StoreVector ||
2396              Opcode() == Op_StoreVector ||
2397              phase->C->get_alias_index(adr_type()) == Compile::AliasIdxRaw ||
2398              (Opcode() == Op_StoreL && st->Opcode() == Op_StoreI), // expanded ClearArrayNode
2399              err_msg_res("no mismatched stores, except on raw memory: %s %s", NodeClassNames[Opcode()], NodeClassNames[st->Opcode()]));
2400 
2401       if (st->in(MemNode::Address)->eqv_uncast(address) &&
2402           st->as_Store()->memory_size() <= this->memory_size()) {
2403         Node* use = st->raw_out(0);
2404         phase->igvn_rehash_node_delayed(use);
2405         if (can_reshape) {
2406           use->set_req_X(MemNode::Memory, st->in(MemNode::Memory), phase->is_IterGVN());
2407         } else {
2408           // It's OK to do this in the parser, since DU info is always accurate,
2409           // and the parser always refers to nodes via SafePointNode maps.
2410           use->set_req(MemNode::Memory, st->in(MemNode::Memory));
2411         }
2412         return this;
2413       }
2414       st = st->in(MemNode::Memory);
2415     }
2416   }
2417 
2418 
2419   // Capture an unaliased, unconditional, simple store into an initializer.
2420   // Or, if it is independent of the allocation, hoist it above the allocation.
2421   if (ReduceFieldZeroing && /*can_reshape &&*/
2422       mem->is_Proj() && mem->in(0)->is_Initialize()) {
2423     InitializeNode* init = mem->in(0)->as_Initialize();
2424     intptr_t offset = init->can_capture_store(this, phase, can_reshape);
2425     if (offset > 0) {
2426       Node* moved = init->capture_store(this, offset, phase, can_reshape);
2427       // If the InitializeNode captured me, it made a raw copy of me,
2428       // and I need to disappear.
2429       if (moved != NULL) {
2430         // %%% hack to ensure that Ideal returns a new node:
2431         mem = MergeMemNode::make(mem);
2432         return mem;             // fold me away
2433       }
2434     }
2435   }
2436 
2437   return NULL;                  // No further progress
2438 }
2439 
2440 //------------------------------Value-----------------------------------------
2441 const Type *StoreNode::Value( PhaseTransform *phase ) const {
2442   // Either input is TOP ==> the result is TOP
2443   const Type *t1 = phase->type( in(MemNode::Memory) );
2444   if( t1 == Type::TOP ) return Type::TOP;
2445   const Type *t2 = phase->type( in(MemNode::Address) );
2446   if( t2 == Type::TOP ) return Type::TOP;
2447   const Type *t3 = phase->type( in(MemNode::ValueIn) );
2448   if( t3 == Type::TOP ) return Type::TOP;
2449   return Type::MEMORY;
2450 }
2451 
2452 //------------------------------Identity---------------------------------------
2453 // Remove redundant stores:
2454 //   Store(m, p, Load(m, p)) changes to m.
2455 //   Store(, p, x) -> Store(m, p, x) changes to Store(m, p, x).
2456 Node *StoreNode::Identity( PhaseTransform *phase ) {
2457   Node* mem = in(MemNode::Memory);
2458   Node* adr = in(MemNode::Address);
2459   Node* val = in(MemNode::ValueIn);
2460 
2461   // Load then Store?  Then the Store is useless
2462   if (val->is_Load() &&
2463       val->in(MemNode::Address)->eqv_uncast(adr) &&
2464       val->in(MemNode::Memory )->eqv_uncast(mem) &&
2465       val->as_Load()->store_Opcode() == Opcode()) {
2466     return mem;
2467   }
2468 
2469   // Two stores in a row of the same value?
2470   if (mem->is_Store() &&
2471       mem->in(MemNode::Address)->eqv_uncast(adr) &&
2472       mem->in(MemNode::ValueIn)->eqv_uncast(val) &&
2473       mem->Opcode() == Opcode()) {
2474     return mem;
2475   }
2476 
2477   // Store of zero anywhere into a freshly-allocated object?
2478   // Then the store is useless.
2479   // (It must already have been captured by the InitializeNode.)
2480   if (ReduceFieldZeroing && phase->type(val)->is_zero_type()) {
2481     // a newly allocated object is already all-zeroes everywhere
2482     if (mem->is_Proj() && mem->in(0)->is_Allocate()) {
2483       return mem;
2484     }
2485 
2486     // the store may also apply to zero-bits in an earlier object
2487     Node* prev_mem = find_previous_store(phase);
2488     // Steps (a), (b):  Walk past independent stores to find an exact match.
2489     if (prev_mem != NULL) {
2490       Node* prev_val = can_see_stored_value(prev_mem, phase);
2491       if (prev_val != NULL && phase->eqv(prev_val, val)) {
2492         // prev_val and val might differ by a cast; it would be good
2493         // to keep the more informative of the two.
2494         return mem;
2495       }
2496     }
2497   }
2498 
2499   return this;
2500 }
2501 
2502 //------------------------------match_edge-------------------------------------
2503 // Do we Match on this edge index or not?  Match only memory & value
2504 uint StoreNode::match_edge(uint idx) const {
2505   return idx == MemNode::Address || idx == MemNode::ValueIn;
2506 }
2507 
2508 //------------------------------cmp--------------------------------------------
2509 // Do not common stores up together.  They generally have to be split
2510 // back up anyways, so do not bother.
2511 uint StoreNode::cmp( const Node &n ) const {
2512   return (&n == this);          // Always fail except on self
2513 }
2514 
2515 //------------------------------Ideal_masked_input-----------------------------
2516 // Check for a useless mask before a partial-word store
2517 // (StoreB ... (AndI valIn conIa) )
2518 // If (conIa & mask == mask) this simplifies to
2519 // (StoreB ... (valIn) )
2520 Node *StoreNode::Ideal_masked_input(PhaseGVN *phase, uint mask) {
2521   Node *val = in(MemNode::ValueIn);
2522   if( val->Opcode() == Op_AndI ) {
2523     const TypeInt *t = phase->type( val->in(2) )->isa_int();
2524     if( t && t->is_con() && (t->get_con() & mask) == mask ) {
2525       set_req(MemNode::ValueIn, val->in(1));
2526       return this;
2527     }
2528   }
2529   return NULL;
2530 }
2531 
2532 
2533 //------------------------------Ideal_sign_extended_input----------------------
2534 // Check for useless sign-extension before a partial-word store
2535 // (StoreB ... (RShiftI _ (LShiftI _ valIn conIL ) conIR) )
2536 // If (conIL == conIR && conIR <= num_bits)  this simplifies to
2537 // (StoreB ... (valIn) )
2538 Node *StoreNode::Ideal_sign_extended_input(PhaseGVN *phase, int num_bits) {
2539   Node *val = in(MemNode::ValueIn);
2540   if( val->Opcode() == Op_RShiftI ) {
2541     const TypeInt *t = phase->type( val->in(2) )->isa_int();
2542     if( t && t->is_con() && (t->get_con() <= num_bits) ) {
2543       Node *shl = val->in(1);
2544       if( shl->Opcode() == Op_LShiftI ) {
2545         const TypeInt *t2 = phase->type( shl->in(2) )->isa_int();
2546         if( t2 && t2->is_con() && (t2->get_con() == t->get_con()) ) {
2547           set_req(MemNode::ValueIn, shl->in(1));
2548           return this;
2549         }
2550       }
2551     }
2552   }
2553   return NULL;
2554 }
2555 
2556 //------------------------------value_never_loaded-----------------------------------
2557 // Determine whether there are any possible loads of the value stored.
2558 // For simplicity, we actually check if there are any loads from the
2559 // address stored to, not just for loads of the value stored by this node.
2560 //
2561 bool StoreNode::value_never_loaded( PhaseTransform *phase) const {
2562   Node *adr = in(Address);
2563   const TypeOopPtr *adr_oop = phase->type(adr)->isa_oopptr();
2564   if (adr_oop == NULL)
2565     return false;
2566   if (!adr_oop->is_known_instance_field())
2567     return false; // if not a distinct instance, there may be aliases of the address
2568   for (DUIterator_Fast imax, i = adr->fast_outs(imax); i < imax; i++) {
2569     Node *use = adr->fast_out(i);
2570     if (use->is_Load() || use->is_LoadStore()) {
2571       return false;
2572     }
2573   }
2574   return true;
2575 }
2576 
2577 //=============================================================================
2578 //------------------------------Ideal------------------------------------------
2579 // If the store is from an AND mask that leaves the low bits untouched, then
2580 // we can skip the AND operation.  If the store is from a sign-extension
2581 // (a left shift, then right shift) we can skip both.
2582 Node *StoreBNode::Ideal(PhaseGVN *phase, bool can_reshape){
2583   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFF);
2584   if( progress != NULL ) return progress;
2585 
2586   progress = StoreNode::Ideal_sign_extended_input(phase, 24);
2587   if( progress != NULL ) return progress;
2588 
2589   // Finally check the default case
2590   return StoreNode::Ideal(phase, can_reshape);
2591 }
2592 
2593 //=============================================================================
2594 //------------------------------Ideal------------------------------------------
2595 // If the store is from an AND mask that leaves the low bits untouched, then
2596 // we can skip the AND operation
2597 Node *StoreCNode::Ideal(PhaseGVN *phase, bool can_reshape){
2598   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFFFF);
2599   if( progress != NULL ) return progress;
2600 
2601   progress = StoreNode::Ideal_sign_extended_input(phase, 16);
2602   if( progress != NULL ) return progress;
2603 
2604   // Finally check the default case
2605   return StoreNode::Ideal(phase, can_reshape);
2606 }
2607 
2608 //=============================================================================
2609 //------------------------------Identity---------------------------------------
2610 Node *StoreCMNode::Identity( PhaseTransform *phase ) {
2611   // No need to card mark when storing a null ptr
2612   Node* my_store = in(MemNode::OopStore);
2613   if (my_store->is_Store()) {
2614     const Type *t1 = phase->type( my_store->in(MemNode::ValueIn) );
2615     if( t1 == TypePtr::NULL_PTR ) {
2616       return in(MemNode::Memory);
2617     }
2618   }
2619   return this;
2620 }
2621 
2622 //=============================================================================
2623 //------------------------------Ideal---------------------------------------
2624 Node *StoreCMNode::Ideal(PhaseGVN *phase, bool can_reshape){
2625   Node* progress = StoreNode::Ideal(phase, can_reshape);
2626   if (progress != NULL) return progress;
2627 
2628   Node* my_store = in(MemNode::OopStore);
2629   if (my_store->is_MergeMem()) {
2630     Node* mem = my_store->as_MergeMem()->memory_at(oop_alias_idx());
2631     set_req(MemNode::OopStore, mem);
2632     return this;
2633   }
2634 
2635   return NULL;
2636 }
2637 
2638 //------------------------------Value-----------------------------------------
2639 const Type *StoreCMNode::Value( PhaseTransform *phase ) const {
2640   // Either input is TOP ==> the result is TOP
2641   const Type *t = phase->type( in(MemNode::Memory) );
2642   if( t == Type::TOP ) return Type::TOP;
2643   t = phase->type( in(MemNode::Address) );
2644   if( t == Type::TOP ) return Type::TOP;
2645   t = phase->type( in(MemNode::ValueIn) );
2646   if( t == Type::TOP ) return Type::TOP;
2647   // If extra input is TOP ==> the result is TOP
2648   t = phase->type( in(MemNode::OopStore) );
2649   if( t == Type::TOP ) return Type::TOP;
2650 
2651   return StoreNode::Value( phase );
2652 }
2653 
2654 
2655 //=============================================================================
2656 //----------------------------------SCMemProjNode------------------------------
2657 const Type * SCMemProjNode::Value( PhaseTransform *phase ) const
2658 {
2659   return bottom_type();
2660 }
2661 
2662 //=============================================================================
2663 //----------------------------------LoadStoreNode------------------------------
2664 LoadStoreNode::LoadStoreNode( Node *c, Node *mem, Node *adr, Node *val, const TypePtr* at, const Type* rt, uint required )
2665   : Node(required),
2666     _type(rt),
2667     _adr_type(at)
2668 {
2669   init_req(MemNode::Control, c  );
2670   init_req(MemNode::Memory , mem);
2671   init_req(MemNode::Address, adr);
2672   init_req(MemNode::ValueIn, val);
2673   init_class_id(Class_LoadStore);
2674 }
2675 
2676 uint LoadStoreNode::ideal_reg() const {
2677   return _type->ideal_reg();
2678 }
2679 
2680 bool LoadStoreNode::result_not_used() const {
2681   for( DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++ ) {
2682     Node *x = fast_out(i);
2683     if (x->Opcode() == Op_SCMemProj) continue;
2684     return false;
2685   }
2686   return true;
2687 }
2688 
2689 uint LoadStoreNode::size_of() const { return sizeof(*this); }
2690 
2691 //=============================================================================
2692 //----------------------------------LoadStoreConditionalNode--------------------
2693 LoadStoreConditionalNode::LoadStoreConditionalNode( Node *c, Node *mem, Node *adr, Node *val, Node *ex ) : LoadStoreNode(c, mem, adr, val, NULL, TypeInt::BOOL, 5) {
2694   init_req(ExpectedIn, ex );
2695 }
2696 
2697 //=============================================================================
2698 //-------------------------------adr_type--------------------------------------
2699 const TypePtr* ClearArrayNode::adr_type() const {
2700   Node *adr = in(3);
2701   if (adr == NULL)  return NULL; // node is dead
2702   return MemNode::calculate_adr_type(adr->bottom_type());
2703 }
2704 
2705 //------------------------------match_edge-------------------------------------
2706 // Do we Match on this edge index or not?  Do not match memory
2707 uint ClearArrayNode::match_edge(uint idx) const {
2708   return idx > 1;
2709 }
2710 
2711 //------------------------------Identity---------------------------------------
2712 // Clearing a zero length array does nothing
2713 Node *ClearArrayNode::Identity( PhaseTransform *phase ) {
2714   return phase->type(in(2))->higher_equal(TypeX::ZERO)  ? in(1) : this;
2715 }
2716 
2717 //------------------------------Idealize---------------------------------------
2718 // Clearing a short array is faster with stores
2719 Node *ClearArrayNode::Ideal(PhaseGVN *phase, bool can_reshape){
2720   const int unit = BytesPerLong;
2721   const TypeX* t = phase->type(in(2))->isa_intptr_t();
2722   if (!t)  return NULL;
2723   if (!t->is_con())  return NULL;
2724   intptr_t raw_count = t->get_con();
2725   intptr_t size = raw_count;
2726   if (!Matcher::init_array_count_is_in_bytes) size *= unit;
2727   // Clearing nothing uses the Identity call.
2728   // Negative clears are possible on dead ClearArrays
2729   // (see jck test stmt114.stmt11402.val).
2730   if (size <= 0 || size % unit != 0)  return NULL;
2731   intptr_t count = size / unit;
2732   // Length too long; use fast hardware clear
2733   if (size > Matcher::init_array_short_size)  return NULL;
2734   Node *mem = in(1);
2735   if( phase->type(mem)==Type::TOP ) return NULL;
2736   Node *adr = in(3);
2737   const Type* at = phase->type(adr);
2738   if( at==Type::TOP ) return NULL;
2739   const TypePtr* atp = at->isa_ptr();
2740   // adjust atp to be the correct array element address type
2741   if (atp == NULL)  atp = TypePtr::BOTTOM;
2742   else              atp = atp->add_offset(Type::OffsetBot);
2743   // Get base for derived pointer purposes
2744   if( adr->Opcode() != Op_AddP ) Unimplemented();
2745   Node *base = adr->in(1);
2746 
2747   Node *zero = phase->makecon(TypeLong::ZERO);
2748   Node *off  = phase->MakeConX(BytesPerLong);
2749   mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
2750   count--;
2751   while( count-- ) {
2752     mem = phase->transform(mem);
2753     adr = phase->transform(new AddPNode(base,adr,off));
2754     mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
2755   }
2756   return mem;
2757 }
2758 
2759 //----------------------------step_through----------------------------------
2760 // Return allocation input memory edge if it is different instance
2761 // or itself if it is the one we are looking for.
2762 bool ClearArrayNode::step_through(Node** np, uint instance_id, PhaseTransform* phase) {
2763   Node* n = *np;
2764   assert(n->is_ClearArray(), "sanity");
2765   intptr_t offset;
2766   AllocateNode* alloc = AllocateNode::Ideal_allocation(n->in(3), phase, offset);
2767   // This method is called only before Allocate nodes are expanded
2768   // during macro nodes expansion. Before that ClearArray nodes are
2769   // only generated in PhaseMacroExpand::generate_arraycopy() (before
2770   // Allocate nodes are expanded) which follows allocations.
2771   assert(alloc != NULL, "should have allocation");
2772   if (alloc->_idx == instance_id) {
2773     // Can not bypass initialization of the instance we are looking for.
2774     return false;
2775   }
2776   // Otherwise skip it.
2777   InitializeNode* init = alloc->initialization();
2778   if (init != NULL)
2779     *np = init->in(TypeFunc::Memory);
2780   else
2781     *np = alloc->in(TypeFunc::Memory);
2782   return true;
2783 }
2784 
2785 //----------------------------clear_memory-------------------------------------
2786 // Generate code to initialize object storage to zero.
2787 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2788                                    intptr_t start_offset,
2789                                    Node* end_offset,
2790                                    PhaseGVN* phase) {
2791   intptr_t offset = start_offset;
2792 
2793   int unit = BytesPerLong;
2794   if ((offset % unit) != 0) {
2795     Node* adr = new AddPNode(dest, dest, phase->MakeConX(offset));
2796     adr = phase->transform(adr);
2797     const TypePtr* atp = TypeRawPtr::BOTTOM;
2798     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
2799     mem = phase->transform(mem);
2800     offset += BytesPerInt;
2801   }
2802   assert((offset % unit) == 0, "");
2803 
2804   // Initialize the remaining stuff, if any, with a ClearArray.
2805   return clear_memory(ctl, mem, dest, phase->MakeConX(offset), end_offset, phase);
2806 }
2807 
2808 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2809                                    Node* start_offset,
2810                                    Node* end_offset,
2811                                    PhaseGVN* phase) {
2812   if (start_offset == end_offset) {
2813     // nothing to do
2814     return mem;
2815   }
2816 
2817   int unit = BytesPerLong;
2818   Node* zbase = start_offset;
2819   Node* zend  = end_offset;
2820 
2821   // Scale to the unit required by the CPU:
2822   if (!Matcher::init_array_count_is_in_bytes) {
2823     Node* shift = phase->intcon(exact_log2(unit));
2824     zbase = phase->transform(new URShiftXNode(zbase, shift) );
2825     zend  = phase->transform(new URShiftXNode(zend,  shift) );
2826   }
2827 
2828   // Bulk clear double-words
2829   Node* zsize = phase->transform(new SubXNode(zend, zbase) );
2830   Node* adr = phase->transform(new AddPNode(dest, dest, start_offset) );
2831   mem = new ClearArrayNode(ctl, mem, zsize, adr);
2832   return phase->transform(mem);
2833 }
2834 
2835 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2836                                    intptr_t start_offset,
2837                                    intptr_t end_offset,
2838                                    PhaseGVN* phase) {
2839   if (start_offset == end_offset) {
2840     // nothing to do
2841     return mem;
2842   }
2843 
2844   assert((end_offset % BytesPerInt) == 0, "odd end offset");
2845   intptr_t done_offset = end_offset;
2846   if ((done_offset % BytesPerLong) != 0) {
2847     done_offset -= BytesPerInt;
2848   }
2849   if (done_offset > start_offset) {
2850     mem = clear_memory(ctl, mem, dest,
2851                        start_offset, phase->MakeConX(done_offset), phase);
2852   }
2853   if (done_offset < end_offset) { // emit the final 32-bit store
2854     Node* adr = new AddPNode(dest, dest, phase->MakeConX(done_offset));
2855     adr = phase->transform(adr);
2856     const TypePtr* atp = TypeRawPtr::BOTTOM;
2857     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
2858     mem = phase->transform(mem);
2859     done_offset += BytesPerInt;
2860   }
2861   assert(done_offset == end_offset, "");
2862   return mem;
2863 }
2864 
2865 //=============================================================================
2866 MemBarNode::MemBarNode(Compile* C, int alias_idx, Node* precedent)
2867   : MultiNode(TypeFunc::Parms + (precedent == NULL? 0: 1)),
2868     _adr_type(C->get_adr_type(alias_idx))
2869 {
2870   init_class_id(Class_MemBar);
2871   Node* top = C->top();
2872   init_req(TypeFunc::I_O,top);
2873   init_req(TypeFunc::FramePtr,top);
2874   init_req(TypeFunc::ReturnAdr,top);
2875   if (precedent != NULL)
2876     init_req(TypeFunc::Parms, precedent);
2877 }
2878 
2879 //------------------------------cmp--------------------------------------------
2880 uint MemBarNode::hash() const { return NO_HASH; }
2881 uint MemBarNode::cmp( const Node &n ) const {
2882   return (&n == this);          // Always fail except on self
2883 }
2884 
2885 //------------------------------make-------------------------------------------
2886 MemBarNode* MemBarNode::make(Compile* C, int opcode, int atp, Node* pn) {
2887   switch (opcode) {
2888   case Op_MemBarAcquire:     return new MemBarAcquireNode(C, atp, pn);
2889   case Op_LoadFence:         return new LoadFenceNode(C, atp, pn);
2890   case Op_MemBarRelease:     return new MemBarReleaseNode(C, atp, pn);
2891   case Op_StoreFence:        return new StoreFenceNode(C, atp, pn);
2892   case Op_MemBarAcquireLock: return new MemBarAcquireLockNode(C, atp, pn);
2893   case Op_MemBarReleaseLock: return new MemBarReleaseLockNode(C, atp, pn);
2894   case Op_MemBarVolatile:    return new MemBarVolatileNode(C, atp, pn);
2895   case Op_MemBarCPUOrder:    return new MemBarCPUOrderNode(C, atp, pn);
2896   case Op_Initialize:        return new InitializeNode(C, atp, pn);
2897   case Op_MemBarStoreStore:  return new MemBarStoreStoreNode(C, atp, pn);
2898   default: ShouldNotReachHere(); return NULL;
2899   }
2900 }
2901 
2902 //------------------------------Ideal------------------------------------------
2903 // Return a node which is more "ideal" than the current node.  Strip out
2904 // control copies
2905 Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2906   if (remove_dead_region(phase, can_reshape)) return this;
2907   // Don't bother trying to transform a dead node
2908   if (in(0) && in(0)->is_top()) {
2909     return NULL;
2910   }
2911 
2912   bool progress = false;
2913   // Eliminate volatile MemBars for scalar replaced objects.
2914   if (can_reshape && req() == (Precedent+1)) {
2915     bool eliminate = false;
2916     int opc = Opcode();
2917     if ((opc == Op_MemBarAcquire || opc == Op_MemBarVolatile)) {
2918       // Volatile field loads and stores.
2919       Node* my_mem = in(MemBarNode::Precedent);
2920       // The MembarAquire may keep an unused LoadNode alive through the Precedent edge
2921       if ((my_mem != NULL) && (opc == Op_MemBarAcquire) && (my_mem->outcnt() == 1)) {
2922         // if the Precedent is a decodeN and its input (a Load) is used at more than one place,
2923         // replace this Precedent (decodeN) with the Load instead.
2924         if ((my_mem->Opcode() == Op_DecodeN) && (my_mem->in(1)->outcnt() > 1))  {
2925           Node* load_node = my_mem->in(1);
2926           set_req(MemBarNode::Precedent, load_node);
2927           phase->is_IterGVN()->_worklist.push(my_mem);
2928           my_mem = load_node;
2929         } else {
2930           assert(my_mem->unique_out() == this, "sanity");
2931           del_req(Precedent);
2932           phase->is_IterGVN()->_worklist.push(my_mem); // remove dead node later
2933           my_mem = NULL;
2934         }
2935         progress = true;
2936       }
2937       if (my_mem != NULL && my_mem->is_Mem()) {
2938         const TypeOopPtr* t_oop = my_mem->in(MemNode::Address)->bottom_type()->isa_oopptr();
2939         // Check for scalar replaced object reference.
2940         if( t_oop != NULL && t_oop->is_known_instance_field() &&
2941             t_oop->offset() != Type::OffsetBot &&
2942             t_oop->offset() != Type::OffsetTop) {
2943           eliminate = true;
2944         }
2945       }
2946     } else if (opc == Op_MemBarRelease) {
2947       // Final field stores.
2948       Node* alloc = AllocateNode::Ideal_allocation(in(MemBarNode::Precedent), phase);
2949       if ((alloc != NULL) && alloc->is_Allocate() &&
2950           alloc->as_Allocate()->_is_non_escaping) {
2951         // The allocated object does not escape.
2952         eliminate = true;
2953       }
2954     }
2955     if (eliminate) {
2956       // Replace MemBar projections by its inputs.
2957       PhaseIterGVN* igvn = phase->is_IterGVN();
2958       igvn->replace_node(proj_out(TypeFunc::Memory), in(TypeFunc::Memory));
2959       igvn->replace_node(proj_out(TypeFunc::Control), in(TypeFunc::Control));
2960       // Must return either the original node (now dead) or a new node
2961       // (Do not return a top here, since that would break the uniqueness of top.)
2962       return new ConINode(TypeInt::ZERO);
2963     }
2964   }
2965   return progress ? this : NULL;
2966 }
2967 
2968 //------------------------------Value------------------------------------------
2969 const Type *MemBarNode::Value( PhaseTransform *phase ) const {
2970   if( !in(0) ) return Type::TOP;
2971   if( phase->type(in(0)) == Type::TOP )
2972     return Type::TOP;
2973   return TypeTuple::MEMBAR;
2974 }
2975 
2976 //------------------------------match------------------------------------------
2977 // Construct projections for memory.
2978 Node *MemBarNode::match( const ProjNode *proj, const Matcher *m ) {
2979   switch (proj->_con) {
2980   case TypeFunc::Control:
2981   case TypeFunc::Memory:
2982     return new MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
2983   }
2984   ShouldNotReachHere();
2985   return NULL;
2986 }
2987 
2988 //===========================InitializeNode====================================
2989 // SUMMARY:
2990 // This node acts as a memory barrier on raw memory, after some raw stores.
2991 // The 'cooked' oop value feeds from the Initialize, not the Allocation.
2992 // The Initialize can 'capture' suitably constrained stores as raw inits.
2993 // It can coalesce related raw stores into larger units (called 'tiles').
2994 // It can avoid zeroing new storage for memory units which have raw inits.
2995 // At macro-expansion, it is marked 'complete', and does not optimize further.
2996 //
2997 // EXAMPLE:
2998 // The object 'new short[2]' occupies 16 bytes in a 32-bit machine.
2999 //   ctl = incoming control; mem* = incoming memory
3000 // (Note:  A star * on a memory edge denotes I/O and other standard edges.)
3001 // First allocate uninitialized memory and fill in the header:
3002 //   alloc = (Allocate ctl mem* 16 #short[].klass ...)
3003 //   ctl := alloc.Control; mem* := alloc.Memory*
3004 //   rawmem = alloc.Memory; rawoop = alloc.RawAddress
3005 // Then initialize to zero the non-header parts of the raw memory block:
3006 //   init = (Initialize alloc.Control alloc.Memory* alloc.RawAddress)
3007 //   ctl := init.Control; mem.SLICE(#short[*]) := init.Memory
3008 // After the initialize node executes, the object is ready for service:
3009 //   oop := (CheckCastPP init.Control alloc.RawAddress #short[])
3010 // Suppose its body is immediately initialized as {1,2}:
3011 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
3012 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
3013 //   mem.SLICE(#short[*]) := store2
3014 //
3015 // DETAILS:
3016 // An InitializeNode collects and isolates object initialization after
3017 // an AllocateNode and before the next possible safepoint.  As a
3018 // memory barrier (MemBarNode), it keeps critical stores from drifting
3019 // down past any safepoint or any publication of the allocation.
3020 // Before this barrier, a newly-allocated object may have uninitialized bits.
3021 // After this barrier, it may be treated as a real oop, and GC is allowed.
3022 //
3023 // The semantics of the InitializeNode include an implicit zeroing of
3024 // the new object from object header to the end of the object.
3025 // (The object header and end are determined by the AllocateNode.)
3026 //
3027 // Certain stores may be added as direct inputs to the InitializeNode.
3028 // These stores must update raw memory, and they must be to addresses
3029 // derived from the raw address produced by AllocateNode, and with
3030 // a constant offset.  They must be ordered by increasing offset.
3031 // The first one is at in(RawStores), the last at in(req()-1).
3032 // Unlike most memory operations, they are not linked in a chain,
3033 // but are displayed in parallel as users of the rawmem output of
3034 // the allocation.
3035 //
3036 // (See comments in InitializeNode::capture_store, which continue
3037 // the example given above.)
3038 //
3039 // When the associated Allocate is macro-expanded, the InitializeNode
3040 // may be rewritten to optimize collected stores.  A ClearArrayNode
3041 // may also be created at that point to represent any required zeroing.
3042 // The InitializeNode is then marked 'complete', prohibiting further
3043 // capturing of nearby memory operations.
3044 //
3045 // During macro-expansion, all captured initializations which store
3046 // constant values of 32 bits or smaller are coalesced (if advantageous)
3047 // into larger 'tiles' 32 or 64 bits.  This allows an object to be
3048 // initialized in fewer memory operations.  Memory words which are
3049 // covered by neither tiles nor non-constant stores are pre-zeroed
3050 // by explicit stores of zero.  (The code shape happens to do all
3051 // zeroing first, then all other stores, with both sequences occurring
3052 // in order of ascending offsets.)
3053 //
3054 // Alternatively, code may be inserted between an AllocateNode and its
3055 // InitializeNode, to perform arbitrary initialization of the new object.
3056 // E.g., the object copying intrinsics insert complex data transfers here.
3057 // The initialization must then be marked as 'complete' disable the
3058 // built-in zeroing semantics and the collection of initializing stores.
3059 //
3060 // While an InitializeNode is incomplete, reads from the memory state
3061 // produced by it are optimizable if they match the control edge and
3062 // new oop address associated with the allocation/initialization.
3063 // They return a stored value (if the offset matches) or else zero.
3064 // A write to the memory state, if it matches control and address,
3065 // and if it is to a constant offset, may be 'captured' by the
3066 // InitializeNode.  It is cloned as a raw memory operation and rewired
3067 // inside the initialization, to the raw oop produced by the allocation.
3068 // Operations on addresses which are provably distinct (e.g., to
3069 // other AllocateNodes) are allowed to bypass the initialization.
3070 //
3071 // The effect of all this is to consolidate object initialization
3072 // (both arrays and non-arrays, both piecewise and bulk) into a
3073 // single location, where it can be optimized as a unit.
3074 //
3075 // Only stores with an offset less than TrackedInitializationLimit words
3076 // will be considered for capture by an InitializeNode.  This puts a
3077 // reasonable limit on the complexity of optimized initializations.
3078 
3079 //---------------------------InitializeNode------------------------------------
3080 InitializeNode::InitializeNode(Compile* C, int adr_type, Node* rawoop)
3081   : _is_complete(Incomplete), _does_not_escape(false),
3082     MemBarNode(C, adr_type, rawoop)
3083 {
3084   init_class_id(Class_Initialize);
3085 
3086   assert(adr_type == Compile::AliasIdxRaw, "only valid atp");
3087   assert(in(RawAddress) == rawoop, "proper init");
3088   // Note:  allocation() can be NULL, for secondary initialization barriers
3089 }
3090 
3091 // Since this node is not matched, it will be processed by the
3092 // register allocator.  Declare that there are no constraints
3093 // on the allocation of the RawAddress edge.
3094 const RegMask &InitializeNode::in_RegMask(uint idx) const {
3095   // This edge should be set to top, by the set_complete.  But be conservative.
3096   if (idx == InitializeNode::RawAddress)
3097     return *(Compile::current()->matcher()->idealreg2spillmask[in(idx)->ideal_reg()]);
3098   return RegMask::Empty;
3099 }
3100 
3101 Node* InitializeNode::memory(uint alias_idx) {
3102   Node* mem = in(Memory);
3103   if (mem->is_MergeMem()) {
3104     return mem->as_MergeMem()->memory_at(alias_idx);
3105   } else {
3106     // incoming raw memory is not split
3107     return mem;
3108   }
3109 }
3110 
3111 bool InitializeNode::is_non_zero() {
3112   if (is_complete())  return false;
3113   remove_extra_zeroes();
3114   return (req() > RawStores);
3115 }
3116 
3117 void InitializeNode::set_complete(PhaseGVN* phase) {
3118   assert(!is_complete(), "caller responsibility");
3119   _is_complete = Complete;
3120 
3121   // After this node is complete, it contains a bunch of
3122   // raw-memory initializations.  There is no need for
3123   // it to have anything to do with non-raw memory effects.
3124   // Therefore, tell all non-raw users to re-optimize themselves,
3125   // after skipping the memory effects of this initialization.
3126   PhaseIterGVN* igvn = phase->is_IterGVN();
3127   if (igvn)  igvn->add_users_to_worklist(this);
3128 }
3129 
3130 // convenience function
3131 // return false if the init contains any stores already
3132 bool AllocateNode::maybe_set_complete(PhaseGVN* phase) {
3133   InitializeNode* init = initialization();
3134   if (init == NULL || init->is_complete())  return false;
3135   init->remove_extra_zeroes();
3136   // for now, if this allocation has already collected any inits, bail:
3137   if (init->is_non_zero())  return false;
3138   init->set_complete(phase);
3139   return true;
3140 }
3141 
3142 void InitializeNode::remove_extra_zeroes() {
3143   if (req() == RawStores)  return;
3144   Node* zmem = zero_memory();
3145   uint fill = RawStores;
3146   for (uint i = fill; i < req(); i++) {
3147     Node* n = in(i);
3148     if (n->is_top() || n == zmem)  continue;  // skip
3149     if (fill < i)  set_req(fill, n);          // compact
3150     ++fill;
3151   }
3152   // delete any empty spaces created:
3153   while (fill < req()) {
3154     del_req(fill);
3155   }
3156 }
3157 
3158 // Helper for remembering which stores go with which offsets.
3159 intptr_t InitializeNode::get_store_offset(Node* st, PhaseTransform* phase) {
3160   if (!st->is_Store())  return -1;  // can happen to dead code via subsume_node
3161   intptr_t offset = -1;
3162   Node* base = AddPNode::Ideal_base_and_offset(st->in(MemNode::Address),
3163                                                phase, offset);
3164   if (base == NULL)     return -1;  // something is dead,
3165   if (offset < 0)       return -1;  //        dead, dead
3166   return offset;
3167 }
3168 
3169 // Helper for proving that an initialization expression is
3170 // "simple enough" to be folded into an object initialization.
3171 // Attempts to prove that a store's initial value 'n' can be captured
3172 // within the initialization without creating a vicious cycle, such as:
3173 //     { Foo p = new Foo(); p.next = p; }
3174 // True for constants and parameters and small combinations thereof.
3175 bool InitializeNode::detect_init_independence(Node* n, int& count) {
3176   if (n == NULL)      return true;   // (can this really happen?)
3177   if (n->is_Proj())   n = n->in(0);
3178   if (n == this)      return false;  // found a cycle
3179   if (n->is_Con())    return true;
3180   if (n->is_Start())  return true;   // params, etc., are OK
3181   if (n->is_Root())   return true;   // even better
3182 
3183   Node* ctl = n->in(0);
3184   if (ctl != NULL && !ctl->is_top()) {
3185     if (ctl->is_Proj())  ctl = ctl->in(0);
3186     if (ctl == this)  return false;
3187 
3188     // If we already know that the enclosing memory op is pinned right after
3189     // the init, then any control flow that the store has picked up
3190     // must have preceded the init, or else be equal to the init.
3191     // Even after loop optimizations (which might change control edges)
3192     // a store is never pinned *before* the availability of its inputs.
3193     if (!MemNode::all_controls_dominate(n, this))
3194       return false;                  // failed to prove a good control
3195   }
3196 
3197   // Check data edges for possible dependencies on 'this'.
3198   if ((count += 1) > 20)  return false;  // complexity limit
3199   for (uint i = 1; i < n->req(); i++) {
3200     Node* m = n->in(i);
3201     if (m == NULL || m == n || m->is_top())  continue;
3202     uint first_i = n->find_edge(m);
3203     if (i != first_i)  continue;  // process duplicate edge just once
3204     if (!detect_init_independence(m, count)) {
3205       return false;
3206     }
3207   }
3208 
3209   return true;
3210 }
3211 
3212 // Here are all the checks a Store must pass before it can be moved into
3213 // an initialization.  Returns zero if a check fails.
3214 // On success, returns the (constant) offset to which the store applies,
3215 // within the initialized memory.
3216 intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseTransform* phase, bool can_reshape) {
3217   const int FAIL = 0;
3218   if (st->req() != MemNode::ValueIn + 1)
3219     return FAIL;                // an inscrutable StoreNode (card mark?)
3220   Node* ctl = st->in(MemNode::Control);
3221   if (!(ctl != NULL && ctl->is_Proj() && ctl->in(0) == this))
3222     return FAIL;                // must be unconditional after the initialization
3223   Node* mem = st->in(MemNode::Memory);
3224   if (!(mem->is_Proj() && mem->in(0) == this))
3225     return FAIL;                // must not be preceded by other stores
3226   Node* adr = st->in(MemNode::Address);
3227   intptr_t offset;
3228   AllocateNode* alloc = AllocateNode::Ideal_allocation(adr, phase, offset);
3229   if (alloc == NULL)
3230     return FAIL;                // inscrutable address
3231   if (alloc != allocation())
3232     return FAIL;                // wrong allocation!  (store needs to float up)
3233   Node* val = st->in(MemNode::ValueIn);
3234   int complexity_count = 0;
3235   if (!detect_init_independence(val, complexity_count))
3236     return FAIL;                // stored value must be 'simple enough'
3237 
3238   // The Store can be captured only if nothing after the allocation
3239   // and before the Store is using the memory location that the store
3240   // overwrites.
3241   bool failed = false;
3242   // If is_complete_with_arraycopy() is true the shape of the graph is
3243   // well defined and is safe so no need for extra checks.
3244   if (!is_complete_with_arraycopy()) {
3245     // We are going to look at each use of the memory state following
3246     // the allocation to make sure nothing reads the memory that the
3247     // Store writes.
3248     const TypePtr* t_adr = phase->type(adr)->isa_ptr();
3249     int alias_idx = phase->C->get_alias_index(t_adr);
3250     ResourceMark rm;
3251     Unique_Node_List mems;
3252     mems.push(mem);
3253     Node* unique_merge = NULL;
3254     for (uint next = 0; next < mems.size(); ++next) {
3255       Node *m  = mems.at(next);
3256       for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
3257         Node *n = m->fast_out(j);
3258         if (n->outcnt() == 0) {
3259           continue;
3260         }
3261         if (n == st) {
3262           continue;
3263         } else if (n->in(0) != NULL && n->in(0) != ctl) {
3264           // If the control of this use is different from the control
3265           // of the Store which is right after the InitializeNode then
3266           // this node cannot be between the InitializeNode and the
3267           // Store.
3268           continue;
3269         } else if (n->is_MergeMem()) {
3270           if (n->as_MergeMem()->memory_at(alias_idx) == m) {
3271             // We can hit a MergeMemNode (that will likely go away
3272             // later) that is a direct use of the memory state
3273             // following the InitializeNode on the same slice as the
3274             // store node that we'd like to capture. We need to check
3275             // the uses of the MergeMemNode.
3276             mems.push(n);
3277           }
3278         } else if (n->is_Mem()) {
3279           Node* other_adr = n->in(MemNode::Address);
3280           if (other_adr == adr) {
3281             failed = true;
3282             break;
3283           } else {
3284             const TypePtr* other_t_adr = phase->type(other_adr)->isa_ptr();
3285             if (other_t_adr != NULL) {
3286               int other_alias_idx = phase->C->get_alias_index(other_t_adr);
3287               if (other_alias_idx == alias_idx) {
3288                 // A load from the same memory slice as the store right
3289                 // after the InitializeNode. We check the control of the
3290                 // object/array that is loaded from. If it's the same as
3291                 // the store control then we cannot capture the store.
3292                 assert(!n->is_Store(), "2 stores to same slice on same control?");
3293                 Node* base = other_adr;
3294                 assert(base->is_AddP(), err_msg_res("should be addp but is %s", base->Name()));
3295                 base = base->in(AddPNode::Base);
3296                 if (base != NULL) {
3297                   base = base->uncast();
3298                   if (base->is_Proj() && base->in(0) == alloc) {
3299                     failed = true;
3300                     break;
3301                   }
3302                 }
3303               }
3304             }
3305           }
3306         } else {
3307           failed = true;
3308           break;
3309         }
3310       }
3311     }
3312   }
3313   if (failed) {
3314     if (!can_reshape) {
3315       // We decided we couldn't capture the store during parsing. We
3316       // should try again during the next IGVN once the graph is
3317       // cleaner.
3318       phase->C->record_for_igvn(st);
3319     }
3320     return FAIL;
3321   }
3322 
3323   return offset;                // success
3324 }
3325 
3326 // Find the captured store in(i) which corresponds to the range
3327 // [start..start+size) in the initialized object.
3328 // If there is one, return its index i.  If there isn't, return the
3329 // negative of the index where it should be inserted.
3330 // Return 0 if the queried range overlaps an initialization boundary
3331 // or if dead code is encountered.
3332 // If size_in_bytes is zero, do not bother with overlap checks.
3333 int InitializeNode::captured_store_insertion_point(intptr_t start,
3334                                                    int size_in_bytes,
3335                                                    PhaseTransform* phase) {
3336   const int FAIL = 0, MAX_STORE = BytesPerLong;
3337 
3338   if (is_complete())
3339     return FAIL;                // arraycopy got here first; punt
3340 
3341   assert(allocation() != NULL, "must be present");
3342 
3343   // no negatives, no header fields:
3344   if (start < (intptr_t) allocation()->minimum_header_size())  return FAIL;
3345 
3346   // after a certain size, we bail out on tracking all the stores:
3347   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
3348   if (start >= ti_limit)  return FAIL;
3349 
3350   for (uint i = InitializeNode::RawStores, limit = req(); ; ) {
3351     if (i >= limit)  return -(int)i; // not found; here is where to put it
3352 
3353     Node*    st     = in(i);
3354     intptr_t st_off = get_store_offset(st, phase);
3355     if (st_off < 0) {
3356       if (st != zero_memory()) {
3357         return FAIL;            // bail out if there is dead garbage
3358       }
3359     } else if (st_off > start) {
3360       // ...we are done, since stores are ordered
3361       if (st_off < start + size_in_bytes) {
3362         return FAIL;            // the next store overlaps
3363       }
3364       return -(int)i;           // not found; here is where to put it
3365     } else if (st_off < start) {
3366       if (size_in_bytes != 0 &&
3367           start < st_off + MAX_STORE &&
3368           start < st_off + st->as_Store()->memory_size()) {
3369         return FAIL;            // the previous store overlaps
3370       }
3371     } else {
3372       if (size_in_bytes != 0 &&
3373           st->as_Store()->memory_size() != size_in_bytes) {
3374         return FAIL;            // mismatched store size
3375       }
3376       return i;
3377     }
3378 
3379     ++i;
3380   }
3381 }
3382 
3383 // Look for a captured store which initializes at the offset 'start'
3384 // with the given size.  If there is no such store, and no other
3385 // initialization interferes, then return zero_memory (the memory
3386 // projection of the AllocateNode).
3387 Node* InitializeNode::find_captured_store(intptr_t start, int size_in_bytes,
3388                                           PhaseTransform* phase) {
3389   assert(stores_are_sane(phase), "");
3390   int i = captured_store_insertion_point(start, size_in_bytes, phase);
3391   if (i == 0) {
3392     return NULL;                // something is dead
3393   } else if (i < 0) {
3394     return zero_memory();       // just primordial zero bits here
3395   } else {
3396     Node* st = in(i);           // here is the store at this position
3397     assert(get_store_offset(st->as_Store(), phase) == start, "sanity");
3398     return st;
3399   }
3400 }
3401 
3402 // Create, as a raw pointer, an address within my new object at 'offset'.
3403 Node* InitializeNode::make_raw_address(intptr_t offset,
3404                                        PhaseTransform* phase) {
3405   Node* addr = in(RawAddress);
3406   if (offset != 0) {
3407     Compile* C = phase->C;
3408     addr = phase->transform( new AddPNode(C->top(), addr,
3409                                                  phase->MakeConX(offset)) );
3410   }
3411   return addr;
3412 }
3413 
3414 // Clone the given store, converting it into a raw store
3415 // initializing a field or element of my new object.
3416 // Caller is responsible for retiring the original store,
3417 // with subsume_node or the like.
3418 //
3419 // From the example above InitializeNode::InitializeNode,
3420 // here are the old stores to be captured:
3421 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
3422 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
3423 //
3424 // Here is the changed code; note the extra edges on init:
3425 //   alloc = (Allocate ...)
3426 //   rawoop = alloc.RawAddress
3427 //   rawstore1 = (StoreC alloc.Control alloc.Memory (+ rawoop 12) 1)
3428 //   rawstore2 = (StoreC alloc.Control alloc.Memory (+ rawoop 14) 2)
3429 //   init = (Initialize alloc.Control alloc.Memory rawoop
3430 //                      rawstore1 rawstore2)
3431 //
3432 Node* InitializeNode::capture_store(StoreNode* st, intptr_t start,
3433                                     PhaseTransform* phase, bool can_reshape) {
3434   assert(stores_are_sane(phase), "");
3435 
3436   if (start < 0)  return NULL;
3437   assert(can_capture_store(st, phase, can_reshape) == start, "sanity");
3438 
3439   Compile* C = phase->C;
3440   int size_in_bytes = st->memory_size();
3441   int i = captured_store_insertion_point(start, size_in_bytes, phase);
3442   if (i == 0)  return NULL;     // bail out
3443   Node* prev_mem = NULL;        // raw memory for the captured store
3444   if (i > 0) {
3445     prev_mem = in(i);           // there is a pre-existing store under this one
3446     set_req(i, C->top());       // temporarily disconnect it
3447     // See StoreNode::Ideal 'st->outcnt() == 1' for the reason to disconnect.
3448   } else {
3449     i = -i;                     // no pre-existing store
3450     prev_mem = zero_memory();   // a slice of the newly allocated object
3451     if (i > InitializeNode::RawStores && in(i-1) == prev_mem)
3452       set_req(--i, C->top());   // reuse this edge; it has been folded away
3453     else
3454       ins_req(i, C->top());     // build a new edge
3455   }
3456   Node* new_st = st->clone();
3457   new_st->set_req(MemNode::Control, in(Control));
3458   new_st->set_req(MemNode::Memory,  prev_mem);
3459   new_st->set_req(MemNode::Address, make_raw_address(start, phase));
3460   new_st = phase->transform(new_st);
3461 
3462   // At this point, new_st might have swallowed a pre-existing store
3463   // at the same offset, or perhaps new_st might have disappeared,
3464   // if it redundantly stored the same value (or zero to fresh memory).
3465 
3466   // In any case, wire it in:
3467   phase->igvn_rehash_node_delayed(this);
3468   set_req(i, new_st);
3469 
3470   // The caller may now kill the old guy.
3471   DEBUG_ONLY(Node* check_st = find_captured_store(start, size_in_bytes, phase));
3472   assert(check_st == new_st || check_st == NULL, "must be findable");
3473   assert(!is_complete(), "");
3474   return new_st;
3475 }
3476 
3477 static bool store_constant(jlong* tiles, int num_tiles,
3478                            intptr_t st_off, int st_size,
3479                            jlong con) {
3480   if ((st_off & (st_size-1)) != 0)
3481     return false;               // strange store offset (assume size==2**N)
3482   address addr = (address)tiles + st_off;
3483   assert(st_off >= 0 && addr+st_size <= (address)&tiles[num_tiles], "oob");
3484   switch (st_size) {
3485   case sizeof(jbyte):  *(jbyte*) addr = (jbyte) con; break;
3486   case sizeof(jchar):  *(jchar*) addr = (jchar) con; break;
3487   case sizeof(jint):   *(jint*)  addr = (jint)  con; break;
3488   case sizeof(jlong):  *(jlong*) addr = (jlong) con; break;
3489   default: return false;        // strange store size (detect size!=2**N here)
3490   }
3491   return true;                  // return success to caller
3492 }
3493 
3494 // Coalesce subword constants into int constants and possibly
3495 // into long constants.  The goal, if the CPU permits,
3496 // is to initialize the object with a small number of 64-bit tiles.
3497 // Also, convert floating-point constants to bit patterns.
3498 // Non-constants are not relevant to this pass.
3499 //
3500 // In terms of the running example on InitializeNode::InitializeNode
3501 // and InitializeNode::capture_store, here is the transformation
3502 // of rawstore1 and rawstore2 into rawstore12:
3503 //   alloc = (Allocate ...)
3504 //   rawoop = alloc.RawAddress
3505 //   tile12 = 0x00010002
3506 //   rawstore12 = (StoreI alloc.Control alloc.Memory (+ rawoop 12) tile12)
3507 //   init = (Initialize alloc.Control alloc.Memory rawoop rawstore12)
3508 //
3509 void
3510 InitializeNode::coalesce_subword_stores(intptr_t header_size,
3511                                         Node* size_in_bytes,
3512                                         PhaseGVN* phase) {
3513   Compile* C = phase->C;
3514 
3515   assert(stores_are_sane(phase), "");
3516   // Note:  After this pass, they are not completely sane,
3517   // since there may be some overlaps.
3518 
3519   int old_subword = 0, old_long = 0, new_int = 0, new_long = 0;
3520 
3521   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
3522   intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, ti_limit);
3523   size_limit = MIN2(size_limit, ti_limit);
3524   size_limit = align_size_up(size_limit, BytesPerLong);
3525   int num_tiles = size_limit / BytesPerLong;
3526 
3527   // allocate space for the tile map:
3528   const int small_len = DEBUG_ONLY(true ? 3 :) 30; // keep stack frames small
3529   jlong  tiles_buf[small_len];
3530   Node*  nodes_buf[small_len];
3531   jlong  inits_buf[small_len];
3532   jlong* tiles = ((num_tiles <= small_len) ? &tiles_buf[0]
3533                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
3534   Node** nodes = ((num_tiles <= small_len) ? &nodes_buf[0]
3535                   : NEW_RESOURCE_ARRAY(Node*, num_tiles));
3536   jlong* inits = ((num_tiles <= small_len) ? &inits_buf[0]
3537                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
3538   // tiles: exact bitwise model of all primitive constants
3539   // nodes: last constant-storing node subsumed into the tiles model
3540   // inits: which bytes (in each tile) are touched by any initializations
3541 
3542   //// Pass A: Fill in the tile model with any relevant stores.
3543 
3544   Copy::zero_to_bytes(tiles, sizeof(tiles[0]) * num_tiles);
3545   Copy::zero_to_bytes(nodes, sizeof(nodes[0]) * num_tiles);
3546   Copy::zero_to_bytes(inits, sizeof(inits[0]) * num_tiles);
3547   Node* zmem = zero_memory(); // initially zero memory state
3548   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
3549     Node* st = in(i);
3550     intptr_t st_off = get_store_offset(st, phase);
3551 
3552     // Figure out the store's offset and constant value:
3553     if (st_off < header_size)             continue; //skip (ignore header)
3554     if (st->in(MemNode::Memory) != zmem)  continue; //skip (odd store chain)
3555     int st_size = st->as_Store()->memory_size();
3556     if (st_off + st_size > size_limit)    break;
3557 
3558     // Record which bytes are touched, whether by constant or not.
3559     if (!store_constant(inits, num_tiles, st_off, st_size, (jlong) -1))
3560       continue;                 // skip (strange store size)
3561 
3562     const Type* val = phase->type(st->in(MemNode::ValueIn));
3563     if (!val->singleton())                continue; //skip (non-con store)
3564     BasicType type = val->basic_type();
3565 
3566     jlong con = 0;
3567     switch (type) {
3568     case T_INT:    con = val->is_int()->get_con();  break;
3569     case T_LONG:   con = val->is_long()->get_con(); break;
3570     case T_FLOAT:  con = jint_cast(val->getf());    break;
3571     case T_DOUBLE: con = jlong_cast(val->getd());   break;
3572     default:                              continue; //skip (odd store type)
3573     }
3574 
3575     if (type == T_LONG && Matcher::isSimpleConstant64(con) &&
3576         st->Opcode() == Op_StoreL) {
3577       continue;                 // This StoreL is already optimal.
3578     }
3579 
3580     // Store down the constant.
3581     store_constant(tiles, num_tiles, st_off, st_size, con);
3582 
3583     intptr_t j = st_off >> LogBytesPerLong;
3584 
3585     if (type == T_INT && st_size == BytesPerInt
3586         && (st_off & BytesPerInt) == BytesPerInt) {
3587       jlong lcon = tiles[j];
3588       if (!Matcher::isSimpleConstant64(lcon) &&
3589           st->Opcode() == Op_StoreI) {
3590         // This StoreI is already optimal by itself.
3591         jint* intcon = (jint*) &tiles[j];
3592         intcon[1] = 0;  // undo the store_constant()
3593 
3594         // If the previous store is also optimal by itself, back up and
3595         // undo the action of the previous loop iteration... if we can.
3596         // But if we can't, just let the previous half take care of itself.
3597         st = nodes[j];
3598         st_off -= BytesPerInt;
3599         con = intcon[0];
3600         if (con != 0 && st != NULL && st->Opcode() == Op_StoreI) {
3601           assert(st_off >= header_size, "still ignoring header");
3602           assert(get_store_offset(st, phase) == st_off, "must be");
3603           assert(in(i-1) == zmem, "must be");
3604           DEBUG_ONLY(const Type* tcon = phase->type(st->in(MemNode::ValueIn)));
3605           assert(con == tcon->is_int()->get_con(), "must be");
3606           // Undo the effects of the previous loop trip, which swallowed st:
3607           intcon[0] = 0;        // undo store_constant()
3608           set_req(i-1, st);     // undo set_req(i, zmem)
3609           nodes[j] = NULL;      // undo nodes[j] = st
3610           --old_subword;        // undo ++old_subword
3611         }
3612         continue;               // This StoreI is already optimal.
3613       }
3614     }
3615 
3616     // This store is not needed.
3617     set_req(i, zmem);
3618     nodes[j] = st;              // record for the moment
3619     if (st_size < BytesPerLong) // something has changed
3620           ++old_subword;        // includes int/float, but who's counting...
3621     else  ++old_long;
3622   }
3623 
3624   if ((old_subword + old_long) == 0)
3625     return;                     // nothing more to do
3626 
3627   //// Pass B: Convert any non-zero tiles into optimal constant stores.
3628   // Be sure to insert them before overlapping non-constant stores.
3629   // (E.g., byte[] x = { 1,2,y,4 }  =>  x[int 0] = 0x01020004, x[2]=y.)
3630   for (int j = 0; j < num_tiles; j++) {
3631     jlong con  = tiles[j];
3632     jlong init = inits[j];
3633     if (con == 0)  continue;
3634     jint con0,  con1;           // split the constant, address-wise
3635     jint init0, init1;          // split the init map, address-wise
3636     { union { jlong con; jint intcon[2]; } u;
3637       u.con = con;
3638       con0  = u.intcon[0];
3639       con1  = u.intcon[1];
3640       u.con = init;
3641       init0 = u.intcon[0];
3642       init1 = u.intcon[1];
3643     }
3644 
3645     Node* old = nodes[j];
3646     assert(old != NULL, "need the prior store");
3647     intptr_t offset = (j * BytesPerLong);
3648 
3649     bool split = !Matcher::isSimpleConstant64(con);
3650 
3651     if (offset < header_size) {
3652       assert(offset + BytesPerInt >= header_size, "second int counts");
3653       assert(*(jint*)&tiles[j] == 0, "junk in header");
3654       split = true;             // only the second word counts
3655       // Example:  int a[] = { 42 ... }
3656     } else if (con0 == 0 && init0 == -1) {
3657       split = true;             // first word is covered by full inits
3658       // Example:  int a[] = { ... foo(), 42 ... }
3659     } else if (con1 == 0 && init1 == -1) {
3660       split = true;             // second word is covered by full inits
3661       // Example:  int a[] = { ... 42, foo() ... }
3662     }
3663 
3664     // Here's a case where init0 is neither 0 nor -1:
3665     //   byte a[] = { ... 0,0,foo(),0,  0,0,0,42 ... }
3666     // Assuming big-endian memory, init0, init1 are 0x0000FF00, 0x000000FF.
3667     // In this case the tile is not split; it is (jlong)42.
3668     // The big tile is stored down, and then the foo() value is inserted.
3669     // (If there were foo(),foo() instead of foo(),0, init0 would be -1.)
3670 
3671     Node* ctl = old->in(MemNode::Control);
3672     Node* adr = make_raw_address(offset, phase);
3673     const TypePtr* atp = TypeRawPtr::BOTTOM;
3674 
3675     // One or two coalesced stores to plop down.
3676     Node*    st[2];
3677     intptr_t off[2];
3678     int  nst = 0;
3679     if (!split) {
3680       ++new_long;
3681       off[nst] = offset;
3682       st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
3683                                   phase->longcon(con), T_LONG, MemNode::unordered);
3684     } else {
3685       // Omit either if it is a zero.
3686       if (con0 != 0) {
3687         ++new_int;
3688         off[nst]  = offset;
3689         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
3690                                     phase->intcon(con0), T_INT, MemNode::unordered);
3691       }
3692       if (con1 != 0) {
3693         ++new_int;
3694         offset += BytesPerInt;
3695         adr = make_raw_address(offset, phase);
3696         off[nst]  = offset;
3697         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
3698                                     phase->intcon(con1), T_INT, MemNode::unordered);
3699       }
3700     }
3701 
3702     // Insert second store first, then the first before the second.
3703     // Insert each one just before any overlapping non-constant stores.
3704     while (nst > 0) {
3705       Node* st1 = st[--nst];
3706       C->copy_node_notes_to(st1, old);
3707       st1 = phase->transform(st1);
3708       offset = off[nst];
3709       assert(offset >= header_size, "do not smash header");
3710       int ins_idx = captured_store_insertion_point(offset, /*size:*/0, phase);
3711       guarantee(ins_idx != 0, "must re-insert constant store");
3712       if (ins_idx < 0)  ins_idx = -ins_idx;  // never overlap
3713       if (ins_idx > InitializeNode::RawStores && in(ins_idx-1) == zmem)
3714         set_req(--ins_idx, st1);
3715       else
3716         ins_req(ins_idx, st1);
3717     }
3718   }
3719 
3720   if (PrintCompilation && WizardMode)
3721     tty->print_cr("Changed %d/%d subword/long constants into %d/%d int/long",
3722                   old_subword, old_long, new_int, new_long);
3723   if (C->log() != NULL)
3724     C->log()->elem("comment that='%d/%d subword/long to %d/%d int/long'",
3725                    old_subword, old_long, new_int, new_long);
3726 
3727   // Clean up any remaining occurrences of zmem:
3728   remove_extra_zeroes();
3729 }
3730 
3731 // Explore forward from in(start) to find the first fully initialized
3732 // word, and return its offset.  Skip groups of subword stores which
3733 // together initialize full words.  If in(start) is itself part of a
3734 // fully initialized word, return the offset of in(start).  If there
3735 // are no following full-word stores, or if something is fishy, return
3736 // a negative value.
3737 intptr_t InitializeNode::find_next_fullword_store(uint start, PhaseGVN* phase) {
3738   int       int_map = 0;
3739   intptr_t  int_map_off = 0;
3740   const int FULL_MAP = right_n_bits(BytesPerInt);  // the int_map we hope for
3741 
3742   for (uint i = start, limit = req(); i < limit; i++) {
3743     Node* st = in(i);
3744 
3745     intptr_t st_off = get_store_offset(st, phase);
3746     if (st_off < 0)  break;  // return conservative answer
3747 
3748     int st_size = st->as_Store()->memory_size();
3749     if (st_size >= BytesPerInt && (st_off % BytesPerInt) == 0) {
3750       return st_off;            // we found a complete word init
3751     }
3752 
3753     // update the map:
3754 
3755     intptr_t this_int_off = align_size_down(st_off, BytesPerInt);
3756     if (this_int_off != int_map_off) {
3757       // reset the map:
3758       int_map = 0;
3759       int_map_off = this_int_off;
3760     }
3761 
3762     int subword_off = st_off - this_int_off;
3763     int_map |= right_n_bits(st_size) << subword_off;
3764     if ((int_map & FULL_MAP) == FULL_MAP) {
3765       return this_int_off;      // we found a complete word init
3766     }
3767 
3768     // Did this store hit or cross the word boundary?
3769     intptr_t next_int_off = align_size_down(st_off + st_size, BytesPerInt);
3770     if (next_int_off == this_int_off + BytesPerInt) {
3771       // We passed the current int, without fully initializing it.
3772       int_map_off = next_int_off;
3773       int_map >>= BytesPerInt;
3774     } else if (next_int_off > this_int_off + BytesPerInt) {
3775       // We passed the current and next int.
3776       return this_int_off + BytesPerInt;
3777     }
3778   }
3779 
3780   return -1;
3781 }
3782 
3783 
3784 // Called when the associated AllocateNode is expanded into CFG.
3785 // At this point, we may perform additional optimizations.
3786 // Linearize the stores by ascending offset, to make memory
3787 // activity as coherent as possible.
3788 Node* InitializeNode::complete_stores(Node* rawctl, Node* rawmem, Node* rawptr,
3789                                       intptr_t header_size,
3790                                       Node* size_in_bytes,
3791                                       PhaseGVN* phase) {
3792   assert(!is_complete(), "not already complete");
3793   assert(stores_are_sane(phase), "");
3794   assert(allocation() != NULL, "must be present");
3795 
3796   remove_extra_zeroes();
3797 
3798   if (ReduceFieldZeroing || ReduceBulkZeroing)
3799     // reduce instruction count for common initialization patterns
3800     coalesce_subword_stores(header_size, size_in_bytes, phase);
3801 
3802   Node* zmem = zero_memory();   // initially zero memory state
3803   Node* inits = zmem;           // accumulating a linearized chain of inits
3804   #ifdef ASSERT
3805   intptr_t first_offset = allocation()->minimum_header_size();
3806   intptr_t last_init_off = first_offset;  // previous init offset
3807   intptr_t last_init_end = first_offset;  // previous init offset+size
3808   intptr_t last_tile_end = first_offset;  // previous tile offset+size
3809   #endif
3810   intptr_t zeroes_done = header_size;
3811 
3812   bool do_zeroing = true;       // we might give up if inits are very sparse
3813   int  big_init_gaps = 0;       // how many large gaps have we seen?
3814 
3815   if (ZeroTLAB)  do_zeroing = false;
3816   if (!ReduceFieldZeroing && !ReduceBulkZeroing)  do_zeroing = false;
3817 
3818   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
3819     Node* st = in(i);
3820     intptr_t st_off = get_store_offset(st, phase);
3821     if (st_off < 0)
3822       break;                    // unknown junk in the inits
3823     if (st->in(MemNode::Memory) != zmem)
3824       break;                    // complicated store chains somehow in list
3825 
3826     int st_size = st->as_Store()->memory_size();
3827     intptr_t next_init_off = st_off + st_size;
3828 
3829     if (do_zeroing && zeroes_done < next_init_off) {
3830       // See if this store needs a zero before it or under it.
3831       intptr_t zeroes_needed = st_off;
3832 
3833       if (st_size < BytesPerInt) {
3834         // Look for subword stores which only partially initialize words.
3835         // If we find some, we must lay down some word-level zeroes first,
3836         // underneath the subword stores.
3837         //
3838         // Examples:
3839         //   byte[] a = { p,q,r,s }  =>  a[0]=p,a[1]=q,a[2]=r,a[3]=s
3840         //   byte[] a = { x,y,0,0 }  =>  a[0..3] = 0, a[0]=x,a[1]=y
3841         //   byte[] a = { 0,0,z,0 }  =>  a[0..3] = 0, a[2]=z
3842         //
3843         // Note:  coalesce_subword_stores may have already done this,
3844         // if it was prompted by constant non-zero subword initializers.
3845         // But this case can still arise with non-constant stores.
3846 
3847         intptr_t next_full_store = find_next_fullword_store(i, phase);
3848 
3849         // In the examples above:
3850         //   in(i)          p   q   r   s     x   y     z
3851         //   st_off        12  13  14  15    12  13    14
3852         //   st_size        1   1   1   1     1   1     1
3853         //   next_full_s.  12  16  16  16    16  16    16
3854         //   z's_done      12  16  16  16    12  16    12
3855         //   z's_needed    12  16  16  16    16  16    16
3856         //   zsize          0   0   0   0     4   0     4
3857         if (next_full_store < 0) {
3858           // Conservative tack:  Zero to end of current word.
3859           zeroes_needed = align_size_up(zeroes_needed, BytesPerInt);
3860         } else {
3861           // Zero to beginning of next fully initialized word.
3862           // Or, don't zero at all, if we are already in that word.
3863           assert(next_full_store >= zeroes_needed, "must go forward");
3864           assert((next_full_store & (BytesPerInt-1)) == 0, "even boundary");
3865           zeroes_needed = next_full_store;
3866         }
3867       }
3868 
3869       if (zeroes_needed > zeroes_done) {
3870         intptr_t zsize = zeroes_needed - zeroes_done;
3871         // Do some incremental zeroing on rawmem, in parallel with inits.
3872         zeroes_done = align_size_down(zeroes_done, BytesPerInt);
3873         rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
3874                                               zeroes_done, zeroes_needed,
3875                                               phase);
3876         zeroes_done = zeroes_needed;
3877         if (zsize > Matcher::init_array_short_size && ++big_init_gaps > 2)
3878           do_zeroing = false;   // leave the hole, next time
3879       }
3880     }
3881 
3882     // Collect the store and move on:
3883     st->set_req(MemNode::Memory, inits);
3884     inits = st;                 // put it on the linearized chain
3885     set_req(i, zmem);           // unhook from previous position
3886 
3887     if (zeroes_done == st_off)
3888       zeroes_done = next_init_off;
3889 
3890     assert(!do_zeroing || zeroes_done >= next_init_off, "don't miss any");
3891 
3892     #ifdef ASSERT
3893     // Various order invariants.  Weaker than stores_are_sane because
3894     // a large constant tile can be filled in by smaller non-constant stores.
3895     assert(st_off >= last_init_off, "inits do not reverse");
3896     last_init_off = st_off;
3897     const Type* val = NULL;
3898     if (st_size >= BytesPerInt &&
3899         (val = phase->type(st->in(MemNode::ValueIn)))->singleton() &&
3900         (int)val->basic_type() < (int)T_OBJECT) {
3901       assert(st_off >= last_tile_end, "tiles do not overlap");
3902       assert(st_off >= last_init_end, "tiles do not overwrite inits");
3903       last_tile_end = MAX2(last_tile_end, next_init_off);
3904     } else {
3905       intptr_t st_tile_end = align_size_up(next_init_off, BytesPerLong);
3906       assert(st_tile_end >= last_tile_end, "inits stay with tiles");
3907       assert(st_off      >= last_init_end, "inits do not overlap");
3908       last_init_end = next_init_off;  // it's a non-tile
3909     }
3910     #endif //ASSERT
3911   }
3912 
3913   remove_extra_zeroes();        // clear out all the zmems left over
3914   add_req(inits);
3915 
3916   if (!ZeroTLAB) {
3917     // If anything remains to be zeroed, zero it all now.
3918     zeroes_done = align_size_down(zeroes_done, BytesPerInt);
3919     // if it is the last unused 4 bytes of an instance, forget about it
3920     intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, max_jint);
3921     if (zeroes_done + BytesPerLong >= size_limit) {
3922       assert(allocation() != NULL, "");
3923       if (allocation()->Opcode() == Op_Allocate) {
3924         Node* klass_node = allocation()->in(AllocateNode::KlassNode);
3925         ciKlass* k = phase->type(klass_node)->is_klassptr()->klass();
3926         if (zeroes_done == k->layout_helper())
3927           zeroes_done = size_limit;
3928       }
3929     }
3930     if (zeroes_done < size_limit) {
3931       rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
3932                                             zeroes_done, size_in_bytes, phase);
3933     }
3934   }
3935 
3936   set_complete(phase);
3937   return rawmem;
3938 }
3939 
3940 
3941 #ifdef ASSERT
3942 bool InitializeNode::stores_are_sane(PhaseTransform* phase) {
3943   if (is_complete())
3944     return true;                // stores could be anything at this point
3945   assert(allocation() != NULL, "must be present");
3946   intptr_t last_off = allocation()->minimum_header_size();
3947   for (uint i = InitializeNode::RawStores; i < req(); i++) {
3948     Node* st = in(i);
3949     intptr_t st_off = get_store_offset(st, phase);
3950     if (st_off < 0)  continue;  // ignore dead garbage
3951     if (last_off > st_off) {
3952       tty->print_cr("*** bad store offset at %d: " INTX_FORMAT " > " INTX_FORMAT, i, last_off, st_off);
3953       this->dump(2);
3954       assert(false, "ascending store offsets");
3955       return false;
3956     }
3957     last_off = st_off + st->as_Store()->memory_size();
3958   }
3959   return true;
3960 }
3961 #endif //ASSERT
3962 
3963 
3964 
3965 
3966 //============================MergeMemNode=====================================
3967 //
3968 // SEMANTICS OF MEMORY MERGES:  A MergeMem is a memory state assembled from several
3969 // contributing store or call operations.  Each contributor provides the memory
3970 // state for a particular "alias type" (see Compile::alias_type).  For example,
3971 // if a MergeMem has an input X for alias category #6, then any memory reference
3972 // to alias category #6 may use X as its memory state input, as an exact equivalent
3973 // to using the MergeMem as a whole.
3974 //   Load<6>( MergeMem(<6>: X, ...), p ) <==> Load<6>(X,p)
3975 //
3976 // (Here, the <N> notation gives the index of the relevant adr_type.)
3977 //
3978 // In one special case (and more cases in the future), alias categories overlap.
3979 // The special alias category "Bot" (Compile::AliasIdxBot) includes all memory
3980 // states.  Therefore, if a MergeMem has only one contributing input W for Bot,
3981 // it is exactly equivalent to that state W:
3982 //   MergeMem(<Bot>: W) <==> W
3983 //
3984 // Usually, the merge has more than one input.  In that case, where inputs
3985 // overlap (i.e., one is Bot), the narrower alias type determines the memory
3986 // state for that type, and the wider alias type (Bot) fills in everywhere else:
3987 //   Load<5>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<5>(W,p)
3988 //   Load<6>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<6>(X,p)
3989 //
3990 // A merge can take a "wide" memory state as one of its narrow inputs.
3991 // This simply means that the merge observes out only the relevant parts of
3992 // the wide input.  That is, wide memory states arriving at narrow merge inputs
3993 // are implicitly "filtered" or "sliced" as necessary.  (This is rare.)
3994 //
3995 // These rules imply that MergeMem nodes may cascade (via their <Bot> links),
3996 // and that memory slices "leak through":
3997 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y)) <==> MergeMem(<Bot>: W, <7>: Y)
3998 //
3999 // But, in such a cascade, repeated memory slices can "block the leak":
4000 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y), <7>: Y') <==> MergeMem(<Bot>: W, <7>: Y')
4001 //
4002 // In the last example, Y is not part of the combined memory state of the
4003 // outermost MergeMem.  The system must, of course, prevent unschedulable
4004 // memory states from arising, so you can be sure that the state Y is somehow
4005 // a precursor to state Y'.
4006 //
4007 //
4008 // REPRESENTATION OF MEMORY MERGES: The indexes used to address the Node::in array
4009 // of each MergeMemNode array are exactly the numerical alias indexes, including
4010 // but not limited to AliasIdxTop, AliasIdxBot, and AliasIdxRaw.  The functions
4011 // Compile::alias_type (and kin) produce and manage these indexes.
4012 //
4013 // By convention, the value of in(AliasIdxTop) (i.e., in(1)) is always the top node.
4014 // (Note that this provides quick access to the top node inside MergeMem methods,
4015 // without the need to reach out via TLS to Compile::current.)
4016 //
4017 // As a consequence of what was just described, a MergeMem that represents a full
4018 // memory state has an edge in(AliasIdxBot) which is a "wide" memory state,
4019 // containing all alias categories.
4020 //
4021 // MergeMem nodes never (?) have control inputs, so in(0) is NULL.
4022 //
4023 // All other edges in(N) (including in(AliasIdxRaw), which is in(3)) are either
4024 // a memory state for the alias type <N>, or else the top node, meaning that
4025 // there is no particular input for that alias type.  Note that the length of
4026 // a MergeMem is variable, and may be extended at any time to accommodate new
4027 // memory states at larger alias indexes.  When merges grow, they are of course
4028 // filled with "top" in the unused in() positions.
4029 //
4030 // This use of top is named "empty_memory()", or "empty_mem" (no-memory) as a variable.
4031 // (Top was chosen because it works smoothly with passes like GCM.)
4032 //
4033 // For convenience, we hardwire the alias index for TypeRawPtr::BOTTOM.  (It is
4034 // the type of random VM bits like TLS references.)  Since it is always the
4035 // first non-Bot memory slice, some low-level loops use it to initialize an
4036 // index variable:  for (i = AliasIdxRaw; i < req(); i++).
4037 //
4038 //
4039 // ACCESSORS:  There is a special accessor MergeMemNode::base_memory which returns
4040 // the distinguished "wide" state.  The accessor MergeMemNode::memory_at(N) returns
4041 // the memory state for alias type <N>, or (if there is no particular slice at <N>,
4042 // it returns the base memory.  To prevent bugs, memory_at does not accept <Top>
4043 // or <Bot> indexes.  The iterator MergeMemStream provides robust iteration over
4044 // MergeMem nodes or pairs of such nodes, ensuring that the non-top edges are visited.
4045 //
4046 // %%%% We may get rid of base_memory as a separate accessor at some point; it isn't
4047 // really that different from the other memory inputs.  An abbreviation called
4048 // "bot_memory()" for "memory_at(AliasIdxBot)" would keep code tidy.
4049 //
4050 //
4051 // PARTIAL MEMORY STATES:  During optimization, MergeMem nodes may arise that represent
4052 // partial memory states.  When a Phi splits through a MergeMem, the copy of the Phi
4053 // that "emerges though" the base memory will be marked as excluding the alias types
4054 // of the other (narrow-memory) copies which "emerged through" the narrow edges:
4055 //
4056 //   Phi<Bot>(U, MergeMem(<Bot>: W, <8>: Y))
4057 //     ==Ideal=>  MergeMem(<Bot>: Phi<Bot-8>(U, W), Phi<8>(U, Y))
4058 //
4059 // This strange "subtraction" effect is necessary to ensure IGVN convergence.
4060 // (It is currently unimplemented.)  As you can see, the resulting merge is
4061 // actually a disjoint union of memory states, rather than an overlay.
4062 //
4063 
4064 //------------------------------MergeMemNode-----------------------------------
4065 Node* MergeMemNode::make_empty_memory() {
4066   Node* empty_memory = (Node*) Compile::current()->top();
4067   assert(empty_memory->is_top(), "correct sentinel identity");
4068   return empty_memory;
4069 }
4070 
4071 MergeMemNode::MergeMemNode(Node *new_base) : Node(1+Compile::AliasIdxRaw) {
4072   init_class_id(Class_MergeMem);
4073   // all inputs are nullified in Node::Node(int)
4074   // set_input(0, NULL);  // no control input
4075 
4076   // Initialize the edges uniformly to top, for starters.
4077   Node* empty_mem = make_empty_memory();
4078   for (uint i = Compile::AliasIdxTop; i < req(); i++) {
4079     init_req(i,empty_mem);
4080   }
4081   assert(empty_memory() == empty_mem, "");
4082 
4083   if( new_base != NULL && new_base->is_MergeMem() ) {
4084     MergeMemNode* mdef = new_base->as_MergeMem();
4085     assert(mdef->empty_memory() == empty_mem, "consistent sentinels");
4086     for (MergeMemStream mms(this, mdef); mms.next_non_empty2(); ) {
4087       mms.set_memory(mms.memory2());
4088     }
4089     assert(base_memory() == mdef->base_memory(), "");
4090   } else {
4091     set_base_memory(new_base);
4092   }
4093 }
4094 
4095 // Make a new, untransformed MergeMem with the same base as 'mem'.
4096 // If mem is itself a MergeMem, populate the result with the same edges.
4097 MergeMemNode* MergeMemNode::make(Node* mem) {
4098   return new MergeMemNode(mem);
4099 }
4100 
4101 //------------------------------cmp--------------------------------------------
4102 uint MergeMemNode::hash() const { return NO_HASH; }
4103 uint MergeMemNode::cmp( const Node &n ) const {
4104   return (&n == this);          // Always fail except on self
4105 }
4106 
4107 //------------------------------Identity---------------------------------------
4108 Node* MergeMemNode::Identity(PhaseTransform *phase) {
4109   // Identity if this merge point does not record any interesting memory
4110   // disambiguations.
4111   Node* base_mem = base_memory();
4112   Node* empty_mem = empty_memory();
4113   if (base_mem != empty_mem) {  // Memory path is not dead?
4114     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4115       Node* mem = in(i);
4116       if (mem != empty_mem && mem != base_mem) {
4117         return this;            // Many memory splits; no change
4118       }
4119     }
4120   }
4121   return base_mem;              // No memory splits; ID on the one true input
4122 }
4123 
4124 //------------------------------Ideal------------------------------------------
4125 // This method is invoked recursively on chains of MergeMem nodes
4126 Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) {
4127   // Remove chain'd MergeMems
4128   //
4129   // This is delicate, because the each "in(i)" (i >= Raw) is interpreted
4130   // relative to the "in(Bot)".  Since we are patching both at the same time,
4131   // we have to be careful to read each "in(i)" relative to the old "in(Bot)",
4132   // but rewrite each "in(i)" relative to the new "in(Bot)".
4133   Node *progress = NULL;
4134 
4135 
4136   Node* old_base = base_memory();
4137   Node* empty_mem = empty_memory();
4138   if (old_base == empty_mem)
4139     return NULL; // Dead memory path.
4140 
4141   MergeMemNode* old_mbase;
4142   if (old_base != NULL && old_base->is_MergeMem())
4143     old_mbase = old_base->as_MergeMem();
4144   else
4145     old_mbase = NULL;
4146   Node* new_base = old_base;
4147 
4148   // simplify stacked MergeMems in base memory
4149   if (old_mbase)  new_base = old_mbase->base_memory();
4150 
4151   // the base memory might contribute new slices beyond my req()
4152   if (old_mbase)  grow_to_match(old_mbase);
4153 
4154   // Look carefully at the base node if it is a phi.
4155   PhiNode* phi_base;
4156   if (new_base != NULL && new_base->is_Phi())
4157     phi_base = new_base->as_Phi();
4158   else
4159     phi_base = NULL;
4160 
4161   Node*    phi_reg = NULL;
4162   uint     phi_len = (uint)-1;
4163   if (phi_base != NULL && !phi_base->is_copy()) {
4164     // do not examine phi if degraded to a copy
4165     phi_reg = phi_base->region();
4166     phi_len = phi_base->req();
4167     // see if the phi is unfinished
4168     for (uint i = 1; i < phi_len; i++) {
4169       if (phi_base->in(i) == NULL) {
4170         // incomplete phi; do not look at it yet!
4171         phi_reg = NULL;
4172         phi_len = (uint)-1;
4173         break;
4174       }
4175     }
4176   }
4177 
4178   // Note:  We do not call verify_sparse on entry, because inputs
4179   // can normalize to the base_memory via subsume_node or similar
4180   // mechanisms.  This method repairs that damage.
4181 
4182   assert(!old_mbase || old_mbase->is_empty_memory(empty_mem), "consistent sentinels");
4183 
4184   // Look at each slice.
4185   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4186     Node* old_in = in(i);
4187     // calculate the old memory value
4188     Node* old_mem = old_in;
4189     if (old_mem == empty_mem)  old_mem = old_base;
4190     assert(old_mem == memory_at(i), "");
4191 
4192     // maybe update (reslice) the old memory value
4193 
4194     // simplify stacked MergeMems
4195     Node* new_mem = old_mem;
4196     MergeMemNode* old_mmem;
4197     if (old_mem != NULL && old_mem->is_MergeMem())
4198       old_mmem = old_mem->as_MergeMem();
4199     else
4200       old_mmem = NULL;
4201     if (old_mmem == this) {
4202       // This can happen if loops break up and safepoints disappear.
4203       // A merge of BotPtr (default) with a RawPtr memory derived from a
4204       // safepoint can be rewritten to a merge of the same BotPtr with
4205       // the BotPtr phi coming into the loop.  If that phi disappears
4206       // also, we can end up with a self-loop of the mergemem.
4207       // In general, if loops degenerate and memory effects disappear,
4208       // a mergemem can be left looking at itself.  This simply means
4209       // that the mergemem's default should be used, since there is
4210       // no longer any apparent effect on this slice.
4211       // Note: If a memory slice is a MergeMem cycle, it is unreachable
4212       //       from start.  Update the input to TOP.
4213       new_mem = (new_base == this || new_base == empty_mem)? empty_mem : new_base;
4214     }
4215     else if (old_mmem != NULL) {
4216       new_mem = old_mmem->memory_at(i);
4217     }
4218     // else preceding memory was not a MergeMem
4219 
4220     // replace equivalent phis (unfortunately, they do not GVN together)
4221     if (new_mem != NULL && new_mem != new_base &&
4222         new_mem->req() == phi_len && new_mem->in(0) == phi_reg) {
4223       if (new_mem->is_Phi()) {
4224         PhiNode* phi_mem = new_mem->as_Phi();
4225         for (uint i = 1; i < phi_len; i++) {
4226           if (phi_base->in(i) != phi_mem->in(i)) {
4227             phi_mem = NULL;
4228             break;
4229           }
4230         }
4231         if (phi_mem != NULL) {
4232           // equivalent phi nodes; revert to the def
4233           new_mem = new_base;
4234         }
4235       }
4236     }
4237 
4238     // maybe store down a new value
4239     Node* new_in = new_mem;
4240     if (new_in == new_base)  new_in = empty_mem;
4241 
4242     if (new_in != old_in) {
4243       // Warning:  Do not combine this "if" with the previous "if"
4244       // A memory slice might have be be rewritten even if it is semantically
4245       // unchanged, if the base_memory value has changed.
4246       set_req(i, new_in);
4247       progress = this;          // Report progress
4248     }
4249   }
4250 
4251   if (new_base != old_base) {
4252     set_req(Compile::AliasIdxBot, new_base);
4253     // Don't use set_base_memory(new_base), because we need to update du.
4254     assert(base_memory() == new_base, "");
4255     progress = this;
4256   }
4257 
4258   if( base_memory() == this ) {
4259     // a self cycle indicates this memory path is dead
4260     set_req(Compile::AliasIdxBot, empty_mem);
4261   }
4262 
4263   // Resolve external cycles by calling Ideal on a MergeMem base_memory
4264   // Recursion must occur after the self cycle check above
4265   if( base_memory()->is_MergeMem() ) {
4266     MergeMemNode *new_mbase = base_memory()->as_MergeMem();
4267     Node *m = phase->transform(new_mbase);  // Rollup any cycles
4268     if( m != NULL && (m->is_top() ||
4269         m->is_MergeMem() && m->as_MergeMem()->base_memory() == empty_mem) ) {
4270       // propagate rollup of dead cycle to self
4271       set_req(Compile::AliasIdxBot, empty_mem);
4272     }
4273   }
4274 
4275   if( base_memory() == empty_mem ) {
4276     progress = this;
4277     // Cut inputs during Parse phase only.
4278     // During Optimize phase a dead MergeMem node will be subsumed by Top.
4279     if( !can_reshape ) {
4280       for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4281         if( in(i) != empty_mem ) { set_req(i, empty_mem); }
4282       }
4283     }
4284   }
4285 
4286   if( !progress && base_memory()->is_Phi() && can_reshape ) {
4287     // Check if PhiNode::Ideal's "Split phis through memory merges"
4288     // transform should be attempted. Look for this->phi->this cycle.
4289     uint merge_width = req();
4290     if (merge_width > Compile::AliasIdxRaw) {
4291       PhiNode* phi = base_memory()->as_Phi();
4292       for( uint i = 1; i < phi->req(); ++i ) {// For all paths in
4293         if (phi->in(i) == this) {
4294           phase->is_IterGVN()->_worklist.push(phi);
4295           break;
4296         }
4297       }
4298     }
4299   }
4300 
4301   assert(progress || verify_sparse(), "please, no dups of base");
4302   return progress;
4303 }
4304 
4305 //-------------------------set_base_memory-------------------------------------
4306 void MergeMemNode::set_base_memory(Node *new_base) {
4307   Node* empty_mem = empty_memory();
4308   set_req(Compile::AliasIdxBot, new_base);
4309   assert(memory_at(req()) == new_base, "must set default memory");
4310   // Clear out other occurrences of new_base:
4311   if (new_base != empty_mem) {
4312     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4313       if (in(i) == new_base)  set_req(i, empty_mem);
4314     }
4315   }
4316 }
4317 
4318 //------------------------------out_RegMask------------------------------------
4319 const RegMask &MergeMemNode::out_RegMask() const {
4320   return RegMask::Empty;
4321 }
4322 
4323 //------------------------------dump_spec--------------------------------------
4324 #ifndef PRODUCT
4325 void MergeMemNode::dump_spec(outputStream *st) const {
4326   st->print(" {");
4327   Node* base_mem = base_memory();
4328   for( uint i = Compile::AliasIdxRaw; i < req(); i++ ) {
4329     Node* mem = (in(i) != NULL) ? memory_at(i) : base_mem;
4330     if (mem == base_mem) { st->print(" -"); continue; }
4331     st->print( " N%d:", mem->_idx );
4332     Compile::current()->get_adr_type(i)->dump_on(st);
4333   }
4334   st->print(" }");
4335 }
4336 #endif // !PRODUCT
4337 
4338 
4339 #ifdef ASSERT
4340 static bool might_be_same(Node* a, Node* b) {
4341   if (a == b)  return true;
4342   if (!(a->is_Phi() || b->is_Phi()))  return false;
4343   // phis shift around during optimization
4344   return true;  // pretty stupid...
4345 }
4346 
4347 // verify a narrow slice (either incoming or outgoing)
4348 static void verify_memory_slice(const MergeMemNode* m, int alias_idx, Node* n) {
4349   if (!VerifyAliases)       return;  // don't bother to verify unless requested
4350   if (is_error_reported())  return;  // muzzle asserts when debugging an error
4351   if (Node::in_dump())      return;  // muzzle asserts when printing
4352   assert(alias_idx >= Compile::AliasIdxRaw, "must not disturb base_memory or sentinel");
4353   assert(n != NULL, "");
4354   // Elide intervening MergeMem's
4355   while (n->is_MergeMem()) {
4356     n = n->as_MergeMem()->memory_at(alias_idx);
4357   }
4358   Compile* C = Compile::current();
4359   const TypePtr* n_adr_type = n->adr_type();
4360   if (n == m->empty_memory()) {
4361     // Implicit copy of base_memory()
4362   } else if (n_adr_type != TypePtr::BOTTOM) {
4363     assert(n_adr_type != NULL, "new memory must have a well-defined adr_type");
4364     assert(C->must_alias(n_adr_type, alias_idx), "new memory must match selected slice");
4365   } else {
4366     // A few places like make_runtime_call "know" that VM calls are narrow,
4367     // and can be used to update only the VM bits stored as TypeRawPtr::BOTTOM.
4368     bool expected_wide_mem = false;
4369     if (n == m->base_memory()) {
4370       expected_wide_mem = true;
4371     } else if (alias_idx == Compile::AliasIdxRaw ||
4372                n == m->memory_at(Compile::AliasIdxRaw)) {
4373       expected_wide_mem = true;
4374     } else if (!C->alias_type(alias_idx)->is_rewritable()) {
4375       // memory can "leak through" calls on channels that
4376       // are write-once.  Allow this also.
4377       expected_wide_mem = true;
4378     }
4379     assert(expected_wide_mem, "expected narrow slice replacement");
4380   }
4381 }
4382 #else // !ASSERT
4383 #define verify_memory_slice(m,i,n) (void)(0)  // PRODUCT version is no-op
4384 #endif
4385 
4386 
4387 //-----------------------------memory_at---------------------------------------
4388 Node* MergeMemNode::memory_at(uint alias_idx) const {
4389   assert(alias_idx >= Compile::AliasIdxRaw ||
4390          alias_idx == Compile::AliasIdxBot && Compile::current()->AliasLevel() == 0,
4391          "must avoid base_memory and AliasIdxTop");
4392 
4393   // Otherwise, it is a narrow slice.
4394   Node* n = alias_idx < req() ? in(alias_idx) : empty_memory();
4395   Compile *C = Compile::current();
4396   if (is_empty_memory(n)) {
4397     // the array is sparse; empty slots are the "top" node
4398     n = base_memory();
4399     assert(Node::in_dump()
4400            || n == NULL || n->bottom_type() == Type::TOP
4401            || n->adr_type() == NULL // address is TOP
4402            || n->adr_type() == TypePtr::BOTTOM
4403            || n->adr_type() == TypeRawPtr::BOTTOM
4404            || Compile::current()->AliasLevel() == 0,
4405            "must be a wide memory");
4406     // AliasLevel == 0 if we are organizing the memory states manually.
4407     // See verify_memory_slice for comments on TypeRawPtr::BOTTOM.
4408   } else {
4409     // make sure the stored slice is sane
4410     #ifdef ASSERT
4411     if (is_error_reported() || Node::in_dump()) {
4412     } else if (might_be_same(n, base_memory())) {
4413       // Give it a pass:  It is a mostly harmless repetition of the base.
4414       // This can arise normally from node subsumption during optimization.
4415     } else {
4416       verify_memory_slice(this, alias_idx, n);
4417     }
4418     #endif
4419   }
4420   return n;
4421 }
4422 
4423 //---------------------------set_memory_at-------------------------------------
4424 void MergeMemNode::set_memory_at(uint alias_idx, Node *n) {
4425   verify_memory_slice(this, alias_idx, n);
4426   Node* empty_mem = empty_memory();
4427   if (n == base_memory())  n = empty_mem;  // collapse default
4428   uint need_req = alias_idx+1;
4429   if (req() < need_req) {
4430     if (n == empty_mem)  return;  // already the default, so do not grow me
4431     // grow the sparse array
4432     do {
4433       add_req(empty_mem);
4434     } while (req() < need_req);
4435   }
4436   set_req( alias_idx, n );
4437 }
4438 
4439 
4440 
4441 //--------------------------iteration_setup------------------------------------
4442 void MergeMemNode::iteration_setup(const MergeMemNode* other) {
4443   if (other != NULL) {
4444     grow_to_match(other);
4445     // invariant:  the finite support of mm2 is within mm->req()
4446     #ifdef ASSERT
4447     for (uint i = req(); i < other->req(); i++) {
4448       assert(other->is_empty_memory(other->in(i)), "slice left uncovered");
4449     }
4450     #endif
4451   }
4452   // Replace spurious copies of base_memory by top.
4453   Node* base_mem = base_memory();
4454   if (base_mem != NULL && !base_mem->is_top()) {
4455     for (uint i = Compile::AliasIdxBot+1, imax = req(); i < imax; i++) {
4456       if (in(i) == base_mem)
4457         set_req(i, empty_memory());
4458     }
4459   }
4460 }
4461 
4462 //---------------------------grow_to_match-------------------------------------
4463 void MergeMemNode::grow_to_match(const MergeMemNode* other) {
4464   Node* empty_mem = empty_memory();
4465   assert(other->is_empty_memory(empty_mem), "consistent sentinels");
4466   // look for the finite support of the other memory
4467   for (uint i = other->req(); --i >= req(); ) {
4468     if (other->in(i) != empty_mem) {
4469       uint new_len = i+1;
4470       while (req() < new_len)  add_req(empty_mem);
4471       break;
4472     }
4473   }
4474 }
4475 
4476 //---------------------------verify_sparse-------------------------------------
4477 #ifndef PRODUCT
4478 bool MergeMemNode::verify_sparse() const {
4479   assert(is_empty_memory(make_empty_memory()), "sane sentinel");
4480   Node* base_mem = base_memory();
4481   // The following can happen in degenerate cases, since empty==top.
4482   if (is_empty_memory(base_mem))  return true;
4483   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4484     assert(in(i) != NULL, "sane slice");
4485     if (in(i) == base_mem)  return false;  // should have been the sentinel value!
4486   }
4487   return true;
4488 }
4489 
4490 bool MergeMemStream::match_memory(Node* mem, const MergeMemNode* mm, int idx) {
4491   Node* n;
4492   n = mm->in(idx);
4493   if (mem == n)  return true;  // might be empty_memory()
4494   n = (idx == Compile::AliasIdxBot)? mm->base_memory(): mm->memory_at(idx);
4495   if (mem == n)  return true;
4496   while (n->is_Phi() && (n = n->as_Phi()->is_copy()) != NULL) {
4497     if (mem == n)  return true;
4498     if (n == NULL)  break;
4499   }
4500   return false;
4501 }
4502 #endif // !PRODUCT