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