1 /*
   2  * Copyright (c) 1997, 2024, 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->isa_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(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(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));
 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);
 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),
 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 uint8_t MemNode::barrier_data(const Node* n) {
 843   if (n->is_LoadStore()) {
 844     return n->as_LoadStore()->barrier_data();
 845   } else if (n->is_Mem()) {
 846     return n->as_Mem()->barrier_data();
 847   }
 848   return 0;
 849 }
 850 
 851 //=============================================================================
 852 // Should LoadNode::Ideal() attempt to remove control edges?
 853 bool LoadNode::can_remove_control() const {
 854   return !has_pinned_control_dependency();
 855 }
 856 uint LoadNode::size_of() const { return sizeof(*this); }
 857 bool LoadNode::cmp(const Node &n) const {
 858   LoadNode& load = (LoadNode &)n;
 859   return Type::equals(_type, load._type) &&
 860          _control_dependency == load._control_dependency &&
 861          _mo == load._mo;
 862 }
 863 const Type *LoadNode::bottom_type() const { return _type; }
 864 uint LoadNode::ideal_reg() const {
 865   return _type->ideal_reg();
 866 }
 867 
 868 #ifndef PRODUCT
 869 void LoadNode::dump_spec(outputStream *st) const {
 870   MemNode::dump_spec(st);
 871   if( !Verbose && !WizardMode ) {
 872     // standard dump does this in Verbose and WizardMode
 873     st->print(" #"); _type->dump_on(st);
 874   }
 875   if (!depends_only_on_test()) {
 876     st->print(" (does not depend only on test, ");
 877     if (control_dependency() == UnknownControl) {
 878       st->print("unknown control");
 879     } else if (control_dependency() == Pinned) {
 880       st->print("pinned");
 881     } else if (adr_type() == TypeRawPtr::BOTTOM) {
 882       st->print("raw access");
 883     } else {
 884       st->print("unknown reason");
 885     }
 886     st->print(")");
 887   }
 888 }
 889 #endif
 890 
 891 #ifdef ASSERT
 892 //----------------------------is_immutable_value-------------------------------
 893 // Helper function to allow a raw load without control edge for some cases
 894 bool LoadNode::is_immutable_value(Node* adr) {
 895   if (adr->is_AddP() && adr->in(AddPNode::Base)->is_top() &&
 896       adr->in(AddPNode::Address)->Opcode() == Op_ThreadLocal) {
 897 
 898     jlong offset = adr->in(AddPNode::Offset)->find_intptr_t_con(-1);
 899     int offsets[] = {
 900       in_bytes(JavaThread::osthread_offset()),
 901       in_bytes(JavaThread::threadObj_offset()),
 902       in_bytes(JavaThread::vthread_offset()),
 903       in_bytes(JavaThread::scopedValueCache_offset()),
 904     };
 905 
 906     for (size_t i = 0; i < sizeof offsets / sizeof offsets[0]; i++) {
 907       if (offset == offsets[i]) {
 908         return true;
 909       }
 910     }
 911   }
 912 
 913   return false;
 914 }
 915 #endif
 916 
 917 //----------------------------LoadNode::make-----------------------------------
 918 // Polymorphic factory method:
 919 Node* LoadNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, BasicType bt, MemOrd mo,
 920                      ControlDependency control_dependency, bool require_atomic_access, bool unaligned, bool mismatched, bool unsafe, uint8_t barrier_data) {
 921   Compile* C = gvn.C;
 922 
 923   // sanity check the alias category against the created node type
 924   assert(!(adr_type->isa_oopptr() &&
 925            adr_type->offset() == oopDesc::klass_offset_in_bytes()),
 926          "use LoadKlassNode instead");
 927   assert(!(adr_type->isa_aryptr() &&
 928            adr_type->offset() == arrayOopDesc::length_offset_in_bytes()),
 929          "use LoadRangeNode instead");
 930   // Check control edge of raw loads
 931   assert( ctl != nullptr || C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
 932           // oop will be recorded in oop map if load crosses safepoint
 933           rt->isa_oopptr() || is_immutable_value(adr),
 934           "raw memory operations should have control edge");
 935   LoadNode* load = nullptr;
 936   switch (bt) {
 937   case T_BOOLEAN: load = new LoadUBNode(ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 938   case T_BYTE:    load = new LoadBNode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 939   case T_INT:     load = new LoadINode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 940   case T_CHAR:    load = new LoadUSNode(ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 941   case T_SHORT:   load = new LoadSNode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 942   case T_LONG:    load = new LoadLNode (ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency, require_atomic_access); break;
 943   case T_FLOAT:   load = new LoadFNode (ctl, mem, adr, adr_type, rt,            mo, control_dependency); break;
 944   case T_DOUBLE:  load = new LoadDNode (ctl, mem, adr, adr_type, rt,            mo, control_dependency, require_atomic_access); break;
 945   case T_ADDRESS: load = new LoadPNode (ctl, mem, adr, adr_type, rt->is_ptr(),  mo, control_dependency); break;
 946   case T_OBJECT:
 947   case T_NARROWOOP:
 948 #ifdef _LP64
 949     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 950       load = new LoadNNode(ctl, mem, adr, adr_type, rt->make_narrowoop(), mo, control_dependency);
 951     } else
 952 #endif
 953     {
 954       assert(!adr->bottom_type()->is_ptr_to_narrowoop() && !adr->bottom_type()->is_ptr_to_narrowklass(), "should have got back a narrow oop");
 955       load = new LoadPNode(ctl, mem, adr, adr_type, rt->is_ptr(), mo, control_dependency);
 956     }
 957     break;
 958   default:
 959     ShouldNotReachHere();
 960     break;
 961   }
 962   assert(load != nullptr, "LoadNode should have been created");
 963   if (unaligned) {
 964     load->set_unaligned_access();
 965   }
 966   if (mismatched) {
 967     load->set_mismatched_access();
 968   }
 969   if (unsafe) {
 970     load->set_unsafe_access();
 971   }
 972   load->set_barrier_data(barrier_data);
 973   if (load->Opcode() == Op_LoadN) {
 974     Node* ld = gvn.transform(load);
 975     return new DecodeNNode(ld, ld->bottom_type()->make_ptr());
 976   }
 977 
 978   return load;
 979 }
 980 
 981 //------------------------------hash-------------------------------------------
 982 uint LoadNode::hash() const {
 983   // unroll addition of interesting fields
 984   return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address);
 985 }
 986 
 987 static bool skip_through_membars(Compile::AliasType* atp, const TypeInstPtr* tp, bool eliminate_boxing) {
 988   if ((atp != nullptr) && (atp->index() >= Compile::AliasIdxRaw)) {
 989     bool non_volatile = (atp->field() != nullptr) && !atp->field()->is_volatile();
 990     bool is_stable_ary = FoldStableValues &&
 991                          (tp != nullptr) && (tp->isa_aryptr() != nullptr) &&
 992                          tp->isa_aryptr()->is_stable();
 993 
 994     return (eliminate_boxing && non_volatile) || is_stable_ary;
 995   }
 996 
 997   return false;
 998 }
 999 
1000 LoadNode* LoadNode::pin_array_access_node() const {
1001   const TypePtr* adr_type = this->adr_type();
1002   if (adr_type != nullptr && adr_type->isa_aryptr()) {
1003     return clone_pinned();
1004   }
1005   return nullptr;
1006 }
1007 
1008 // Is the value loaded previously stored by an arraycopy? If so return
1009 // a load node that reads from the source array so we may be able to
1010 // optimize out the ArrayCopy node later.
1011 Node* LoadNode::can_see_arraycopy_value(Node* st, PhaseGVN* phase) const {
1012   Node* ld_adr = in(MemNode::Address);
1013   intptr_t ld_off = 0;
1014   AllocateNode* ld_alloc = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off);
1015   Node* ac = find_previous_arraycopy(phase, ld_alloc, st, true);
1016   if (ac != nullptr) {
1017     assert(ac->is_ArrayCopy(), "what kind of node can this be?");
1018 
1019     Node* mem = ac->in(TypeFunc::Memory);
1020     Node* ctl = ac->in(0);
1021     Node* src = ac->in(ArrayCopyNode::Src);
1022 
1023     if (!ac->as_ArrayCopy()->is_clonebasic() && !phase->type(src)->isa_aryptr()) {
1024       return nullptr;
1025     }
1026 
1027     // load depends on the tests that validate the arraycopy
1028     LoadNode* ld = clone_pinned();
1029     Node* addp = in(MemNode::Address)->clone();
1030     if (ac->as_ArrayCopy()->is_clonebasic()) {
1031       assert(ld_alloc != nullptr, "need an alloc");
1032       assert(addp->is_AddP(), "address must be addp");
1033       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1034       assert(bs->step_over_gc_barrier(addp->in(AddPNode::Base)) == bs->step_over_gc_barrier(ac->in(ArrayCopyNode::Dest)), "strange pattern");
1035       assert(bs->step_over_gc_barrier(addp->in(AddPNode::Address)) == bs->step_over_gc_barrier(ac->in(ArrayCopyNode::Dest)), "strange pattern");
1036       addp->set_req(AddPNode::Base, src);
1037       addp->set_req(AddPNode::Address, src);
1038     } else {
1039       assert(ac->as_ArrayCopy()->is_arraycopy_validated() ||
1040              ac->as_ArrayCopy()->is_copyof_validated() ||
1041              ac->as_ArrayCopy()->is_copyofrange_validated(), "only supported cases");
1042       assert(addp->in(AddPNode::Base) == addp->in(AddPNode::Address), "should be");
1043       addp->set_req(AddPNode::Base, src);
1044       addp->set_req(AddPNode::Address, src);
1045 
1046       const TypeAryPtr* ary_t = phase->type(in(MemNode::Address))->isa_aryptr();
1047       BasicType ary_elem = ary_t->isa_aryptr()->elem()->array_element_basic_type();
1048       if (is_reference_type(ary_elem, true)) ary_elem = T_OBJECT;
1049 
1050       uint header = arrayOopDesc::base_offset_in_bytes(ary_elem);
1051       uint shift  = exact_log2(type2aelembytes(ary_elem));
1052 
1053       Node* diff = phase->transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
1054 #ifdef _LP64
1055       diff = phase->transform(new ConvI2LNode(diff));
1056 #endif
1057       diff = phase->transform(new LShiftXNode(diff, phase->intcon(shift)));
1058 
1059       Node* offset = phase->transform(new AddXNode(addp->in(AddPNode::Offset), diff));
1060       addp->set_req(AddPNode::Offset, offset);
1061     }
1062     addp = phase->transform(addp);
1063 #ifdef ASSERT
1064     const TypePtr* adr_type = phase->type(addp)->is_ptr();
1065     ld->_adr_type = adr_type;
1066 #endif
1067     ld->set_req(MemNode::Address, addp);
1068     ld->set_req(0, ctl);
1069     ld->set_req(MemNode::Memory, mem);
1070     return ld;
1071   }
1072   return nullptr;
1073 }
1074 
1075 
1076 //---------------------------can_see_stored_value------------------------------
1077 // This routine exists to make sure this set of tests is done the same
1078 // everywhere.  We need to make a coordinated change: first LoadNode::Ideal
1079 // will change the graph shape in a way which makes memory alive twice at the
1080 // same time (uses the Oracle model of aliasing), then some
1081 // LoadXNode::Identity will fold things back to the equivalence-class model
1082 // of aliasing.
1083 Node* MemNode::can_see_stored_value(Node* st, PhaseValues* phase) const {
1084   Node* ld_adr = in(MemNode::Address);
1085   intptr_t ld_off = 0;
1086   Node* ld_base = AddPNode::Ideal_base_and_offset(ld_adr, phase, ld_off);
1087   Node* ld_alloc = AllocateNode::Ideal_allocation(ld_base);
1088   const TypeInstPtr* tp = phase->type(ld_adr)->isa_instptr();
1089   Compile::AliasType* atp = (tp != nullptr) ? phase->C->alias_type(tp) : nullptr;
1090   // This is more general than load from boxing objects.
1091   if (skip_through_membars(atp, tp, phase->C->eliminate_boxing())) {
1092     uint alias_idx = atp->index();
1093     Node* result = nullptr;
1094     Node* current = st;
1095     // Skip through chains of MemBarNodes checking the MergeMems for
1096     // new states for the slice of this load.  Stop once any other
1097     // kind of node is encountered.  Loads from final memory can skip
1098     // through any kind of MemBar but normal loads shouldn't skip
1099     // through MemBarAcquire since the could allow them to move out of
1100     // a synchronized region. It is not safe to step over MemBarCPUOrder,
1101     // because alias info above them may be inaccurate (e.g., due to
1102     // mixed/mismatched unsafe accesses).
1103     bool is_final_mem = !atp->is_rewritable();
1104     while (current->is_Proj()) {
1105       int opc = current->in(0)->Opcode();
1106       if ((is_final_mem && (opc == Op_MemBarAcquire ||
1107                             opc == Op_MemBarAcquireLock ||
1108                             opc == Op_LoadFence)) ||
1109           opc == Op_MemBarRelease ||
1110           opc == Op_StoreFence ||
1111           opc == Op_MemBarReleaseLock ||
1112           opc == Op_MemBarStoreStore ||
1113           opc == Op_StoreStoreFence) {
1114         Node* mem = current->in(0)->in(TypeFunc::Memory);
1115         if (mem->is_MergeMem()) {
1116           MergeMemNode* merge = mem->as_MergeMem();
1117           Node* new_st = merge->memory_at(alias_idx);
1118           if (new_st == merge->base_memory()) {
1119             // Keep searching
1120             current = new_st;
1121             continue;
1122           }
1123           // Save the new memory state for the slice and fall through
1124           // to exit.
1125           result = new_st;
1126         }
1127       }
1128       break;
1129     }
1130     if (result != nullptr) {
1131       st = result;
1132     }
1133   }
1134 
1135   // Loop around twice in the case Load -> Initialize -> Store.
1136   // (See PhaseIterGVN::add_users_to_worklist, which knows about this case.)
1137   for (int trip = 0; trip <= 1; trip++) {
1138 
1139     if (st->is_Store()) {
1140       Node* st_adr = st->in(MemNode::Address);
1141       if (st_adr != ld_adr) {
1142         // Try harder before giving up. Unify base pointers with casts (e.g., raw/non-raw pointers).
1143         intptr_t st_off = 0;
1144         Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_off);
1145         if (ld_base == nullptr)                                return nullptr;
1146         if (st_base == nullptr)                                return nullptr;
1147         if (!ld_base->eqv_uncast(st_base, /*keep_deps=*/true)) return nullptr;
1148         if (ld_off != st_off)                                  return nullptr;
1149         if (ld_off == Type::OffsetBot)                         return nullptr;
1150         // Same base, same offset.
1151         // Possible improvement for arrays: check index value instead of absolute offset.
1152 
1153         // At this point we have proven something like this setup:
1154         //   B = << base >>
1155         //   L =  LoadQ(AddP(Check/CastPP(B), #Off))
1156         //   S = StoreQ(AddP(             B , #Off), V)
1157         // (Actually, we haven't yet proven the Q's are the same.)
1158         // In other words, we are loading from a casted version of
1159         // the same pointer-and-offset that we stored to.
1160         // Casted version may carry a dependency and it is respected.
1161         // Thus, we are able to replace L by V.
1162       }
1163       // Now prove that we have a LoadQ matched to a StoreQ, for some Q.
1164       if (store_Opcode() != st->Opcode()) {
1165         return nullptr;
1166       }
1167       // LoadVector/StoreVector needs additional check to ensure the types match.
1168       if (st->is_StoreVector()) {
1169         const TypeVect*  in_vt = st->as_StoreVector()->vect_type();
1170         const TypeVect* out_vt = as_LoadVector()->vect_type();
1171         if (in_vt != out_vt) {
1172           return nullptr;
1173         }
1174       }
1175       return st->in(MemNode::ValueIn);
1176     }
1177 
1178     // A load from a freshly-created object always returns zero.
1179     // (This can happen after LoadNode::Ideal resets the load's memory input
1180     // to find_captured_store, which returned InitializeNode::zero_memory.)
1181     if (st->is_Proj() && st->in(0)->is_Allocate() &&
1182         (st->in(0) == ld_alloc) &&
1183         (ld_off >= st->in(0)->as_Allocate()->minimum_header_size())) {
1184       // return a zero value for the load's basic type
1185       // (This is one of the few places where a generic PhaseTransform
1186       // can create new nodes.  Think of it as lazily manifesting
1187       // virtually pre-existing constants.)
1188       if (memory_type() != T_VOID) {
1189         if (ReduceBulkZeroing || find_array_copy_clone(ld_alloc, in(MemNode::Memory)) == nullptr) {
1190           // If ReduceBulkZeroing is disabled, we need to check if the allocation does not belong to an
1191           // ArrayCopyNode clone. If it does, then we cannot assume zero since the initialization is done
1192           // by the ArrayCopyNode.
1193           return phase->zerocon(memory_type());
1194         }
1195       } else {
1196         // TODO: materialize all-zero vector constant
1197         assert(!isa_Load() || as_Load()->type()->isa_vect(), "");
1198       }
1199     }
1200 
1201     // A load from an initialization barrier can match a captured store.
1202     if (st->is_Proj() && st->in(0)->is_Initialize()) {
1203       InitializeNode* init = st->in(0)->as_Initialize();
1204       AllocateNode* alloc = init->allocation();
1205       if ((alloc != nullptr) && (alloc == ld_alloc)) {
1206         // examine a captured store value
1207         st = init->find_captured_store(ld_off, memory_size(), phase);
1208         if (st != nullptr) {
1209           continue;             // take one more trip around
1210         }
1211       }
1212     }
1213 
1214     // Load boxed value from result of valueOf() call is input parameter.
1215     if (this->is_Load() && ld_adr->is_AddP() &&
1216         (tp != nullptr) && tp->is_ptr_to_boxed_value()) {
1217       intptr_t ignore = 0;
1218       Node* base = AddPNode::Ideal_base_and_offset(ld_adr, phase, ignore);
1219       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1220       base = bs->step_over_gc_barrier(base);
1221       if (base != nullptr && base->is_Proj() &&
1222           base->as_Proj()->_con == TypeFunc::Parms &&
1223           base->in(0)->is_CallStaticJava() &&
1224           base->in(0)->as_CallStaticJava()->is_boxing_method()) {
1225         return base->in(0)->in(TypeFunc::Parms);
1226       }
1227     }
1228 
1229     break;
1230   }
1231 
1232   return nullptr;
1233 }
1234 
1235 //----------------------is_instance_field_load_with_local_phi------------------
1236 bool LoadNode::is_instance_field_load_with_local_phi(Node* ctrl) {
1237   if( in(Memory)->is_Phi() && in(Memory)->in(0) == ctrl &&
1238       in(Address)->is_AddP() ) {
1239     const TypeOopPtr* t_oop = in(Address)->bottom_type()->isa_oopptr();
1240     // Only instances and boxed values.
1241     if( t_oop != nullptr &&
1242         (t_oop->is_ptr_to_boxed_value() ||
1243          t_oop->is_known_instance_field()) &&
1244         t_oop->offset() != Type::OffsetBot &&
1245         t_oop->offset() != Type::OffsetTop) {
1246       return true;
1247     }
1248   }
1249   return false;
1250 }
1251 
1252 //------------------------------Identity---------------------------------------
1253 // Loads are identity if previous store is to same address
1254 Node* LoadNode::Identity(PhaseGVN* phase) {
1255   // If the previous store-maker is the right kind of Store, and the store is
1256   // to the same address, then we are equal to the value stored.
1257   Node* mem = in(Memory);
1258   Node* value = can_see_stored_value(mem, phase);
1259   if( value ) {
1260     // byte, short & char stores truncate naturally.
1261     // A load has to load the truncated value which requires
1262     // some sort of masking operation and that requires an
1263     // Ideal call instead of an Identity call.
1264     if (memory_size() < BytesPerInt) {
1265       // If the input to the store does not fit with the load's result type,
1266       // it must be truncated via an Ideal call.
1267       if (!phase->type(value)->higher_equal(phase->type(this)))
1268         return this;
1269     }
1270     // (This works even when value is a Con, but LoadNode::Value
1271     // usually runs first, producing the singleton type of the Con.)
1272     if (!has_pinned_control_dependency() || value->is_Con()) {
1273       return value;
1274     } else {
1275       return this;
1276     }
1277   }
1278 
1279   if (has_pinned_control_dependency()) {
1280     return this;
1281   }
1282   // Search for an existing data phi which was generated before for the same
1283   // instance's field to avoid infinite generation of phis in a loop.
1284   Node *region = mem->in(0);
1285   if (is_instance_field_load_with_local_phi(region)) {
1286     const TypeOopPtr *addr_t = in(Address)->bottom_type()->isa_oopptr();
1287     int this_index  = phase->C->get_alias_index(addr_t);
1288     int this_offset = addr_t->offset();
1289     int this_iid    = addr_t->instance_id();
1290     if (!addr_t->is_known_instance() &&
1291          addr_t->is_ptr_to_boxed_value()) {
1292       // Use _idx of address base (could be Phi node) for boxed values.
1293       intptr_t   ignore = 0;
1294       Node*      base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore);
1295       if (base == nullptr) {
1296         return this;
1297       }
1298       this_iid = base->_idx;
1299     }
1300     const Type* this_type = bottom_type();
1301     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1302       Node* phi = region->fast_out(i);
1303       if (phi->is_Phi() && phi != mem &&
1304           phi->as_Phi()->is_same_inst_field(this_type, (int)mem->_idx, this_iid, this_index, this_offset)) {
1305         return phi;
1306       }
1307     }
1308   }
1309 
1310   return this;
1311 }
1312 
1313 // Construct an equivalent unsigned load.
1314 Node* LoadNode::convert_to_unsigned_load(PhaseGVN& gvn) {
1315   BasicType bt = T_ILLEGAL;
1316   const Type* rt = nullptr;
1317   switch (Opcode()) {
1318     case Op_LoadUB: return this;
1319     case Op_LoadUS: return this;
1320     case Op_LoadB: bt = T_BOOLEAN; rt = TypeInt::UBYTE; break;
1321     case Op_LoadS: bt = T_CHAR;    rt = TypeInt::CHAR;  break;
1322     default:
1323       assert(false, "no unsigned variant: %s", Name());
1324       return nullptr;
1325   }
1326   return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1327                         raw_adr_type(), rt, bt, _mo, _control_dependency,
1328                         false /*require_atomic_access*/, is_unaligned_access(), is_mismatched_access());
1329 }
1330 
1331 // Construct an equivalent signed load.
1332 Node* LoadNode::convert_to_signed_load(PhaseGVN& gvn) {
1333   BasicType bt = T_ILLEGAL;
1334   const Type* rt = nullptr;
1335   switch (Opcode()) {
1336     case Op_LoadUB: bt = T_BYTE;  rt = TypeInt::BYTE;  break;
1337     case Op_LoadUS: bt = T_SHORT; rt = TypeInt::SHORT; break;
1338     case Op_LoadB: // fall through
1339     case Op_LoadS: // fall through
1340     case Op_LoadI: // fall through
1341     case Op_LoadL: return this;
1342     default:
1343       assert(false, "no signed variant: %s", Name());
1344       return nullptr;
1345   }
1346   return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1347                         raw_adr_type(), rt, bt, _mo, _control_dependency,
1348                         false /*require_atomic_access*/, is_unaligned_access(), is_mismatched_access());
1349 }
1350 
1351 bool LoadNode::has_reinterpret_variant(const Type* rt) {
1352   BasicType bt = rt->basic_type();
1353   switch (Opcode()) {
1354     case Op_LoadI: return (bt == T_FLOAT);
1355     case Op_LoadL: return (bt == T_DOUBLE);
1356     case Op_LoadF: return (bt == T_INT);
1357     case Op_LoadD: return (bt == T_LONG);
1358 
1359     default: return false;
1360   }
1361 }
1362 
1363 Node* LoadNode::convert_to_reinterpret_load(PhaseGVN& gvn, const Type* rt) {
1364   BasicType bt = rt->basic_type();
1365   assert(has_reinterpret_variant(rt), "no reinterpret variant: %s %s", Name(), type2name(bt));
1366   bool is_mismatched = is_mismatched_access();
1367   const TypeRawPtr* raw_type = gvn.type(in(MemNode::Memory))->isa_rawptr();
1368   if (raw_type == nullptr) {
1369     is_mismatched = true; // conservatively match all non-raw accesses as mismatched
1370   }
1371   const int op = Opcode();
1372   bool require_atomic_access = (op == Op_LoadL && ((LoadLNode*)this)->require_atomic_access()) ||
1373                                (op == Op_LoadD && ((LoadDNode*)this)->require_atomic_access());
1374   return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1375                         raw_adr_type(), rt, bt, _mo, _control_dependency,
1376                         require_atomic_access, is_unaligned_access(), is_mismatched);
1377 }
1378 
1379 bool StoreNode::has_reinterpret_variant(const Type* vt) {
1380   BasicType bt = vt->basic_type();
1381   switch (Opcode()) {
1382     case Op_StoreI: return (bt == T_FLOAT);
1383     case Op_StoreL: return (bt == T_DOUBLE);
1384     case Op_StoreF: return (bt == T_INT);
1385     case Op_StoreD: return (bt == T_LONG);
1386 
1387     default: return false;
1388   }
1389 }
1390 
1391 Node* StoreNode::convert_to_reinterpret_store(PhaseGVN& gvn, Node* val, const Type* vt) {
1392   BasicType bt = vt->basic_type();
1393   assert(has_reinterpret_variant(vt), "no reinterpret variant: %s %s", Name(), type2name(bt));
1394   const int op = Opcode();
1395   bool require_atomic_access = (op == Op_StoreL && ((StoreLNode*)this)->require_atomic_access()) ||
1396                                (op == Op_StoreD && ((StoreDNode*)this)->require_atomic_access());
1397   StoreNode* st = StoreNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1398                                   raw_adr_type(), val, bt, _mo, require_atomic_access);
1399 
1400   bool is_mismatched = is_mismatched_access();
1401   const TypeRawPtr* raw_type = gvn.type(in(MemNode::Memory))->isa_rawptr();
1402   if (raw_type == nullptr) {
1403     is_mismatched = true; // conservatively match all non-raw accesses as mismatched
1404   }
1405   if (is_mismatched) {
1406     st->set_mismatched_access();
1407   }
1408   return st;
1409 }
1410 
1411 // We're loading from an object which has autobox behaviour.
1412 // If this object is result of a valueOf call we'll have a phi
1413 // merging a newly allocated object and a load from the cache.
1414 // We want to replace this load with the original incoming
1415 // argument to the valueOf call.
1416 Node* LoadNode::eliminate_autobox(PhaseIterGVN* igvn) {
1417   assert(igvn->C->eliminate_boxing(), "sanity");
1418   intptr_t ignore = 0;
1419   Node* base = AddPNode::Ideal_base_and_offset(in(Address), igvn, ignore);
1420   if ((base == nullptr) || base->is_Phi()) {
1421     // Push the loads from the phi that comes from valueOf up
1422     // through it to allow elimination of the loads and the recovery
1423     // of the original value. It is done in split_through_phi().
1424     return nullptr;
1425   } else if (base->is_Load() ||
1426              (base->is_DecodeN() && base->in(1)->is_Load())) {
1427     // Eliminate the load of boxed value for integer types from the cache
1428     // array by deriving the value from the index into the array.
1429     // Capture the offset of the load and then reverse the computation.
1430 
1431     // Get LoadN node which loads a boxing object from 'cache' array.
1432     if (base->is_DecodeN()) {
1433       base = base->in(1);
1434     }
1435     if (!base->in(Address)->is_AddP()) {
1436       return nullptr; // Complex address
1437     }
1438     AddPNode* address = base->in(Address)->as_AddP();
1439     Node* cache_base = address->in(AddPNode::Base);
1440     if ((cache_base != nullptr) && cache_base->is_DecodeN()) {
1441       // Get ConP node which is static 'cache' field.
1442       cache_base = cache_base->in(1);
1443     }
1444     if ((cache_base != nullptr) && cache_base->is_Con()) {
1445       const TypeAryPtr* base_type = cache_base->bottom_type()->isa_aryptr();
1446       if ((base_type != nullptr) && base_type->is_autobox_cache()) {
1447         Node* elements[4];
1448         int shift = exact_log2(type2aelembytes(T_OBJECT));
1449         int count = address->unpack_offsets(elements, ARRAY_SIZE(elements));
1450         if (count > 0 && elements[0]->is_Con() &&
1451             (count == 1 ||
1452              (count == 2 && elements[1]->Opcode() == Op_LShiftX &&
1453                             elements[1]->in(2) == igvn->intcon(shift)))) {
1454           ciObjArray* array = base_type->const_oop()->as_obj_array();
1455           // Fetch the box object cache[0] at the base of the array and get its value
1456           ciInstance* box = array->obj_at(0)->as_instance();
1457           ciInstanceKlass* ik = box->klass()->as_instance_klass();
1458           assert(ik->is_box_klass(), "sanity");
1459           assert(ik->nof_nonstatic_fields() == 1, "change following code");
1460           if (ik->nof_nonstatic_fields() == 1) {
1461             // This should be true nonstatic_field_at requires calling
1462             // nof_nonstatic_fields so check it anyway
1463             ciConstant c = box->field_value(ik->nonstatic_field_at(0));
1464             BasicType bt = c.basic_type();
1465             // Only integer types have boxing cache.
1466             assert(bt == T_BOOLEAN || bt == T_CHAR  ||
1467                    bt == T_BYTE    || bt == T_SHORT ||
1468                    bt == T_INT     || bt == T_LONG, "wrong type = %s", type2name(bt));
1469             jlong cache_low = (bt == T_LONG) ? c.as_long() : c.as_int();
1470             if (cache_low != (int)cache_low) {
1471               return nullptr; // should not happen since cache is array indexed by value
1472             }
1473             jlong offset = arrayOopDesc::base_offset_in_bytes(T_OBJECT) - (cache_low << shift);
1474             if (offset != (int)offset) {
1475               return nullptr; // should not happen since cache is array indexed by value
1476             }
1477            // Add up all the offsets making of the address of the load
1478             Node* result = elements[0];
1479             for (int i = 1; i < count; i++) {
1480               result = igvn->transform(new AddXNode(result, elements[i]));
1481             }
1482             // Remove the constant offset from the address and then
1483             result = igvn->transform(new AddXNode(result, igvn->MakeConX(-(int)offset)));
1484             // remove the scaling of the offset to recover the original index.
1485             if (result->Opcode() == Op_LShiftX && result->in(2) == igvn->intcon(shift)) {
1486               // Peel the shift off directly but wrap it in a dummy node
1487               // since Ideal can't return existing nodes
1488               igvn->_worklist.push(result); // remove dead node later
1489               result = new RShiftXNode(result->in(1), igvn->intcon(0));
1490             } else if (result->is_Add() && result->in(2)->is_Con() &&
1491                        result->in(1)->Opcode() == Op_LShiftX &&
1492                        result->in(1)->in(2) == igvn->intcon(shift)) {
1493               // We can't do general optimization: ((X<<Z) + Y) >> Z ==> X + (Y>>Z)
1494               // but for boxing cache access we know that X<<Z will not overflow
1495               // (there is range check) so we do this optimizatrion by hand here.
1496               igvn->_worklist.push(result); // remove dead node later
1497               Node* add_con = new RShiftXNode(result->in(2), igvn->intcon(shift));
1498               result = new AddXNode(result->in(1)->in(1), igvn->transform(add_con));
1499             } else {
1500               result = new RShiftXNode(result, igvn->intcon(shift));
1501             }
1502 #ifdef _LP64
1503             if (bt != T_LONG) {
1504               result = new ConvL2INode(igvn->transform(result));
1505             }
1506 #else
1507             if (bt == T_LONG) {
1508               result = new ConvI2LNode(igvn->transform(result));
1509             }
1510 #endif
1511             // Boxing/unboxing can be done from signed & unsigned loads (e.g. LoadUB -> ... -> LoadB pair).
1512             // Need to preserve unboxing load type if it is unsigned.
1513             switch(this->Opcode()) {
1514               case Op_LoadUB:
1515                 result = new AndINode(igvn->transform(result), igvn->intcon(0xFF));
1516                 break;
1517               case Op_LoadUS:
1518                 result = new AndINode(igvn->transform(result), igvn->intcon(0xFFFF));
1519                 break;
1520             }
1521             return result;
1522           }
1523         }
1524       }
1525     }
1526   }
1527   return nullptr;
1528 }
1529 
1530 static bool stable_phi(PhiNode* phi, PhaseGVN *phase) {
1531   Node* region = phi->in(0);
1532   if (region == nullptr) {
1533     return false; // Wait stable graph
1534   }
1535   uint cnt = phi->req();
1536   for (uint i = 1; i < cnt; i++) {
1537     Node* rc = region->in(i);
1538     if (rc == nullptr || phase->type(rc) == Type::TOP)
1539       return false; // Wait stable graph
1540     Node* in = phi->in(i);
1541     if (in == nullptr || phase->type(in) == Type::TOP)
1542       return false; // Wait stable graph
1543   }
1544   return true;
1545 }
1546 
1547 //------------------------------split_through_phi------------------------------
1548 // Check whether a call to 'split_through_phi' would split this load through the
1549 // Phi *base*. This method is essentially a copy of the validations performed
1550 // by 'split_through_phi'. The first use of this method was in EA code as part
1551 // of simplification of allocation merges.
1552 // Some differences from original method (split_through_phi):
1553 //  - If base->is_CastPP(): base = base->in(1)
1554 bool LoadNode::can_split_through_phi_base(PhaseGVN* phase) {
1555   Node* mem        = in(Memory);
1556   Node* address    = in(Address);
1557   intptr_t ignore  = 0;
1558   Node*    base    = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1559 
1560   if (base->is_CastPP()) {
1561     base = base->in(1);
1562   }
1563 
1564   if (req() > 3 || base == nullptr || !base->is_Phi()) {
1565     return false;
1566   }
1567 
1568   if (!mem->is_Phi()) {
1569     if (!MemNode::all_controls_dominate(mem, base->in(0)))
1570       return false;
1571   } else if (base->in(0) != mem->in(0)) {
1572     if (!MemNode::all_controls_dominate(mem, base->in(0))) {
1573       return false;
1574     }
1575   }
1576 
1577   return true;
1578 }
1579 
1580 //------------------------------split_through_phi------------------------------
1581 // Split instance or boxed field load through Phi.
1582 Node* LoadNode::split_through_phi(PhaseGVN* phase, bool ignore_missing_instance_id) {
1583   if (req() > 3) {
1584     assert(is_LoadVector() && Opcode() != Op_LoadVector, "load has too many inputs");
1585     // LoadVector subclasses such as LoadVectorMasked have extra inputs that the logic below doesn't take into account
1586     return nullptr;
1587   }
1588   Node* mem     = in(Memory);
1589   Node* address = in(Address);
1590   const TypeOopPtr *t_oop = phase->type(address)->isa_oopptr();
1591 
1592   assert((t_oop != nullptr) &&
1593          (ignore_missing_instance_id ||
1594           t_oop->is_known_instance_field() ||
1595           t_oop->is_ptr_to_boxed_value()), "invalid conditions");
1596 
1597   Compile* C = phase->C;
1598   intptr_t ignore = 0;
1599   Node*    base = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1600   bool base_is_phi = (base != nullptr) && base->is_Phi();
1601   bool load_boxed_values = t_oop->is_ptr_to_boxed_value() && C->aggressive_unboxing() &&
1602                            (base != nullptr) && (base == address->in(AddPNode::Base)) &&
1603                            phase->type(base)->higher_equal(TypePtr::NOTNULL);
1604 
1605   if (!((mem->is_Phi() || base_is_phi) &&
1606         (ignore_missing_instance_id || load_boxed_values || t_oop->is_known_instance_field()))) {
1607     return nullptr; // Neither memory or base are Phi
1608   }
1609 
1610   if (mem->is_Phi()) {
1611     if (!stable_phi(mem->as_Phi(), phase)) {
1612       return nullptr; // Wait stable graph
1613     }
1614     uint cnt = mem->req();
1615     // Check for loop invariant memory.
1616     if (cnt == 3) {
1617       for (uint i = 1; i < cnt; i++) {
1618         Node* in = mem->in(i);
1619         Node*  m = optimize_memory_chain(in, t_oop, this, phase);
1620         if (m == mem) {
1621           if (i == 1) {
1622             // if the first edge was a loop, check second edge too.
1623             // If both are replaceable - we are in an infinite loop
1624             Node *n = optimize_memory_chain(mem->in(2), t_oop, this, phase);
1625             if (n == mem) {
1626               break;
1627             }
1628           }
1629           set_req(Memory, mem->in(cnt - i));
1630           return this; // made change
1631         }
1632       }
1633     }
1634   }
1635   if (base_is_phi) {
1636     if (!stable_phi(base->as_Phi(), phase)) {
1637       return nullptr; // Wait stable graph
1638     }
1639     uint cnt = base->req();
1640     // Check for loop invariant memory.
1641     if (cnt == 3) {
1642       for (uint i = 1; i < cnt; i++) {
1643         if (base->in(i) == base) {
1644           return nullptr; // Wait stable graph
1645         }
1646       }
1647     }
1648   }
1649 
1650   // Split through Phi (see original code in loopopts.cpp).
1651   assert(ignore_missing_instance_id || C->have_alias_type(t_oop), "instance should have alias type");
1652 
1653   // Do nothing here if Identity will find a value
1654   // (to avoid infinite chain of value phis generation).
1655   if (this != Identity(phase)) {
1656     return nullptr;
1657   }
1658 
1659   // Select Region to split through.
1660   Node* region;
1661   if (!base_is_phi) {
1662     assert(mem->is_Phi(), "sanity");
1663     region = mem->in(0);
1664     // Skip if the region dominates some control edge of the address.
1665     if (!MemNode::all_controls_dominate(address, region))
1666       return nullptr;
1667   } else if (!mem->is_Phi()) {
1668     assert(base_is_phi, "sanity");
1669     region = base->in(0);
1670     // Skip if the region dominates some control edge of the memory.
1671     if (!MemNode::all_controls_dominate(mem, region))
1672       return nullptr;
1673   } else if (base->in(0) != mem->in(0)) {
1674     assert(base_is_phi && mem->is_Phi(), "sanity");
1675     if (MemNode::all_controls_dominate(mem, base->in(0))) {
1676       region = base->in(0);
1677     } else if (MemNode::all_controls_dominate(address, mem->in(0))) {
1678       region = mem->in(0);
1679     } else {
1680       return nullptr; // complex graph
1681     }
1682   } else {
1683     assert(base->in(0) == mem->in(0), "sanity");
1684     region = mem->in(0);
1685   }
1686 
1687   Node* phi = nullptr;
1688   const Type* this_type = this->bottom_type();
1689   PhaseIterGVN* igvn = phase->is_IterGVN();
1690   if (t_oop != nullptr && (t_oop->is_known_instance_field() || load_boxed_values)) {
1691     int this_index = C->get_alias_index(t_oop);
1692     int this_offset = t_oop->offset();
1693     int this_iid = t_oop->is_known_instance_field() ? t_oop->instance_id() : base->_idx;
1694     phi = new PhiNode(region, this_type, nullptr, mem->_idx, this_iid, this_index, this_offset);
1695   } else if (ignore_missing_instance_id) {
1696     phi = new PhiNode(region, this_type, nullptr, mem->_idx);
1697   } else {
1698     return nullptr;
1699   }
1700 
1701   for (uint i = 1; i < region->req(); i++) {
1702     Node* x;
1703     Node* the_clone = nullptr;
1704     Node* in = region->in(i);
1705     if (region->is_CountedLoop() && region->as_Loop()->is_strip_mined() && i == LoopNode::EntryControl &&
1706         in != nullptr && in->is_OuterStripMinedLoop()) {
1707       // No node should go in the outer strip mined loop
1708       in = in->in(LoopNode::EntryControl);
1709     }
1710     if (in == nullptr || in == C->top()) {
1711       x = C->top();      // Dead path?  Use a dead data op
1712     } else {
1713       x = this->clone();        // Else clone up the data op
1714       the_clone = x;            // Remember for possible deletion.
1715       // Alter data node to use pre-phi inputs
1716       if (this->in(0) == region) {
1717         x->set_req(0, in);
1718       } else {
1719         x->set_req(0, nullptr);
1720       }
1721       if (mem->is_Phi() && (mem->in(0) == region)) {
1722         x->set_req(Memory, mem->in(i)); // Use pre-Phi input for the clone.
1723       }
1724       if (address->is_Phi() && address->in(0) == region) {
1725         x->set_req(Address, address->in(i)); // Use pre-Phi input for the clone
1726       }
1727       if (base_is_phi && (base->in(0) == region)) {
1728         Node* base_x = base->in(i); // Clone address for loads from boxed objects.
1729         Node* adr_x = phase->transform(new AddPNode(base_x,base_x,address->in(AddPNode::Offset)));
1730         x->set_req(Address, adr_x);
1731       }
1732     }
1733     // Check for a 'win' on some paths
1734     const Type *t = x->Value(igvn);
1735 
1736     bool singleton = t->singleton();
1737 
1738     // See comments in PhaseIdealLoop::split_thru_phi().
1739     if (singleton && t == Type::TOP) {
1740       singleton &= region->is_Loop() && (i != LoopNode::EntryControl);
1741     }
1742 
1743     if (singleton) {
1744       x = igvn->makecon(t);
1745     } else {
1746       // We now call Identity to try to simplify the cloned node.
1747       // Note that some Identity methods call phase->type(this).
1748       // Make sure that the type array is big enough for
1749       // our new node, even though we may throw the node away.
1750       // (This tweaking with igvn only works because x is a new node.)
1751       igvn->set_type(x, t);
1752       // If x is a TypeNode, capture any more-precise type permanently into Node
1753       // otherwise it will be not updated during igvn->transform since
1754       // igvn->type(x) is set to x->Value() already.
1755       x->raise_bottom_type(t);
1756       Node* y = x->Identity(igvn);
1757       if (y != x) {
1758         x = y;
1759       } else {
1760         y = igvn->hash_find_insert(x);
1761         if (y) {
1762           x = y;
1763         } else {
1764           // Else x is a new node we are keeping
1765           // We do not need register_new_node_with_optimizer
1766           // because set_type has already been called.
1767           igvn->_worklist.push(x);
1768         }
1769       }
1770     }
1771     if (x != the_clone && the_clone != nullptr) {
1772       igvn->remove_dead_node(the_clone);
1773     }
1774     phi->set_req(i, x);
1775   }
1776   // Record Phi
1777   igvn->register_new_node_with_optimizer(phi);
1778   return phi;
1779 }
1780 
1781 AllocateNode* LoadNode::is_new_object_mark_load() const {
1782   if (Opcode() == Op_LoadX) {
1783     Node* address = in(MemNode::Address);
1784     AllocateNode* alloc = AllocateNode::Ideal_allocation(address);
1785     Node* mem = in(MemNode::Memory);
1786     if (alloc != nullptr && mem->is_Proj() &&
1787         mem->in(0) != nullptr &&
1788         mem->in(0) == alloc->initialization() &&
1789         alloc->initialization()->proj_out_or_null(0) != nullptr) {
1790       return alloc;
1791     }
1792   }
1793   return nullptr;
1794 }
1795 
1796 
1797 //------------------------------Ideal------------------------------------------
1798 // If the load is from Field memory and the pointer is non-null, it might be possible to
1799 // zero out the control input.
1800 // If the offset is constant and the base is an object allocation,
1801 // try to hook me up to the exact initializing store.
1802 Node *LoadNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1803   if (has_pinned_control_dependency()) {
1804     return nullptr;
1805   }
1806   Node* p = MemNode::Ideal_common(phase, can_reshape);
1807   if (p)  return (p == NodeSentinel) ? nullptr : p;
1808 
1809   Node* ctrl    = in(MemNode::Control);
1810   Node* address = in(MemNode::Address);
1811   bool progress = false;
1812 
1813   bool addr_mark = ((phase->type(address)->isa_oopptr() || phase->type(address)->isa_narrowoop()) &&
1814          phase->type(address)->is_ptr()->offset() == oopDesc::mark_offset_in_bytes());
1815 
1816   // Skip up past a SafePoint control.  Cannot do this for Stores because
1817   // pointer stores & cardmarks must stay on the same side of a SafePoint.
1818   if( ctrl != nullptr && ctrl->Opcode() == Op_SafePoint &&
1819       phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw  &&
1820       !addr_mark &&
1821       (depends_only_on_test() || has_unknown_control_dependency())) {
1822     ctrl = ctrl->in(0);
1823     set_req(MemNode::Control,ctrl);
1824     progress = true;
1825   }
1826 
1827   intptr_t ignore = 0;
1828   Node*    base   = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1829   if (base != nullptr
1830       && phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw) {
1831     // Check for useless control edge in some common special cases
1832     if (in(MemNode::Control) != nullptr
1833         && can_remove_control()
1834         && phase->type(base)->higher_equal(TypePtr::NOTNULL)
1835         && all_controls_dominate(base, phase->C->start())) {
1836       // A method-invariant, non-null address (constant or 'this' argument).
1837       set_req(MemNode::Control, nullptr);
1838       progress = true;
1839     }
1840   }
1841 
1842   Node* mem = in(MemNode::Memory);
1843   const TypePtr *addr_t = phase->type(address)->isa_ptr();
1844 
1845   if (can_reshape && (addr_t != nullptr)) {
1846     // try to optimize our memory input
1847     Node* opt_mem = MemNode::optimize_memory_chain(mem, addr_t, this, phase);
1848     if (opt_mem != mem) {
1849       set_req_X(MemNode::Memory, opt_mem, phase);
1850       if (phase->type( opt_mem ) == Type::TOP) return nullptr;
1851       return this;
1852     }
1853     const TypeOopPtr *t_oop = addr_t->isa_oopptr();
1854     if ((t_oop != nullptr) &&
1855         (t_oop->is_known_instance_field() ||
1856          t_oop->is_ptr_to_boxed_value())) {
1857       PhaseIterGVN *igvn = phase->is_IterGVN();
1858       assert(igvn != nullptr, "must be PhaseIterGVN when can_reshape is true");
1859       if (igvn->_worklist.member(opt_mem)) {
1860         // Delay this transformation until memory Phi is processed.
1861         igvn->_worklist.push(this);
1862         return nullptr;
1863       }
1864       // Split instance field load through Phi.
1865       Node* result = split_through_phi(phase);
1866       if (result != nullptr) return result;
1867 
1868       if (t_oop->is_ptr_to_boxed_value()) {
1869         Node* result = eliminate_autobox(igvn);
1870         if (result != nullptr) return result;
1871       }
1872     }
1873   }
1874 
1875   // Is there a dominating load that loads the same value?  Leave
1876   // anything that is not a load of a field/array element (like
1877   // barriers etc.) alone
1878   if (in(0) != nullptr && !adr_type()->isa_rawptr() && can_reshape) {
1879     for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
1880       Node *use = mem->fast_out(i);
1881       if (use != this &&
1882           use->Opcode() == Opcode() &&
1883           use->in(0) != nullptr &&
1884           use->in(0) != in(0) &&
1885           use->in(Address) == in(Address)) {
1886         Node* ctl = in(0);
1887         for (int i = 0; i < 10 && ctl != nullptr; i++) {
1888           ctl = IfNode::up_one_dom(ctl);
1889           if (ctl == use->in(0)) {
1890             set_req(0, use->in(0));
1891             return this;
1892           }
1893         }
1894       }
1895     }
1896   }
1897 
1898   // Check for prior store with a different base or offset; make Load
1899   // independent.  Skip through any number of them.  Bail out if the stores
1900   // are in an endless dead cycle and report no progress.  This is a key
1901   // transform for Reflection.  However, if after skipping through the Stores
1902   // we can't then fold up against a prior store do NOT do the transform as
1903   // this amounts to using the 'Oracle' model of aliasing.  It leaves the same
1904   // array memory alive twice: once for the hoisted Load and again after the
1905   // bypassed Store.  This situation only works if EVERYBODY who does
1906   // anti-dependence work knows how to bypass.  I.e. we need all
1907   // anti-dependence checks to ask the same Oracle.  Right now, that Oracle is
1908   // the alias index stuff.  So instead, peek through Stores and IFF we can
1909   // fold up, do so.
1910   Node* prev_mem = find_previous_store(phase);
1911   if (prev_mem != nullptr) {
1912     Node* value = can_see_arraycopy_value(prev_mem, phase);
1913     if (value != nullptr) {
1914       return value;
1915     }
1916   }
1917   // Steps (a), (b):  Walk past independent stores to find an exact match.
1918   if (prev_mem != nullptr && prev_mem != in(MemNode::Memory)) {
1919     // (c) See if we can fold up on the spot, but don't fold up here.
1920     // Fold-up might require truncation (for LoadB/LoadS/LoadUS) or
1921     // just return a prior value, which is done by Identity calls.
1922     if (can_see_stored_value(prev_mem, phase)) {
1923       // Make ready for step (d):
1924       set_req_X(MemNode::Memory, prev_mem, phase);
1925       return this;
1926     }
1927   }
1928 
1929   return progress ? this : nullptr;
1930 }
1931 
1932 // Helper to recognize certain Klass fields which are invariant across
1933 // some group of array types (e.g., int[] or all T[] where T < Object).
1934 const Type*
1935 LoadNode::load_array_final_field(const TypeKlassPtr *tkls,
1936                                  ciKlass* klass) const {
1937   if (UseCompactObjectHeaders) {
1938     if (tkls->offset() == in_bytes(Klass::prototype_header_offset())) {
1939       // The field is Klass::_prototype_header.  Return its (constant) value.
1940       assert(this->Opcode() == Op_LoadX, "must load a proper type from _prototype_header");
1941       return TypeX::make(klass->prototype_header());
1942     }
1943   }
1944   if (tkls->offset() == in_bytes(Klass::modifier_flags_offset())) {
1945     // The field is Klass::_modifier_flags.  Return its (constant) value.
1946     // (Folds up the 2nd indirection in aClassConstant.getModifiers().)
1947     assert(this->Opcode() == Op_LoadI, "must load an int from _modifier_flags");
1948     return TypeInt::make(klass->modifier_flags());
1949   }
1950   if (tkls->offset() == in_bytes(Klass::access_flags_offset())) {
1951     // The field is Klass::_access_flags.  Return its (constant) value.
1952     // (Folds up the 2nd indirection in Reflection.getClassAccessFlags(aClassConstant).)
1953     assert(this->Opcode() == Op_LoadI, "must load an int from _access_flags");
1954     return TypeInt::make(klass->access_flags());
1955   }
1956   if (tkls->offset() == in_bytes(Klass::layout_helper_offset())) {
1957     // The field is Klass::_layout_helper.  Return its constant value if known.
1958     assert(this->Opcode() == Op_LoadI, "must load an int from _layout_helper");
1959     return TypeInt::make(klass->layout_helper());
1960   }
1961 
1962   // No match.
1963   return nullptr;
1964 }
1965 
1966 //------------------------------Value-----------------------------------------
1967 const Type* LoadNode::Value(PhaseGVN* phase) const {
1968   // Either input is TOP ==> the result is TOP
1969   Node* mem = in(MemNode::Memory);
1970   const Type *t1 = phase->type(mem);
1971   if (t1 == Type::TOP)  return Type::TOP;
1972   Node* adr = in(MemNode::Address);
1973   const TypePtr* tp = phase->type(adr)->isa_ptr();
1974   if (tp == nullptr || tp->empty())  return Type::TOP;
1975   int off = tp->offset();
1976   assert(off != Type::OffsetTop, "case covered by TypePtr::empty");
1977   Compile* C = phase->C;
1978 
1979   // Try to guess loaded type from pointer type
1980   if (tp->isa_aryptr()) {
1981     const TypeAryPtr* ary = tp->is_aryptr();
1982     const Type* t = ary->elem();
1983 
1984     // Determine whether the reference is beyond the header or not, by comparing
1985     // the offset against the offset of the start of the array's data.
1986     // Different array types begin at slightly different offsets (12 vs. 16).
1987     // We choose T_BYTE as an example base type that is least restrictive
1988     // as to alignment, which will therefore produce the smallest
1989     // possible base offset.
1990     const int min_base_off = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1991     const bool off_beyond_header = (off >= min_base_off);
1992 
1993     // Try to constant-fold a stable array element.
1994     if (FoldStableValues && !is_mismatched_access() && ary->is_stable()) {
1995       // Make sure the reference is not into the header and the offset is constant
1996       ciObject* aobj = ary->const_oop();
1997       if (aobj != nullptr && off_beyond_header && adr->is_AddP() && off != Type::OffsetBot) {
1998         int stable_dimension = (ary->stable_dimension() > 0 ? ary->stable_dimension() - 1 : 0);
1999         const Type* con_type = Type::make_constant_from_array_element(aobj->as_array(), off,
2000                                                                       stable_dimension,
2001                                                                       memory_type(), is_unsigned());
2002         if (con_type != nullptr) {
2003           return con_type;
2004         }
2005       }
2006     }
2007 
2008     // Don't do this for integer types. There is only potential profit if
2009     // the element type t is lower than _type; that is, for int types, if _type is
2010     // more restrictive than t.  This only happens here if one is short and the other
2011     // char (both 16 bits), and in those cases we've made an intentional decision
2012     // to use one kind of load over the other. See AndINode::Ideal and 4965907.
2013     // Also, do not try to narrow the type for a LoadKlass, regardless of offset.
2014     //
2015     // Yes, it is possible to encounter an expression like (LoadKlass p1:(AddP x x 8))
2016     // where the _gvn.type of the AddP is wider than 8.  This occurs when an earlier
2017     // copy p0 of (AddP x x 8) has been proven equal to p1, and the p0 has been
2018     // subsumed by p1.  If p1 is on the worklist but has not yet been re-transformed,
2019     // it is possible that p1 will have a type like Foo*[int+]:NotNull*+any.
2020     // In fact, that could have been the original type of p1, and p1 could have
2021     // had an original form like p1:(AddP x x (LShiftL quux 3)), where the
2022     // expression (LShiftL quux 3) independently optimized to the constant 8.
2023     if ((t->isa_int() == nullptr) && (t->isa_long() == nullptr)
2024         && (_type->isa_vect() == nullptr)
2025         && Opcode() != Op_LoadKlass && Opcode() != Op_LoadNKlass) {
2026       // t might actually be lower than _type, if _type is a unique
2027       // concrete subclass of abstract class t.
2028       if (off_beyond_header || off == Type::OffsetBot) {  // is the offset beyond the header?
2029         const Type* jt = t->join_speculative(_type);
2030         // In any case, do not allow the join, per se, to empty out the type.
2031         if (jt->empty() && !t->empty()) {
2032           // This can happen if a interface-typed array narrows to a class type.
2033           jt = _type;
2034         }
2035 #ifdef ASSERT
2036         if (phase->C->eliminate_boxing() && adr->is_AddP()) {
2037           // The pointers in the autobox arrays are always non-null
2038           Node* base = adr->in(AddPNode::Base);
2039           if ((base != nullptr) && base->is_DecodeN()) {
2040             // Get LoadN node which loads IntegerCache.cache field
2041             base = base->in(1);
2042           }
2043           if ((base != nullptr) && base->is_Con()) {
2044             const TypeAryPtr* base_type = base->bottom_type()->isa_aryptr();
2045             if ((base_type != nullptr) && base_type->is_autobox_cache()) {
2046               // It could be narrow oop
2047               assert(jt->make_ptr()->ptr() == TypePtr::NotNull,"sanity");
2048             }
2049           }
2050         }
2051 #endif
2052         return jt;
2053       }
2054     }
2055   } else if (tp->base() == Type::InstPtr) {
2056     assert( off != Type::OffsetBot ||
2057             // arrays can be cast to Objects
2058             !tp->isa_instptr() ||
2059             tp->is_instptr()->instance_klass()->is_java_lang_Object() ||
2060             // unsafe field access may not have a constant offset
2061             C->has_unsafe_access(),
2062             "Field accesses must be precise" );
2063     // For oop loads, we expect the _type to be precise.
2064 
2065     // Optimize loads from constant fields.
2066     const TypeInstPtr* tinst = tp->is_instptr();
2067     ciObject* const_oop = tinst->const_oop();
2068     if (!is_mismatched_access() && off != Type::OffsetBot && const_oop != nullptr && const_oop->is_instance()) {
2069       const Type* con_type = Type::make_constant_from_field(const_oop->as_instance(), off, is_unsigned(), memory_type());
2070       if (con_type != nullptr) {
2071         return con_type;
2072       }
2073     }
2074   } else if (tp->base() == Type::KlassPtr || tp->base() == Type::InstKlassPtr || tp->base() == Type::AryKlassPtr) {
2075     assert(off != Type::OffsetBot ||
2076             !tp->isa_instklassptr() ||
2077            // arrays can be cast to Objects
2078            tp->isa_instklassptr()->instance_klass()->is_java_lang_Object() ||
2079            // also allow array-loading from the primary supertype
2080            // array during subtype checks
2081            Opcode() == Op_LoadKlass,
2082            "Field accesses must be precise");
2083     // For klass/static loads, we expect the _type to be precise
2084   } else if (tp->base() == Type::RawPtr && adr->is_Load() && off == 0) {
2085     /* With mirrors being an indirect in the Klass*
2086      * the VM is now using two loads. LoadKlass(LoadP(LoadP(Klass, mirror_offset), zero_offset))
2087      * The LoadP from the Klass has a RawPtr type (see LibraryCallKit::load_mirror_from_klass).
2088      *
2089      * So check the type and klass of the node before the LoadP.
2090      */
2091     Node* adr2 = adr->in(MemNode::Address);
2092     const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
2093     if (tkls != nullptr && !StressReflectiveCode) {
2094       if (tkls->is_loaded() && tkls->klass_is_exact() && tkls->offset() == in_bytes(Klass::java_mirror_offset())) {
2095         ciKlass* klass = tkls->exact_klass();
2096         assert(adr->Opcode() == Op_LoadP, "must load an oop from _java_mirror");
2097         assert(Opcode() == Op_LoadP, "must load an oop from _java_mirror");
2098         return TypeInstPtr::make(klass->java_mirror());
2099       }
2100     }
2101   }
2102 
2103   const TypeKlassPtr *tkls = tp->isa_klassptr();
2104   if (tkls != nullptr) {
2105     if (tkls->is_loaded() && tkls->klass_is_exact()) {
2106       ciKlass* klass = tkls->exact_klass();
2107       // We are loading a field from a Klass metaobject whose identity
2108       // is known at compile time (the type is "exact" or "precise").
2109       // Check for fields we know are maintained as constants by the VM.
2110       if (tkls->offset() == in_bytes(Klass::super_check_offset_offset())) {
2111         // The field is Klass::_super_check_offset.  Return its (constant) value.
2112         // (Folds up type checking code.)
2113         assert(Opcode() == Op_LoadI, "must load an int from _super_check_offset");
2114         return TypeInt::make(klass->super_check_offset());
2115       }
2116       if (UseCompactObjectHeaders) {
2117         if (tkls->offset() == in_bytes(Klass::prototype_header_offset())) {
2118           // The field is Klass::_prototype_header. Return its (constant) value.
2119           assert(this->Opcode() == Op_LoadX, "must load a proper type from _prototype_header");
2120           return TypeX::make(klass->prototype_header());
2121         }
2122       }
2123       // Compute index into primary_supers array
2124       juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
2125       // Check for overflowing; use unsigned compare to handle the negative case.
2126       if( depth < ciKlass::primary_super_limit() ) {
2127         // The field is an element of Klass::_primary_supers.  Return its (constant) value.
2128         // (Folds up type checking code.)
2129         assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
2130         ciKlass *ss = klass->super_of_depth(depth);
2131         return ss ? TypeKlassPtr::make(ss, Type::trust_interfaces) : TypePtr::NULL_PTR;
2132       }
2133       const Type* aift = load_array_final_field(tkls, klass);
2134       if (aift != nullptr)  return aift;
2135     }
2136 
2137     // We can still check if we are loading from the primary_supers array at a
2138     // shallow enough depth.  Even though the klass is not exact, entries less
2139     // than or equal to its super depth are correct.
2140     if (tkls->is_loaded()) {
2141       ciKlass* klass = nullptr;
2142       if (tkls->isa_instklassptr()) {
2143         klass = tkls->is_instklassptr()->instance_klass();
2144       } else {
2145         int dims;
2146         const Type* inner = tkls->is_aryklassptr()->base_element_type(dims);
2147         if (inner->isa_instklassptr()) {
2148           klass = inner->is_instklassptr()->instance_klass();
2149           klass = ciObjArrayKlass::make(klass, dims);
2150         }
2151       }
2152       if (klass != nullptr) {
2153         // Compute index into primary_supers array
2154         juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
2155         // Check for overflowing; use unsigned compare to handle the negative case.
2156         if (depth < ciKlass::primary_super_limit() &&
2157             depth <= klass->super_depth()) { // allow self-depth checks to handle self-check case
2158           // The field is an element of Klass::_primary_supers.  Return its (constant) value.
2159           // (Folds up type checking code.)
2160           assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
2161           ciKlass *ss = klass->super_of_depth(depth);
2162           return ss ? TypeKlassPtr::make(ss, Type::trust_interfaces) : TypePtr::NULL_PTR;
2163         }
2164       }
2165     }
2166 
2167     // If the type is enough to determine that the thing is not an array,
2168     // we can give the layout_helper a positive interval type.
2169     // This will help short-circuit some reflective code.
2170     if (tkls->offset() == in_bytes(Klass::layout_helper_offset()) &&
2171         tkls->isa_instklassptr() && // not directly typed as an array
2172         !tkls->is_instklassptr()->instance_klass()->is_java_lang_Object() // not the supertype of all T[] and specifically not Serializable & Cloneable
2173         ) {
2174       // Note:  When interfaces are reliable, we can narrow the interface
2175       // test to (klass != Serializable && klass != Cloneable).
2176       assert(Opcode() == Op_LoadI, "must load an int from _layout_helper");
2177       jint min_size = Klass::instance_layout_helper(oopDesc::header_size(), false);
2178       // The key property of this type is that it folds up tests
2179       // for array-ness, since it proves that the layout_helper is positive.
2180       // Thus, a generic value like the basic object layout helper works fine.
2181       return TypeInt::make(min_size, max_jint, Type::WidenMin);
2182     }
2183   }
2184 
2185   // If we are loading from a freshly-allocated object, produce a zero,
2186   // if the load is provably beyond the header of the object.
2187   // (Also allow a variable load from a fresh array to produce zero.)
2188   const TypeOopPtr *tinst = tp->isa_oopptr();
2189   bool is_instance = (tinst != nullptr) && tinst->is_known_instance_field();
2190   bool is_boxed_value = (tinst != nullptr) && tinst->is_ptr_to_boxed_value();
2191   if (ReduceFieldZeroing || is_instance || is_boxed_value) {
2192     Node* value = can_see_stored_value(mem,phase);
2193     if (value != nullptr && value->is_Con()) {
2194       assert(value->bottom_type()->higher_equal(_type),"sanity");
2195       return value->bottom_type();
2196     }
2197   }
2198 
2199   bool is_vect = (_type->isa_vect() != nullptr);
2200   if (is_instance && !is_vect) {
2201     // If we have an instance type and our memory input is the
2202     // programs's initial memory state, there is no matching store,
2203     // so just return a zero of the appropriate type -
2204     // except if it is vectorized - then we have no zero constant.
2205     Node *mem = in(MemNode::Memory);
2206     if (mem->is_Parm() && mem->in(0)->is_Start()) {
2207       assert(mem->as_Parm()->_con == TypeFunc::Memory, "must be memory Parm");
2208       return Type::get_zero_type(_type->basic_type());
2209     }
2210   }
2211 
2212   Node* alloc = is_new_object_mark_load();
2213   if (!UseCompactObjectHeaders && alloc != nullptr) {
2214     return TypeX::make(markWord::prototype().value());
2215   }
2216 
2217   return _type;
2218 }
2219 
2220 //------------------------------match_edge-------------------------------------
2221 // Do we Match on this edge index or not?  Match only the address.
2222 uint LoadNode::match_edge(uint idx) const {
2223   return idx == MemNode::Address;
2224 }
2225 
2226 //--------------------------LoadBNode::Ideal--------------------------------------
2227 //
2228 //  If the previous store is to the same address as this load,
2229 //  and the value stored was larger than a byte, replace this load
2230 //  with the value stored truncated to a byte.  If no truncation is
2231 //  needed, the replacement is done in LoadNode::Identity().
2232 //
2233 Node* LoadBNode::Ideal(PhaseGVN* phase, bool can_reshape) {
2234   Node* mem = in(MemNode::Memory);
2235   Node* value = can_see_stored_value(mem,phase);
2236   if (value != nullptr) {
2237     Node* narrow = Compile::narrow_value(T_BYTE, value, _type, phase, false);
2238     if (narrow != value) {
2239       return narrow;
2240     }
2241   }
2242   // Identity call will handle the case where truncation is not needed.
2243   return LoadNode::Ideal(phase, can_reshape);
2244 }
2245 
2246 const Type* LoadBNode::Value(PhaseGVN* phase) const {
2247   Node* mem = in(MemNode::Memory);
2248   Node* value = can_see_stored_value(mem,phase);
2249   if (value != nullptr && value->is_Con() &&
2250       !value->bottom_type()->higher_equal(_type)) {
2251     // If the input to the store does not fit with the load's result type,
2252     // it must be truncated. We can't delay until Ideal call since
2253     // a singleton Value is needed for split_thru_phi optimization.
2254     int con = value->get_int();
2255     return TypeInt::make((con << 24) >> 24);
2256   }
2257   return LoadNode::Value(phase);
2258 }
2259 
2260 //--------------------------LoadUBNode::Ideal-------------------------------------
2261 //
2262 //  If the previous store is to the same address as this load,
2263 //  and the value stored was larger than a byte, replace this load
2264 //  with the value stored truncated to a byte.  If no truncation is
2265 //  needed, the replacement is done in LoadNode::Identity().
2266 //
2267 Node* LoadUBNode::Ideal(PhaseGVN* phase, bool can_reshape) {
2268   Node* mem = in(MemNode::Memory);
2269   Node* value = can_see_stored_value(mem, phase);
2270   if (value != nullptr) {
2271     Node* narrow = Compile::narrow_value(T_BOOLEAN, value, _type, phase, false);
2272     if (narrow != value) {
2273       return narrow;
2274     }
2275   }
2276   // Identity call will handle the case where truncation is not needed.
2277   return LoadNode::Ideal(phase, can_reshape);
2278 }
2279 
2280 const Type* LoadUBNode::Value(PhaseGVN* phase) const {
2281   Node* mem = in(MemNode::Memory);
2282   Node* value = can_see_stored_value(mem,phase);
2283   if (value != nullptr && value->is_Con() &&
2284       !value->bottom_type()->higher_equal(_type)) {
2285     // If the input to the store does not fit with the load's result type,
2286     // it must be truncated. We can't delay until Ideal call since
2287     // a singleton Value is needed for split_thru_phi optimization.
2288     int con = value->get_int();
2289     return TypeInt::make(con & 0xFF);
2290   }
2291   return LoadNode::Value(phase);
2292 }
2293 
2294 //--------------------------LoadUSNode::Ideal-------------------------------------
2295 //
2296 //  If the previous store is to the same address as this load,
2297 //  and the value stored was larger than a char, replace this load
2298 //  with the value stored truncated to a char.  If no truncation is
2299 //  needed, the replacement is done in LoadNode::Identity().
2300 //
2301 Node* LoadUSNode::Ideal(PhaseGVN* phase, bool can_reshape) {
2302   Node* mem = in(MemNode::Memory);
2303   Node* value = can_see_stored_value(mem,phase);
2304   if (value != nullptr) {
2305     Node* narrow = Compile::narrow_value(T_CHAR, value, _type, phase, false);
2306     if (narrow != value) {
2307       return narrow;
2308     }
2309   }
2310   // Identity call will handle the case where truncation is not needed.
2311   return LoadNode::Ideal(phase, can_reshape);
2312 }
2313 
2314 const Type* LoadUSNode::Value(PhaseGVN* phase) const {
2315   Node* mem = in(MemNode::Memory);
2316   Node* value = can_see_stored_value(mem,phase);
2317   if (value != nullptr && value->is_Con() &&
2318       !value->bottom_type()->higher_equal(_type)) {
2319     // If the input to the store does not fit with the load's result type,
2320     // it must be truncated. We can't delay until Ideal call since
2321     // a singleton Value is needed for split_thru_phi optimization.
2322     int con = value->get_int();
2323     return TypeInt::make(con & 0xFFFF);
2324   }
2325   return LoadNode::Value(phase);
2326 }
2327 
2328 //--------------------------LoadSNode::Ideal--------------------------------------
2329 //
2330 //  If the previous store is to the same address as this load,
2331 //  and the value stored was larger than a short, replace this load
2332 //  with the value stored truncated to a short.  If no truncation is
2333 //  needed, the replacement is done in LoadNode::Identity().
2334 //
2335 Node* LoadSNode::Ideal(PhaseGVN* phase, bool can_reshape) {
2336   Node* mem = in(MemNode::Memory);
2337   Node* value = can_see_stored_value(mem,phase);
2338   if (value != nullptr) {
2339     Node* narrow = Compile::narrow_value(T_SHORT, value, _type, phase, false);
2340     if (narrow != value) {
2341       return narrow;
2342     }
2343   }
2344   // Identity call will handle the case where truncation is not needed.
2345   return LoadNode::Ideal(phase, can_reshape);
2346 }
2347 
2348 const Type* LoadSNode::Value(PhaseGVN* phase) const {
2349   Node* mem = in(MemNode::Memory);
2350   Node* value = can_see_stored_value(mem,phase);
2351   if (value != nullptr && value->is_Con() &&
2352       !value->bottom_type()->higher_equal(_type)) {
2353     // If the input to the store does not fit with the load's result type,
2354     // it must be truncated. We can't delay until Ideal call since
2355     // a singleton Value is needed for split_thru_phi optimization.
2356     int con = value->get_int();
2357     return TypeInt::make((con << 16) >> 16);
2358   }
2359   return LoadNode::Value(phase);
2360 }
2361 
2362 //=============================================================================
2363 //----------------------------LoadKlassNode::make------------------------------
2364 // Polymorphic factory method:
2365 Node* LoadKlassNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* at, const TypeKlassPtr* tk) {
2366   // sanity check the alias category against the created node type
2367   const TypePtr *adr_type = adr->bottom_type()->isa_ptr();
2368   assert(adr_type != nullptr, "expecting TypeKlassPtr");
2369 #ifdef _LP64
2370   if (adr_type->is_ptr_to_narrowklass()) {
2371     assert(UseCompressedClassPointers, "no compressed klasses");
2372     Node* load_klass = gvn.transform(new LoadNKlassNode(ctl, mem, adr, at, tk->make_narrowklass(), MemNode::unordered));
2373     return new DecodeNKlassNode(load_klass, load_klass->bottom_type()->make_ptr());
2374   }
2375 #endif
2376   assert(!adr_type->is_ptr_to_narrowklass() && !adr_type->is_ptr_to_narrowoop(), "should have got back a narrow oop");
2377   return new LoadKlassNode(ctl, mem, adr, at, tk, MemNode::unordered);
2378 }
2379 
2380 //------------------------------Value------------------------------------------
2381 const Type* LoadKlassNode::Value(PhaseGVN* phase) const {
2382   return klass_value_common(phase);
2383 }
2384 
2385 // In most cases, LoadKlassNode does not have the control input set. If the control
2386 // input is set, it must not be removed (by LoadNode::Ideal()).
2387 bool LoadKlassNode::can_remove_control() const {
2388   return false;
2389 }
2390 
2391 const Type* LoadNode::klass_value_common(PhaseGVN* phase) const {
2392   // Either input is TOP ==> the result is TOP
2393   const Type *t1 = phase->type( in(MemNode::Memory) );
2394   if (t1 == Type::TOP)  return Type::TOP;
2395   Node *adr = in(MemNode::Address);
2396   const Type *t2 = phase->type( adr );
2397   if (t2 == Type::TOP)  return Type::TOP;
2398   const TypePtr *tp = t2->is_ptr();
2399   if (TypePtr::above_centerline(tp->ptr()) ||
2400       tp->ptr() == TypePtr::Null)  return Type::TOP;
2401 
2402   // Return a more precise klass, if possible
2403   const TypeInstPtr *tinst = tp->isa_instptr();
2404   if (tinst != nullptr) {
2405     ciInstanceKlass* ik = tinst->instance_klass();
2406     int offset = tinst->offset();
2407     if (ik == phase->C->env()->Class_klass()
2408         && (offset == java_lang_Class::klass_offset() ||
2409             offset == java_lang_Class::array_klass_offset())) {
2410       // We are loading a special hidden field from a Class mirror object,
2411       // the field which points to the VM's Klass metaobject.
2412       ciType* t = tinst->java_mirror_type();
2413       // java_mirror_type returns non-null for compile-time Class constants.
2414       if (t != nullptr) {
2415         // constant oop => constant klass
2416         if (offset == java_lang_Class::array_klass_offset()) {
2417           if (t->is_void()) {
2418             // We cannot create a void array.  Since void is a primitive type return null
2419             // klass.  Users of this result need to do a null check on the returned klass.
2420             return TypePtr::NULL_PTR;
2421           }
2422           return TypeKlassPtr::make(ciArrayKlass::make(t), Type::trust_interfaces);
2423         }
2424         if (!t->is_klass()) {
2425           // a primitive Class (e.g., int.class) has null for a klass field
2426           return TypePtr::NULL_PTR;
2427         }
2428         // (Folds up the 1st indirection in aClassConstant.getModifiers().)
2429         return TypeKlassPtr::make(t->as_klass(), Type::trust_interfaces);
2430       }
2431       // non-constant mirror, so we can't tell what's going on
2432     }
2433     if (!tinst->is_loaded())
2434       return _type;             // Bail out if not loaded
2435     if (offset == oopDesc::klass_offset_in_bytes()) {
2436       return tinst->as_klass_type(true);
2437     }
2438   }
2439 
2440   // Check for loading klass from an array
2441   const TypeAryPtr *tary = tp->isa_aryptr();
2442   if (tary != nullptr &&
2443       tary->offset() == oopDesc::klass_offset_in_bytes()) {
2444     return tary->as_klass_type(true);
2445   }
2446 
2447   // Check for loading klass from an array klass
2448   const TypeKlassPtr *tkls = tp->isa_klassptr();
2449   if (tkls != nullptr && !StressReflectiveCode) {
2450     if (!tkls->is_loaded())
2451      return _type;             // Bail out if not loaded
2452     if (tkls->isa_aryklassptr() && tkls->is_aryklassptr()->elem()->isa_klassptr() &&
2453         tkls->offset() == in_bytes(ObjArrayKlass::element_klass_offset())) {
2454       // // Always returning precise element type is incorrect,
2455       // // e.g., element type could be object and array may contain strings
2456       // return TypeKlassPtr::make(TypePtr::Constant, elem, 0);
2457 
2458       // The array's TypeKlassPtr was declared 'precise' or 'not precise'
2459       // according to the element type's subclassing.
2460       return tkls->is_aryklassptr()->elem()->isa_klassptr()->cast_to_exactness(tkls->klass_is_exact());
2461     }
2462     if (tkls->isa_instklassptr() != nullptr && tkls->klass_is_exact() &&
2463         tkls->offset() == in_bytes(Klass::super_offset())) {
2464       ciKlass* sup = tkls->is_instklassptr()->instance_klass()->super();
2465       // The field is Klass::_super.  Return its (constant) value.
2466       // (Folds up the 2nd indirection in aClassConstant.getSuperClass().)
2467       return sup ? TypeKlassPtr::make(sup, Type::trust_interfaces) : TypePtr::NULL_PTR;
2468     }
2469   }
2470 
2471   if (tkls != nullptr && !UseSecondarySupersCache
2472       && tkls->offset() == in_bytes(Klass::secondary_super_cache_offset()))  {
2473     // Treat Klass::_secondary_super_cache as a constant when the cache is disabled.
2474     return TypePtr::NULL_PTR;
2475   }
2476 
2477   // Bailout case
2478   return LoadNode::Value(phase);
2479 }
2480 
2481 //------------------------------Identity---------------------------------------
2482 // To clean up reflective code, simplify k.java_mirror.as_klass to plain k.
2483 // Also feed through the klass in Allocate(...klass...)._klass.
2484 Node* LoadKlassNode::Identity(PhaseGVN* phase) {
2485   return klass_identity_common(phase);
2486 }
2487 
2488 Node* LoadNode::klass_identity_common(PhaseGVN* phase) {
2489   Node* x = LoadNode::Identity(phase);
2490   if (x != this)  return x;
2491 
2492   // Take apart the address into an oop and offset.
2493   // Return 'this' if we cannot.
2494   Node*    adr    = in(MemNode::Address);
2495   intptr_t offset = 0;
2496   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2497   if (base == nullptr)     return this;
2498   const TypeOopPtr* toop = phase->type(adr)->isa_oopptr();
2499   if (toop == nullptr)     return this;
2500 
2501   // Step over potential GC barrier for OopHandle resolve
2502   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2503   if (bs->is_gc_barrier_node(base)) {
2504     base = bs->step_over_gc_barrier(base);
2505   }
2506 
2507   // We can fetch the klass directly through an AllocateNode.
2508   // This works even if the klass is not constant (clone or newArray).
2509   if (offset == oopDesc::klass_offset_in_bytes()) {
2510     Node* allocated_klass = AllocateNode::Ideal_klass(base, phase);
2511     if (allocated_klass != nullptr) {
2512       return allocated_klass;
2513     }
2514   }
2515 
2516   // Simplify k.java_mirror.as_klass to plain k, where k is a Klass*.
2517   // See inline_native_Class_query for occurrences of these patterns.
2518   // Java Example:  x.getClass().isAssignableFrom(y)
2519   //
2520   // This improves reflective code, often making the Class
2521   // mirror go completely dead.  (Current exception:  Class
2522   // mirrors may appear in debug info, but we could clean them out by
2523   // introducing a new debug info operator for Klass.java_mirror).
2524 
2525   if (toop->isa_instptr() && toop->is_instptr()->instance_klass() == phase->C->env()->Class_klass()
2526       && offset == java_lang_Class::klass_offset()) {
2527     if (base->is_Load()) {
2528       Node* base2 = base->in(MemNode::Address);
2529       if (base2->is_Load()) { /* direct load of a load which is the OopHandle */
2530         Node* adr2 = base2->in(MemNode::Address);
2531         const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
2532         if (tkls != nullptr && !tkls->empty()
2533             && (tkls->isa_instklassptr() || tkls->isa_aryklassptr())
2534             && adr2->is_AddP()
2535            ) {
2536           int mirror_field = in_bytes(Klass::java_mirror_offset());
2537           if (tkls->offset() == mirror_field) {
2538             return adr2->in(AddPNode::Base);
2539           }
2540         }
2541       }
2542     }
2543   }
2544 
2545   return this;
2546 }
2547 
2548 LoadNode* LoadNode::clone_pinned() const {
2549   LoadNode* ld = clone()->as_Load();
2550   ld->_control_dependency = UnknownControl;
2551   return ld;
2552 }
2553 
2554 
2555 //------------------------------Value------------------------------------------
2556 const Type* LoadNKlassNode::Value(PhaseGVN* phase) const {
2557   const Type *t = klass_value_common(phase);
2558   if (t == Type::TOP)
2559     return t;
2560 
2561   return t->make_narrowklass();
2562 }
2563 
2564 //------------------------------Identity---------------------------------------
2565 // To clean up reflective code, simplify k.java_mirror.as_klass to narrow k.
2566 // Also feed through the klass in Allocate(...klass...)._klass.
2567 Node* LoadNKlassNode::Identity(PhaseGVN* phase) {
2568   Node *x = klass_identity_common(phase);
2569 
2570   const Type *t = phase->type( x );
2571   if( t == Type::TOP ) return x;
2572   if( t->isa_narrowklass()) return x;
2573   assert (!t->isa_narrowoop(), "no narrow oop here");
2574 
2575   return phase->transform(new EncodePKlassNode(x, t->make_narrowklass()));
2576 }
2577 
2578 //------------------------------Value-----------------------------------------
2579 const Type* LoadRangeNode::Value(PhaseGVN* phase) const {
2580   // Either input is TOP ==> the result is TOP
2581   const Type *t1 = phase->type( in(MemNode::Memory) );
2582   if( t1 == Type::TOP ) return Type::TOP;
2583   Node *adr = in(MemNode::Address);
2584   const Type *t2 = phase->type( adr );
2585   if( t2 == Type::TOP ) return Type::TOP;
2586   const TypePtr *tp = t2->is_ptr();
2587   if (TypePtr::above_centerline(tp->ptr()))  return Type::TOP;
2588   const TypeAryPtr *tap = tp->isa_aryptr();
2589   if( !tap ) return _type;
2590   return tap->size();
2591 }
2592 
2593 //-------------------------------Ideal---------------------------------------
2594 // Feed through the length in AllocateArray(...length...)._length.
2595 Node *LoadRangeNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2596   Node* p = MemNode::Ideal_common(phase, can_reshape);
2597   if (p)  return (p == NodeSentinel) ? nullptr : p;
2598 
2599   // Take apart the address into an oop and offset.
2600   // Return 'this' if we cannot.
2601   Node*    adr    = in(MemNode::Address);
2602   intptr_t offset = 0;
2603   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase,  offset);
2604   if (base == nullptr)     return nullptr;
2605   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2606   if (tary == nullptr)     return nullptr;
2607 
2608   // We can fetch the length directly through an AllocateArrayNode.
2609   // This works even if the length is not constant (clone or newArray).
2610   if (offset == arrayOopDesc::length_offset_in_bytes()) {
2611     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base);
2612     if (alloc != nullptr) {
2613       Node* allocated_length = alloc->Ideal_length();
2614       Node* len = alloc->make_ideal_length(tary, phase);
2615       if (allocated_length != len) {
2616         // New CastII improves on this.
2617         return len;
2618       }
2619     }
2620   }
2621 
2622   return nullptr;
2623 }
2624 
2625 //------------------------------Identity---------------------------------------
2626 // Feed through the length in AllocateArray(...length...)._length.
2627 Node* LoadRangeNode::Identity(PhaseGVN* phase) {
2628   Node* x = LoadINode::Identity(phase);
2629   if (x != this)  return x;
2630 
2631   // Take apart the address into an oop and offset.
2632   // Return 'this' if we cannot.
2633   Node*    adr    = in(MemNode::Address);
2634   intptr_t offset = 0;
2635   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2636   if (base == nullptr)     return this;
2637   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2638   if (tary == nullptr)     return this;
2639 
2640   // We can fetch the length directly through an AllocateArrayNode.
2641   // This works even if the length is not constant (clone or newArray).
2642   if (offset == arrayOopDesc::length_offset_in_bytes()) {
2643     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base);
2644     if (alloc != nullptr) {
2645       Node* allocated_length = alloc->Ideal_length();
2646       // Do not allow make_ideal_length to allocate a CastII node.
2647       Node* len = alloc->make_ideal_length(tary, phase, false);
2648       if (allocated_length == len) {
2649         // Return allocated_length only if it would not be improved by a CastII.
2650         return allocated_length;
2651       }
2652     }
2653   }
2654 
2655   return this;
2656 
2657 }
2658 
2659 //=============================================================================
2660 //---------------------------StoreNode::make-----------------------------------
2661 // Polymorphic factory method:
2662 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) {
2663   assert((mo == unordered || mo == release), "unexpected");
2664   Compile* C = gvn.C;
2665   assert(C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
2666          ctl != nullptr, "raw memory operations should have control edge");
2667 
2668   switch (bt) {
2669   case T_BOOLEAN: val = gvn.transform(new AndINode(val, gvn.intcon(0x1))); // Fall through to T_BYTE case
2670   case T_BYTE:    return new StoreBNode(ctl, mem, adr, adr_type, val, mo);
2671   case T_INT:     return new StoreINode(ctl, mem, adr, adr_type, val, mo);
2672   case T_CHAR:
2673   case T_SHORT:   return new StoreCNode(ctl, mem, adr, adr_type, val, mo);
2674   case T_LONG:    return new StoreLNode(ctl, mem, adr, adr_type, val, mo, require_atomic_access);
2675   case T_FLOAT:   return new StoreFNode(ctl, mem, adr, adr_type, val, mo);
2676   case T_DOUBLE:  return new StoreDNode(ctl, mem, adr, adr_type, val, mo, require_atomic_access);
2677   case T_METADATA:
2678   case T_ADDRESS:
2679   case T_OBJECT:
2680 #ifdef _LP64
2681     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
2682       val = gvn.transform(new EncodePNode(val, val->bottom_type()->make_narrowoop()));
2683       return new StoreNNode(ctl, mem, adr, adr_type, val, mo);
2684     } else if (adr->bottom_type()->is_ptr_to_narrowklass() ||
2685                (UseCompressedClassPointers && val->bottom_type()->isa_klassptr() &&
2686                 adr->bottom_type()->isa_rawptr())) {
2687       val = gvn.transform(new EncodePKlassNode(val, val->bottom_type()->make_narrowklass()));
2688       return new StoreNKlassNode(ctl, mem, adr, adr_type, val, mo);
2689     }
2690 #endif
2691     {
2692       return new StorePNode(ctl, mem, adr, adr_type, val, mo);
2693     }
2694   default:
2695     ShouldNotReachHere();
2696     return (StoreNode*)nullptr;
2697   }
2698 }
2699 
2700 //--------------------------bottom_type----------------------------------------
2701 const Type *StoreNode::bottom_type() const {
2702   return Type::MEMORY;
2703 }
2704 
2705 //------------------------------hash-------------------------------------------
2706 uint StoreNode::hash() const {
2707   // unroll addition of interesting fields
2708   //return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address) + (uintptr_t)in(ValueIn);
2709 
2710   // Since they are not commoned, do not hash them:
2711   return NO_HASH;
2712 }
2713 
2714 // Class to parse array pointers, and determine if they are adjacent. We parse the form:
2715 //
2716 //   pointer =   base
2717 //             + constant_offset
2718 //             + LShiftL( ConvI2L(int_offset + int_con), int_offset_shift)
2719 //             + sum(other_offsets)
2720 //
2721 //
2722 // Note: we accumulate all constant offsets into constant_offset, even the int constant behind
2723 //       the "LShiftL(ConvI2L(...))" pattern. We convert "ConvI2L(int_offset + int_con)" to
2724 //       "ConvI2L(int_offset) + int_con", which is only safe if we can assume that either all
2725 //       compared addresses have an overflow for "int_offset + int_con" or none.
2726 //       For loads and stores on arrays, we know that if one overflows and the other not, then
2727 //       the two addresses lay almost max_int indices apart, but the maximal array size is
2728 //       only about half of that. Therefore, the RangeCheck on at least one of them must have
2729 //       failed.
2730 //
2731 //   constant_offset += LShiftL( ConvI2L(int_con), int_offset_shift)
2732 //
2733 //   pointer =   base
2734 //             + constant_offset
2735 //             + LShiftL( ConvI2L(int_offset), int_offset_shift)
2736 //             + sum(other_offsets)
2737 //
2738 class ArrayPointer {
2739 private:
2740   const bool _is_valid;          // The parsing succeeded
2741   const Node* _pointer;          // The final pointer to the position in the array
2742   const Node* _base;             // Base address of the array
2743   const jlong _constant_offset;  // Sum of collected constant offsets
2744   const Node* _int_offset;       // (optional) Offset behind LShiftL and ConvI2L
2745   const jint  _int_offset_shift; // (optional) Shift value for int_offset
2746   const GrowableArray<Node*>* _other_offsets; // List of other AddP offsets
2747 
2748   ArrayPointer(const bool is_valid,
2749                const Node* pointer,
2750                const Node* base,
2751                const jlong constant_offset,
2752                const Node* int_offset,
2753                const jint int_offset_shift,
2754                const GrowableArray<Node*>* other_offsets) :
2755       _is_valid(is_valid),
2756       _pointer(pointer),
2757       _base(base),
2758       _constant_offset(constant_offset),
2759       _int_offset(int_offset),
2760       _int_offset_shift(int_offset_shift),
2761       _other_offsets(other_offsets)
2762   {
2763     assert(_pointer != nullptr, "must always have pointer");
2764     assert(is_valid == (_base != nullptr), "have base exactly if valid");
2765     assert(is_valid == (_other_offsets != nullptr), "have other_offsets exactly if valid");
2766   }
2767 
2768   static ArrayPointer make_invalid(const Node* pointer) {
2769     return ArrayPointer(false, pointer, nullptr, 0, nullptr, 0, nullptr);
2770   }
2771 
2772   static bool parse_int_offset(Node* offset, Node*& int_offset, jint& int_offset_shift) {
2773     // offset = LShiftL( ConvI2L(int_offset), int_offset_shift)
2774     if (offset->Opcode() == Op_LShiftL &&
2775         offset->in(1)->Opcode() == Op_ConvI2L &&
2776         offset->in(2)->Opcode() == Op_ConI) {
2777       int_offset = offset->in(1)->in(1); // LShiftL -> ConvI2L -> int_offset
2778       int_offset_shift = offset->in(2)->get_int(); // LShiftL -> int_offset_shift
2779       return true;
2780     }
2781 
2782     // offset = ConvI2L(int_offset) = LShiftL( ConvI2L(int_offset), 0)
2783     if (offset->Opcode() == Op_ConvI2L) {
2784       int_offset = offset->in(1);
2785       int_offset_shift = 0;
2786       return true;
2787     }
2788 
2789     // parse failed
2790     return false;
2791   }
2792 
2793 public:
2794   // Parse the structure above the pointer
2795   static ArrayPointer make(PhaseGVN* phase, const Node* pointer) {
2796     assert(phase->type(pointer)->isa_aryptr() != nullptr, "must be array pointer");
2797     if (!pointer->is_AddP()) { return ArrayPointer::make_invalid(pointer); }
2798 
2799     const Node* base = pointer->in(AddPNode::Base);
2800     if (base == nullptr) { return ArrayPointer::make_invalid(pointer); }
2801 
2802     const int search_depth = 5;
2803     Node* offsets[search_depth];
2804     int count = pointer->as_AddP()->unpack_offsets(offsets, search_depth);
2805 
2806     // We expect at least a constant each
2807     if (count <= 0) { return ArrayPointer::make_invalid(pointer); }
2808 
2809     // We extract the form:
2810     //
2811     //   pointer =   base
2812     //             + constant_offset
2813     //             + LShiftL( ConvI2L(int_offset + int_con), int_offset_shift)
2814     //             + sum(other_offsets)
2815     //
2816     jlong constant_offset = 0;
2817     Node* int_offset = nullptr;
2818     jint int_offset_shift = 0;
2819     GrowableArray<Node*>* other_offsets = new GrowableArray<Node*>(count);
2820 
2821     for (int i = 0; i < count; i++) {
2822       Node* offset = offsets[i];
2823       if (offset->Opcode() == Op_ConI) {
2824         // Constant int offset
2825         constant_offset += offset->get_int();
2826       } else if (offset->Opcode() == Op_ConL) {
2827         // Constant long offset
2828         constant_offset += offset->get_long();
2829       } else if(int_offset == nullptr && parse_int_offset(offset, int_offset, int_offset_shift)) {
2830         // LShiftL( ConvI2L(int_offset), int_offset_shift)
2831         int_offset = int_offset->uncast();
2832         if (int_offset->Opcode() == Op_AddI && int_offset->in(2)->Opcode() == Op_ConI) {
2833           // LShiftL( ConvI2L(int_offset + int_con), int_offset_shift)
2834           constant_offset += ((jlong)int_offset->in(2)->get_int()) << int_offset_shift;
2835           int_offset = int_offset->in(1);
2836         }
2837       } else {
2838         // All others
2839         other_offsets->append(offset);
2840       }
2841     }
2842 
2843     return ArrayPointer(true, pointer, base, constant_offset, int_offset, int_offset_shift, other_offsets);
2844   }
2845 
2846   bool is_adjacent_to_and_before(const ArrayPointer& other, const jlong data_size) const {
2847     if (!_is_valid || !other._is_valid) { return false; }
2848 
2849     // Offset adjacent?
2850     if (this->_constant_offset + data_size != other._constant_offset) { return false; }
2851 
2852     // All other components identical?
2853     if (this->_base != other._base ||
2854         this->_int_offset != other._int_offset ||
2855         this->_int_offset_shift != other._int_offset_shift ||
2856         this->_other_offsets->length() != other._other_offsets->length()) {
2857       return false;
2858     }
2859 
2860     for (int i = 0; i < this->_other_offsets->length(); i++) {
2861       Node* o1 = this->_other_offsets->at(i);
2862       Node* o2 = other._other_offsets->at(i);
2863       if (o1 != o2) { return false; }
2864     }
2865 
2866     return true;
2867   }
2868 
2869 #ifndef PRODUCT
2870   void dump() {
2871     if (!_is_valid) {
2872       tty->print("ArrayPointer[%d %s, invalid]", _pointer->_idx, _pointer->Name());
2873       return;
2874     }
2875     tty->print("ArrayPointer[%d %s, base[%d %s] + %lld",
2876                _pointer->_idx, _pointer->Name(),
2877                _base->_idx, _base->Name(),
2878                (long long)_constant_offset);
2879     if (_int_offset != 0) {
2880       tty->print(" + I2L[%d %s] << %d",
2881                  _int_offset->_idx, _int_offset->Name(), _int_offset_shift);
2882     }
2883     for (int i = 0; i < _other_offsets->length(); i++) {
2884       Node* n = _other_offsets->at(i);
2885       tty->print(" + [%d %s]", n->_idx, n->Name());
2886     }
2887     tty->print_cr("]");
2888   }
2889 #endif
2890 };
2891 
2892 // Link together multiple stores (B/S/C/I) into a longer one.
2893 //
2894 // Example: _store = StoreB[i+3]
2895 //
2896 //   RangeCheck[i+0]           RangeCheck[i+0]
2897 //   StoreB[i+0]
2898 //   RangeCheck[i+3]           RangeCheck[i+3]
2899 //   StoreB[i+1]         -->   pass:             fail:
2900 //   StoreB[i+2]               StoreI[i+0]       StoreB[i+0]
2901 //   StoreB[i+3]
2902 //
2903 // The 4 StoreB are merged into a single StoreI node. We have to be careful with RangeCheck[i+1]: before
2904 // the optimization, if this RangeCheck[i+1] fails, then we execute only StoreB[i+0], and then trap. After
2905 // the optimization, the new StoreI[i+0] is on the passing path of RangeCheck[i+3], and StoreB[i+0] on the
2906 // failing path.
2907 //
2908 // Note: For normal array stores, every store at first has a RangeCheck. But they can be removed with:
2909 //       - RCE (RangeCheck Elimination): the RangeChecks in the loop are hoisted out and before the loop,
2910 //                                       and possibly no RangeChecks remain between the stores.
2911 //       - RangeCheck smearing: the earlier RangeChecks are adjusted such that they cover later RangeChecks,
2912 //                              and those later RangeChecks can be removed. Example:
2913 //
2914 //                              RangeCheck[i+0]                         RangeCheck[i+0] <- before first store
2915 //                              StoreB[i+0]                             StoreB[i+0]     <- first store
2916 //                              RangeCheck[i+1]     --> smeared -->     RangeCheck[i+3] <- only RC between first and last store
2917 //                              StoreB[i+1]                             StoreB[i+1]     <- second store
2918 //                              RangeCheck[i+2]     --> removed
2919 //                              StoreB[i+2]                             StoreB[i+2]
2920 //                              RangeCheck[i+3]     --> removed
2921 //                              StoreB[i+3]                             StoreB[i+3]     <- last store
2922 //
2923 //                              Thus, it is a common pattern that between the first and last store in a chain
2924 //                              of adjacent stores there remains exactly one RangeCheck, located between the
2925 //                              first and the second store (e.g. RangeCheck[i+3]).
2926 //
2927 class MergePrimitiveArrayStores : public StackObj {
2928 private:
2929   PhaseGVN* _phase;
2930   StoreNode* _store;
2931 
2932 public:
2933   MergePrimitiveArrayStores(PhaseGVN* phase, StoreNode* store) : _phase(phase), _store(store) {}
2934 
2935   StoreNode* run();
2936 
2937 private:
2938   bool is_compatible_store(const StoreNode* other_store) const;
2939   bool is_adjacent_pair(const StoreNode* use_store, const StoreNode* def_store) const;
2940   bool is_adjacent_input_pair(const Node* n1, const Node* n2, const int memory_size) const;
2941   static bool is_con_RShift(const Node* n, Node const*& base_out, jint& shift_out);
2942   enum CFGStatus { SuccessNoRangeCheck, SuccessWithRangeCheck, Failure };
2943   static CFGStatus cfg_status_for_pair(const StoreNode* use_store, const StoreNode* def_store);
2944 
2945   class Status {
2946   private:
2947     StoreNode* _found_store;
2948     bool       _found_range_check;
2949 
2950     Status(StoreNode* found_store, bool found_range_check)
2951       : _found_store(found_store), _found_range_check(found_range_check) {}
2952 
2953   public:
2954     StoreNode* found_store() const { return _found_store; }
2955     bool found_range_check() const { return _found_range_check; }
2956     static Status make_failure() { return Status(nullptr, false); }
2957 
2958     static Status make(StoreNode* found_store, const CFGStatus cfg_status) {
2959       if (cfg_status == CFGStatus::Failure) {
2960         return Status::make_failure();
2961       }
2962       return Status(found_store, cfg_status == CFGStatus::SuccessWithRangeCheck);
2963     }
2964   };
2965 
2966   Status find_adjacent_use_store(const StoreNode* def_store) const;
2967   Status find_adjacent_def_store(const StoreNode* use_store) const;
2968   Status find_use_store(const StoreNode* def_store) const;
2969   Status find_def_store(const StoreNode* use_store) const;
2970   Status find_use_store_unidirectional(const StoreNode* def_store) const;
2971   Status find_def_store_unidirectional(const StoreNode* use_store) const;
2972 
2973   void collect_merge_list(Node_List& merge_list) const;
2974   Node* make_merged_input_value(const Node_List& merge_list);
2975   StoreNode* make_merged_store(const Node_List& merge_list, Node* merged_input_value);
2976 
2977   DEBUG_ONLY( void trace(const Node_List& merge_list, const Node* merged_input_value, const StoreNode* merged_store) const; )
2978 };
2979 
2980 StoreNode* MergePrimitiveArrayStores::run() {
2981   // Check for B/S/C/I
2982   int opc = _store->Opcode();
2983   if (opc != Op_StoreB && opc != Op_StoreC && opc != Op_StoreI) {
2984     return nullptr;
2985   }
2986 
2987   // Only merge stores on arrays, and the stores must have the same size as the elements.
2988   const TypePtr* ptr_t = _store->adr_type();
2989   if (ptr_t == nullptr) {
2990     return nullptr;
2991   }
2992   const TypeAryPtr* aryptr_t = ptr_t->isa_aryptr();
2993   if (aryptr_t == nullptr) {
2994     return nullptr;
2995   }
2996   BasicType bt = aryptr_t->elem()->array_element_basic_type();
2997   if (!is_java_primitive(bt) ||
2998       type2aelembytes(bt) != _store->memory_size()) {
2999     return nullptr;
3000   }
3001 
3002   // The _store must be the "last" store in a chain. If we find a use we could merge with
3003   // then that use or a store further down is the "last" store.
3004   Status status_use = find_adjacent_use_store(_store);
3005   if (status_use.found_store() != nullptr) {
3006     return nullptr;
3007   }
3008 
3009   // Check if we can merge with at least one def, so that we have at least 2 stores to merge.
3010   Status status_def = find_adjacent_def_store(_store);
3011   if (status_def.found_store() == nullptr) {
3012     return nullptr;
3013   }
3014 
3015   ResourceMark rm;
3016   Node_List merge_list;
3017   collect_merge_list(merge_list);
3018 
3019   Node* merged_input_value = make_merged_input_value(merge_list);
3020   if (merged_input_value == nullptr) { return nullptr; }
3021 
3022   StoreNode* merged_store = make_merged_store(merge_list, merged_input_value);
3023 
3024   DEBUG_ONLY( if(TraceMergeStores) { trace(merge_list, merged_input_value, merged_store); } )
3025 
3026   return merged_store;
3027 }
3028 
3029 // Check compatibility between _store and other_store.
3030 bool MergePrimitiveArrayStores::is_compatible_store(const StoreNode* other_store) const {
3031   int opc = _store->Opcode();
3032   assert(opc == Op_StoreB || opc == Op_StoreC || opc == Op_StoreI, "precondition");
3033   assert(_store->adr_type()->isa_aryptr() != nullptr, "must be array store");
3034 
3035   if (other_store == nullptr ||
3036       _store->Opcode() != other_store->Opcode() ||
3037       other_store->adr_type() == nullptr ||
3038       other_store->adr_type()->isa_aryptr() == nullptr) {
3039     return false;
3040   }
3041 
3042   // Check that the size of the stores, and the array elements are all the same.
3043   const TypeAryPtr* aryptr_t1 = _store->adr_type()->is_aryptr();
3044   const TypeAryPtr* aryptr_t2 = other_store->adr_type()->is_aryptr();
3045   BasicType aryptr_bt1 = aryptr_t1->elem()->array_element_basic_type();
3046   BasicType aryptr_bt2 = aryptr_t2->elem()->array_element_basic_type();
3047   if (!is_java_primitive(aryptr_bt1) || !is_java_primitive(aryptr_bt2)) {
3048     return false;
3049   }
3050   int size1 = type2aelembytes(aryptr_bt1);
3051   int size2 = type2aelembytes(aryptr_bt2);
3052   if (size1 != size2 ||
3053       size1 != _store->memory_size() ||
3054       _store->memory_size() != other_store->memory_size()) {
3055     return false;
3056   }
3057   return true;
3058 }
3059 
3060 bool MergePrimitiveArrayStores::is_adjacent_pair(const StoreNode* use_store, const StoreNode* def_store) const {
3061   if (!is_adjacent_input_pair(def_store->in(MemNode::ValueIn),
3062                               use_store->in(MemNode::ValueIn),
3063                               def_store->memory_size())) {
3064     return false;
3065   }
3066 
3067   ResourceMark rm;
3068   ArrayPointer array_pointer_use = ArrayPointer::make(_phase, use_store->in(MemNode::Address));
3069   ArrayPointer array_pointer_def = ArrayPointer::make(_phase, def_store->in(MemNode::Address));
3070   if (!array_pointer_def.is_adjacent_to_and_before(array_pointer_use, use_store->memory_size())) {
3071     return false;
3072   }
3073 
3074   return true;
3075 }
3076 
3077 bool MergePrimitiveArrayStores::is_adjacent_input_pair(const Node* n1, const Node* n2, const int memory_size) const {
3078   // Pattern: [n1 = ConI, n2 = ConI]
3079   if (n1->Opcode() == Op_ConI) {
3080     return n2->Opcode() == Op_ConI;
3081   }
3082 
3083   // Pattern: [n1 = base >> shift, n2 = base >> (shift + memory_size)]
3084 #ifndef VM_LITTLE_ENDIAN
3085   // Pattern: [n1 = base >> (shift + memory_size), n2 = base >> shift]
3086   // Swapping n1 with n2 gives same pattern as on little endian platforms.
3087   swap(n1, n2);
3088 #endif // !VM_LITTLE_ENDIAN
3089   Node const* base_n2;
3090   jint shift_n2;
3091   if (!is_con_RShift(n2, base_n2, shift_n2)) {
3092     return false;
3093   }
3094   if (n1->Opcode() == Op_ConvL2I) {
3095     // look through
3096     n1 = n1->in(1);
3097   }
3098   Node const* base_n1;
3099   jint shift_n1;
3100   if (n1 == base_n2) {
3101     // n1 = base = base >> 0
3102     base_n1 = n1;
3103     shift_n1 = 0;
3104   } else if (!is_con_RShift(n1, base_n1, shift_n1)) {
3105     return false;
3106   }
3107   int bits_per_store = memory_size * 8;
3108   if (base_n1 != base_n2 ||
3109       shift_n1 + bits_per_store != shift_n2 ||
3110       shift_n1 % bits_per_store != 0) {
3111     return false;
3112   }
3113 
3114   // both load from same value with correct shift
3115   return true;
3116 }
3117 
3118 // Detect pattern: n = base_out >> shift_out
3119 bool MergePrimitiveArrayStores::is_con_RShift(const Node* n, Node const*& base_out, jint& shift_out) {
3120   assert(n != nullptr, "precondition");
3121 
3122   int opc = n->Opcode();
3123   if (opc == Op_ConvL2I) {
3124     n = n->in(1);
3125     opc = n->Opcode();
3126   }
3127 
3128   if ((opc == Op_RShiftI ||
3129        opc == Op_RShiftL ||
3130        opc == Op_URShiftI ||
3131        opc == Op_URShiftL) &&
3132       n->in(2)->is_ConI()) {
3133     base_out = n->in(1);
3134     shift_out = n->in(2)->get_int();
3135     // The shift must be positive:
3136     return shift_out >= 0;
3137   }
3138   return false;
3139 }
3140 
3141 // Check if there is nothing between the two stores, except optionally a RangeCheck leading to an uncommon trap.
3142 MergePrimitiveArrayStores::CFGStatus MergePrimitiveArrayStores::cfg_status_for_pair(const StoreNode* use_store, const StoreNode* def_store) {
3143   assert(use_store->in(MemNode::Memory) == def_store, "use-def relationship");
3144 
3145   Node* ctrl_use = use_store->in(MemNode::Control);
3146   Node* ctrl_def = def_store->in(MemNode::Control);
3147   if (ctrl_use == nullptr || ctrl_def == nullptr) {
3148     return CFGStatus::Failure;
3149   }
3150 
3151   if (ctrl_use == ctrl_def) {
3152     // Same ctrl -> no RangeCheck in between.
3153     // Check: use_store must be the only use of def_store.
3154     if (def_store->outcnt() > 1) {
3155       return CFGStatus::Failure;
3156     }
3157     return CFGStatus::SuccessNoRangeCheck;
3158   }
3159 
3160   // Different ctrl -> could have RangeCheck in between.
3161   // Check: 1. def_store only has these uses: use_store and MergeMem for uncommon trap, and
3162   //        2. ctrl separated by RangeCheck.
3163   if (def_store->outcnt() != 2) {
3164     return CFGStatus::Failure; // Cannot have exactly these uses: use_store and MergeMem for uncommon trap.
3165   }
3166   int use_store_out_idx = def_store->raw_out(0) == use_store ? 0 : 1;
3167   Node* merge_mem = def_store->raw_out(1 - use_store_out_idx)->isa_MergeMem();
3168   if (merge_mem == nullptr ||
3169       merge_mem->outcnt() != 1) {
3170     return CFGStatus::Failure; // Does not have MergeMem for uncommon trap.
3171   }
3172   if (!ctrl_use->is_IfProj() ||
3173       !ctrl_use->in(0)->is_RangeCheck() ||
3174       ctrl_use->in(0)->outcnt() != 2) {
3175     return CFGStatus::Failure; // Not RangeCheck.
3176   }
3177   ProjNode* other_proj = ctrl_use->as_IfProj()->other_if_proj();
3178   Node* trap = other_proj->is_uncommon_trap_proj(Deoptimization::Reason_range_check);
3179   if (trap != merge_mem->unique_out() ||
3180       ctrl_use->in(0)->in(0) != ctrl_def) {
3181     return CFGStatus::Failure; // Not RangeCheck with merge_mem leading to uncommon trap.
3182   }
3183 
3184   return CFGStatus::SuccessWithRangeCheck;
3185 }
3186 
3187 MergePrimitiveArrayStores::Status MergePrimitiveArrayStores::find_adjacent_use_store(const StoreNode* def_store) const {
3188   Status status_use = find_use_store(def_store);
3189   StoreNode* use_store = status_use.found_store();
3190   if (use_store != nullptr && !is_adjacent_pair(use_store, def_store)) {
3191     return Status::make_failure();
3192   }
3193   return status_use;
3194 }
3195 
3196 MergePrimitiveArrayStores::Status MergePrimitiveArrayStores::find_adjacent_def_store(const StoreNode* use_store) const {
3197   Status status_def = find_def_store(use_store);
3198   StoreNode* def_store = status_def.found_store();
3199   if (def_store != nullptr && !is_adjacent_pair(use_store, def_store)) {
3200     return Status::make_failure();
3201   }
3202   return status_def;
3203 }
3204 
3205 MergePrimitiveArrayStores::Status MergePrimitiveArrayStores::find_use_store(const StoreNode* def_store) const {
3206   Status status_use = find_use_store_unidirectional(def_store);
3207 
3208 #ifdef ASSERT
3209   StoreNode* use_store = status_use.found_store();
3210   if (use_store != nullptr) {
3211     Status status_def = find_def_store_unidirectional(use_store);
3212     assert(status_def.found_store() == def_store &&
3213            status_def.found_range_check() == status_use.found_range_check(),
3214            "find_use_store and find_def_store must be symmetric");
3215   }
3216 #endif
3217 
3218   return status_use;
3219 }
3220 
3221 MergePrimitiveArrayStores::Status MergePrimitiveArrayStores::find_def_store(const StoreNode* use_store) const {
3222   Status status_def = find_def_store_unidirectional(use_store);
3223 
3224 #ifdef ASSERT
3225   StoreNode* def_store = status_def.found_store();
3226   if (def_store != nullptr) {
3227     Status status_use = find_use_store_unidirectional(def_store);
3228     assert(status_use.found_store() == use_store &&
3229            status_use.found_range_check() == status_def.found_range_check(),
3230            "find_use_store and find_def_store must be symmetric");
3231   }
3232 #endif
3233 
3234   return status_def;
3235 }
3236 
3237 MergePrimitiveArrayStores::Status MergePrimitiveArrayStores::find_use_store_unidirectional(const StoreNode* def_store) const {
3238   assert(is_compatible_store(def_store), "precondition: must be compatible with _store");
3239 
3240   for (DUIterator_Fast imax, i = def_store->fast_outs(imax); i < imax; i++) {
3241     StoreNode* use_store = def_store->fast_out(i)->isa_Store();
3242     if (is_compatible_store(use_store)) {
3243       return Status::make(use_store, cfg_status_for_pair(use_store, def_store));
3244     }
3245   }
3246 
3247   return Status::make_failure();
3248 }
3249 
3250 MergePrimitiveArrayStores::Status MergePrimitiveArrayStores::find_def_store_unidirectional(const StoreNode* use_store) const {
3251   assert(is_compatible_store(use_store), "precondition: must be compatible with _store");
3252 
3253   StoreNode* def_store = use_store->in(MemNode::Memory)->isa_Store();
3254   if (!is_compatible_store(def_store)) {
3255     return Status::make_failure();
3256   }
3257 
3258   return Status::make(def_store, cfg_status_for_pair(use_store, def_store));
3259 }
3260 
3261 void MergePrimitiveArrayStores::collect_merge_list(Node_List& merge_list) const {
3262   // The merged store can be at most 8 bytes.
3263   const uint merge_list_max_size = 8 / _store->memory_size();
3264   assert(merge_list_max_size >= 2 &&
3265          merge_list_max_size <= 8 &&
3266          is_power_of_2(merge_list_max_size),
3267          "must be 2, 4 or 8");
3268 
3269   // Traverse up the chain of adjacent def stores.
3270   StoreNode* current = _store;
3271   merge_list.push(current);
3272   while (current != nullptr && merge_list.size() < merge_list_max_size) {
3273     Status status = find_adjacent_def_store(current);
3274     current = status.found_store();
3275     if (current != nullptr) {
3276       merge_list.push(current);
3277 
3278       // We can have at most one RangeCheck.
3279       if (status.found_range_check()) {
3280         break;
3281       }
3282     }
3283   }
3284 
3285   // Truncate the merge_list to a power of 2.
3286   const uint pow2size = round_down_power_of_2(merge_list.size());
3287   assert(pow2size >= 2, "must be merging at least 2 stores");
3288   while (merge_list.size() > pow2size) { merge_list.pop(); }
3289 }
3290 
3291 // Merge the input values of the smaller stores to a single larger input value.
3292 Node* MergePrimitiveArrayStores::make_merged_input_value(const Node_List& merge_list) {
3293   int new_memory_size = _store->memory_size() * merge_list.size();
3294   Node* first = merge_list.at(merge_list.size()-1);
3295   Node* merged_input_value = nullptr;
3296   if (_store->in(MemNode::ValueIn)->Opcode() == Op_ConI) {
3297     // Pattern: [ConI, ConI, ...] -> new constant
3298     jlong con = 0;
3299     jlong bits_per_store = _store->memory_size() * 8;
3300     jlong mask = (((jlong)1) << bits_per_store) - 1;
3301     for (uint i = 0; i < merge_list.size(); i++) {
3302       jlong con_i = merge_list.at(i)->in(MemNode::ValueIn)->get_int();
3303 #ifdef VM_LITTLE_ENDIAN
3304       con = con << bits_per_store;
3305       con = con | (mask & con_i);
3306 #else // VM_LITTLE_ENDIAN
3307       con_i = (mask & con_i) << (i * bits_per_store);
3308       con = con | con_i;
3309 #endif // VM_LITTLE_ENDIAN
3310     }
3311     merged_input_value = _phase->longcon(con);
3312   } else {
3313     // Pattern: [base >> 24, base >> 16, base >> 8, base] -> base
3314     //             |                                  |
3315     //           _store                             first
3316     //
3317     Node* hi = _store->in(MemNode::ValueIn);
3318     Node* lo = first->in(MemNode::ValueIn);
3319 #ifndef VM_LITTLE_ENDIAN
3320     // `_store` and `first` are swapped in the diagram above
3321     swap(hi, lo);
3322 #endif // !VM_LITTLE_ENDIAN
3323     Node const* hi_base;
3324     jint hi_shift;
3325     merged_input_value = lo;
3326     bool is_true = is_con_RShift(hi, hi_base, hi_shift);
3327     assert(is_true, "must detect con RShift");
3328     if (merged_input_value != hi_base && merged_input_value->Opcode() == Op_ConvL2I) {
3329       // look through
3330       merged_input_value = merged_input_value->in(1);
3331     }
3332     if (merged_input_value != hi_base) {
3333       // merged_input_value is not the base
3334       return nullptr;
3335     }
3336   }
3337 
3338   if (_phase->type(merged_input_value)->isa_long() != nullptr && new_memory_size <= 4) {
3339     // Example:
3340     //
3341     //   long base = ...;
3342     //   a[0] = (byte)(base >> 0);
3343     //   a[1] = (byte)(base >> 8);
3344     //
3345     merged_input_value = _phase->transform(new ConvL2INode(merged_input_value));
3346   }
3347 
3348   assert((_phase->type(merged_input_value)->isa_int() != nullptr && new_memory_size <= 4) ||
3349          (_phase->type(merged_input_value)->isa_long() != nullptr && new_memory_size == 8),
3350          "merged_input_value is either int or long, and new_memory_size is small enough");
3351 
3352   return merged_input_value;
3353 }
3354 
3355 //                                                                                                          //
3356 // first_ctrl    first_mem   first_adr                first_ctrl    first_mem         first_adr             //
3357 //  |                |           |                     |                |                 |                 //
3358 //  |                |           |                     |                +---------------+ |                 //
3359 //  |                |           |                     |                |               | |                 //
3360 //  |                | +---------+                     |                | +---------------+                 //
3361 //  |                | |                               |                | |             | |                 //
3362 //  +--------------+ | |  v1                           +------------------------------+ | |  v1             //
3363 //  |              | | |  |                            |                | |           | | |  |              //
3364 // RangeCheck     first_store                         RangeCheck        | |          first_store            //
3365 //  |                |  |                              |                | |                |                //
3366 // last_ctrl         |  +----> unc_trap               last_ctrl         | |                +----> unc_trap  //
3367 //  |                |                       ===>      |                | |                                 //
3368 //  +--------------+ | a2 v2                           |                | |                                 //
3369 //  |              | | |  |                            |                | |                                 //
3370 //  |             second_store                         |                | |                                 //
3371 //  |                |                                 |                | | [v1 v2   ...   vn]              //
3372 // ...              ...                                |                | |         |                       //
3373 //  |                |                                 |                | |         v                       //
3374 //  +--------------+ | an vn                           +--------------+ | | merged_input_value              //
3375 //                 | | |  |                                           | | |  |                              //
3376 //                last_store (= _store)                              merged_store                           //
3377 //                                                                                                          //
3378 StoreNode* MergePrimitiveArrayStores::make_merged_store(const Node_List& merge_list, Node* merged_input_value) {
3379   Node* first_store = merge_list.at(merge_list.size()-1);
3380   Node* last_ctrl   = _store->in(MemNode::Control); // after (optional) RangeCheck
3381   Node* first_mem   = first_store->in(MemNode::Memory);
3382   Node* first_adr   = first_store->in(MemNode::Address);
3383 
3384   const TypePtr* new_adr_type = _store->adr_type();
3385 
3386   int new_memory_size = _store->memory_size() * merge_list.size();
3387   BasicType bt = T_ILLEGAL;
3388   switch (new_memory_size) {
3389     case 2: bt = T_SHORT; break;
3390     case 4: bt = T_INT;   break;
3391     case 8: bt = T_LONG;  break;
3392   }
3393 
3394   StoreNode* merged_store = StoreNode::make(*_phase, last_ctrl, first_mem, first_adr,
3395                                             new_adr_type, merged_input_value, bt, MemNode::unordered);
3396 
3397   // Marking the store mismatched is sufficient to prevent reordering, since array stores
3398   // are all on the same slice. Hence, we need no barriers.
3399   merged_store->set_mismatched_access();
3400 
3401   // Constants above may now also be be packed -> put candidate on worklist
3402   _phase->is_IterGVN()->_worklist.push(first_mem);
3403 
3404   return merged_store;
3405 }
3406 
3407 #ifdef ASSERT
3408 void MergePrimitiveArrayStores::trace(const Node_List& merge_list, const Node* merged_input_value, const StoreNode* merged_store) const {
3409   stringStream ss;
3410   ss.print_cr("[TraceMergeStores]: Replace");
3411   for (int i = (int)merge_list.size() - 1; i >= 0; i--) {
3412     merge_list.at(i)->dump("\n", false, &ss);
3413   }
3414   ss.print_cr("[TraceMergeStores]: with");
3415   merged_input_value->dump("\n", false, &ss);
3416   merged_store->dump("\n", false, &ss);
3417   tty->print("%s", ss.as_string());
3418 }
3419 #endif
3420 
3421 //------------------------------Ideal------------------------------------------
3422 // Change back-to-back Store(, p, x) -> Store(m, p, y) to Store(m, p, x).
3423 // When a store immediately follows a relevant allocation/initialization,
3424 // try to capture it into the initialization, or hoist it above.
3425 Node *StoreNode::Ideal(PhaseGVN *phase, bool can_reshape) {
3426   Node* p = MemNode::Ideal_common(phase, can_reshape);
3427   if (p)  return (p == NodeSentinel) ? nullptr : p;
3428 
3429   Node* mem     = in(MemNode::Memory);
3430   Node* address = in(MemNode::Address);
3431   Node* value   = in(MemNode::ValueIn);
3432   // Back-to-back stores to same address?  Fold em up.  Generally
3433   // unsafe if I have intervening uses...  Also disallowed for StoreCM
3434   // since they must follow each StoreP operation.  Redundant StoreCMs
3435   // are eliminated just before matching in final_graph_reshape.
3436   {
3437     Node* st = mem;
3438     // If Store 'st' has more than one use, we cannot fold 'st' away.
3439     // For example, 'st' might be the final state at a conditional
3440     // return.  Or, 'st' might be used by some node which is live at
3441     // the same time 'st' is live, which might be unschedulable.  So,
3442     // require exactly ONE user until such time as we clone 'mem' for
3443     // each of 'mem's uses (thus making the exactly-1-user-rule hold
3444     // true).
3445     while (st->is_Store() && st->outcnt() == 1 && st->Opcode() != Op_StoreCM) {
3446       // Looking at a dead closed cycle of memory?
3447       assert(st != st->in(MemNode::Memory), "dead loop in StoreNode::Ideal");
3448       assert(Opcode() == st->Opcode() ||
3449              st->Opcode() == Op_StoreVector ||
3450              Opcode() == Op_StoreVector ||
3451              st->Opcode() == Op_StoreVectorScatter ||
3452              Opcode() == Op_StoreVectorScatter ||
3453              phase->C->get_alias_index(adr_type()) == Compile::AliasIdxRaw ||
3454              (Opcode() == Op_StoreL && st->Opcode() == Op_StoreI) || // expanded ClearArrayNode
3455              (Opcode() == Op_StoreI && st->Opcode() == Op_StoreL) || // initialization by arraycopy
3456              (is_mismatched_access() || st->as_Store()->is_mismatched_access()),
3457              "no mismatched stores, except on raw memory: %s %s", NodeClassNames[Opcode()], NodeClassNames[st->Opcode()]);
3458 
3459       if (st->in(MemNode::Address)->eqv_uncast(address) &&
3460           st->as_Store()->memory_size() <= this->memory_size()) {
3461         Node* use = st->raw_out(0);
3462         if (phase->is_IterGVN()) {
3463           phase->is_IterGVN()->rehash_node_delayed(use);
3464         }
3465         // It's OK to do this in the parser, since DU info is always accurate,
3466         // and the parser always refers to nodes via SafePointNode maps.
3467         use->set_req_X(MemNode::Memory, st->in(MemNode::Memory), phase);
3468         return this;
3469       }
3470       st = st->in(MemNode::Memory);
3471     }
3472   }
3473 
3474 
3475   // Capture an unaliased, unconditional, simple store into an initializer.
3476   // Or, if it is independent of the allocation, hoist it above the allocation.
3477   if (ReduceFieldZeroing && /*can_reshape &&*/
3478       mem->is_Proj() && mem->in(0)->is_Initialize()) {
3479     InitializeNode* init = mem->in(0)->as_Initialize();
3480     intptr_t offset = init->can_capture_store(this, phase, can_reshape);
3481     if (offset > 0) {
3482       Node* moved = init->capture_store(this, offset, phase, can_reshape);
3483       // If the InitializeNode captured me, it made a raw copy of me,
3484       // and I need to disappear.
3485       if (moved != nullptr) {
3486         // %%% hack to ensure that Ideal returns a new node:
3487         mem = MergeMemNode::make(mem);
3488         return mem;             // fold me away
3489       }
3490     }
3491   }
3492 
3493   // Fold reinterpret cast into memory operation:
3494   //    StoreX mem (MoveY2X v) => StoreY mem v
3495   if (value->is_Move()) {
3496     const Type* vt = value->in(1)->bottom_type();
3497     if (has_reinterpret_variant(vt)) {
3498       if (phase->C->post_loop_opts_phase()) {
3499         return convert_to_reinterpret_store(*phase, value->in(1), vt);
3500       } else {
3501         phase->C->record_for_post_loop_opts_igvn(this); // attempt the transformation once loop opts are over
3502       }
3503     }
3504   }
3505 
3506   if (MergeStores && UseUnalignedAccesses) {
3507     if (phase->C->post_loop_opts_phase()) {
3508       MergePrimitiveArrayStores merge(phase, this);
3509       Node* progress = merge.run();
3510       if (progress != nullptr) { return progress; }
3511     } else {
3512       phase->C->record_for_post_loop_opts_igvn(this);
3513     }
3514   }
3515 
3516   return nullptr;                  // No further progress
3517 }
3518 
3519 //------------------------------Value-----------------------------------------
3520 const Type* StoreNode::Value(PhaseGVN* phase) const {
3521   // Either input is TOP ==> the result is TOP
3522   const Type *t1 = phase->type( in(MemNode::Memory) );
3523   if( t1 == Type::TOP ) return Type::TOP;
3524   const Type *t2 = phase->type( in(MemNode::Address) );
3525   if( t2 == Type::TOP ) return Type::TOP;
3526   const Type *t3 = phase->type( in(MemNode::ValueIn) );
3527   if( t3 == Type::TOP ) return Type::TOP;
3528   return Type::MEMORY;
3529 }
3530 
3531 //------------------------------Identity---------------------------------------
3532 // Remove redundant stores:
3533 //   Store(m, p, Load(m, p)) changes to m.
3534 //   Store(, p, x) -> Store(m, p, x) changes to Store(m, p, x).
3535 Node* StoreNode::Identity(PhaseGVN* phase) {
3536   Node* mem = in(MemNode::Memory);
3537   Node* adr = in(MemNode::Address);
3538   Node* val = in(MemNode::ValueIn);
3539 
3540   Node* result = this;
3541 
3542   // Load then Store?  Then the Store is useless
3543   if (val->is_Load() &&
3544       val->in(MemNode::Address)->eqv_uncast(adr) &&
3545       val->in(MemNode::Memory )->eqv_uncast(mem) &&
3546       val->as_Load()->store_Opcode() == Opcode()) {
3547     // Ensure vector type is the same
3548     if (!is_StoreVector() || (mem->is_LoadVector() && as_StoreVector()->vect_type() == mem->as_LoadVector()->vect_type())) {
3549       result = mem;
3550     }
3551   }
3552 
3553   // Two stores in a row of the same value?
3554   if (result == this &&
3555       mem->is_Store() &&
3556       mem->in(MemNode::Address)->eqv_uncast(adr) &&
3557       mem->in(MemNode::ValueIn)->eqv_uncast(val) &&
3558       mem->Opcode() == Opcode()) {
3559     if (!is_StoreVector()) {
3560       result = mem;
3561     } else {
3562       const StoreVectorNode* store_vector = as_StoreVector();
3563       const StoreVectorNode* mem_vector = mem->as_StoreVector();
3564       const Node* store_indices = store_vector->indices();
3565       const Node* mem_indices = mem_vector->indices();
3566       const Node* store_mask = store_vector->mask();
3567       const Node* mem_mask = mem_vector->mask();
3568       // Ensure types, indices, and masks match
3569       if (store_vector->vect_type() == mem_vector->vect_type() &&
3570           ((store_indices == nullptr) == (mem_indices == nullptr) &&
3571            (store_indices == nullptr || store_indices->eqv_uncast(mem_indices))) &&
3572           ((store_mask == nullptr) == (mem_mask == nullptr) &&
3573            (store_mask == nullptr || store_mask->eqv_uncast(mem_mask)))) {
3574         result = mem;
3575       }
3576     }
3577   }
3578 
3579   // Store of zero anywhere into a freshly-allocated object?
3580   // Then the store is useless.
3581   // (It must already have been captured by the InitializeNode.)
3582   if (result == this &&
3583       ReduceFieldZeroing && phase->type(val)->is_zero_type()) {
3584     // a newly allocated object is already all-zeroes everywhere
3585     if (mem->is_Proj() && mem->in(0)->is_Allocate()) {
3586       result = mem;
3587     }
3588 
3589     if (result == this) {
3590       // the store may also apply to zero-bits in an earlier object
3591       Node* prev_mem = find_previous_store(phase);
3592       // Steps (a), (b):  Walk past independent stores to find an exact match.
3593       if (prev_mem != nullptr) {
3594         Node* prev_val = can_see_stored_value(prev_mem, phase);
3595         if (prev_val != nullptr && prev_val == val) {
3596           // prev_val and val might differ by a cast; it would be good
3597           // to keep the more informative of the two.
3598           result = mem;
3599         }
3600       }
3601     }
3602   }
3603 
3604   PhaseIterGVN* igvn = phase->is_IterGVN();
3605   if (result != this && igvn != nullptr) {
3606     MemBarNode* trailing = trailing_membar();
3607     if (trailing != nullptr) {
3608 #ifdef ASSERT
3609       const TypeOopPtr* t_oop = phase->type(in(Address))->isa_oopptr();
3610       assert(t_oop == nullptr || t_oop->is_known_instance_field(), "only for non escaping objects");
3611 #endif
3612       trailing->remove(igvn);
3613     }
3614   }
3615 
3616   return result;
3617 }
3618 
3619 //------------------------------match_edge-------------------------------------
3620 // Do we Match on this edge index or not?  Match only memory & value
3621 uint StoreNode::match_edge(uint idx) const {
3622   return idx == MemNode::Address || idx == MemNode::ValueIn;
3623 }
3624 
3625 //------------------------------cmp--------------------------------------------
3626 // Do not common stores up together.  They generally have to be split
3627 // back up anyways, so do not bother.
3628 bool StoreNode::cmp( const Node &n ) const {
3629   return (&n == this);          // Always fail except on self
3630 }
3631 
3632 //------------------------------Ideal_masked_input-----------------------------
3633 // Check for a useless mask before a partial-word store
3634 // (StoreB ... (AndI valIn conIa) )
3635 // If (conIa & mask == mask) this simplifies to
3636 // (StoreB ... (valIn) )
3637 Node *StoreNode::Ideal_masked_input(PhaseGVN *phase, uint mask) {
3638   Node *val = in(MemNode::ValueIn);
3639   if( val->Opcode() == Op_AndI ) {
3640     const TypeInt *t = phase->type( val->in(2) )->isa_int();
3641     if( t && t->is_con() && (t->get_con() & mask) == mask ) {
3642       set_req_X(MemNode::ValueIn, val->in(1), phase);
3643       return this;
3644     }
3645   }
3646   return nullptr;
3647 }
3648 
3649 
3650 //------------------------------Ideal_sign_extended_input----------------------
3651 // Check for useless sign-extension before a partial-word store
3652 // (StoreB ... (RShiftI _ (LShiftI _ valIn conIL ) conIR) )
3653 // If (conIL == conIR && conIR <= num_bits)  this simplifies to
3654 // (StoreB ... (valIn) )
3655 Node *StoreNode::Ideal_sign_extended_input(PhaseGVN *phase, int num_bits) {
3656   Node *val = in(MemNode::ValueIn);
3657   if( val->Opcode() == Op_RShiftI ) {
3658     const TypeInt *t = phase->type( val->in(2) )->isa_int();
3659     if( t && t->is_con() && (t->get_con() <= num_bits) ) {
3660       Node *shl = val->in(1);
3661       if( shl->Opcode() == Op_LShiftI ) {
3662         const TypeInt *t2 = phase->type( shl->in(2) )->isa_int();
3663         if( t2 && t2->is_con() && (t2->get_con() == t->get_con()) ) {
3664           set_req_X(MemNode::ValueIn, shl->in(1), phase);
3665           return this;
3666         }
3667       }
3668     }
3669   }
3670   return nullptr;
3671 }
3672 
3673 //------------------------------value_never_loaded-----------------------------------
3674 // Determine whether there are any possible loads of the value stored.
3675 // For simplicity, we actually check if there are any loads from the
3676 // address stored to, not just for loads of the value stored by this node.
3677 //
3678 bool StoreNode::value_never_loaded(PhaseValues* phase) const {
3679   Node *adr = in(Address);
3680   const TypeOopPtr *adr_oop = phase->type(adr)->isa_oopptr();
3681   if (adr_oop == nullptr)
3682     return false;
3683   if (!adr_oop->is_known_instance_field())
3684     return false; // if not a distinct instance, there may be aliases of the address
3685   for (DUIterator_Fast imax, i = adr->fast_outs(imax); i < imax; i++) {
3686     Node *use = adr->fast_out(i);
3687     if (use->is_Load() || use->is_LoadStore()) {
3688       return false;
3689     }
3690   }
3691   return true;
3692 }
3693 
3694 MemBarNode* StoreNode::trailing_membar() const {
3695   if (is_release()) {
3696     MemBarNode* trailing_mb = nullptr;
3697     for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
3698       Node* u = fast_out(i);
3699       if (u->is_MemBar()) {
3700         if (u->as_MemBar()->trailing_store()) {
3701           assert(u->Opcode() == Op_MemBarVolatile, "");
3702           assert(trailing_mb == nullptr, "only one");
3703           trailing_mb = u->as_MemBar();
3704 #ifdef ASSERT
3705           Node* leading = u->as_MemBar()->leading_membar();
3706           assert(leading->Opcode() == Op_MemBarRelease, "incorrect membar");
3707           assert(leading->as_MemBar()->leading_store(), "incorrect membar pair");
3708           assert(leading->as_MemBar()->trailing_membar() == u, "incorrect membar pair");
3709 #endif
3710         } else {
3711           assert(u->as_MemBar()->standalone(), "");
3712         }
3713       }
3714     }
3715     return trailing_mb;
3716   }
3717   return nullptr;
3718 }
3719 
3720 
3721 //=============================================================================
3722 //------------------------------Ideal------------------------------------------
3723 // If the store is from an AND mask that leaves the low bits untouched, then
3724 // we can skip the AND operation.  If the store is from a sign-extension
3725 // (a left shift, then right shift) we can skip both.
3726 Node *StoreBNode::Ideal(PhaseGVN *phase, bool can_reshape){
3727   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFF);
3728   if( progress != nullptr ) return progress;
3729 
3730   progress = StoreNode::Ideal_sign_extended_input(phase, 24);
3731   if( progress != nullptr ) return progress;
3732 
3733   // Finally check the default case
3734   return StoreNode::Ideal(phase, can_reshape);
3735 }
3736 
3737 //=============================================================================
3738 //------------------------------Ideal------------------------------------------
3739 // If the store is from an AND mask that leaves the low bits untouched, then
3740 // we can skip the AND operation
3741 Node *StoreCNode::Ideal(PhaseGVN *phase, bool can_reshape){
3742   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFFFF);
3743   if( progress != nullptr ) return progress;
3744 
3745   progress = StoreNode::Ideal_sign_extended_input(phase, 16);
3746   if( progress != nullptr ) return progress;
3747 
3748   // Finally check the default case
3749   return StoreNode::Ideal(phase, can_reshape);
3750 }
3751 
3752 //=============================================================================
3753 //------------------------------Identity---------------------------------------
3754 Node* StoreCMNode::Identity(PhaseGVN* phase) {
3755   // No need to card mark when storing a null ptr
3756   Node* my_store = in(MemNode::OopStore);
3757   if (my_store->is_Store()) {
3758     const Type *t1 = phase->type( my_store->in(MemNode::ValueIn) );
3759     if( t1 == TypePtr::NULL_PTR ) {
3760       return in(MemNode::Memory);
3761     }
3762   }
3763   return this;
3764 }
3765 
3766 //=============================================================================
3767 //------------------------------Ideal---------------------------------------
3768 Node *StoreCMNode::Ideal(PhaseGVN *phase, bool can_reshape){
3769   Node* progress = StoreNode::Ideal(phase, can_reshape);
3770   if (progress != nullptr) return progress;
3771 
3772   Node* my_store = in(MemNode::OopStore);
3773   if (my_store->is_MergeMem()) {
3774     Node* mem = my_store->as_MergeMem()->memory_at(oop_alias_idx());
3775     set_req_X(MemNode::OopStore, mem, phase);
3776     return this;
3777   }
3778 
3779   return nullptr;
3780 }
3781 
3782 //------------------------------Value-----------------------------------------
3783 const Type* StoreCMNode::Value(PhaseGVN* phase) const {
3784   // Either input is TOP ==> the result is TOP (checked in StoreNode::Value).
3785   // If extra input is TOP ==> the result is TOP
3786   const Type* t = phase->type(in(MemNode::OopStore));
3787   if (t == Type::TOP) {
3788     return Type::TOP;
3789   }
3790   return StoreNode::Value(phase);
3791 }
3792 
3793 
3794 //=============================================================================
3795 //----------------------------------SCMemProjNode------------------------------
3796 const Type* SCMemProjNode::Value(PhaseGVN* phase) const
3797 {
3798   if (in(0) == nullptr || phase->type(in(0)) == Type::TOP) {
3799     return Type::TOP;
3800   }
3801   return bottom_type();
3802 }
3803 
3804 //=============================================================================
3805 //----------------------------------LoadStoreNode------------------------------
3806 LoadStoreNode::LoadStoreNode( Node *c, Node *mem, Node *adr, Node *val, const TypePtr* at, const Type* rt, uint required )
3807   : Node(required),
3808     _type(rt),
3809     _adr_type(at),
3810     _barrier_data(0)
3811 {
3812   init_req(MemNode::Control, c  );
3813   init_req(MemNode::Memory , mem);
3814   init_req(MemNode::Address, adr);
3815   init_req(MemNode::ValueIn, val);
3816   init_class_id(Class_LoadStore);
3817 }
3818 
3819 //------------------------------Value-----------------------------------------
3820 const Type* LoadStoreNode::Value(PhaseGVN* phase) const {
3821   // Either input is TOP ==> the result is TOP
3822   if (!in(MemNode::Control) || phase->type(in(MemNode::Control)) == Type::TOP) {
3823     return Type::TOP;
3824   }
3825   const Type* t = phase->type(in(MemNode::Memory));
3826   if (t == Type::TOP) {
3827     return Type::TOP;
3828   }
3829   t = phase->type(in(MemNode::Address));
3830   if (t == Type::TOP) {
3831     return Type::TOP;
3832   }
3833   t = phase->type(in(MemNode::ValueIn));
3834   if (t == Type::TOP) {
3835     return Type::TOP;
3836   }
3837   return bottom_type();
3838 }
3839 
3840 uint LoadStoreNode::ideal_reg() const {
3841   return _type->ideal_reg();
3842 }
3843 
3844 // This method conservatively checks if the result of a LoadStoreNode is
3845 // used, that is, if it returns true, then it is definitely the case that
3846 // the result of the node is not needed.
3847 // For example, GetAndAdd can be matched into a lock_add instead of a
3848 // lock_xadd if the result of LoadStoreNode::result_not_used() is true
3849 bool LoadStoreNode::result_not_used() const {
3850   for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
3851     Node *x = fast_out(i);
3852     if (x->Opcode() == Op_SCMemProj) {
3853       continue;
3854     }
3855     if (x->bottom_type() == TypeTuple::MEMBAR &&
3856         !x->is_Call() &&
3857         x->Opcode() != Op_Blackhole) {
3858       continue;
3859     }
3860     return false;
3861   }
3862   return true;
3863 }
3864 
3865 MemBarNode* LoadStoreNode::trailing_membar() const {
3866   MemBarNode* trailing = nullptr;
3867   for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
3868     Node* u = fast_out(i);
3869     if (u->is_MemBar()) {
3870       if (u->as_MemBar()->trailing_load_store()) {
3871         assert(u->Opcode() == Op_MemBarAcquire, "");
3872         assert(trailing == nullptr, "only one");
3873         trailing = u->as_MemBar();
3874 #ifdef ASSERT
3875         Node* leading = trailing->leading_membar();
3876         assert(support_IRIW_for_not_multiple_copy_atomic_cpu || leading->Opcode() == Op_MemBarRelease, "incorrect membar");
3877         assert(leading->as_MemBar()->leading_load_store(), "incorrect membar pair");
3878         assert(leading->as_MemBar()->trailing_membar() == trailing, "incorrect membar pair");
3879 #endif
3880       } else {
3881         assert(u->as_MemBar()->standalone(), "wrong barrier kind");
3882       }
3883     }
3884   }
3885 
3886   return trailing;
3887 }
3888 
3889 uint LoadStoreNode::size_of() const { return sizeof(*this); }
3890 
3891 //=============================================================================
3892 //----------------------------------LoadStoreConditionalNode--------------------
3893 LoadStoreConditionalNode::LoadStoreConditionalNode( Node *c, Node *mem, Node *adr, Node *val, Node *ex ) : LoadStoreNode(c, mem, adr, val, nullptr, TypeInt::BOOL, 5) {
3894   init_req(ExpectedIn, ex );
3895 }
3896 
3897 const Type* LoadStoreConditionalNode::Value(PhaseGVN* phase) const {
3898   // Either input is TOP ==> the result is TOP
3899   const Type* t = phase->type(in(ExpectedIn));
3900   if (t == Type::TOP) {
3901     return Type::TOP;
3902   }
3903   return LoadStoreNode::Value(phase);
3904 }
3905 
3906 //=============================================================================
3907 //-------------------------------adr_type--------------------------------------
3908 const TypePtr* ClearArrayNode::adr_type() const {
3909   Node *adr = in(3);
3910   if (adr == nullptr)  return nullptr; // node is dead
3911   return MemNode::calculate_adr_type(adr->bottom_type());
3912 }
3913 
3914 //------------------------------match_edge-------------------------------------
3915 // Do we Match on this edge index or not?  Do not match memory
3916 uint ClearArrayNode::match_edge(uint idx) const {
3917   return idx > 1;
3918 }
3919 
3920 //------------------------------Identity---------------------------------------
3921 // Clearing a zero length array does nothing
3922 Node* ClearArrayNode::Identity(PhaseGVN* phase) {
3923   return phase->type(in(2))->higher_equal(TypeX::ZERO)  ? in(1) : this;
3924 }
3925 
3926 //------------------------------Idealize---------------------------------------
3927 // Clearing a short array is faster with stores
3928 Node *ClearArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) {
3929   // Already know this is a large node, do not try to ideal it
3930   if (_is_large) return nullptr;
3931 
3932   const int unit = BytesPerLong;
3933   const TypeX* t = phase->type(in(2))->isa_intptr_t();
3934   if (!t)  return nullptr;
3935   if (!t->is_con())  return nullptr;
3936   intptr_t raw_count = t->get_con();
3937   intptr_t size = raw_count;
3938   if (!Matcher::init_array_count_is_in_bytes) size *= unit;
3939   // Clearing nothing uses the Identity call.
3940   // Negative clears are possible on dead ClearArrays
3941   // (see jck test stmt114.stmt11402.val).
3942   if (size <= 0 || size % unit != 0)  return nullptr;
3943   intptr_t count = size / unit;
3944   // Length too long; communicate this to matchers and assemblers.
3945   // Assemblers are responsible to produce fast hardware clears for it.
3946   if (size > InitArrayShortSize) {
3947     return new ClearArrayNode(in(0), in(1), in(2), in(3), true);
3948   } else if (size > 2 && Matcher::match_rule_supported_vector(Op_ClearArray, 4, T_LONG)) {
3949     return nullptr;
3950   }
3951   if (!IdealizeClearArrayNode) return nullptr;
3952   Node *mem = in(1);
3953   if( phase->type(mem)==Type::TOP ) return nullptr;
3954   Node *adr = in(3);
3955   const Type* at = phase->type(adr);
3956   if( at==Type::TOP ) return nullptr;
3957   const TypePtr* atp = at->isa_ptr();
3958   // adjust atp to be the correct array element address type
3959   if (atp == nullptr)  atp = TypePtr::BOTTOM;
3960   else              atp = atp->add_offset(Type::OffsetBot);
3961   // Get base for derived pointer purposes
3962   if( adr->Opcode() != Op_AddP ) Unimplemented();
3963   Node *base = adr->in(1);
3964 
3965   Node *zero = phase->makecon(TypeLong::ZERO);
3966   Node *off  = phase->MakeConX(BytesPerLong);
3967   mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
3968   count--;
3969   while( count-- ) {
3970     mem = phase->transform(mem);
3971     adr = phase->transform(new AddPNode(base,adr,off));
3972     mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
3973   }
3974   return mem;
3975 }
3976 
3977 //----------------------------step_through----------------------------------
3978 // Return allocation input memory edge if it is different instance
3979 // or itself if it is the one we are looking for.
3980 bool ClearArrayNode::step_through(Node** np, uint instance_id, PhaseValues* phase) {
3981   Node* n = *np;
3982   assert(n->is_ClearArray(), "sanity");
3983   intptr_t offset;
3984   AllocateNode* alloc = AllocateNode::Ideal_allocation(n->in(3), phase, offset);
3985   // This method is called only before Allocate nodes are expanded
3986   // during macro nodes expansion. Before that ClearArray nodes are
3987   // only generated in PhaseMacroExpand::generate_arraycopy() (before
3988   // Allocate nodes are expanded) which follows allocations.
3989   assert(alloc != nullptr, "should have allocation");
3990   if (alloc->_idx == instance_id) {
3991     // Can not bypass initialization of the instance we are looking for.
3992     return false;
3993   }
3994   // Otherwise skip it.
3995   InitializeNode* init = alloc->initialization();
3996   if (init != nullptr)
3997     *np = init->in(TypeFunc::Memory);
3998   else
3999     *np = alloc->in(TypeFunc::Memory);
4000   return true;
4001 }
4002 
4003 //----------------------------clear_memory-------------------------------------
4004 // Generate code to initialize object storage to zero.
4005 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
4006                                    intptr_t start_offset,
4007                                    Node* end_offset,
4008                                    PhaseGVN* phase) {
4009   intptr_t offset = start_offset;
4010 
4011   int unit = BytesPerLong;
4012   if ((offset % unit) != 0) {
4013     Node* adr = new AddPNode(dest, dest, phase->MakeConX(offset));
4014     adr = phase->transform(adr);
4015     const TypePtr* atp = TypeRawPtr::BOTTOM;
4016     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
4017     mem = phase->transform(mem);
4018     offset += BytesPerInt;
4019   }
4020   assert((offset % unit) == 0, "");
4021 
4022   // Initialize the remaining stuff, if any, with a ClearArray.
4023   return clear_memory(ctl, mem, dest, phase->MakeConX(offset), end_offset, phase);
4024 }
4025 
4026 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
4027                                    Node* start_offset,
4028                                    Node* end_offset,
4029                                    PhaseGVN* phase) {
4030   if (start_offset == end_offset) {
4031     // nothing to do
4032     return mem;
4033   }
4034 
4035   int unit = BytesPerLong;
4036   Node* zbase = start_offset;
4037   Node* zend  = end_offset;
4038 
4039   // Scale to the unit required by the CPU:
4040   if (!Matcher::init_array_count_is_in_bytes) {
4041     Node* shift = phase->intcon(exact_log2(unit));
4042     zbase = phase->transform(new URShiftXNode(zbase, shift) );
4043     zend  = phase->transform(new URShiftXNode(zend,  shift) );
4044   }
4045 
4046   // Bulk clear double-words
4047   Node* zsize = phase->transform(new SubXNode(zend, zbase) );
4048   Node* adr = phase->transform(new AddPNode(dest, dest, start_offset) );
4049   mem = new ClearArrayNode(ctl, mem, zsize, adr, false);
4050   return phase->transform(mem);
4051 }
4052 
4053 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
4054                                    intptr_t start_offset,
4055                                    intptr_t end_offset,
4056                                    PhaseGVN* phase) {
4057   if (start_offset == end_offset) {
4058     // nothing to do
4059     return mem;
4060   }
4061 
4062   assert((end_offset % BytesPerInt) == 0, "odd end offset");
4063   intptr_t done_offset = end_offset;
4064   if ((done_offset % BytesPerLong) != 0) {
4065     done_offset -= BytesPerInt;
4066   }
4067   if (done_offset > start_offset) {
4068     mem = clear_memory(ctl, mem, dest,
4069                        start_offset, phase->MakeConX(done_offset), phase);
4070   }
4071   if (done_offset < end_offset) { // emit the final 32-bit store
4072     Node* adr = new AddPNode(dest, dest, phase->MakeConX(done_offset));
4073     adr = phase->transform(adr);
4074     const TypePtr* atp = TypeRawPtr::BOTTOM;
4075     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
4076     mem = phase->transform(mem);
4077     done_offset += BytesPerInt;
4078   }
4079   assert(done_offset == end_offset, "");
4080   return mem;
4081 }
4082 
4083 //=============================================================================
4084 MemBarNode::MemBarNode(Compile* C, int alias_idx, Node* precedent)
4085   : MultiNode(TypeFunc::Parms + (precedent == nullptr? 0: 1)),
4086     _adr_type(C->get_adr_type(alias_idx)), _kind(Standalone)
4087 #ifdef ASSERT
4088   , _pair_idx(0)
4089 #endif
4090 {
4091   init_class_id(Class_MemBar);
4092   Node* top = C->top();
4093   init_req(TypeFunc::I_O,top);
4094   init_req(TypeFunc::FramePtr,top);
4095   init_req(TypeFunc::ReturnAdr,top);
4096   if (precedent != nullptr)
4097     init_req(TypeFunc::Parms, precedent);
4098 }
4099 
4100 //------------------------------cmp--------------------------------------------
4101 uint MemBarNode::hash() const { return NO_HASH; }
4102 bool MemBarNode::cmp( const Node &n ) const {
4103   return (&n == this);          // Always fail except on self
4104 }
4105 
4106 //------------------------------make-------------------------------------------
4107 MemBarNode* MemBarNode::make(Compile* C, int opcode, int atp, Node* pn) {
4108   switch (opcode) {
4109   case Op_MemBarAcquire:     return new MemBarAcquireNode(C, atp, pn);
4110   case Op_LoadFence:         return new LoadFenceNode(C, atp, pn);
4111   case Op_MemBarRelease:     return new MemBarReleaseNode(C, atp, pn);
4112   case Op_StoreFence:        return new StoreFenceNode(C, atp, pn);
4113   case Op_MemBarStoreStore:  return new MemBarStoreStoreNode(C, atp, pn);
4114   case Op_StoreStoreFence:   return new StoreStoreFenceNode(C, atp, pn);
4115   case Op_MemBarAcquireLock: return new MemBarAcquireLockNode(C, atp, pn);
4116   case Op_MemBarReleaseLock: return new MemBarReleaseLockNode(C, atp, pn);
4117   case Op_MemBarVolatile:    return new MemBarVolatileNode(C, atp, pn);
4118   case Op_MemBarCPUOrder:    return new MemBarCPUOrderNode(C, atp, pn);
4119   case Op_OnSpinWait:        return new OnSpinWaitNode(C, atp, pn);
4120   case Op_Initialize:        return new InitializeNode(C, atp, pn);
4121   default: ShouldNotReachHere(); return nullptr;
4122   }
4123 }
4124 
4125 void MemBarNode::remove(PhaseIterGVN *igvn) {
4126   if (outcnt() != 2) {
4127     assert(Opcode() == Op_Initialize, "Only seen when there are no use of init memory");
4128     assert(outcnt() == 1, "Only control then");
4129   }
4130   if (trailing_store() || trailing_load_store()) {
4131     MemBarNode* leading = leading_membar();
4132     if (leading != nullptr) {
4133       assert(leading->trailing_membar() == this, "inconsistent leading/trailing membars");
4134       leading->remove(igvn);
4135     }
4136   }
4137   if (proj_out_or_null(TypeFunc::Memory) != nullptr) {
4138     igvn->replace_node(proj_out(TypeFunc::Memory), in(TypeFunc::Memory));
4139   }
4140   if (proj_out_or_null(TypeFunc::Control) != nullptr) {
4141     igvn->replace_node(proj_out(TypeFunc::Control), in(TypeFunc::Control));
4142   }
4143 }
4144 
4145 //------------------------------Ideal------------------------------------------
4146 // Return a node which is more "ideal" than the current node.  Strip out
4147 // control copies
4148 Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) {
4149   if (remove_dead_region(phase, can_reshape)) return this;
4150   // Don't bother trying to transform a dead node
4151   if (in(0) && in(0)->is_top()) {
4152     return nullptr;
4153   }
4154 
4155   bool progress = false;
4156   // Eliminate volatile MemBars for scalar replaced objects.
4157   if (can_reshape && req() == (Precedent+1)) {
4158     bool eliminate = false;
4159     int opc = Opcode();
4160     if ((opc == Op_MemBarAcquire || opc == Op_MemBarVolatile)) {
4161       // Volatile field loads and stores.
4162       Node* my_mem = in(MemBarNode::Precedent);
4163       // The MembarAquire may keep an unused LoadNode alive through the Precedent edge
4164       if ((my_mem != nullptr) && (opc == Op_MemBarAcquire) && (my_mem->outcnt() == 1)) {
4165         // if the Precedent is a decodeN and its input (a Load) is used at more than one place,
4166         // replace this Precedent (decodeN) with the Load instead.
4167         if ((my_mem->Opcode() == Op_DecodeN) && (my_mem->in(1)->outcnt() > 1))  {
4168           Node* load_node = my_mem->in(1);
4169           set_req(MemBarNode::Precedent, load_node);
4170           phase->is_IterGVN()->_worklist.push(my_mem);
4171           my_mem = load_node;
4172         } else {
4173           assert(my_mem->unique_out() == this, "sanity");
4174           assert(!trailing_load_store(), "load store node can't be eliminated");
4175           del_req(Precedent);
4176           phase->is_IterGVN()->_worklist.push(my_mem); // remove dead node later
4177           my_mem = nullptr;
4178         }
4179         progress = true;
4180       }
4181       if (my_mem != nullptr && my_mem->is_Mem()) {
4182         const TypeOopPtr* t_oop = my_mem->in(MemNode::Address)->bottom_type()->isa_oopptr();
4183         // Check for scalar replaced object reference.
4184         if( t_oop != nullptr && t_oop->is_known_instance_field() &&
4185             t_oop->offset() != Type::OffsetBot &&
4186             t_oop->offset() != Type::OffsetTop) {
4187           eliminate = true;
4188         }
4189       }
4190     } else if (opc == Op_MemBarRelease || (UseStoreStoreForCtor && opc == Op_MemBarStoreStore)) {
4191       // Final field stores.
4192       Node* alloc = AllocateNode::Ideal_allocation(in(MemBarNode::Precedent));
4193       if ((alloc != nullptr) && alloc->is_Allocate() &&
4194           alloc->as_Allocate()->does_not_escape_thread()) {
4195         // The allocated object does not escape.
4196         eliminate = true;
4197       }
4198     }
4199     if (eliminate) {
4200       // Replace MemBar projections by its inputs.
4201       PhaseIterGVN* igvn = phase->is_IterGVN();
4202       remove(igvn);
4203       // Must return either the original node (now dead) or a new node
4204       // (Do not return a top here, since that would break the uniqueness of top.)
4205       return new ConINode(TypeInt::ZERO);
4206     }
4207   }
4208   return progress ? this : nullptr;
4209 }
4210 
4211 //------------------------------Value------------------------------------------
4212 const Type* MemBarNode::Value(PhaseGVN* phase) const {
4213   if( !in(0) ) return Type::TOP;
4214   if( phase->type(in(0)) == Type::TOP )
4215     return Type::TOP;
4216   return TypeTuple::MEMBAR;
4217 }
4218 
4219 //------------------------------match------------------------------------------
4220 // Construct projections for memory.
4221 Node *MemBarNode::match( const ProjNode *proj, const Matcher *m ) {
4222   switch (proj->_con) {
4223   case TypeFunc::Control:
4224   case TypeFunc::Memory:
4225     return new MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
4226   }
4227   ShouldNotReachHere();
4228   return nullptr;
4229 }
4230 
4231 void MemBarNode::set_store_pair(MemBarNode* leading, MemBarNode* trailing) {
4232   trailing->_kind = TrailingStore;
4233   leading->_kind = LeadingStore;
4234 #ifdef ASSERT
4235   trailing->_pair_idx = leading->_idx;
4236   leading->_pair_idx = leading->_idx;
4237 #endif
4238 }
4239 
4240 void MemBarNode::set_load_store_pair(MemBarNode* leading, MemBarNode* trailing) {
4241   trailing->_kind = TrailingLoadStore;
4242   leading->_kind = LeadingLoadStore;
4243 #ifdef ASSERT
4244   trailing->_pair_idx = leading->_idx;
4245   leading->_pair_idx = leading->_idx;
4246 #endif
4247 }
4248 
4249 MemBarNode* MemBarNode::trailing_membar() const {
4250   ResourceMark rm;
4251   Node* trailing = (Node*)this;
4252   VectorSet seen;
4253   Node_Stack multis(0);
4254   do {
4255     Node* c = trailing;
4256     uint i = 0;
4257     do {
4258       trailing = nullptr;
4259       for (; i < c->outcnt(); i++) {
4260         Node* next = c->raw_out(i);
4261         if (next != c && next->is_CFG()) {
4262           if (c->is_MultiBranch()) {
4263             if (multis.node() == c) {
4264               multis.set_index(i+1);
4265             } else {
4266               multis.push(c, i+1);
4267             }
4268           }
4269           trailing = next;
4270           break;
4271         }
4272       }
4273       if (trailing != nullptr && !seen.test_set(trailing->_idx)) {
4274         break;
4275       }
4276       while (multis.size() > 0) {
4277         c = multis.node();
4278         i = multis.index();
4279         if (i < c->req()) {
4280           break;
4281         }
4282         multis.pop();
4283       }
4284     } while (multis.size() > 0);
4285   } while (!trailing->is_MemBar() || !trailing->as_MemBar()->trailing());
4286 
4287   MemBarNode* mb = trailing->as_MemBar();
4288   assert((mb->_kind == TrailingStore && _kind == LeadingStore) ||
4289          (mb->_kind == TrailingLoadStore && _kind == LeadingLoadStore), "bad trailing membar");
4290   assert(mb->_pair_idx == _pair_idx, "bad trailing membar");
4291   return mb;
4292 }
4293 
4294 MemBarNode* MemBarNode::leading_membar() const {
4295   ResourceMark rm;
4296   VectorSet seen;
4297   Node_Stack regions(0);
4298   Node* leading = in(0);
4299   while (leading != nullptr && (!leading->is_MemBar() || !leading->as_MemBar()->leading())) {
4300     while (leading == nullptr || leading->is_top() || seen.test_set(leading->_idx)) {
4301       leading = nullptr;
4302       while (regions.size() > 0 && leading == nullptr) {
4303         Node* r = regions.node();
4304         uint i = regions.index();
4305         if (i < r->req()) {
4306           leading = r->in(i);
4307           regions.set_index(i+1);
4308         } else {
4309           regions.pop();
4310         }
4311       }
4312       if (leading == nullptr) {
4313         assert(regions.size() == 0, "all paths should have been tried");
4314         return nullptr;
4315       }
4316     }
4317     if (leading->is_Region()) {
4318       regions.push(leading, 2);
4319       leading = leading->in(1);
4320     } else {
4321       leading = leading->in(0);
4322     }
4323   }
4324 #ifdef ASSERT
4325   Unique_Node_List wq;
4326   wq.push((Node*)this);
4327   uint found = 0;
4328   for (uint i = 0; i < wq.size(); i++) {
4329     Node* n = wq.at(i);
4330     if (n->is_Region()) {
4331       for (uint j = 1; j < n->req(); j++) {
4332         Node* in = n->in(j);
4333         if (in != nullptr && !in->is_top()) {
4334           wq.push(in);
4335         }
4336       }
4337     } else {
4338       if (n->is_MemBar() && n->as_MemBar()->leading()) {
4339         assert(n == leading, "consistency check failed");
4340         found++;
4341       } else {
4342         Node* in = n->in(0);
4343         if (in != nullptr && !in->is_top()) {
4344           wq.push(in);
4345         }
4346       }
4347     }
4348   }
4349   assert(found == 1 || (found == 0 && leading == nullptr), "consistency check failed");
4350 #endif
4351   if (leading == nullptr) {
4352     return nullptr;
4353   }
4354   MemBarNode* mb = leading->as_MemBar();
4355   assert((mb->_kind == LeadingStore && _kind == TrailingStore) ||
4356          (mb->_kind == LeadingLoadStore && _kind == TrailingLoadStore), "bad leading membar");
4357   assert(mb->_pair_idx == _pair_idx, "bad leading membar");
4358   return mb;
4359 }
4360 
4361 
4362 //===========================InitializeNode====================================
4363 // SUMMARY:
4364 // This node acts as a memory barrier on raw memory, after some raw stores.
4365 // The 'cooked' oop value feeds from the Initialize, not the Allocation.
4366 // The Initialize can 'capture' suitably constrained stores as raw inits.
4367 // It can coalesce related raw stores into larger units (called 'tiles').
4368 // It can avoid zeroing new storage for memory units which have raw inits.
4369 // At macro-expansion, it is marked 'complete', and does not optimize further.
4370 //
4371 // EXAMPLE:
4372 // The object 'new short[2]' occupies 16 bytes in a 32-bit machine.
4373 //   ctl = incoming control; mem* = incoming memory
4374 // (Note:  A star * on a memory edge denotes I/O and other standard edges.)
4375 // First allocate uninitialized memory and fill in the header:
4376 //   alloc = (Allocate ctl mem* 16 #short[].klass ...)
4377 //   ctl := alloc.Control; mem* := alloc.Memory*
4378 //   rawmem = alloc.Memory; rawoop = alloc.RawAddress
4379 // Then initialize to zero the non-header parts of the raw memory block:
4380 //   init = (Initialize alloc.Control alloc.Memory* alloc.RawAddress)
4381 //   ctl := init.Control; mem.SLICE(#short[*]) := init.Memory
4382 // After the initialize node executes, the object is ready for service:
4383 //   oop := (CheckCastPP init.Control alloc.RawAddress #short[])
4384 // Suppose its body is immediately initialized as {1,2}:
4385 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
4386 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
4387 //   mem.SLICE(#short[*]) := store2
4388 //
4389 // DETAILS:
4390 // An InitializeNode collects and isolates object initialization after
4391 // an AllocateNode and before the next possible safepoint.  As a
4392 // memory barrier (MemBarNode), it keeps critical stores from drifting
4393 // down past any safepoint or any publication of the allocation.
4394 // Before this barrier, a newly-allocated object may have uninitialized bits.
4395 // After this barrier, it may be treated as a real oop, and GC is allowed.
4396 //
4397 // The semantics of the InitializeNode include an implicit zeroing of
4398 // the new object from object header to the end of the object.
4399 // (The object header and end are determined by the AllocateNode.)
4400 //
4401 // Certain stores may be added as direct inputs to the InitializeNode.
4402 // These stores must update raw memory, and they must be to addresses
4403 // derived from the raw address produced by AllocateNode, and with
4404 // a constant offset.  They must be ordered by increasing offset.
4405 // The first one is at in(RawStores), the last at in(req()-1).
4406 // Unlike most memory operations, they are not linked in a chain,
4407 // but are displayed in parallel as users of the rawmem output of
4408 // the allocation.
4409 //
4410 // (See comments in InitializeNode::capture_store, which continue
4411 // the example given above.)
4412 //
4413 // When the associated Allocate is macro-expanded, the InitializeNode
4414 // may be rewritten to optimize collected stores.  A ClearArrayNode
4415 // may also be created at that point to represent any required zeroing.
4416 // The InitializeNode is then marked 'complete', prohibiting further
4417 // capturing of nearby memory operations.
4418 //
4419 // During macro-expansion, all captured initializations which store
4420 // constant values of 32 bits or smaller are coalesced (if advantageous)
4421 // into larger 'tiles' 32 or 64 bits.  This allows an object to be
4422 // initialized in fewer memory operations.  Memory words which are
4423 // covered by neither tiles nor non-constant stores are pre-zeroed
4424 // by explicit stores of zero.  (The code shape happens to do all
4425 // zeroing first, then all other stores, with both sequences occurring
4426 // in order of ascending offsets.)
4427 //
4428 // Alternatively, code may be inserted between an AllocateNode and its
4429 // InitializeNode, to perform arbitrary initialization of the new object.
4430 // E.g., the object copying intrinsics insert complex data transfers here.
4431 // The initialization must then be marked as 'complete' disable the
4432 // built-in zeroing semantics and the collection of initializing stores.
4433 //
4434 // While an InitializeNode is incomplete, reads from the memory state
4435 // produced by it are optimizable if they match the control edge and
4436 // new oop address associated with the allocation/initialization.
4437 // They return a stored value (if the offset matches) or else zero.
4438 // A write to the memory state, if it matches control and address,
4439 // and if it is to a constant offset, may be 'captured' by the
4440 // InitializeNode.  It is cloned as a raw memory operation and rewired
4441 // inside the initialization, to the raw oop produced by the allocation.
4442 // Operations on addresses which are provably distinct (e.g., to
4443 // other AllocateNodes) are allowed to bypass the initialization.
4444 //
4445 // The effect of all this is to consolidate object initialization
4446 // (both arrays and non-arrays, both piecewise and bulk) into a
4447 // single location, where it can be optimized as a unit.
4448 //
4449 // Only stores with an offset less than TrackedInitializationLimit words
4450 // will be considered for capture by an InitializeNode.  This puts a
4451 // reasonable limit on the complexity of optimized initializations.
4452 
4453 //---------------------------InitializeNode------------------------------------
4454 InitializeNode::InitializeNode(Compile* C, int adr_type, Node* rawoop)
4455   : MemBarNode(C, adr_type, rawoop),
4456     _is_complete(Incomplete), _does_not_escape(false)
4457 {
4458   init_class_id(Class_Initialize);
4459 
4460   assert(adr_type == Compile::AliasIdxRaw, "only valid atp");
4461   assert(in(RawAddress) == rawoop, "proper init");
4462   // Note:  allocation() can be null, for secondary initialization barriers
4463 }
4464 
4465 // Since this node is not matched, it will be processed by the
4466 // register allocator.  Declare that there are no constraints
4467 // on the allocation of the RawAddress edge.
4468 const RegMask &InitializeNode::in_RegMask(uint idx) const {
4469   // This edge should be set to top, by the set_complete.  But be conservative.
4470   if (idx == InitializeNode::RawAddress)
4471     return *(Compile::current()->matcher()->idealreg2spillmask[in(idx)->ideal_reg()]);
4472   return RegMask::Empty;
4473 }
4474 
4475 Node* InitializeNode::memory(uint alias_idx) {
4476   Node* mem = in(Memory);
4477   if (mem->is_MergeMem()) {
4478     return mem->as_MergeMem()->memory_at(alias_idx);
4479   } else {
4480     // incoming raw memory is not split
4481     return mem;
4482   }
4483 }
4484 
4485 bool InitializeNode::is_non_zero() {
4486   if (is_complete())  return false;
4487   remove_extra_zeroes();
4488   return (req() > RawStores);
4489 }
4490 
4491 void InitializeNode::set_complete(PhaseGVN* phase) {
4492   assert(!is_complete(), "caller responsibility");
4493   _is_complete = Complete;
4494 
4495   // After this node is complete, it contains a bunch of
4496   // raw-memory initializations.  There is no need for
4497   // it to have anything to do with non-raw memory effects.
4498   // Therefore, tell all non-raw users to re-optimize themselves,
4499   // after skipping the memory effects of this initialization.
4500   PhaseIterGVN* igvn = phase->is_IterGVN();
4501   if (igvn)  igvn->add_users_to_worklist(this);
4502 }
4503 
4504 // convenience function
4505 // return false if the init contains any stores already
4506 bool AllocateNode::maybe_set_complete(PhaseGVN* phase) {
4507   InitializeNode* init = initialization();
4508   if (init == nullptr || init->is_complete())  return false;
4509   init->remove_extra_zeroes();
4510   // for now, if this allocation has already collected any inits, bail:
4511   if (init->is_non_zero())  return false;
4512   init->set_complete(phase);
4513   return true;
4514 }
4515 
4516 void InitializeNode::remove_extra_zeroes() {
4517   if (req() == RawStores)  return;
4518   Node* zmem = zero_memory();
4519   uint fill = RawStores;
4520   for (uint i = fill; i < req(); i++) {
4521     Node* n = in(i);
4522     if (n->is_top() || n == zmem)  continue;  // skip
4523     if (fill < i)  set_req(fill, n);          // compact
4524     ++fill;
4525   }
4526   // delete any empty spaces created:
4527   while (fill < req()) {
4528     del_req(fill);
4529   }
4530 }
4531 
4532 // Helper for remembering which stores go with which offsets.
4533 intptr_t InitializeNode::get_store_offset(Node* st, PhaseValues* phase) {
4534   if (!st->is_Store())  return -1;  // can happen to dead code via subsume_node
4535   intptr_t offset = -1;
4536   Node* base = AddPNode::Ideal_base_and_offset(st->in(MemNode::Address),
4537                                                phase, offset);
4538   if (base == nullptr)  return -1;  // something is dead,
4539   if (offset < 0)       return -1;  //        dead, dead
4540   return offset;
4541 }
4542 
4543 // Helper for proving that an initialization expression is
4544 // "simple enough" to be folded into an object initialization.
4545 // Attempts to prove that a store's initial value 'n' can be captured
4546 // within the initialization without creating a vicious cycle, such as:
4547 //     { Foo p = new Foo(); p.next = p; }
4548 // True for constants and parameters and small combinations thereof.
4549 bool InitializeNode::detect_init_independence(Node* value, PhaseGVN* phase) {
4550   ResourceMark rm;
4551   Unique_Node_List worklist;
4552   worklist.push(value);
4553 
4554   uint complexity_limit = 20;
4555   for (uint j = 0; j < worklist.size(); j++) {
4556     if (j >= complexity_limit) {
4557       return false;  // Bail out if processed too many nodes
4558     }
4559 
4560     Node* n = worklist.at(j);
4561     if (n == nullptr)   continue;   // (can this really happen?)
4562     if (n->is_Proj())   n = n->in(0);
4563     if (n == this)      return false;  // found a cycle
4564     if (n->is_Con())    continue;
4565     if (n->is_Start())  continue;   // params, etc., are OK
4566     if (n->is_Root())   continue;   // even better
4567 
4568     // There cannot be any dependency if 'n' is a CFG node that dominates the current allocation
4569     if (n->is_CFG() && phase->is_dominator(n, allocation())) {
4570       continue;
4571     }
4572 
4573     Node* ctl = n->in(0);
4574     if (ctl != nullptr && !ctl->is_top()) {
4575       if (ctl->is_Proj())  ctl = ctl->in(0);
4576       if (ctl == this)  return false;
4577 
4578       // If we already know that the enclosing memory op is pinned right after
4579       // the init, then any control flow that the store has picked up
4580       // must have preceded the init, or else be equal to the init.
4581       // Even after loop optimizations (which might change control edges)
4582       // a store is never pinned *before* the availability of its inputs.
4583       if (!MemNode::all_controls_dominate(n, this))
4584         return false;                  // failed to prove a good control
4585     }
4586 
4587     // Check data edges for possible dependencies on 'this'.
4588     for (uint i = 1; i < n->req(); i++) {
4589       Node* m = n->in(i);
4590       if (m == nullptr || m == n || m->is_top())  continue;
4591 
4592       // Only process data inputs once
4593       worklist.push(m);
4594     }
4595   }
4596 
4597   return true;
4598 }
4599 
4600 // Here are all the checks a Store must pass before it can be moved into
4601 // an initialization.  Returns zero if a check fails.
4602 // On success, returns the (constant) offset to which the store applies,
4603 // within the initialized memory.
4604 intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseGVN* phase, bool can_reshape) {
4605   const int FAIL = 0;
4606   if (st->req() != MemNode::ValueIn + 1)
4607     return FAIL;                // an inscrutable StoreNode (card mark?)
4608   Node* ctl = st->in(MemNode::Control);
4609   if (!(ctl != nullptr && ctl->is_Proj() && ctl->in(0) == this))
4610     return FAIL;                // must be unconditional after the initialization
4611   Node* mem = st->in(MemNode::Memory);
4612   if (!(mem->is_Proj() && mem->in(0) == this))
4613     return FAIL;                // must not be preceded by other stores
4614   Node* adr = st->in(MemNode::Address);
4615   intptr_t offset;
4616   AllocateNode* alloc = AllocateNode::Ideal_allocation(adr, phase, offset);
4617   if (alloc == nullptr)
4618     return FAIL;                // inscrutable address
4619   if (alloc != allocation())
4620     return FAIL;                // wrong allocation!  (store needs to float up)
4621   int size_in_bytes = st->memory_size();
4622   if ((size_in_bytes != 0) && (offset % size_in_bytes) != 0) {
4623     return FAIL;                // mismatched access
4624   }
4625   Node* val = st->in(MemNode::ValueIn);
4626 
4627   if (!detect_init_independence(val, phase))
4628     return FAIL;                // stored value must be 'simple enough'
4629 
4630   // The Store can be captured only if nothing after the allocation
4631   // and before the Store is using the memory location that the store
4632   // overwrites.
4633   bool failed = false;
4634   // If is_complete_with_arraycopy() is true the shape of the graph is
4635   // well defined and is safe so no need for extra checks.
4636   if (!is_complete_with_arraycopy()) {
4637     // We are going to look at each use of the memory state following
4638     // the allocation to make sure nothing reads the memory that the
4639     // Store writes.
4640     const TypePtr* t_adr = phase->type(adr)->isa_ptr();
4641     int alias_idx = phase->C->get_alias_index(t_adr);
4642     ResourceMark rm;
4643     Unique_Node_List mems;
4644     mems.push(mem);
4645     Node* unique_merge = nullptr;
4646     for (uint next = 0; next < mems.size(); ++next) {
4647       Node *m  = mems.at(next);
4648       for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
4649         Node *n = m->fast_out(j);
4650         if (n->outcnt() == 0) {
4651           continue;
4652         }
4653         if (n == st) {
4654           continue;
4655         } else if (n->in(0) != nullptr && n->in(0) != ctl) {
4656           // If the control of this use is different from the control
4657           // of the Store which is right after the InitializeNode then
4658           // this node cannot be between the InitializeNode and the
4659           // Store.
4660           continue;
4661         } else if (n->is_MergeMem()) {
4662           if (n->as_MergeMem()->memory_at(alias_idx) == m) {
4663             // We can hit a MergeMemNode (that will likely go away
4664             // later) that is a direct use of the memory state
4665             // following the InitializeNode on the same slice as the
4666             // store node that we'd like to capture. We need to check
4667             // the uses of the MergeMemNode.
4668             mems.push(n);
4669           }
4670         } else if (n->is_Mem()) {
4671           Node* other_adr = n->in(MemNode::Address);
4672           if (other_adr == adr) {
4673             failed = true;
4674             break;
4675           } else {
4676             const TypePtr* other_t_adr = phase->type(other_adr)->isa_ptr();
4677             if (other_t_adr != nullptr) {
4678               int other_alias_idx = phase->C->get_alias_index(other_t_adr);
4679               if (other_alias_idx == alias_idx) {
4680                 // A load from the same memory slice as the store right
4681                 // after the InitializeNode. We check the control of the
4682                 // object/array that is loaded from. If it's the same as
4683                 // the store control then we cannot capture the store.
4684                 assert(!n->is_Store(), "2 stores to same slice on same control?");
4685                 Node* base = other_adr;
4686                 assert(base->is_AddP(), "should be addp but is %s", base->Name());
4687                 base = base->in(AddPNode::Base);
4688                 if (base != nullptr) {
4689                   base = base->uncast();
4690                   if (base->is_Proj() && base->in(0) == alloc) {
4691                     failed = true;
4692                     break;
4693                   }
4694                 }
4695               }
4696             }
4697           }
4698         } else {
4699           failed = true;
4700           break;
4701         }
4702       }
4703     }
4704   }
4705   if (failed) {
4706     if (!can_reshape) {
4707       // We decided we couldn't capture the store during parsing. We
4708       // should try again during the next IGVN once the graph is
4709       // cleaner.
4710       phase->C->record_for_igvn(st);
4711     }
4712     return FAIL;
4713   }
4714 
4715   return offset;                // success
4716 }
4717 
4718 // Find the captured store in(i) which corresponds to the range
4719 // [start..start+size) in the initialized object.
4720 // If there is one, return its index i.  If there isn't, return the
4721 // negative of the index where it should be inserted.
4722 // Return 0 if the queried range overlaps an initialization boundary
4723 // or if dead code is encountered.
4724 // If size_in_bytes is zero, do not bother with overlap checks.
4725 int InitializeNode::captured_store_insertion_point(intptr_t start,
4726                                                    int size_in_bytes,
4727                                                    PhaseValues* phase) {
4728   const int FAIL = 0, MAX_STORE = MAX2(BytesPerLong, (int)MaxVectorSize);
4729 
4730   if (is_complete())
4731     return FAIL;                // arraycopy got here first; punt
4732 
4733   assert(allocation() != nullptr, "must be present");
4734 
4735   // no negatives, no header fields:
4736   if (start < (intptr_t) allocation()->minimum_header_size())  return FAIL;
4737 
4738   // after a certain size, we bail out on tracking all the stores:
4739   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
4740   if (start >= ti_limit)  return FAIL;
4741 
4742   for (uint i = InitializeNode::RawStores, limit = req(); ; ) {
4743     if (i >= limit)  return -(int)i; // not found; here is where to put it
4744 
4745     Node*    st     = in(i);
4746     intptr_t st_off = get_store_offset(st, phase);
4747     if (st_off < 0) {
4748       if (st != zero_memory()) {
4749         return FAIL;            // bail out if there is dead garbage
4750       }
4751     } else if (st_off > start) {
4752       // ...we are done, since stores are ordered
4753       if (st_off < start + size_in_bytes) {
4754         return FAIL;            // the next store overlaps
4755       }
4756       return -(int)i;           // not found; here is where to put it
4757     } else if (st_off < start) {
4758       assert(st->as_Store()->memory_size() <= MAX_STORE, "");
4759       if (size_in_bytes != 0 &&
4760           start < st_off + MAX_STORE &&
4761           start < st_off + st->as_Store()->memory_size()) {
4762         return FAIL;            // the previous store overlaps
4763       }
4764     } else {
4765       if (size_in_bytes != 0 &&
4766           st->as_Store()->memory_size() != size_in_bytes) {
4767         return FAIL;            // mismatched store size
4768       }
4769       return i;
4770     }
4771 
4772     ++i;
4773   }
4774 }
4775 
4776 // Look for a captured store which initializes at the offset 'start'
4777 // with the given size.  If there is no such store, and no other
4778 // initialization interferes, then return zero_memory (the memory
4779 // projection of the AllocateNode).
4780 Node* InitializeNode::find_captured_store(intptr_t start, int size_in_bytes,
4781                                           PhaseValues* phase) {
4782   assert(stores_are_sane(phase), "");
4783   int i = captured_store_insertion_point(start, size_in_bytes, phase);
4784   if (i == 0) {
4785     return nullptr;              // something is dead
4786   } else if (i < 0) {
4787     return zero_memory();       // just primordial zero bits here
4788   } else {
4789     Node* st = in(i);           // here is the store at this position
4790     assert(get_store_offset(st->as_Store(), phase) == start, "sanity");
4791     return st;
4792   }
4793 }
4794 
4795 // Create, as a raw pointer, an address within my new object at 'offset'.
4796 Node* InitializeNode::make_raw_address(intptr_t offset,
4797                                        PhaseGVN* phase) {
4798   Node* addr = in(RawAddress);
4799   if (offset != 0) {
4800     Compile* C = phase->C;
4801     addr = phase->transform( new AddPNode(C->top(), addr,
4802                                                  phase->MakeConX(offset)) );
4803   }
4804   return addr;
4805 }
4806 
4807 // Clone the given store, converting it into a raw store
4808 // initializing a field or element of my new object.
4809 // Caller is responsible for retiring the original store,
4810 // with subsume_node or the like.
4811 //
4812 // From the example above InitializeNode::InitializeNode,
4813 // here are the old stores to be captured:
4814 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
4815 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
4816 //
4817 // Here is the changed code; note the extra edges on init:
4818 //   alloc = (Allocate ...)
4819 //   rawoop = alloc.RawAddress
4820 //   rawstore1 = (StoreC alloc.Control alloc.Memory (+ rawoop 12) 1)
4821 //   rawstore2 = (StoreC alloc.Control alloc.Memory (+ rawoop 14) 2)
4822 //   init = (Initialize alloc.Control alloc.Memory rawoop
4823 //                      rawstore1 rawstore2)
4824 //
4825 Node* InitializeNode::capture_store(StoreNode* st, intptr_t start,
4826                                     PhaseGVN* phase, bool can_reshape) {
4827   assert(stores_are_sane(phase), "");
4828 
4829   if (start < 0)  return nullptr;
4830   assert(can_capture_store(st, phase, can_reshape) == start, "sanity");
4831 
4832   Compile* C = phase->C;
4833   int size_in_bytes = st->memory_size();
4834   int i = captured_store_insertion_point(start, size_in_bytes, phase);
4835   if (i == 0)  return nullptr;  // bail out
4836   Node* prev_mem = nullptr;     // raw memory for the captured store
4837   if (i > 0) {
4838     prev_mem = in(i);           // there is a pre-existing store under this one
4839     set_req(i, C->top());       // temporarily disconnect it
4840     // See StoreNode::Ideal 'st->outcnt() == 1' for the reason to disconnect.
4841   } else {
4842     i = -i;                     // no pre-existing store
4843     prev_mem = zero_memory();   // a slice of the newly allocated object
4844     if (i > InitializeNode::RawStores && in(i-1) == prev_mem)
4845       set_req(--i, C->top());   // reuse this edge; it has been folded away
4846     else
4847       ins_req(i, C->top());     // build a new edge
4848   }
4849   Node* new_st = st->clone();
4850   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
4851   new_st->set_req(MemNode::Control, in(Control));
4852   new_st->set_req(MemNode::Memory,  prev_mem);
4853   new_st->set_req(MemNode::Address, make_raw_address(start, phase));
4854   bs->eliminate_gc_barrier_data(new_st);
4855   new_st = phase->transform(new_st);
4856 
4857   // At this point, new_st might have swallowed a pre-existing store
4858   // at the same offset, or perhaps new_st might have disappeared,
4859   // if it redundantly stored the same value (or zero to fresh memory).
4860 
4861   // In any case, wire it in:
4862   PhaseIterGVN* igvn = phase->is_IterGVN();
4863   if (igvn) {
4864     igvn->rehash_node_delayed(this);
4865   }
4866   set_req(i, new_st);
4867 
4868   // The caller may now kill the old guy.
4869   DEBUG_ONLY(Node* check_st = find_captured_store(start, size_in_bytes, phase));
4870   assert(check_st == new_st || check_st == nullptr, "must be findable");
4871   assert(!is_complete(), "");
4872   return new_st;
4873 }
4874 
4875 static bool store_constant(jlong* tiles, int num_tiles,
4876                            intptr_t st_off, int st_size,
4877                            jlong con) {
4878   if ((st_off & (st_size-1)) != 0)
4879     return false;               // strange store offset (assume size==2**N)
4880   address addr = (address)tiles + st_off;
4881   assert(st_off >= 0 && addr+st_size <= (address)&tiles[num_tiles], "oob");
4882   switch (st_size) {
4883   case sizeof(jbyte):  *(jbyte*) addr = (jbyte) con; break;
4884   case sizeof(jchar):  *(jchar*) addr = (jchar) con; break;
4885   case sizeof(jint):   *(jint*)  addr = (jint)  con; break;
4886   case sizeof(jlong):  *(jlong*) addr = (jlong) con; break;
4887   default: return false;        // strange store size (detect size!=2**N here)
4888   }
4889   return true;                  // return success to caller
4890 }
4891 
4892 // Coalesce subword constants into int constants and possibly
4893 // into long constants.  The goal, if the CPU permits,
4894 // is to initialize the object with a small number of 64-bit tiles.
4895 // Also, convert floating-point constants to bit patterns.
4896 // Non-constants are not relevant to this pass.
4897 //
4898 // In terms of the running example on InitializeNode::InitializeNode
4899 // and InitializeNode::capture_store, here is the transformation
4900 // of rawstore1 and rawstore2 into rawstore12:
4901 //   alloc = (Allocate ...)
4902 //   rawoop = alloc.RawAddress
4903 //   tile12 = 0x00010002
4904 //   rawstore12 = (StoreI alloc.Control alloc.Memory (+ rawoop 12) tile12)
4905 //   init = (Initialize alloc.Control alloc.Memory rawoop rawstore12)
4906 //
4907 void
4908 InitializeNode::coalesce_subword_stores(intptr_t header_size,
4909                                         Node* size_in_bytes,
4910                                         PhaseGVN* phase) {
4911   Compile* C = phase->C;
4912 
4913   assert(stores_are_sane(phase), "");
4914   // Note:  After this pass, they are not completely sane,
4915   // since there may be some overlaps.
4916 
4917   int old_subword = 0, old_long = 0, new_int = 0, new_long = 0;
4918 
4919   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
4920   intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, ti_limit);
4921   size_limit = MIN2(size_limit, ti_limit);
4922   size_limit = align_up(size_limit, BytesPerLong);
4923   int num_tiles = size_limit / BytesPerLong;
4924 
4925   // allocate space for the tile map:
4926   const int small_len = DEBUG_ONLY(true ? 3 :) 30; // keep stack frames small
4927   jlong  tiles_buf[small_len];
4928   Node*  nodes_buf[small_len];
4929   jlong  inits_buf[small_len];
4930   jlong* tiles = ((num_tiles <= small_len) ? &tiles_buf[0]
4931                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
4932   Node** nodes = ((num_tiles <= small_len) ? &nodes_buf[0]
4933                   : NEW_RESOURCE_ARRAY(Node*, num_tiles));
4934   jlong* inits = ((num_tiles <= small_len) ? &inits_buf[0]
4935                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
4936   // tiles: exact bitwise model of all primitive constants
4937   // nodes: last constant-storing node subsumed into the tiles model
4938   // inits: which bytes (in each tile) are touched by any initializations
4939 
4940   //// Pass A: Fill in the tile model with any relevant stores.
4941 
4942   Copy::zero_to_bytes(tiles, sizeof(tiles[0]) * num_tiles);
4943   Copy::zero_to_bytes(nodes, sizeof(nodes[0]) * num_tiles);
4944   Copy::zero_to_bytes(inits, sizeof(inits[0]) * num_tiles);
4945   Node* zmem = zero_memory(); // initially zero memory state
4946   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
4947     Node* st = in(i);
4948     intptr_t st_off = get_store_offset(st, phase);
4949 
4950     // Figure out the store's offset and constant value:
4951     if (st_off < header_size)             continue; //skip (ignore header)
4952     if (st->in(MemNode::Memory) != zmem)  continue; //skip (odd store chain)
4953     int st_size = st->as_Store()->memory_size();
4954     if (st_off + st_size > size_limit)    break;
4955 
4956     // Record which bytes are touched, whether by constant or not.
4957     if (!store_constant(inits, num_tiles, st_off, st_size, (jlong) -1))
4958       continue;                 // skip (strange store size)
4959 
4960     const Type* val = phase->type(st->in(MemNode::ValueIn));
4961     if (!val->singleton())                continue; //skip (non-con store)
4962     BasicType type = val->basic_type();
4963 
4964     jlong con = 0;
4965     switch (type) {
4966     case T_INT:    con = val->is_int()->get_con();  break;
4967     case T_LONG:   con = val->is_long()->get_con(); break;
4968     case T_FLOAT:  con = jint_cast(val->getf());    break;
4969     case T_DOUBLE: con = jlong_cast(val->getd());   break;
4970     default:                              continue; //skip (odd store type)
4971     }
4972 
4973     if (type == T_LONG && Matcher::isSimpleConstant64(con) &&
4974         st->Opcode() == Op_StoreL) {
4975       continue;                 // This StoreL is already optimal.
4976     }
4977 
4978     // Store down the constant.
4979     store_constant(tiles, num_tiles, st_off, st_size, con);
4980 
4981     intptr_t j = st_off >> LogBytesPerLong;
4982 
4983     if (type == T_INT && st_size == BytesPerInt
4984         && (st_off & BytesPerInt) == BytesPerInt) {
4985       jlong lcon = tiles[j];
4986       if (!Matcher::isSimpleConstant64(lcon) &&
4987           st->Opcode() == Op_StoreI) {
4988         // This StoreI is already optimal by itself.
4989         jint* intcon = (jint*) &tiles[j];
4990         intcon[1] = 0;  // undo the store_constant()
4991 
4992         // If the previous store is also optimal by itself, back up and
4993         // undo the action of the previous loop iteration... if we can.
4994         // But if we can't, just let the previous half take care of itself.
4995         st = nodes[j];
4996         st_off -= BytesPerInt;
4997         con = intcon[0];
4998         if (con != 0 && st != nullptr && st->Opcode() == Op_StoreI) {
4999           assert(st_off >= header_size, "still ignoring header");
5000           assert(get_store_offset(st, phase) == st_off, "must be");
5001           assert(in(i-1) == zmem, "must be");
5002           DEBUG_ONLY(const Type* tcon = phase->type(st->in(MemNode::ValueIn)));
5003           assert(con == tcon->is_int()->get_con(), "must be");
5004           // Undo the effects of the previous loop trip, which swallowed st:
5005           intcon[0] = 0;        // undo store_constant()
5006           set_req(i-1, st);     // undo set_req(i, zmem)
5007           nodes[j] = nullptr;   // undo nodes[j] = st
5008           --old_subword;        // undo ++old_subword
5009         }
5010         continue;               // This StoreI is already optimal.
5011       }
5012     }
5013 
5014     // This store is not needed.
5015     set_req(i, zmem);
5016     nodes[j] = st;              // record for the moment
5017     if (st_size < BytesPerLong) // something has changed
5018           ++old_subword;        // includes int/float, but who's counting...
5019     else  ++old_long;
5020   }
5021 
5022   if ((old_subword + old_long) == 0)
5023     return;                     // nothing more to do
5024 
5025   //// Pass B: Convert any non-zero tiles into optimal constant stores.
5026   // Be sure to insert them before overlapping non-constant stores.
5027   // (E.g., byte[] x = { 1,2,y,4 }  =>  x[int 0] = 0x01020004, x[2]=y.)
5028   for (int j = 0; j < num_tiles; j++) {
5029     jlong con  = tiles[j];
5030     jlong init = inits[j];
5031     if (con == 0)  continue;
5032     jint con0,  con1;           // split the constant, address-wise
5033     jint init0, init1;          // split the init map, address-wise
5034     { union { jlong con; jint intcon[2]; } u;
5035       u.con = con;
5036       con0  = u.intcon[0];
5037       con1  = u.intcon[1];
5038       u.con = init;
5039       init0 = u.intcon[0];
5040       init1 = u.intcon[1];
5041     }
5042 
5043     Node* old = nodes[j];
5044     assert(old != nullptr, "need the prior store");
5045     intptr_t offset = (j * BytesPerLong);
5046 
5047     bool split = !Matcher::isSimpleConstant64(con);
5048 
5049     if (offset < header_size) {
5050       assert(offset + BytesPerInt >= header_size, "second int counts");
5051       assert(*(jint*)&tiles[j] == 0, "junk in header");
5052       split = true;             // only the second word counts
5053       // Example:  int a[] = { 42 ... }
5054     } else if (con0 == 0 && init0 == -1) {
5055       split = true;             // first word is covered by full inits
5056       // Example:  int a[] = { ... foo(), 42 ... }
5057     } else if (con1 == 0 && init1 == -1) {
5058       split = true;             // second word is covered by full inits
5059       // Example:  int a[] = { ... 42, foo() ... }
5060     }
5061 
5062     // Here's a case where init0 is neither 0 nor -1:
5063     //   byte a[] = { ... 0,0,foo(),0,  0,0,0,42 ... }
5064     // Assuming big-endian memory, init0, init1 are 0x0000FF00, 0x000000FF.
5065     // In this case the tile is not split; it is (jlong)42.
5066     // The big tile is stored down, and then the foo() value is inserted.
5067     // (If there were foo(),foo() instead of foo(),0, init0 would be -1.)
5068 
5069     Node* ctl = old->in(MemNode::Control);
5070     Node* adr = make_raw_address(offset, phase);
5071     const TypePtr* atp = TypeRawPtr::BOTTOM;
5072 
5073     // One or two coalesced stores to plop down.
5074     Node*    st[2];
5075     intptr_t off[2];
5076     int  nst = 0;
5077     if (!split) {
5078       ++new_long;
5079       off[nst] = offset;
5080       st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
5081                                   phase->longcon(con), T_LONG, MemNode::unordered);
5082     } else {
5083       // Omit either if it is a zero.
5084       if (con0 != 0) {
5085         ++new_int;
5086         off[nst]  = offset;
5087         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
5088                                     phase->intcon(con0), T_INT, MemNode::unordered);
5089       }
5090       if (con1 != 0) {
5091         ++new_int;
5092         offset += BytesPerInt;
5093         adr = make_raw_address(offset, phase);
5094         off[nst]  = offset;
5095         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
5096                                     phase->intcon(con1), T_INT, MemNode::unordered);
5097       }
5098     }
5099 
5100     // Insert second store first, then the first before the second.
5101     // Insert each one just before any overlapping non-constant stores.
5102     while (nst > 0) {
5103       Node* st1 = st[--nst];
5104       C->copy_node_notes_to(st1, old);
5105       st1 = phase->transform(st1);
5106       offset = off[nst];
5107       assert(offset >= header_size, "do not smash header");
5108       int ins_idx = captured_store_insertion_point(offset, /*size:*/0, phase);
5109       guarantee(ins_idx != 0, "must re-insert constant store");
5110       if (ins_idx < 0)  ins_idx = -ins_idx;  // never overlap
5111       if (ins_idx > InitializeNode::RawStores && in(ins_idx-1) == zmem)
5112         set_req(--ins_idx, st1);
5113       else
5114         ins_req(ins_idx, st1);
5115     }
5116   }
5117 
5118   if (PrintCompilation && WizardMode)
5119     tty->print_cr("Changed %d/%d subword/long constants into %d/%d int/long",
5120                   old_subword, old_long, new_int, new_long);
5121   if (C->log() != nullptr)
5122     C->log()->elem("comment that='%d/%d subword/long to %d/%d int/long'",
5123                    old_subword, old_long, new_int, new_long);
5124 
5125   // Clean up any remaining occurrences of zmem:
5126   remove_extra_zeroes();
5127 }
5128 
5129 // Explore forward from in(start) to find the first fully initialized
5130 // word, and return its offset.  Skip groups of subword stores which
5131 // together initialize full words.  If in(start) is itself part of a
5132 // fully initialized word, return the offset of in(start).  If there
5133 // are no following full-word stores, or if something is fishy, return
5134 // a negative value.
5135 intptr_t InitializeNode::find_next_fullword_store(uint start, PhaseGVN* phase) {
5136   int       int_map = 0;
5137   intptr_t  int_map_off = 0;
5138   const int FULL_MAP = right_n_bits(BytesPerInt);  // the int_map we hope for
5139 
5140   for (uint i = start, limit = req(); i < limit; i++) {
5141     Node* st = in(i);
5142 
5143     intptr_t st_off = get_store_offset(st, phase);
5144     if (st_off < 0)  break;  // return conservative answer
5145 
5146     int st_size = st->as_Store()->memory_size();
5147     if (st_size >= BytesPerInt && (st_off % BytesPerInt) == 0) {
5148       return st_off;            // we found a complete word init
5149     }
5150 
5151     // update the map:
5152 
5153     intptr_t this_int_off = align_down(st_off, BytesPerInt);
5154     if (this_int_off != int_map_off) {
5155       // reset the map:
5156       int_map = 0;
5157       int_map_off = this_int_off;
5158     }
5159 
5160     int subword_off = st_off - this_int_off;
5161     int_map |= right_n_bits(st_size) << subword_off;
5162     if ((int_map & FULL_MAP) == FULL_MAP) {
5163       return this_int_off;      // we found a complete word init
5164     }
5165 
5166     // Did this store hit or cross the word boundary?
5167     intptr_t next_int_off = align_down(st_off + st_size, BytesPerInt);
5168     if (next_int_off == this_int_off + BytesPerInt) {
5169       // We passed the current int, without fully initializing it.
5170       int_map_off = next_int_off;
5171       int_map >>= BytesPerInt;
5172     } else if (next_int_off > this_int_off + BytesPerInt) {
5173       // We passed the current and next int.
5174       return this_int_off + BytesPerInt;
5175     }
5176   }
5177 
5178   return -1;
5179 }
5180 
5181 
5182 // Called when the associated AllocateNode is expanded into CFG.
5183 // At this point, we may perform additional optimizations.
5184 // Linearize the stores by ascending offset, to make memory
5185 // activity as coherent as possible.
5186 Node* InitializeNode::complete_stores(Node* rawctl, Node* rawmem, Node* rawptr,
5187                                       intptr_t header_size,
5188                                       Node* size_in_bytes,
5189                                       PhaseIterGVN* phase) {
5190   assert(!is_complete(), "not already complete");
5191   assert(stores_are_sane(phase), "");
5192   assert(allocation() != nullptr, "must be present");
5193 
5194   remove_extra_zeroes();
5195 
5196   if (ReduceFieldZeroing || ReduceBulkZeroing)
5197     // reduce instruction count for common initialization patterns
5198     coalesce_subword_stores(header_size, size_in_bytes, phase);
5199 
5200   Node* zmem = zero_memory();   // initially zero memory state
5201   Node* inits = zmem;           // accumulating a linearized chain of inits
5202   #ifdef ASSERT
5203   intptr_t first_offset = allocation()->minimum_header_size();
5204   intptr_t last_init_off = first_offset;  // previous init offset
5205   intptr_t last_init_end = first_offset;  // previous init offset+size
5206   intptr_t last_tile_end = first_offset;  // previous tile offset+size
5207   #endif
5208   intptr_t zeroes_done = header_size;
5209 
5210   bool do_zeroing = true;       // we might give up if inits are very sparse
5211   int  big_init_gaps = 0;       // how many large gaps have we seen?
5212 
5213   if (UseTLAB && ZeroTLAB)  do_zeroing = false;
5214   if (!ReduceFieldZeroing && !ReduceBulkZeroing)  do_zeroing = false;
5215 
5216   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
5217     Node* st = in(i);
5218     intptr_t st_off = get_store_offset(st, phase);
5219     if (st_off < 0)
5220       break;                    // unknown junk in the inits
5221     if (st->in(MemNode::Memory) != zmem)
5222       break;                    // complicated store chains somehow in list
5223 
5224     int st_size = st->as_Store()->memory_size();
5225     intptr_t next_init_off = st_off + st_size;
5226 
5227     if (do_zeroing && zeroes_done < next_init_off) {
5228       // See if this store needs a zero before it or under it.
5229       intptr_t zeroes_needed = st_off;
5230 
5231       if (st_size < BytesPerInt) {
5232         // Look for subword stores which only partially initialize words.
5233         // If we find some, we must lay down some word-level zeroes first,
5234         // underneath the subword stores.
5235         //
5236         // Examples:
5237         //   byte[] a = { p,q,r,s }  =>  a[0]=p,a[1]=q,a[2]=r,a[3]=s
5238         //   byte[] a = { x,y,0,0 }  =>  a[0..3] = 0, a[0]=x,a[1]=y
5239         //   byte[] a = { 0,0,z,0 }  =>  a[0..3] = 0, a[2]=z
5240         //
5241         // Note:  coalesce_subword_stores may have already done this,
5242         // if it was prompted by constant non-zero subword initializers.
5243         // But this case can still arise with non-constant stores.
5244 
5245         intptr_t next_full_store = find_next_fullword_store(i, phase);
5246 
5247         // In the examples above:
5248         //   in(i)          p   q   r   s     x   y     z
5249         //   st_off        12  13  14  15    12  13    14
5250         //   st_size        1   1   1   1     1   1     1
5251         //   next_full_s.  12  16  16  16    16  16    16
5252         //   z's_done      12  16  16  16    12  16    12
5253         //   z's_needed    12  16  16  16    16  16    16
5254         //   zsize          0   0   0   0     4   0     4
5255         if (next_full_store < 0) {
5256           // Conservative tack:  Zero to end of current word.
5257           zeroes_needed = align_up(zeroes_needed, BytesPerInt);
5258         } else {
5259           // Zero to beginning of next fully initialized word.
5260           // Or, don't zero at all, if we are already in that word.
5261           assert(next_full_store >= zeroes_needed, "must go forward");
5262           assert((next_full_store & (BytesPerInt-1)) == 0, "even boundary");
5263           zeroes_needed = next_full_store;
5264         }
5265       }
5266 
5267       if (zeroes_needed > zeroes_done) {
5268         intptr_t zsize = zeroes_needed - zeroes_done;
5269         // Do some incremental zeroing on rawmem, in parallel with inits.
5270         zeroes_done = align_down(zeroes_done, BytesPerInt);
5271         rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
5272                                               zeroes_done, zeroes_needed,
5273                                               phase);
5274         zeroes_done = zeroes_needed;
5275         if (zsize > InitArrayShortSize && ++big_init_gaps > 2)
5276           do_zeroing = false;   // leave the hole, next time
5277       }
5278     }
5279 
5280     // Collect the store and move on:
5281     phase->replace_input_of(st, MemNode::Memory, inits);
5282     inits = st;                 // put it on the linearized chain
5283     set_req(i, zmem);           // unhook from previous position
5284 
5285     if (zeroes_done == st_off)
5286       zeroes_done = next_init_off;
5287 
5288     assert(!do_zeroing || zeroes_done >= next_init_off, "don't miss any");
5289 
5290     #ifdef ASSERT
5291     // Various order invariants.  Weaker than stores_are_sane because
5292     // a large constant tile can be filled in by smaller non-constant stores.
5293     assert(st_off >= last_init_off, "inits do not reverse");
5294     last_init_off = st_off;
5295     const Type* val = nullptr;
5296     if (st_size >= BytesPerInt &&
5297         (val = phase->type(st->in(MemNode::ValueIn)))->singleton() &&
5298         (int)val->basic_type() < (int)T_OBJECT) {
5299       assert(st_off >= last_tile_end, "tiles do not overlap");
5300       assert(st_off >= last_init_end, "tiles do not overwrite inits");
5301       last_tile_end = MAX2(last_tile_end, next_init_off);
5302     } else {
5303       intptr_t st_tile_end = align_up(next_init_off, BytesPerLong);
5304       assert(st_tile_end >= last_tile_end, "inits stay with tiles");
5305       assert(st_off      >= last_init_end, "inits do not overlap");
5306       last_init_end = next_init_off;  // it's a non-tile
5307     }
5308     #endif //ASSERT
5309   }
5310 
5311   remove_extra_zeroes();        // clear out all the zmems left over
5312   add_req(inits);
5313 
5314   if (!(UseTLAB && ZeroTLAB)) {
5315     // If anything remains to be zeroed, zero it all now.
5316     zeroes_done = align_down(zeroes_done, BytesPerInt);
5317     // if it is the last unused 4 bytes of an instance, forget about it
5318     intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, max_jint);
5319     if (zeroes_done + BytesPerLong >= size_limit) {
5320       AllocateNode* alloc = allocation();
5321       assert(alloc != nullptr, "must be present");
5322       if (alloc != nullptr && alloc->Opcode() == Op_Allocate) {
5323         Node* klass_node = alloc->in(AllocateNode::KlassNode);
5324         ciKlass* k = phase->type(klass_node)->is_instklassptr()->instance_klass();
5325         if (zeroes_done == k->layout_helper())
5326           zeroes_done = size_limit;
5327       }
5328     }
5329     if (zeroes_done < size_limit) {
5330       rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
5331                                             zeroes_done, size_in_bytes, phase);
5332     }
5333   }
5334 
5335   set_complete(phase);
5336   return rawmem;
5337 }
5338 
5339 
5340 #ifdef ASSERT
5341 bool InitializeNode::stores_are_sane(PhaseValues* phase) {
5342   if (is_complete())
5343     return true;                // stores could be anything at this point
5344   assert(allocation() != nullptr, "must be present");
5345   intptr_t last_off = allocation()->minimum_header_size();
5346   for (uint i = InitializeNode::RawStores; i < req(); i++) {
5347     Node* st = in(i);
5348     intptr_t st_off = get_store_offset(st, phase);
5349     if (st_off < 0)  continue;  // ignore dead garbage
5350     if (last_off > st_off) {
5351       tty->print_cr("*** bad store offset at %d: " INTX_FORMAT " > " INTX_FORMAT, i, last_off, st_off);
5352       this->dump(2);
5353       assert(false, "ascending store offsets");
5354       return false;
5355     }
5356     last_off = st_off + st->as_Store()->memory_size();
5357   }
5358   return true;
5359 }
5360 #endif //ASSERT
5361 
5362 
5363 
5364 
5365 //============================MergeMemNode=====================================
5366 //
5367 // SEMANTICS OF MEMORY MERGES:  A MergeMem is a memory state assembled from several
5368 // contributing store or call operations.  Each contributor provides the memory
5369 // state for a particular "alias type" (see Compile::alias_type).  For example,
5370 // if a MergeMem has an input X for alias category #6, then any memory reference
5371 // to alias category #6 may use X as its memory state input, as an exact equivalent
5372 // to using the MergeMem as a whole.
5373 //   Load<6>( MergeMem(<6>: X, ...), p ) <==> Load<6>(X,p)
5374 //
5375 // (Here, the <N> notation gives the index of the relevant adr_type.)
5376 //
5377 // In one special case (and more cases in the future), alias categories overlap.
5378 // The special alias category "Bot" (Compile::AliasIdxBot) includes all memory
5379 // states.  Therefore, if a MergeMem has only one contributing input W for Bot,
5380 // it is exactly equivalent to that state W:
5381 //   MergeMem(<Bot>: W) <==> W
5382 //
5383 // Usually, the merge has more than one input.  In that case, where inputs
5384 // overlap (i.e., one is Bot), the narrower alias type determines the memory
5385 // state for that type, and the wider alias type (Bot) fills in everywhere else:
5386 //   Load<5>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<5>(W,p)
5387 //   Load<6>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<6>(X,p)
5388 //
5389 // A merge can take a "wide" memory state as one of its narrow inputs.
5390 // This simply means that the merge observes out only the relevant parts of
5391 // the wide input.  That is, wide memory states arriving at narrow merge inputs
5392 // are implicitly "filtered" or "sliced" as necessary.  (This is rare.)
5393 //
5394 // These rules imply that MergeMem nodes may cascade (via their <Bot> links),
5395 // and that memory slices "leak through":
5396 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y)) <==> MergeMem(<Bot>: W, <7>: Y)
5397 //
5398 // But, in such a cascade, repeated memory slices can "block the leak":
5399 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y), <7>: Y') <==> MergeMem(<Bot>: W, <7>: Y')
5400 //
5401 // In the last example, Y is not part of the combined memory state of the
5402 // outermost MergeMem.  The system must, of course, prevent unschedulable
5403 // memory states from arising, so you can be sure that the state Y is somehow
5404 // a precursor to state Y'.
5405 //
5406 //
5407 // REPRESENTATION OF MEMORY MERGES: The indexes used to address the Node::in array
5408 // of each MergeMemNode array are exactly the numerical alias indexes, including
5409 // but not limited to AliasIdxTop, AliasIdxBot, and AliasIdxRaw.  The functions
5410 // Compile::alias_type (and kin) produce and manage these indexes.
5411 //
5412 // By convention, the value of in(AliasIdxTop) (i.e., in(1)) is always the top node.
5413 // (Note that this provides quick access to the top node inside MergeMem methods,
5414 // without the need to reach out via TLS to Compile::current.)
5415 //
5416 // As a consequence of what was just described, a MergeMem that represents a full
5417 // memory state has an edge in(AliasIdxBot) which is a "wide" memory state,
5418 // containing all alias categories.
5419 //
5420 // MergeMem nodes never (?) have control inputs, so in(0) is null.
5421 //
5422 // All other edges in(N) (including in(AliasIdxRaw), which is in(3)) are either
5423 // a memory state for the alias type <N>, or else the top node, meaning that
5424 // there is no particular input for that alias type.  Note that the length of
5425 // a MergeMem is variable, and may be extended at any time to accommodate new
5426 // memory states at larger alias indexes.  When merges grow, they are of course
5427 // filled with "top" in the unused in() positions.
5428 //
5429 // This use of top is named "empty_memory()", or "empty_mem" (no-memory) as a variable.
5430 // (Top was chosen because it works smoothly with passes like GCM.)
5431 //
5432 // For convenience, we hardwire the alias index for TypeRawPtr::BOTTOM.  (It is
5433 // the type of random VM bits like TLS references.)  Since it is always the
5434 // first non-Bot memory slice, some low-level loops use it to initialize an
5435 // index variable:  for (i = AliasIdxRaw; i < req(); i++).
5436 //
5437 //
5438 // ACCESSORS:  There is a special accessor MergeMemNode::base_memory which returns
5439 // the distinguished "wide" state.  The accessor MergeMemNode::memory_at(N) returns
5440 // the memory state for alias type <N>, or (if there is no particular slice at <N>,
5441 // it returns the base memory.  To prevent bugs, memory_at does not accept <Top>
5442 // or <Bot> indexes.  The iterator MergeMemStream provides robust iteration over
5443 // MergeMem nodes or pairs of such nodes, ensuring that the non-top edges are visited.
5444 //
5445 // %%%% We may get rid of base_memory as a separate accessor at some point; it isn't
5446 // really that different from the other memory inputs.  An abbreviation called
5447 // "bot_memory()" for "memory_at(AliasIdxBot)" would keep code tidy.
5448 //
5449 //
5450 // PARTIAL MEMORY STATES:  During optimization, MergeMem nodes may arise that represent
5451 // partial memory states.  When a Phi splits through a MergeMem, the copy of the Phi
5452 // that "emerges though" the base memory will be marked as excluding the alias types
5453 // of the other (narrow-memory) copies which "emerged through" the narrow edges:
5454 //
5455 //   Phi<Bot>(U, MergeMem(<Bot>: W, <8>: Y))
5456 //     ==Ideal=>  MergeMem(<Bot>: Phi<Bot-8>(U, W), Phi<8>(U, Y))
5457 //
5458 // This strange "subtraction" effect is necessary to ensure IGVN convergence.
5459 // (It is currently unimplemented.)  As you can see, the resulting merge is
5460 // actually a disjoint union of memory states, rather than an overlay.
5461 //
5462 
5463 //------------------------------MergeMemNode-----------------------------------
5464 Node* MergeMemNode::make_empty_memory() {
5465   Node* empty_memory = (Node*) Compile::current()->top();
5466   assert(empty_memory->is_top(), "correct sentinel identity");
5467   return empty_memory;
5468 }
5469 
5470 MergeMemNode::MergeMemNode(Node *new_base) : Node(1+Compile::AliasIdxRaw) {
5471   init_class_id(Class_MergeMem);
5472   // all inputs are nullified in Node::Node(int)
5473   // set_input(0, nullptr);  // no control input
5474 
5475   // Initialize the edges uniformly to top, for starters.
5476   Node* empty_mem = make_empty_memory();
5477   for (uint i = Compile::AliasIdxTop; i < req(); i++) {
5478     init_req(i,empty_mem);
5479   }
5480   assert(empty_memory() == empty_mem, "");
5481 
5482   if( new_base != nullptr && new_base->is_MergeMem() ) {
5483     MergeMemNode* mdef = new_base->as_MergeMem();
5484     assert(mdef->empty_memory() == empty_mem, "consistent sentinels");
5485     for (MergeMemStream mms(this, mdef); mms.next_non_empty2(); ) {
5486       mms.set_memory(mms.memory2());
5487     }
5488     assert(base_memory() == mdef->base_memory(), "");
5489   } else {
5490     set_base_memory(new_base);
5491   }
5492 }
5493 
5494 // Make a new, untransformed MergeMem with the same base as 'mem'.
5495 // If mem is itself a MergeMem, populate the result with the same edges.
5496 MergeMemNode* MergeMemNode::make(Node* mem) {
5497   return new MergeMemNode(mem);
5498 }
5499 
5500 //------------------------------cmp--------------------------------------------
5501 uint MergeMemNode::hash() const { return NO_HASH; }
5502 bool MergeMemNode::cmp( const Node &n ) const {
5503   return (&n == this);          // Always fail except on self
5504 }
5505 
5506 //------------------------------Identity---------------------------------------
5507 Node* MergeMemNode::Identity(PhaseGVN* phase) {
5508   // Identity if this merge point does not record any interesting memory
5509   // disambiguations.
5510   Node* base_mem = base_memory();
5511   Node* empty_mem = empty_memory();
5512   if (base_mem != empty_mem) {  // Memory path is not dead?
5513     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
5514       Node* mem = in(i);
5515       if (mem != empty_mem && mem != base_mem) {
5516         return this;            // Many memory splits; no change
5517       }
5518     }
5519   }
5520   return base_mem;              // No memory splits; ID on the one true input
5521 }
5522 
5523 //------------------------------Ideal------------------------------------------
5524 // This method is invoked recursively on chains of MergeMem nodes
5525 Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) {
5526   // Remove chain'd MergeMems
5527   //
5528   // This is delicate, because the each "in(i)" (i >= Raw) is interpreted
5529   // relative to the "in(Bot)".  Since we are patching both at the same time,
5530   // we have to be careful to read each "in(i)" relative to the old "in(Bot)",
5531   // but rewrite each "in(i)" relative to the new "in(Bot)".
5532   Node *progress = nullptr;
5533 
5534 
5535   Node* old_base = base_memory();
5536   Node* empty_mem = empty_memory();
5537   if (old_base == empty_mem)
5538     return nullptr; // Dead memory path.
5539 
5540   MergeMemNode* old_mbase;
5541   if (old_base != nullptr && old_base->is_MergeMem())
5542     old_mbase = old_base->as_MergeMem();
5543   else
5544     old_mbase = nullptr;
5545   Node* new_base = old_base;
5546 
5547   // simplify stacked MergeMems in base memory
5548   if (old_mbase)  new_base = old_mbase->base_memory();
5549 
5550   // the base memory might contribute new slices beyond my req()
5551   if (old_mbase)  grow_to_match(old_mbase);
5552 
5553   // Note:  We do not call verify_sparse on entry, because inputs
5554   // can normalize to the base_memory via subsume_node or similar
5555   // mechanisms.  This method repairs that damage.
5556 
5557   assert(!old_mbase || old_mbase->is_empty_memory(empty_mem), "consistent sentinels");
5558 
5559   // Look at each slice.
5560   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
5561     Node* old_in = in(i);
5562     // calculate the old memory value
5563     Node* old_mem = old_in;
5564     if (old_mem == empty_mem)  old_mem = old_base;
5565     assert(old_mem == memory_at(i), "");
5566 
5567     // maybe update (reslice) the old memory value
5568 
5569     // simplify stacked MergeMems
5570     Node* new_mem = old_mem;
5571     MergeMemNode* old_mmem;
5572     if (old_mem != nullptr && old_mem->is_MergeMem())
5573       old_mmem = old_mem->as_MergeMem();
5574     else
5575       old_mmem = nullptr;
5576     if (old_mmem == this) {
5577       // This can happen if loops break up and safepoints disappear.
5578       // A merge of BotPtr (default) with a RawPtr memory derived from a
5579       // safepoint can be rewritten to a merge of the same BotPtr with
5580       // the BotPtr phi coming into the loop.  If that phi disappears
5581       // also, we can end up with a self-loop of the mergemem.
5582       // In general, if loops degenerate and memory effects disappear,
5583       // a mergemem can be left looking at itself.  This simply means
5584       // that the mergemem's default should be used, since there is
5585       // no longer any apparent effect on this slice.
5586       // Note: If a memory slice is a MergeMem cycle, it is unreachable
5587       //       from start.  Update the input to TOP.
5588       new_mem = (new_base == this || new_base == empty_mem)? empty_mem : new_base;
5589     }
5590     else if (old_mmem != nullptr) {
5591       new_mem = old_mmem->memory_at(i);
5592     }
5593     // else preceding memory was not a MergeMem
5594 
5595     // maybe store down a new value
5596     Node* new_in = new_mem;
5597     if (new_in == new_base)  new_in = empty_mem;
5598 
5599     if (new_in != old_in) {
5600       // Warning:  Do not combine this "if" with the previous "if"
5601       // A memory slice might have be be rewritten even if it is semantically
5602       // unchanged, if the base_memory value has changed.
5603       set_req_X(i, new_in, phase);
5604       progress = this;          // Report progress
5605     }
5606   }
5607 
5608   if (new_base != old_base) {
5609     set_req_X(Compile::AliasIdxBot, new_base, phase);
5610     // Don't use set_base_memory(new_base), because we need to update du.
5611     assert(base_memory() == new_base, "");
5612     progress = this;
5613   }
5614 
5615   if( base_memory() == this ) {
5616     // a self cycle indicates this memory path is dead
5617     set_req(Compile::AliasIdxBot, empty_mem);
5618   }
5619 
5620   // Resolve external cycles by calling Ideal on a MergeMem base_memory
5621   // Recursion must occur after the self cycle check above
5622   if( base_memory()->is_MergeMem() ) {
5623     MergeMemNode *new_mbase = base_memory()->as_MergeMem();
5624     Node *m = phase->transform(new_mbase);  // Rollup any cycles
5625     if( m != nullptr &&
5626         (m->is_top() ||
5627          (m->is_MergeMem() && m->as_MergeMem()->base_memory() == empty_mem)) ) {
5628       // propagate rollup of dead cycle to self
5629       set_req(Compile::AliasIdxBot, empty_mem);
5630     }
5631   }
5632 
5633   if( base_memory() == empty_mem ) {
5634     progress = this;
5635     // Cut inputs during Parse phase only.
5636     // During Optimize phase a dead MergeMem node will be subsumed by Top.
5637     if( !can_reshape ) {
5638       for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
5639         if( in(i) != empty_mem ) { set_req(i, empty_mem); }
5640       }
5641     }
5642   }
5643 
5644   if( !progress && base_memory()->is_Phi() && can_reshape ) {
5645     // Check if PhiNode::Ideal's "Split phis through memory merges"
5646     // transform should be attempted. Look for this->phi->this cycle.
5647     uint merge_width = req();
5648     if (merge_width > Compile::AliasIdxRaw) {
5649       PhiNode* phi = base_memory()->as_Phi();
5650       for( uint i = 1; i < phi->req(); ++i ) {// For all paths in
5651         if (phi->in(i) == this) {
5652           phase->is_IterGVN()->_worklist.push(phi);
5653           break;
5654         }
5655       }
5656     }
5657   }
5658 
5659   assert(progress || verify_sparse(), "please, no dups of base");
5660   return progress;
5661 }
5662 
5663 //-------------------------set_base_memory-------------------------------------
5664 void MergeMemNode::set_base_memory(Node *new_base) {
5665   Node* empty_mem = empty_memory();
5666   set_req(Compile::AliasIdxBot, new_base);
5667   assert(memory_at(req()) == new_base, "must set default memory");
5668   // Clear out other occurrences of new_base:
5669   if (new_base != empty_mem) {
5670     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
5671       if (in(i) == new_base)  set_req(i, empty_mem);
5672     }
5673   }
5674 }
5675 
5676 //------------------------------out_RegMask------------------------------------
5677 const RegMask &MergeMemNode::out_RegMask() const {
5678   return RegMask::Empty;
5679 }
5680 
5681 //------------------------------dump_spec--------------------------------------
5682 #ifndef PRODUCT
5683 void MergeMemNode::dump_spec(outputStream *st) const {
5684   st->print(" {");
5685   Node* base_mem = base_memory();
5686   for( uint i = Compile::AliasIdxRaw; i < req(); i++ ) {
5687     Node* mem = (in(i) != nullptr) ? memory_at(i) : base_mem;
5688     if (mem == base_mem) { st->print(" -"); continue; }
5689     st->print( " N%d:", mem->_idx );
5690     Compile::current()->get_adr_type(i)->dump_on(st);
5691   }
5692   st->print(" }");
5693 }
5694 #endif // !PRODUCT
5695 
5696 
5697 #ifdef ASSERT
5698 static bool might_be_same(Node* a, Node* b) {
5699   if (a == b)  return true;
5700   if (!(a->is_Phi() || b->is_Phi()))  return false;
5701   // phis shift around during optimization
5702   return true;  // pretty stupid...
5703 }
5704 
5705 // verify a narrow slice (either incoming or outgoing)
5706 static void verify_memory_slice(const MergeMemNode* m, int alias_idx, Node* n) {
5707   if (!VerifyAliases)                return;  // don't bother to verify unless requested
5708   if (VMError::is_error_reported())  return;  // muzzle asserts when debugging an error
5709   if (Node::in_dump())               return;  // muzzle asserts when printing
5710   assert(alias_idx >= Compile::AliasIdxRaw, "must not disturb base_memory or sentinel");
5711   assert(n != nullptr, "");
5712   // Elide intervening MergeMem's
5713   while (n->is_MergeMem()) {
5714     n = n->as_MergeMem()->memory_at(alias_idx);
5715   }
5716   Compile* C = Compile::current();
5717   const TypePtr* n_adr_type = n->adr_type();
5718   if (n == m->empty_memory()) {
5719     // Implicit copy of base_memory()
5720   } else if (n_adr_type != TypePtr::BOTTOM) {
5721     assert(n_adr_type != nullptr, "new memory must have a well-defined adr_type");
5722     assert(C->must_alias(n_adr_type, alias_idx), "new memory must match selected slice");
5723   } else {
5724     // A few places like make_runtime_call "know" that VM calls are narrow,
5725     // and can be used to update only the VM bits stored as TypeRawPtr::BOTTOM.
5726     bool expected_wide_mem = false;
5727     if (n == m->base_memory()) {
5728       expected_wide_mem = true;
5729     } else if (alias_idx == Compile::AliasIdxRaw ||
5730                n == m->memory_at(Compile::AliasIdxRaw)) {
5731       expected_wide_mem = true;
5732     } else if (!C->alias_type(alias_idx)->is_rewritable()) {
5733       // memory can "leak through" calls on channels that
5734       // are write-once.  Allow this also.
5735       expected_wide_mem = true;
5736     }
5737     assert(expected_wide_mem, "expected narrow slice replacement");
5738   }
5739 }
5740 #else // !ASSERT
5741 #define verify_memory_slice(m,i,n) (void)(0)  // PRODUCT version is no-op
5742 #endif
5743 
5744 
5745 //-----------------------------memory_at---------------------------------------
5746 Node* MergeMemNode::memory_at(uint alias_idx) const {
5747   assert(alias_idx >= Compile::AliasIdxRaw ||
5748          (alias_idx == Compile::AliasIdxBot && !Compile::current()->do_aliasing()),
5749          "must avoid base_memory and AliasIdxTop");
5750 
5751   // Otherwise, it is a narrow slice.
5752   Node* n = alias_idx < req() ? in(alias_idx) : empty_memory();
5753   if (is_empty_memory(n)) {
5754     // the array is sparse; empty slots are the "top" node
5755     n = base_memory();
5756     assert(Node::in_dump()
5757            || n == nullptr || n->bottom_type() == Type::TOP
5758            || n->adr_type() == nullptr // address is TOP
5759            || n->adr_type() == TypePtr::BOTTOM
5760            || n->adr_type() == TypeRawPtr::BOTTOM
5761            || !Compile::current()->do_aliasing(),
5762            "must be a wide memory");
5763     // do_aliasing == false if we are organizing the memory states manually.
5764     // See verify_memory_slice for comments on TypeRawPtr::BOTTOM.
5765   } else {
5766     // make sure the stored slice is sane
5767     #ifdef ASSERT
5768     if (VMError::is_error_reported() || Node::in_dump()) {
5769     } else if (might_be_same(n, base_memory())) {
5770       // Give it a pass:  It is a mostly harmless repetition of the base.
5771       // This can arise normally from node subsumption during optimization.
5772     } else {
5773       verify_memory_slice(this, alias_idx, n);
5774     }
5775     #endif
5776   }
5777   return n;
5778 }
5779 
5780 //---------------------------set_memory_at-------------------------------------
5781 void MergeMemNode::set_memory_at(uint alias_idx, Node *n) {
5782   verify_memory_slice(this, alias_idx, n);
5783   Node* empty_mem = empty_memory();
5784   if (n == base_memory())  n = empty_mem;  // collapse default
5785   uint need_req = alias_idx+1;
5786   if (req() < need_req) {
5787     if (n == empty_mem)  return;  // already the default, so do not grow me
5788     // grow the sparse array
5789     do {
5790       add_req(empty_mem);
5791     } while (req() < need_req);
5792   }
5793   set_req( alias_idx, n );
5794 }
5795 
5796 
5797 
5798 //--------------------------iteration_setup------------------------------------
5799 void MergeMemNode::iteration_setup(const MergeMemNode* other) {
5800   if (other != nullptr) {
5801     grow_to_match(other);
5802     // invariant:  the finite support of mm2 is within mm->req()
5803     #ifdef ASSERT
5804     for (uint i = req(); i < other->req(); i++) {
5805       assert(other->is_empty_memory(other->in(i)), "slice left uncovered");
5806     }
5807     #endif
5808   }
5809   // Replace spurious copies of base_memory by top.
5810   Node* base_mem = base_memory();
5811   if (base_mem != nullptr && !base_mem->is_top()) {
5812     for (uint i = Compile::AliasIdxBot+1, imax = req(); i < imax; i++) {
5813       if (in(i) == base_mem)
5814         set_req(i, empty_memory());
5815     }
5816   }
5817 }
5818 
5819 //---------------------------grow_to_match-------------------------------------
5820 void MergeMemNode::grow_to_match(const MergeMemNode* other) {
5821   Node* empty_mem = empty_memory();
5822   assert(other->is_empty_memory(empty_mem), "consistent sentinels");
5823   // look for the finite support of the other memory
5824   for (uint i = other->req(); --i >= req(); ) {
5825     if (other->in(i) != empty_mem) {
5826       uint new_len = i+1;
5827       while (req() < new_len)  add_req(empty_mem);
5828       break;
5829     }
5830   }
5831 }
5832 
5833 //---------------------------verify_sparse-------------------------------------
5834 #ifndef PRODUCT
5835 bool MergeMemNode::verify_sparse() const {
5836   assert(is_empty_memory(make_empty_memory()), "sane sentinel");
5837   Node* base_mem = base_memory();
5838   // The following can happen in degenerate cases, since empty==top.
5839   if (is_empty_memory(base_mem))  return true;
5840   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
5841     assert(in(i) != nullptr, "sane slice");
5842     if (in(i) == base_mem)  return false;  // should have been the sentinel value!
5843   }
5844   return true;
5845 }
5846 
5847 bool MergeMemStream::match_memory(Node* mem, const MergeMemNode* mm, int idx) {
5848   Node* n;
5849   n = mm->in(idx);
5850   if (mem == n)  return true;  // might be empty_memory()
5851   n = (idx == Compile::AliasIdxBot)? mm->base_memory(): mm->memory_at(idx);
5852   if (mem == n)  return true;
5853   return false;
5854 }
5855 #endif // !PRODUCT