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