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