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