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