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