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