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