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