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