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