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