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