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