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