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