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 (tkls->offset() == in_bytes(Klass::modifier_flags_offset())) {
1856     // The field is Klass::_modifier_flags.  Return its (constant) value.
1857     // (Folds up the 2nd indirection in aClassConstant.getModifiers().)
1858     assert(this->Opcode() == Op_LoadI, "must load an int from _modifier_flags");
1859     return TypeInt::make(klass->modifier_flags());
1860   }
1861   if (tkls->offset() == in_bytes(Klass::access_flags_offset())) {
1862     // The field is Klass::_access_flags.  Return its (constant) value.
1863     // (Folds up the 2nd indirection in Reflection.getClassAccessFlags(aClassConstant).)
1864     assert(this->Opcode() == Op_LoadI, "must load an int from _access_flags");
1865     return TypeInt::make(klass->access_flags());
1866   }
1867   if (tkls->offset() == in_bytes(Klass::layout_helper_offset())) {
1868     // The field is Klass::_layout_helper.  Return its constant value if known.
1869     assert(this->Opcode() == Op_LoadI, "must load an int from _layout_helper");
1870     return TypeInt::make(klass->layout_helper());
1871   }
1872 
1873   // No match.
1874   return nullptr;
1875 }
1876 
1877 //------------------------------Value-----------------------------------------
1878 const Type* LoadNode::Value(PhaseGVN* phase) const {
1879   // Either input is TOP ==> the result is TOP
1880   Node* mem = in(MemNode::Memory);
1881   const Type *t1 = phase->type(mem);
1882   if (t1 == Type::TOP)  return Type::TOP;
1883   Node* adr = in(MemNode::Address);
1884   const TypePtr* tp = phase->type(adr)->isa_ptr();
1885   if (tp == nullptr || tp->empty())  return Type::TOP;
1886   int off = tp->offset();
1887   assert(off != Type::OffsetTop, "case covered by TypePtr::empty");
1888   Compile* C = phase->C;
1889 
1890   // Try to guess loaded type from pointer type
1891   if (tp->isa_aryptr()) {
1892     const TypeAryPtr* ary = tp->is_aryptr();
1893     const Type* t = ary->elem();
1894 
1895     // Determine whether the reference is beyond the header or not, by comparing
1896     // the offset against the offset of the start of the array's data.
1897     // Different array types begin at slightly different offsets (12 vs. 16).
1898     // We choose T_BYTE as an example base type that is least restrictive
1899     // as to alignment, which will therefore produce the smallest
1900     // possible base offset.
1901     const int min_base_off = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1902     const bool off_beyond_header = (off >= min_base_off);
1903 
1904     // Try to constant-fold a stable array element.
1905     if (FoldStableValues && !is_mismatched_access() && ary->is_stable()) {
1906       // Make sure the reference is not into the header and the offset is constant
1907       ciObject* aobj = ary->const_oop();
1908       if (aobj != nullptr && off_beyond_header && adr->is_AddP() && off != Type::OffsetBot) {
1909         int stable_dimension = (ary->stable_dimension() > 0 ? ary->stable_dimension() - 1 : 0);
1910         const Type* con_type = Type::make_constant_from_array_element(aobj->as_array(), off,
1911                                                                       stable_dimension,
1912                                                                       memory_type(), is_unsigned());
1913         if (con_type != nullptr) {
1914           return con_type;
1915         }
1916       }
1917     }
1918 
1919     // Don't do this for integer types. There is only potential profit if
1920     // the element type t is lower than _type; that is, for int types, if _type is
1921     // more restrictive than t.  This only happens here if one is short and the other
1922     // char (both 16 bits), and in those cases we've made an intentional decision
1923     // to use one kind of load over the other. See AndINode::Ideal and 4965907.
1924     // Also, do not try to narrow the type for a LoadKlass, regardless of offset.
1925     //
1926     // Yes, it is possible to encounter an expression like (LoadKlass p1:(AddP x x 8))
1927     // where the _gvn.type of the AddP is wider than 8.  This occurs when an earlier
1928     // copy p0 of (AddP x x 8) has been proven equal to p1, and the p0 has been
1929     // subsumed by p1.  If p1 is on the worklist but has not yet been re-transformed,
1930     // it is possible that p1 will have a type like Foo*[int+]:NotNull*+any.
1931     // In fact, that could have been the original type of p1, and p1 could have
1932     // had an original form like p1:(AddP x x (LShiftL quux 3)), where the
1933     // expression (LShiftL quux 3) independently optimized to the constant 8.
1934     if ((t->isa_int() == nullptr) && (t->isa_long() == nullptr)
1935         && (_type->isa_vect() == nullptr)
1936         && Opcode() != Op_LoadKlass && Opcode() != Op_LoadNKlass) {
1937       // t might actually be lower than _type, if _type is a unique
1938       // concrete subclass of abstract class t.
1939       if (off_beyond_header || off == Type::OffsetBot) {  // is the offset beyond the header?
1940         const Type* jt = t->join_speculative(_type);
1941         // In any case, do not allow the join, per se, to empty out the type.
1942         if (jt->empty() && !t->empty()) {
1943           // This can happen if a interface-typed array narrows to a class type.
1944           jt = _type;
1945         }
1946 #ifdef ASSERT
1947         if (phase->C->eliminate_boxing() && adr->is_AddP()) {
1948           // The pointers in the autobox arrays are always non-null
1949           Node* base = adr->in(AddPNode::Base);
1950           if ((base != nullptr) && base->is_DecodeN()) {
1951             // Get LoadN node which loads IntegerCache.cache field
1952             base = base->in(1);
1953           }
1954           if ((base != nullptr) && base->is_Con()) {
1955             const TypeAryPtr* base_type = base->bottom_type()->isa_aryptr();
1956             if ((base_type != nullptr) && base_type->is_autobox_cache()) {
1957               // It could be narrow oop
1958               assert(jt->make_ptr()->ptr() == TypePtr::NotNull,"sanity");
1959             }
1960           }
1961         }
1962 #endif
1963         return jt;
1964       }
1965     }
1966   } else if (tp->base() == Type::InstPtr) {
1967     assert( off != Type::OffsetBot ||
1968             // arrays can be cast to Objects
1969             tp->is_oopptr()->klass()->is_java_lang_Object() ||
1970             // unsafe field access may not have a constant offset
1971             C->has_unsafe_access(),
1972             "Field accesses must be precise" );
1973     // For oop loads, we expect the _type to be precise.
1974 
1975     // Optimize loads from constant fields.
1976     const TypeInstPtr* tinst = tp->is_instptr();
1977     ciObject* const_oop = tinst->const_oop();
1978     if (!is_mismatched_access() && off != Type::OffsetBot && const_oop != nullptr && const_oop->is_instance()) {
1979       const Type* con_type = Type::make_constant_from_field(const_oop->as_instance(), off, is_unsigned(), memory_type());
1980       if (con_type != nullptr) {
1981         return con_type;
1982       }
1983     }
1984   } else if (tp->base() == Type::KlassPtr) {
1985     assert( off != Type::OffsetBot ||
1986             // arrays can be cast to Objects
1987             tp->is_klassptr()->klass()->is_java_lang_Object() ||
1988             // also allow array-loading from the primary supertype
1989             // array during subtype checks
1990             Opcode() == Op_LoadKlass,
1991             "Field accesses must be precise" );
1992     // For klass/static loads, we expect the _type to be precise
1993   } else if (tp->base() == Type::RawPtr && adr->is_Load() && off == 0) {
1994     /* With mirrors being an indirect in the Klass*
1995      * the VM is now using two loads. LoadKlass(LoadP(LoadP(Klass, mirror_offset), zero_offset))
1996      * The LoadP from the Klass has a RawPtr type (see LibraryCallKit::load_mirror_from_klass).
1997      *
1998      * So check the type and klass of the node before the LoadP.
1999      */
2000     Node* adr2 = adr->in(MemNode::Address);
2001     const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
2002     if (tkls != nullptr && !StressReflectiveCode) {
2003       ciKlass* klass = tkls->klass();
2004       if (klass->is_loaded() && tkls->klass_is_exact() && tkls->offset() == in_bytes(Klass::java_mirror_offset())) {
2005         assert(adr->Opcode() == Op_LoadP, "must load an oop from _java_mirror");
2006         assert(Opcode() == Op_LoadP, "must load an oop from _java_mirror");
2007         return TypeInstPtr::make(klass->java_mirror());
2008       }
2009     }
2010   }
2011 
2012   const TypeKlassPtr *tkls = tp->isa_klassptr();
2013   if (tkls != nullptr && !StressReflectiveCode) {
2014     ciKlass* klass = tkls->klass();
2015     if (klass->is_loaded() && tkls->klass_is_exact()) {
2016       // We are loading a field from a Klass metaobject whose identity
2017       // is known at compile time (the type is "exact" or "precise").
2018       // Check for fields we know are maintained as constants by the VM.
2019       if (tkls->offset() == in_bytes(Klass::super_check_offset_offset())) {
2020         // The field is Klass::_super_check_offset.  Return its (constant) value.
2021         // (Folds up type checking code.)
2022         assert(Opcode() == Op_LoadI, "must load an int from _super_check_offset");
2023         return TypeInt::make(klass->super_check_offset());
2024       }
2025       // Compute index into primary_supers array
2026       juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
2027       // Check for overflowing; use unsigned compare to handle the negative case.
2028       if( depth < ciKlass::primary_super_limit() ) {
2029         // The field is an element of Klass::_primary_supers.  Return its (constant) value.
2030         // (Folds up type checking code.)
2031         assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
2032         ciKlass *ss = klass->super_of_depth(depth);
2033         return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
2034       }
2035       const Type* aift = load_array_final_field(tkls, klass);
2036       if (aift != nullptr)  return aift;
2037     }
2038 
2039     // We can still check if we are loading from the primary_supers array at a
2040     // shallow enough depth.  Even though the klass is not exact, entries less
2041     // than or equal to its super depth are correct.
2042     if (klass->is_loaded() ) {
2043       ciType *inner = klass;
2044       while( inner->is_obj_array_klass() )
2045         inner = inner->as_obj_array_klass()->base_element_type();
2046       if( inner->is_instance_klass() &&
2047           !inner->as_instance_klass()->flags().is_interface() ) {
2048         // Compute index into primary_supers array
2049         juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
2050         // Check for overflowing; use unsigned compare to handle the negative case.
2051         if( depth < ciKlass::primary_super_limit() &&
2052             depth <= klass->super_depth() ) { // allow self-depth checks to handle self-check case
2053           // The field is an element of Klass::_primary_supers.  Return its (constant) value.
2054           // (Folds up type checking code.)
2055           assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
2056           ciKlass *ss = klass->super_of_depth(depth);
2057           return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
2058         }
2059       }
2060     }
2061 
2062     // If the type is enough to determine that the thing is not an array,
2063     // we can give the layout_helper a positive interval type.
2064     // This will help short-circuit some reflective code.
2065     if (tkls->offset() == in_bytes(Klass::layout_helper_offset())
2066         && !klass->is_array_klass() // not directly typed as an array
2067         && !klass->is_interface()  // specifically not Serializable & Cloneable
2068         && !klass->is_java_lang_Object()   // not the supertype of all T[]
2069         ) {
2070       // Note:  When interfaces are reliable, we can narrow the interface
2071       // test to (klass != Serializable && klass != Cloneable).
2072       assert(Opcode() == Op_LoadI, "must load an int from _layout_helper");
2073       jint min_size = Klass::instance_layout_helper(oopDesc::header_size(), false);
2074       // The key property of this type is that it folds up tests
2075       // for array-ness, since it proves that the layout_helper is positive.
2076       // Thus, a generic value like the basic object layout helper works fine.
2077       return TypeInt::make(min_size, max_jint, Type::WidenMin);
2078     }
2079   }
2080 
2081   // If we are loading from a freshly-allocated object, produce a zero,
2082   // if the load is provably beyond the header of the object.
2083   // (Also allow a variable load from a fresh array to produce zero.)
2084   const TypeOopPtr *tinst = tp->isa_oopptr();
2085   bool is_instance = (tinst != nullptr) && tinst->is_known_instance_field();
2086   bool is_boxed_value = (tinst != nullptr) && tinst->is_ptr_to_boxed_value();
2087   if (ReduceFieldZeroing || is_instance || is_boxed_value) {
2088     Node* value = can_see_stored_value(mem,phase);
2089     if (value != nullptr && value->is_Con()) {
2090       assert(value->bottom_type()->higher_equal(_type),"sanity");
2091       return value->bottom_type();
2092     }
2093   }
2094 
2095   bool is_vect = (_type->isa_vect() != nullptr);
2096   if (is_instance && !is_vect) {
2097     // If we have an instance type and our memory input is the
2098     // programs's initial memory state, there is no matching store,
2099     // so just return a zero of the appropriate type -
2100     // except if it is vectorized - then we have no zero constant.
2101     Node *mem = in(MemNode::Memory);
2102     if (mem->is_Parm() && mem->in(0)->is_Start()) {
2103       assert(mem->as_Parm()->_con == TypeFunc::Memory, "must be memory Parm");
2104       return Type::get_zero_type(_type->basic_type());
2105     }
2106   }
2107 
2108   Node* alloc = is_new_object_mark_load(phase);
2109   if (alloc != nullptr && !(alloc->Opcode() == Op_Allocate && UseBiasedLocking)) {
2110     return TypeX::make(markWord::prototype().value());
2111   }
2112 
2113   return _type;
2114 }
2115 
2116 //------------------------------match_edge-------------------------------------
2117 // Do we Match on this edge index or not?  Match only the address.
2118 uint LoadNode::match_edge(uint idx) const {
2119   return idx == MemNode::Address;
2120 }
2121 
2122 //--------------------------LoadBNode::Ideal--------------------------------------
2123 //
2124 //  If the previous store is to the same address as this load,
2125 //  and the value stored was larger than a byte, replace this load
2126 //  with the value stored truncated to a byte.  If no truncation is
2127 //  needed, the replacement is done in LoadNode::Identity().
2128 //
2129 Node* LoadBNode::Ideal(PhaseGVN* phase, bool can_reshape) {
2130   Node* mem = in(MemNode::Memory);
2131   Node* value = can_see_stored_value(mem,phase);
2132   if (value != nullptr) {
2133     Node* narrow = Compile::narrow_value(T_BYTE, value, _type, phase, false);
2134     if (narrow != value) {
2135       return narrow;
2136     }
2137   }
2138   // Identity call will handle the case where truncation is not needed.
2139   return LoadNode::Ideal(phase, can_reshape);
2140 }
2141 
2142 const Type* LoadBNode::Value(PhaseGVN* phase) const {
2143   Node* mem = in(MemNode::Memory);
2144   Node* value = can_see_stored_value(mem,phase);
2145   if (value != nullptr && value->is_Con() &&
2146       !value->bottom_type()->higher_equal(_type)) {
2147     // If the input to the store does not fit with the load's result type,
2148     // it must be truncated. We can't delay until Ideal call since
2149     // a singleton Value is needed for split_thru_phi optimization.
2150     int con = value->get_int();
2151     return TypeInt::make((con << 24) >> 24);
2152   }
2153   return LoadNode::Value(phase);
2154 }
2155 
2156 //--------------------------LoadUBNode::Ideal-------------------------------------
2157 //
2158 //  If the previous store is to the same address as this load,
2159 //  and the value stored was larger than a byte, replace this load
2160 //  with the value stored truncated to a byte.  If no truncation is
2161 //  needed, the replacement is done in LoadNode::Identity().
2162 //
2163 Node* LoadUBNode::Ideal(PhaseGVN* phase, bool can_reshape) {
2164   Node* mem = in(MemNode::Memory);
2165   Node* value = can_see_stored_value(mem, phase);
2166   if (value != nullptr) {
2167     Node* narrow = Compile::narrow_value(T_BOOLEAN, value, _type, phase, false);
2168     if (narrow != value) {
2169       return narrow;
2170     }
2171   }
2172   // Identity call will handle the case where truncation is not needed.
2173   return LoadNode::Ideal(phase, can_reshape);
2174 }
2175 
2176 const Type* LoadUBNode::Value(PhaseGVN* phase) const {
2177   Node* mem = in(MemNode::Memory);
2178   Node* value = can_see_stored_value(mem,phase);
2179   if (value != nullptr && value->is_Con() &&
2180       !value->bottom_type()->higher_equal(_type)) {
2181     // If the input to the store does not fit with the load's result type,
2182     // it must be truncated. We can't delay until Ideal call since
2183     // a singleton Value is needed for split_thru_phi optimization.
2184     int con = value->get_int();
2185     return TypeInt::make(con & 0xFF);
2186   }
2187   return LoadNode::Value(phase);
2188 }
2189 
2190 //--------------------------LoadUSNode::Ideal-------------------------------------
2191 //
2192 //  If the previous store is to the same address as this load,
2193 //  and the value stored was larger than a char, replace this load
2194 //  with the value stored truncated to a char.  If no truncation is
2195 //  needed, the replacement is done in LoadNode::Identity().
2196 //
2197 Node* LoadUSNode::Ideal(PhaseGVN* phase, bool can_reshape) {
2198   Node* mem = in(MemNode::Memory);
2199   Node* value = can_see_stored_value(mem,phase);
2200   if (value != nullptr) {
2201     Node* narrow = Compile::narrow_value(T_CHAR, value, _type, phase, false);
2202     if (narrow != value) {
2203       return narrow;
2204     }
2205   }
2206   // Identity call will handle the case where truncation is not needed.
2207   return LoadNode::Ideal(phase, can_reshape);
2208 }
2209 
2210 const Type* LoadUSNode::Value(PhaseGVN* phase) const {
2211   Node* mem = in(MemNode::Memory);
2212   Node* value = can_see_stored_value(mem,phase);
2213   if (value != nullptr && value->is_Con() &&
2214       !value->bottom_type()->higher_equal(_type)) {
2215     // If the input to the store does not fit with the load's result type,
2216     // it must be truncated. We can't delay until Ideal call since
2217     // a singleton Value is needed for split_thru_phi optimization.
2218     int con = value->get_int();
2219     return TypeInt::make(con & 0xFFFF);
2220   }
2221   return LoadNode::Value(phase);
2222 }
2223 
2224 //--------------------------LoadSNode::Ideal--------------------------------------
2225 //
2226 //  If the previous store is to the same address as this load,
2227 //  and the value stored was larger than a short, replace this load
2228 //  with the value stored truncated to a short.  If no truncation is
2229 //  needed, the replacement is done in LoadNode::Identity().
2230 //
2231 Node* LoadSNode::Ideal(PhaseGVN* phase, bool can_reshape) {
2232   Node* mem = in(MemNode::Memory);
2233   Node* value = can_see_stored_value(mem,phase);
2234   if (value != nullptr) {
2235     Node* narrow = Compile::narrow_value(T_SHORT, value, _type, phase, false);
2236     if (narrow != value) {
2237       return narrow;
2238     }
2239   }
2240   // Identity call will handle the case where truncation is not needed.
2241   return LoadNode::Ideal(phase, can_reshape);
2242 }
2243 
2244 const Type* LoadSNode::Value(PhaseGVN* phase) const {
2245   Node* mem = in(MemNode::Memory);
2246   Node* value = can_see_stored_value(mem,phase);
2247   if (value != nullptr && value->is_Con() &&
2248       !value->bottom_type()->higher_equal(_type)) {
2249     // If the input to the store does not fit with the load's result type,
2250     // it must be truncated. We can't delay until Ideal call since
2251     // a singleton Value is needed for split_thru_phi optimization.
2252     int con = value->get_int();
2253     return TypeInt::make((con << 16) >> 16);
2254   }
2255   return LoadNode::Value(phase);
2256 }
2257 
2258 //=============================================================================
2259 //----------------------------LoadKlassNode::make------------------------------
2260 // Polymorphic factory method:
2261 Node* LoadKlassNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* at, const TypeKlassPtr* tk) {
2262   // sanity check the alias category against the created node type
2263   const TypePtr *adr_type = adr->bottom_type()->isa_ptr();
2264   assert(adr_type != nullptr, "expecting TypeKlassPtr");
2265 #ifdef _LP64
2266   if (adr_type->is_ptr_to_narrowklass()) {
2267     assert(UseCompressedClassPointers, "no compressed klasses");
2268     Node* load_klass = gvn.transform(new LoadNKlassNode(ctl, mem, adr, at, tk->make_narrowklass(), MemNode::unordered));
2269     return new DecodeNKlassNode(load_klass, load_klass->bottom_type()->make_ptr());
2270   }
2271 #endif
2272   assert(!adr_type->is_ptr_to_narrowklass() && !adr_type->is_ptr_to_narrowoop(), "should have got back a narrow oop");
2273   return new LoadKlassNode(ctl, mem, adr, at, tk, MemNode::unordered);
2274 }
2275 
2276 //------------------------------Value------------------------------------------
2277 const Type* LoadKlassNode::Value(PhaseGVN* phase) const {
2278   return klass_value_common(phase);
2279 }
2280 
2281 // In most cases, LoadKlassNode does not have the control input set. If the control
2282 // input is set, it must not be removed (by LoadNode::Ideal()).
2283 bool LoadKlassNode::can_remove_control() const {
2284   return false;
2285 }
2286 
2287 const Type* LoadNode::klass_value_common(PhaseGVN* phase) const {
2288   // Either input is TOP ==> the result is TOP
2289   const Type *t1 = phase->type( in(MemNode::Memory) );
2290   if (t1 == Type::TOP)  return Type::TOP;
2291   Node *adr = in(MemNode::Address);
2292   const Type *t2 = phase->type( adr );
2293   if (t2 == Type::TOP)  return Type::TOP;
2294   const TypePtr *tp = t2->is_ptr();
2295   if (TypePtr::above_centerline(tp->ptr()) ||
2296       tp->ptr() == TypePtr::Null)  return Type::TOP;
2297 
2298   // Return a more precise klass, if possible
2299   const TypeInstPtr *tinst = tp->isa_instptr();
2300   if (tinst != nullptr) {
2301     ciInstanceKlass* ik = tinst->klass()->as_instance_klass();
2302     int offset = tinst->offset();
2303     if (ik == phase->C->env()->Class_klass()
2304         && (offset == java_lang_Class::klass_offset() ||
2305             offset == java_lang_Class::array_klass_offset())) {
2306       // We are loading a special hidden field from a Class mirror object,
2307       // the field which points to the VM's Klass metaobject.
2308       ciType* t = tinst->java_mirror_type();
2309       // java_mirror_type returns non-null for compile-time Class constants.
2310       if (t != nullptr) {
2311         // constant oop => constant klass
2312         if (offset == java_lang_Class::array_klass_offset()) {
2313           if (t->is_void()) {
2314             // We cannot create a void array.  Since void is a primitive type return null
2315             // klass.  Users of this result need to do a null check on the returned klass.
2316             return TypePtr::NULL_PTR;
2317           }
2318           return TypeKlassPtr::make(ciArrayKlass::make(t));
2319         }
2320         if (!t->is_klass()) {
2321           // a primitive Class (e.g., int.class) has null for a klass field
2322           return TypePtr::NULL_PTR;
2323         }
2324         // (Folds up the 1st indirection in aClassConstant.getModifiers().)
2325         return TypeKlassPtr::make(t->as_klass());
2326       }
2327       // non-constant mirror, so we can't tell what's going on
2328     }
2329     if( !ik->is_loaded() )
2330       return _type;             // Bail out if not loaded
2331     if (offset == oopDesc::klass_offset_in_bytes()) {
2332       if (tinst->klass_is_exact()) {
2333         return TypeKlassPtr::make(ik);
2334       }
2335       // See if we can become precise: no subklasses and no interface
2336       // (Note:  We need to support verified interfaces.)
2337       if (!ik->is_interface() && !ik->has_subklass()) {
2338         // Add a dependence; if any subclass added we need to recompile
2339         if (!ik->is_final()) {
2340           // %%% should use stronger assert_unique_concrete_subtype instead
2341           phase->C->dependencies()->assert_leaf_type(ik);
2342         }
2343         // Return precise klass
2344         return TypeKlassPtr::make(ik);
2345       }
2346 
2347       // Return root of possible klass
2348       return TypeKlassPtr::make(TypePtr::NotNull, ik, 0/*offset*/);
2349     }
2350   }
2351 
2352   // Check for loading klass from an array
2353   const TypeAryPtr *tary = tp->isa_aryptr();
2354   if( tary != nullptr ) {
2355     ciKlass *tary_klass = tary->klass();
2356     if (tary_klass != nullptr   // can be null when at BOTTOM or TOP
2357         && tary->offset() == oopDesc::klass_offset_in_bytes()) {
2358       if (tary->klass_is_exact()) {
2359         return TypeKlassPtr::make(tary_klass);
2360       }
2361       ciArrayKlass *ak = tary->klass()->as_array_klass();
2362       // If the klass is an object array, we defer the question to the
2363       // array component klass.
2364       if( ak->is_obj_array_klass() ) {
2365         assert( ak->is_loaded(), "" );
2366         ciKlass *base_k = ak->as_obj_array_klass()->base_element_klass();
2367         if( base_k->is_loaded() && base_k->is_instance_klass() ) {
2368           ciInstanceKlass* ik = base_k->as_instance_klass();
2369           // See if we can become precise: no subklasses and no interface
2370           if (!ik->is_interface() && !ik->has_subklass()) {
2371             // Add a dependence; if any subclass added we need to recompile
2372             if (!ik->is_final()) {
2373               phase->C->dependencies()->assert_leaf_type(ik);
2374             }
2375             // Return precise array klass
2376             return TypeKlassPtr::make(ak);
2377           }
2378         }
2379         return TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
2380       } else {                  // Found a type-array?
2381         assert( ak->is_type_array_klass(), "" );
2382         return TypeKlassPtr::make(ak); // These are always precise
2383       }
2384     }
2385   }
2386 
2387   // Check for loading klass from an array klass
2388   const TypeKlassPtr *tkls = tp->isa_klassptr();
2389   if (tkls != nullptr && !StressReflectiveCode) {
2390     ciKlass* klass = tkls->klass();
2391     if( !klass->is_loaded() )
2392       return _type;             // Bail out if not loaded
2393     if( klass->is_obj_array_klass() &&
2394         tkls->offset() == in_bytes(ObjArrayKlass::element_klass_offset())) {
2395       ciKlass* elem = klass->as_obj_array_klass()->element_klass();
2396       // // Always returning precise element type is incorrect,
2397       // // e.g., element type could be object and array may contain strings
2398       // return TypeKlassPtr::make(TypePtr::Constant, elem, 0);
2399 
2400       // The array's TypeKlassPtr was declared 'precise' or 'not precise'
2401       // according to the element type's subclassing.
2402       return TypeKlassPtr::make(tkls->ptr(), elem, 0/*offset*/);
2403     }
2404     if( klass->is_instance_klass() && tkls->klass_is_exact() &&
2405         tkls->offset() == in_bytes(Klass::super_offset())) {
2406       ciKlass* sup = klass->as_instance_klass()->super();
2407       // The field is Klass::_super.  Return its (constant) value.
2408       // (Folds up the 2nd indirection in aClassConstant.getSuperClass().)
2409       return sup ? TypeKlassPtr::make(sup) : TypePtr::NULL_PTR;
2410     }
2411   }
2412 
2413   // Bailout case
2414   return LoadNode::Value(phase);
2415 }
2416 
2417 //------------------------------Identity---------------------------------------
2418 // To clean up reflective code, simplify k.java_mirror.as_klass to plain k.
2419 // Also feed through the klass in Allocate(...klass...)._klass.
2420 Node* LoadKlassNode::Identity(PhaseGVN* phase) {
2421   return klass_identity_common(phase);
2422 }
2423 
2424 Node* LoadNode::klass_identity_common(PhaseGVN* phase) {
2425   Node* x = LoadNode::Identity(phase);
2426   if (x != this)  return x;
2427 
2428   // Take apart the address into an oop and and offset.
2429   // Return 'this' if we cannot.
2430   Node*    adr    = in(MemNode::Address);
2431   intptr_t offset = 0;
2432   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2433   if (base == nullptr)     return this;
2434   const TypeOopPtr* toop = phase->type(adr)->isa_oopptr();
2435   if (toop == nullptr)     return this;
2436 
2437   // Step over potential GC barrier for OopHandle resolve
2438   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2439   if (bs->is_gc_barrier_node(base)) {
2440     base = bs->step_over_gc_barrier(base);
2441   }
2442 
2443   // We can fetch the klass directly through an AllocateNode.
2444   // This works even if the klass is not constant (clone or newArray).
2445   if (offset == oopDesc::klass_offset_in_bytes()) {
2446     Node* allocated_klass = AllocateNode::Ideal_klass(base, phase);
2447     if (allocated_klass != nullptr) {
2448       return allocated_klass;
2449     }
2450   }
2451 
2452   // Simplify k.java_mirror.as_klass to plain k, where k is a Klass*.
2453   // See inline_native_Class_query for occurrences of these patterns.
2454   // Java Example:  x.getClass().isAssignableFrom(y)
2455   //
2456   // This improves reflective code, often making the Class
2457   // mirror go completely dead.  (Current exception:  Class
2458   // mirrors may appear in debug info, but we could clean them out by
2459   // introducing a new debug info operator for Klass.java_mirror).
2460 
2461   if (toop->isa_instptr() && toop->klass() == phase->C->env()->Class_klass()
2462       && offset == java_lang_Class::klass_offset()) {
2463     if (base->is_Load()) {
2464       Node* base2 = base->in(MemNode::Address);
2465       if (base2->is_Load()) { /* direct load of a load which is the OopHandle */
2466         Node* adr2 = base2->in(MemNode::Address);
2467         const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
2468         if (tkls != nullptr && !tkls->empty()
2469             && (tkls->klass()->is_instance_klass() ||
2470               tkls->klass()->is_array_klass())
2471             && adr2->is_AddP()
2472            ) {
2473           int mirror_field = in_bytes(Klass::java_mirror_offset());
2474           if (tkls->offset() == mirror_field) {
2475             return adr2->in(AddPNode::Base);
2476           }
2477         }
2478       }
2479     }
2480   }
2481 
2482   return this;
2483 }
2484 
2485 
2486 //------------------------------Value------------------------------------------
2487 const Type* LoadNKlassNode::Value(PhaseGVN* phase) const {
2488   const Type *t = klass_value_common(phase);
2489   if (t == Type::TOP)
2490     return t;
2491 
2492   return t->make_narrowklass();
2493 }
2494 
2495 //------------------------------Identity---------------------------------------
2496 // To clean up reflective code, simplify k.java_mirror.as_klass to narrow k.
2497 // Also feed through the klass in Allocate(...klass...)._klass.
2498 Node* LoadNKlassNode::Identity(PhaseGVN* phase) {
2499   Node *x = klass_identity_common(phase);
2500 
2501   const Type *t = phase->type( x );
2502   if( t == Type::TOP ) return x;
2503   if( t->isa_narrowklass()) return x;
2504   assert (!t->isa_narrowoop(), "no narrow oop here");
2505 
2506   return phase->transform(new EncodePKlassNode(x, t->make_narrowklass()));
2507 }
2508 
2509 //------------------------------Value-----------------------------------------
2510 const Type* LoadRangeNode::Value(PhaseGVN* phase) const {
2511   // Either input is TOP ==> the result is TOP
2512   const Type *t1 = phase->type( in(MemNode::Memory) );
2513   if( t1 == Type::TOP ) return Type::TOP;
2514   Node *adr = in(MemNode::Address);
2515   const Type *t2 = phase->type( adr );
2516   if( t2 == Type::TOP ) return Type::TOP;
2517   const TypePtr *tp = t2->is_ptr();
2518   if (TypePtr::above_centerline(tp->ptr()))  return Type::TOP;
2519   const TypeAryPtr *tap = tp->isa_aryptr();
2520   if( !tap ) return _type;
2521   return tap->size();
2522 }
2523 
2524 //-------------------------------Ideal---------------------------------------
2525 // Feed through the length in AllocateArray(...length...)._length.
2526 Node *LoadRangeNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2527   Node* p = MemNode::Ideal_common(phase, can_reshape);
2528   if (p)  return (p == NodeSentinel) ? nullptr : p;
2529 
2530   // Take apart the address into an oop and and offset.
2531   // Return 'this' if we cannot.
2532   Node*    adr    = in(MemNode::Address);
2533   intptr_t offset = 0;
2534   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase,  offset);
2535   if (base == nullptr)     return nullptr;
2536   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2537   if (tary == nullptr)     return nullptr;
2538 
2539   // We can fetch the length directly through an AllocateArrayNode.
2540   // This works even if the length is not constant (clone or newArray).
2541   if (offset == arrayOopDesc::length_offset_in_bytes()) {
2542     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
2543     if (alloc != nullptr) {
2544       Node* allocated_length = alloc->Ideal_length();
2545       Node* len = alloc->make_ideal_length(tary, phase);
2546       if (allocated_length != len) {
2547         // New CastII improves on this.
2548         return len;
2549       }
2550     }
2551   }
2552 
2553   return nullptr;
2554 }
2555 
2556 //------------------------------Identity---------------------------------------
2557 // Feed through the length in AllocateArray(...length...)._length.
2558 Node* LoadRangeNode::Identity(PhaseGVN* phase) {
2559   Node* x = LoadINode::Identity(phase);
2560   if (x != this)  return x;
2561 
2562   // Take apart the address into an oop and and offset.
2563   // Return 'this' if we cannot.
2564   Node*    adr    = in(MemNode::Address);
2565   intptr_t offset = 0;
2566   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2567   if (base == nullptr)     return this;
2568   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2569   if (tary == nullptr)     return this;
2570 
2571   // We can fetch the length directly through an AllocateArrayNode.
2572   // This works even if the length is not constant (clone or newArray).
2573   if (offset == arrayOopDesc::length_offset_in_bytes()) {
2574     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
2575     if (alloc != nullptr) {
2576       Node* allocated_length = alloc->Ideal_length();
2577       // Do not allow make_ideal_length to allocate a CastII node.
2578       Node* len = alloc->make_ideal_length(tary, phase, false);
2579       if (allocated_length == len) {
2580         // Return allocated_length only if it would not be improved by a CastII.
2581         return allocated_length;
2582       }
2583     }
2584   }
2585 
2586   return this;
2587 
2588 }
2589 
2590 //=============================================================================
2591 //---------------------------StoreNode::make-----------------------------------
2592 // Polymorphic factory method:
2593 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) {
2594   assert((mo == unordered || mo == release), "unexpected");
2595   Compile* C = gvn.C;
2596   assert(C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
2597          ctl != nullptr, "raw memory operations should have control edge");
2598 
2599   switch (bt) {
2600   case T_BOOLEAN: val = gvn.transform(new AndINode(val, gvn.intcon(0x1))); // Fall through to T_BYTE case
2601   case T_BYTE:    return new StoreBNode(ctl, mem, adr, adr_type, val, mo);
2602   case T_INT:     return new StoreINode(ctl, mem, adr, adr_type, val, mo);
2603   case T_CHAR:
2604   case T_SHORT:   return new StoreCNode(ctl, mem, adr, adr_type, val, mo);
2605   case T_LONG:    return new StoreLNode(ctl, mem, adr, adr_type, val, mo, require_atomic_access);
2606   case T_FLOAT:   return new StoreFNode(ctl, mem, adr, adr_type, val, mo);
2607   case T_DOUBLE:  return new StoreDNode(ctl, mem, adr, adr_type, val, mo, require_atomic_access);
2608   case T_METADATA:
2609   case T_ADDRESS:
2610   case T_OBJECT:
2611 #ifdef _LP64
2612     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
2613       val = gvn.transform(new EncodePNode(val, val->bottom_type()->make_narrowoop()));
2614       return new StoreNNode(ctl, mem, adr, adr_type, val, mo);
2615     } else if (adr->bottom_type()->is_ptr_to_narrowklass() ||
2616                (UseCompressedClassPointers && val->bottom_type()->isa_klassptr() &&
2617                 adr->bottom_type()->isa_rawptr())) {
2618       val = gvn.transform(new EncodePKlassNode(val, val->bottom_type()->make_narrowklass()));
2619       return new StoreNKlassNode(ctl, mem, adr, adr_type, val, mo);
2620     }
2621 #endif
2622     {
2623       return new StorePNode(ctl, mem, adr, adr_type, val, mo);
2624     }
2625   default:
2626     ShouldNotReachHere();
2627     return (StoreNode*)nullptr;
2628   }
2629 }
2630 
2631 //--------------------------bottom_type----------------------------------------
2632 const Type *StoreNode::bottom_type() const {
2633   return Type::MEMORY;
2634 }
2635 
2636 //------------------------------hash-------------------------------------------
2637 uint StoreNode::hash() const {
2638   // unroll addition of interesting fields
2639   //return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address) + (uintptr_t)in(ValueIn);
2640 
2641   // Since they are not commoned, do not hash them:
2642   return NO_HASH;
2643 }
2644 
2645 //------------------------------Ideal------------------------------------------
2646 // Change back-to-back Store(, p, x) -> Store(m, p, y) to Store(m, p, x).
2647 // When a store immediately follows a relevant allocation/initialization,
2648 // try to capture it into the initialization, or hoist it above.
2649 Node *StoreNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2650   Node* p = MemNode::Ideal_common(phase, can_reshape);
2651   if (p)  return (p == NodeSentinel) ? nullptr : p;
2652 
2653   Node* mem     = in(MemNode::Memory);
2654   Node* address = in(MemNode::Address);
2655   Node* value   = in(MemNode::ValueIn);
2656   // Back-to-back stores to same address?  Fold em up.  Generally
2657   // unsafe if I have intervening uses...  Also disallowed for StoreCM
2658   // since they must follow each StoreP operation.  Redundant StoreCMs
2659   // are eliminated just before matching in final_graph_reshape.
2660   {
2661     Node* st = mem;
2662     // If Store 'st' has more than one use, we cannot fold 'st' away.
2663     // For example, 'st' might be the final state at a conditional
2664     // return.  Or, 'st' might be used by some node which is live at
2665     // the same time 'st' is live, which might be unschedulable.  So,
2666     // require exactly ONE user until such time as we clone 'mem' for
2667     // each of 'mem's uses (thus making the exactly-1-user-rule hold
2668     // true).
2669     while (st->is_Store() && st->outcnt() == 1 && st->Opcode() != Op_StoreCM) {
2670       // Looking at a dead closed cycle of memory?
2671       assert(st != st->in(MemNode::Memory), "dead loop in StoreNode::Ideal");
2672       assert(Opcode() == st->Opcode() ||
2673              st->Opcode() == Op_StoreVector ||
2674              Opcode() == Op_StoreVector ||
2675              st->Opcode() == Op_StoreVectorScatter ||
2676              Opcode() == Op_StoreVectorScatter ||
2677              phase->C->get_alias_index(adr_type()) == Compile::AliasIdxRaw ||
2678              (Opcode() == Op_StoreL && st->Opcode() == Op_StoreI) || // expanded ClearArrayNode
2679              (Opcode() == Op_StoreI && st->Opcode() == Op_StoreL) || // initialization by arraycopy
2680              (is_mismatched_access() || st->as_Store()->is_mismatched_access()),
2681              "no mismatched stores, except on raw memory: %s %s", NodeClassNames[Opcode()], NodeClassNames[st->Opcode()]);
2682 
2683       if (st->in(MemNode::Address)->eqv_uncast(address) &&
2684           st->as_Store()->memory_size() <= this->memory_size()) {
2685         Node* use = st->raw_out(0);
2686         if (phase->is_IterGVN()) {
2687           phase->is_IterGVN()->rehash_node_delayed(use);
2688         }
2689         // It's OK to do this in the parser, since DU info is always accurate,
2690         // and the parser always refers to nodes via SafePointNode maps.
2691         use->set_req_X(MemNode::Memory, st->in(MemNode::Memory), phase);
2692         return this;
2693       }
2694       st = st->in(MemNode::Memory);
2695     }
2696   }
2697 
2698 
2699   // Capture an unaliased, unconditional, simple store into an initializer.
2700   // Or, if it is independent of the allocation, hoist it above the allocation.
2701   if (ReduceFieldZeroing && /*can_reshape &&*/
2702       mem->is_Proj() && mem->in(0)->is_Initialize()) {
2703     InitializeNode* init = mem->in(0)->as_Initialize();
2704     intptr_t offset = init->can_capture_store(this, phase, can_reshape);
2705     if (offset > 0) {
2706       Node* moved = init->capture_store(this, offset, phase, can_reshape);
2707       // If the InitializeNode captured me, it made a raw copy of me,
2708       // and I need to disappear.
2709       if (moved != nullptr) {
2710         // %%% hack to ensure that Ideal returns a new node:
2711         mem = MergeMemNode::make(mem);
2712         return mem;             // fold me away
2713       }
2714     }
2715   }
2716 
2717   // Fold reinterpret cast into memory operation:
2718   //    StoreX mem (MoveY2X v) => StoreY mem v
2719   if (value->is_Move()) {
2720     const Type* vt = value->in(1)->bottom_type();
2721     if (has_reinterpret_variant(vt)) {
2722       if (phase->C->post_loop_opts_phase()) {
2723         return convert_to_reinterpret_store(*phase, value->in(1), vt);
2724       } else {
2725         phase->C->record_for_post_loop_opts_igvn(this); // attempt the transformation once loop opts are over
2726       }
2727     }
2728   }
2729 
2730   return nullptr;                  // No further progress
2731 }
2732 
2733 //------------------------------Value-----------------------------------------
2734 const Type* StoreNode::Value(PhaseGVN* phase) const {
2735   // Either input is TOP ==> the result is TOP
2736   const Type *t1 = phase->type( in(MemNode::Memory) );
2737   if( t1 == Type::TOP ) return Type::TOP;
2738   const Type *t2 = phase->type( in(MemNode::Address) );
2739   if( t2 == Type::TOP ) return Type::TOP;
2740   const Type *t3 = phase->type( in(MemNode::ValueIn) );
2741   if( t3 == Type::TOP ) return Type::TOP;
2742   return Type::MEMORY;
2743 }
2744 
2745 //------------------------------Identity---------------------------------------
2746 // Remove redundant stores:
2747 //   Store(m, p, Load(m, p)) changes to m.
2748 //   Store(, p, x) -> Store(m, p, x) changes to Store(m, p, x).
2749 Node* StoreNode::Identity(PhaseGVN* phase) {
2750   Node* mem = in(MemNode::Memory);
2751   Node* adr = in(MemNode::Address);
2752   Node* val = in(MemNode::ValueIn);
2753 
2754   Node* result = this;
2755 
2756   // Load then Store?  Then the Store is useless
2757   if (val->is_Load() &&
2758       val->in(MemNode::Address)->eqv_uncast(adr) &&
2759       val->in(MemNode::Memory )->eqv_uncast(mem) &&
2760       val->as_Load()->store_Opcode() == Opcode()) {
2761     result = mem;
2762   }
2763 
2764   // Two stores in a row of the same value?
2765   if (result == this &&
2766       mem->is_Store() &&
2767       mem->in(MemNode::Address)->eqv_uncast(adr) &&
2768       mem->in(MemNode::ValueIn)->eqv_uncast(val) &&
2769       mem->Opcode() == Opcode()) {
2770     result = mem;
2771   }
2772 
2773   // Store of zero anywhere into a freshly-allocated object?
2774   // Then the store is useless.
2775   // (It must already have been captured by the InitializeNode.)
2776   if (result == this &&
2777       ReduceFieldZeroing && phase->type(val)->is_zero_type()) {
2778     // a newly allocated object is already all-zeroes everywhere
2779     if (mem->is_Proj() && mem->in(0)->is_Allocate()) {
2780       result = mem;
2781     }
2782 
2783     if (result == this) {
2784       // the store may also apply to zero-bits in an earlier object
2785       Node* prev_mem = find_previous_store(phase);
2786       // Steps (a), (b):  Walk past independent stores to find an exact match.
2787       if (prev_mem != nullptr) {
2788         Node* prev_val = can_see_stored_value(prev_mem, phase);
2789         if (prev_val != nullptr && prev_val == val) {
2790           // prev_val and val might differ by a cast; it would be good
2791           // to keep the more informative of the two.
2792           result = mem;
2793         }
2794       }
2795     }
2796   }
2797 
2798   PhaseIterGVN* igvn = phase->is_IterGVN();
2799   if (result != this && igvn != nullptr) {
2800     MemBarNode* trailing = trailing_membar();
2801     if (trailing != nullptr) {
2802 #ifdef ASSERT
2803       const TypeOopPtr* t_oop = phase->type(in(Address))->isa_oopptr();
2804       assert(t_oop == nullptr || t_oop->is_known_instance_field(), "only for non escaping objects");
2805 #endif
2806       trailing->remove(igvn);
2807     }
2808   }
2809 
2810   return result;
2811 }
2812 
2813 //------------------------------match_edge-------------------------------------
2814 // Do we Match on this edge index or not?  Match only memory & value
2815 uint StoreNode::match_edge(uint idx) const {
2816   return idx == MemNode::Address || idx == MemNode::ValueIn;
2817 }
2818 
2819 //------------------------------cmp--------------------------------------------
2820 // Do not common stores up together.  They generally have to be split
2821 // back up anyways, so do not bother.
2822 bool StoreNode::cmp( const Node &n ) const {
2823   return (&n == this);          // Always fail except on self
2824 }
2825 
2826 //------------------------------Ideal_masked_input-----------------------------
2827 // Check for a useless mask before a partial-word store
2828 // (StoreB ... (AndI valIn conIa) )
2829 // If (conIa & mask == mask) this simplifies to
2830 // (StoreB ... (valIn) )
2831 Node *StoreNode::Ideal_masked_input(PhaseGVN *phase, uint mask) {
2832   Node *val = in(MemNode::ValueIn);
2833   if( val->Opcode() == Op_AndI ) {
2834     const TypeInt *t = phase->type( val->in(2) )->isa_int();
2835     if( t && t->is_con() && (t->get_con() & mask) == mask ) {
2836       set_req_X(MemNode::ValueIn, val->in(1), phase);
2837       return this;
2838     }
2839   }
2840   return nullptr;
2841 }
2842 
2843 
2844 //------------------------------Ideal_sign_extended_input----------------------
2845 // Check for useless sign-extension before a partial-word store
2846 // (StoreB ... (RShiftI _ (LShiftI _ valIn conIL ) conIR) )
2847 // If (conIL == conIR && conIR <= num_bits)  this simplifies to
2848 // (StoreB ... (valIn) )
2849 Node *StoreNode::Ideal_sign_extended_input(PhaseGVN *phase, int num_bits) {
2850   Node *val = in(MemNode::ValueIn);
2851   if( val->Opcode() == Op_RShiftI ) {
2852     const TypeInt *t = phase->type( val->in(2) )->isa_int();
2853     if( t && t->is_con() && (t->get_con() <= num_bits) ) {
2854       Node *shl = val->in(1);
2855       if( shl->Opcode() == Op_LShiftI ) {
2856         const TypeInt *t2 = phase->type( shl->in(2) )->isa_int();
2857         if( t2 && t2->is_con() && (t2->get_con() == t->get_con()) ) {
2858           set_req_X(MemNode::ValueIn, shl->in(1), phase);
2859           return this;
2860         }
2861       }
2862     }
2863   }
2864   return nullptr;
2865 }
2866 
2867 //------------------------------value_never_loaded-----------------------------------
2868 // Determine whether there are any possible loads of the value stored.
2869 // For simplicity, we actually check if there are any loads from the
2870 // address stored to, not just for loads of the value stored by this node.
2871 //
2872 bool StoreNode::value_never_loaded( PhaseTransform *phase) const {
2873   Node *adr = in(Address);
2874   const TypeOopPtr *adr_oop = phase->type(adr)->isa_oopptr();
2875   if (adr_oop == nullptr)
2876     return false;
2877   if (!adr_oop->is_known_instance_field())
2878     return false; // if not a distinct instance, there may be aliases of the address
2879   for (DUIterator_Fast imax, i = adr->fast_outs(imax); i < imax; i++) {
2880     Node *use = adr->fast_out(i);
2881     if (use->is_Load() || use->is_LoadStore()) {
2882       return false;
2883     }
2884   }
2885   return true;
2886 }
2887 
2888 MemBarNode* StoreNode::trailing_membar() const {
2889   if (is_release()) {
2890     MemBarNode* trailing_mb = nullptr;
2891     for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
2892       Node* u = fast_out(i);
2893       if (u->is_MemBar()) {
2894         if (u->as_MemBar()->trailing_store()) {
2895           assert(u->Opcode() == Op_MemBarVolatile, "");
2896           assert(trailing_mb == nullptr, "only one");
2897           trailing_mb = u->as_MemBar();
2898 #ifdef ASSERT
2899           Node* leading = u->as_MemBar()->leading_membar();
2900           assert(leading->Opcode() == Op_MemBarRelease, "incorrect membar");
2901           assert(leading->as_MemBar()->leading_store(), "incorrect membar pair");
2902           assert(leading->as_MemBar()->trailing_membar() == u, "incorrect membar pair");
2903 #endif
2904         } else {
2905           assert(u->as_MemBar()->standalone(), "");
2906         }
2907       }
2908     }
2909     return trailing_mb;
2910   }
2911   return nullptr;
2912 }
2913 
2914 
2915 //=============================================================================
2916 //------------------------------Ideal------------------------------------------
2917 // If the store is from an AND mask that leaves the low bits untouched, then
2918 // we can skip the AND operation.  If the store is from a sign-extension
2919 // (a left shift, then right shift) we can skip both.
2920 Node *StoreBNode::Ideal(PhaseGVN *phase, bool can_reshape){
2921   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFF);
2922   if( progress != nullptr ) return progress;
2923 
2924   progress = StoreNode::Ideal_sign_extended_input(phase, 24);
2925   if( progress != nullptr ) return progress;
2926 
2927   // Finally check the default case
2928   return StoreNode::Ideal(phase, can_reshape);
2929 }
2930 
2931 //=============================================================================
2932 //------------------------------Ideal------------------------------------------
2933 // If the store is from an AND mask that leaves the low bits untouched, then
2934 // we can skip the AND operation
2935 Node *StoreCNode::Ideal(PhaseGVN *phase, bool can_reshape){
2936   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFFFF);
2937   if( progress != nullptr ) return progress;
2938 
2939   progress = StoreNode::Ideal_sign_extended_input(phase, 16);
2940   if( progress != nullptr ) return progress;
2941 
2942   // Finally check the default case
2943   return StoreNode::Ideal(phase, can_reshape);
2944 }
2945 
2946 //=============================================================================
2947 //------------------------------Identity---------------------------------------
2948 Node* StoreCMNode::Identity(PhaseGVN* phase) {
2949   // No need to card mark when storing a null ptr
2950   Node* my_store = in(MemNode::OopStore);
2951   if (my_store->is_Store()) {
2952     const Type *t1 = phase->type( my_store->in(MemNode::ValueIn) );
2953     if( t1 == TypePtr::NULL_PTR ) {
2954       return in(MemNode::Memory);
2955     }
2956   }
2957   return this;
2958 }
2959 
2960 //=============================================================================
2961 //------------------------------Ideal---------------------------------------
2962 Node *StoreCMNode::Ideal(PhaseGVN *phase, bool can_reshape){
2963   Node* progress = StoreNode::Ideal(phase, can_reshape);
2964   if (progress != nullptr) return progress;
2965 
2966   Node* my_store = in(MemNode::OopStore);
2967   if (my_store->is_MergeMem()) {
2968     Node* mem = my_store->as_MergeMem()->memory_at(oop_alias_idx());
2969     set_req_X(MemNode::OopStore, mem, phase);
2970     return this;
2971   }
2972 
2973   return nullptr;
2974 }
2975 
2976 //------------------------------Value-----------------------------------------
2977 const Type* StoreCMNode::Value(PhaseGVN* phase) const {
2978   // Either input is TOP ==> the result is TOP (checked in StoreNode::Value).
2979   // If extra input is TOP ==> the result is TOP
2980   const Type* t = phase->type(in(MemNode::OopStore));
2981   if (t == Type::TOP) {
2982     return Type::TOP;
2983   }
2984   return StoreNode::Value(phase);
2985 }
2986 
2987 
2988 //=============================================================================
2989 //----------------------------------SCMemProjNode------------------------------
2990 const Type* SCMemProjNode::Value(PhaseGVN* phase) const
2991 {
2992   if (in(0) == nullptr || phase->type(in(0)) == Type::TOP) {
2993     return Type::TOP;
2994   }
2995   return bottom_type();
2996 }
2997 
2998 //=============================================================================
2999 //----------------------------------LoadStoreNode------------------------------
3000 LoadStoreNode::LoadStoreNode( Node *c, Node *mem, Node *adr, Node *val, const TypePtr* at, const Type* rt, uint required )
3001   : Node(required),
3002     _type(rt),
3003     _adr_type(at),
3004     _barrier_data(0)
3005 {
3006   init_req(MemNode::Control, c  );
3007   init_req(MemNode::Memory , mem);
3008   init_req(MemNode::Address, adr);
3009   init_req(MemNode::ValueIn, val);
3010   init_class_id(Class_LoadStore);
3011 }
3012 
3013 //------------------------------Value-----------------------------------------
3014 const Type* LoadStoreNode::Value(PhaseGVN* phase) const {
3015   // Either input is TOP ==> the result is TOP
3016   if (!in(MemNode::Control) || phase->type(in(MemNode::Control)) == Type::TOP) {
3017     return Type::TOP;
3018   }
3019   const Type* t = phase->type(in(MemNode::Memory));
3020   if (t == Type::TOP) {
3021     return Type::TOP;
3022   }
3023   t = phase->type(in(MemNode::Address));
3024   if (t == Type::TOP) {
3025     return Type::TOP;
3026   }
3027   t = phase->type(in(MemNode::ValueIn));
3028   if (t == Type::TOP) {
3029     return Type::TOP;
3030   }
3031   return bottom_type();
3032 }
3033 
3034 uint LoadStoreNode::ideal_reg() const {
3035   return _type->ideal_reg();
3036 }
3037 
3038 bool LoadStoreNode::result_not_used() const {
3039   for( DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++ ) {
3040     Node *x = fast_out(i);
3041     if (x->Opcode() == Op_SCMemProj) continue;
3042     return false;
3043   }
3044   return true;
3045 }
3046 
3047 MemBarNode* LoadStoreNode::trailing_membar() const {
3048   MemBarNode* trailing = nullptr;
3049   for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
3050     Node* u = fast_out(i);
3051     if (u->is_MemBar()) {
3052       if (u->as_MemBar()->trailing_load_store()) {
3053         assert(u->Opcode() == Op_MemBarAcquire, "");
3054         assert(trailing == nullptr, "only one");
3055         trailing = u->as_MemBar();
3056 #ifdef ASSERT
3057         Node* leading = trailing->leading_membar();
3058         assert(support_IRIW_for_not_multiple_copy_atomic_cpu || leading->Opcode() == Op_MemBarRelease, "incorrect membar");
3059         assert(leading->as_MemBar()->leading_load_store(), "incorrect membar pair");
3060         assert(leading->as_MemBar()->trailing_membar() == trailing, "incorrect membar pair");
3061 #endif
3062       } else {
3063         assert(u->as_MemBar()->standalone(), "wrong barrier kind");
3064       }
3065     }
3066   }
3067 
3068   return trailing;
3069 }
3070 
3071 uint LoadStoreNode::size_of() const { return sizeof(*this); }
3072 
3073 //=============================================================================
3074 //----------------------------------LoadStoreConditionalNode--------------------
3075 LoadStoreConditionalNode::LoadStoreConditionalNode( Node *c, Node *mem, Node *adr, Node *val, Node *ex ) : LoadStoreNode(c, mem, adr, val, nullptr, TypeInt::BOOL, 5) {
3076   init_req(ExpectedIn, ex );
3077 }
3078 
3079 const Type* LoadStoreConditionalNode::Value(PhaseGVN* phase) const {
3080   // Either input is TOP ==> the result is TOP
3081   const Type* t = phase->type(in(ExpectedIn));
3082   if (t == Type::TOP) {
3083     return Type::TOP;
3084   }
3085   return LoadStoreNode::Value(phase);
3086 }
3087 
3088 //=============================================================================
3089 //-------------------------------adr_type--------------------------------------
3090 const TypePtr* ClearArrayNode::adr_type() const {
3091   Node *adr = in(3);
3092   if (adr == nullptr)  return nullptr; // node is dead
3093   return MemNode::calculate_adr_type(adr->bottom_type());
3094 }
3095 
3096 //------------------------------match_edge-------------------------------------
3097 // Do we Match on this edge index or not?  Do not match memory
3098 uint ClearArrayNode::match_edge(uint idx) const {
3099   return idx > 1;
3100 }
3101 
3102 //------------------------------Identity---------------------------------------
3103 // Clearing a zero length array does nothing
3104 Node* ClearArrayNode::Identity(PhaseGVN* phase) {
3105   return phase->type(in(2))->higher_equal(TypeX::ZERO)  ? in(1) : this;
3106 }
3107 
3108 //------------------------------Idealize---------------------------------------
3109 // Clearing a short array is faster with stores
3110 Node *ClearArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) {
3111   // Already know this is a large node, do not try to ideal it
3112   if (_is_large) return nullptr;
3113 
3114   const int unit = BytesPerLong;
3115   const TypeX* t = phase->type(in(2))->isa_intptr_t();
3116   if (!t)  return nullptr;
3117   if (!t->is_con())  return nullptr;
3118   intptr_t raw_count = t->get_con();
3119   intptr_t size = raw_count;
3120   if (!Matcher::init_array_count_is_in_bytes) size *= unit;
3121   // Clearing nothing uses the Identity call.
3122   // Negative clears are possible on dead ClearArrays
3123   // (see jck test stmt114.stmt11402.val).
3124   if (size <= 0 || size % unit != 0)  return nullptr;
3125   intptr_t count = size / unit;
3126   // Length too long; communicate this to matchers and assemblers.
3127   // Assemblers are responsible to produce fast hardware clears for it.
3128   if (size > InitArrayShortSize) {
3129     return new ClearArrayNode(in(0), in(1), in(2), in(3), true);
3130   } else if (size > 2 && Matcher::match_rule_supported_vector(Op_ClearArray, 4, T_LONG)) {
3131     return nullptr;
3132   }
3133   if (!IdealizeClearArrayNode) return nullptr;
3134   Node *mem = in(1);
3135   if( phase->type(mem)==Type::TOP ) return nullptr;
3136   Node *adr = in(3);
3137   const Type* at = phase->type(adr);
3138   if( at==Type::TOP ) return nullptr;
3139   const TypePtr* atp = at->isa_ptr();
3140   // adjust atp to be the correct array element address type
3141   if (atp == nullptr)  atp = TypePtr::BOTTOM;
3142   else              atp = atp->add_offset(Type::OffsetBot);
3143   // Get base for derived pointer purposes
3144   if( adr->Opcode() != Op_AddP ) Unimplemented();
3145   Node *base = adr->in(1);
3146 
3147   Node *zero = phase->makecon(TypeLong::ZERO);
3148   Node *off  = phase->MakeConX(BytesPerLong);
3149   mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
3150   count--;
3151   while( count-- ) {
3152     mem = phase->transform(mem);
3153     adr = phase->transform(new AddPNode(base,adr,off));
3154     mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
3155   }
3156   return mem;
3157 }
3158 
3159 //----------------------------step_through----------------------------------
3160 // Return allocation input memory edge if it is different instance
3161 // or itself if it is the one we are looking for.
3162 bool ClearArrayNode::step_through(Node** np, uint instance_id, PhaseTransform* phase) {
3163   Node* n = *np;
3164   assert(n->is_ClearArray(), "sanity");
3165   intptr_t offset;
3166   AllocateNode* alloc = AllocateNode::Ideal_allocation(n->in(3), phase, offset);
3167   // This method is called only before Allocate nodes are expanded
3168   // during macro nodes expansion. Before that ClearArray nodes are
3169   // only generated in PhaseMacroExpand::generate_arraycopy() (before
3170   // Allocate nodes are expanded) which follows allocations.
3171   assert(alloc != nullptr, "should have allocation");
3172   if (alloc->_idx == instance_id) {
3173     // Can not bypass initialization of the instance we are looking for.
3174     return false;
3175   }
3176   // Otherwise skip it.
3177   InitializeNode* init = alloc->initialization();
3178   if (init != nullptr)
3179     *np = init->in(TypeFunc::Memory);
3180   else
3181     *np = alloc->in(TypeFunc::Memory);
3182   return true;
3183 }
3184 
3185 //----------------------------clear_memory-------------------------------------
3186 // Generate code to initialize object storage to zero.
3187 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
3188                                    intptr_t start_offset,
3189                                    Node* end_offset,
3190                                    PhaseGVN* phase) {
3191   intptr_t offset = start_offset;
3192 
3193   int unit = BytesPerLong;
3194   if ((offset % unit) != 0) {
3195     Node* adr = new AddPNode(dest, dest, phase->MakeConX(offset));
3196     adr = phase->transform(adr);
3197     const TypePtr* atp = TypeRawPtr::BOTTOM;
3198     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
3199     mem = phase->transform(mem);
3200     offset += BytesPerInt;
3201   }
3202   assert((offset % unit) == 0, "");
3203 
3204   // Initialize the remaining stuff, if any, with a ClearArray.
3205   return clear_memory(ctl, mem, dest, phase->MakeConX(offset), end_offset, phase);
3206 }
3207 
3208 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
3209                                    Node* start_offset,
3210                                    Node* end_offset,
3211                                    PhaseGVN* phase) {
3212   if (start_offset == end_offset) {
3213     // nothing to do
3214     return mem;
3215   }
3216 
3217   int unit = BytesPerLong;
3218   Node* zbase = start_offset;
3219   Node* zend  = end_offset;
3220 
3221   // Scale to the unit required by the CPU:
3222   if (!Matcher::init_array_count_is_in_bytes) {
3223     Node* shift = phase->intcon(exact_log2(unit));
3224     zbase = phase->transform(new URShiftXNode(zbase, shift) );
3225     zend  = phase->transform(new URShiftXNode(zend,  shift) );
3226   }
3227 
3228   // Bulk clear double-words
3229   Node* zsize = phase->transform(new SubXNode(zend, zbase) );
3230   Node* adr = phase->transform(new AddPNode(dest, dest, start_offset) );
3231   mem = new ClearArrayNode(ctl, mem, zsize, adr, false);
3232   return phase->transform(mem);
3233 }
3234 
3235 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
3236                                    intptr_t start_offset,
3237                                    intptr_t end_offset,
3238                                    PhaseGVN* phase) {
3239   if (start_offset == end_offset) {
3240     // nothing to do
3241     return mem;
3242   }
3243 
3244   assert((end_offset % BytesPerInt) == 0, "odd end offset");
3245   intptr_t done_offset = end_offset;
3246   if ((done_offset % BytesPerLong) != 0) {
3247     done_offset -= BytesPerInt;
3248   }
3249   if (done_offset > start_offset) {
3250     mem = clear_memory(ctl, mem, dest,
3251                        start_offset, phase->MakeConX(done_offset), phase);
3252   }
3253   if (done_offset < end_offset) { // emit the final 32-bit store
3254     Node* adr = new AddPNode(dest, dest, phase->MakeConX(done_offset));
3255     adr = phase->transform(adr);
3256     const TypePtr* atp = TypeRawPtr::BOTTOM;
3257     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
3258     mem = phase->transform(mem);
3259     done_offset += BytesPerInt;
3260   }
3261   assert(done_offset == end_offset, "");
3262   return mem;
3263 }
3264 
3265 //=============================================================================
3266 MemBarNode::MemBarNode(Compile* C, int alias_idx, Node* precedent)
3267   : MultiNode(TypeFunc::Parms + (precedent == nullptr? 0: 1)),
3268     _adr_type(C->get_adr_type(alias_idx)), _kind(Standalone)
3269 #ifdef ASSERT
3270   , _pair_idx(0)
3271 #endif
3272 {
3273   init_class_id(Class_MemBar);
3274   Node* top = C->top();
3275   init_req(TypeFunc::I_O,top);
3276   init_req(TypeFunc::FramePtr,top);
3277   init_req(TypeFunc::ReturnAdr,top);
3278   if (precedent != nullptr)
3279     init_req(TypeFunc::Parms, precedent);
3280 }
3281 
3282 //------------------------------cmp--------------------------------------------
3283 uint MemBarNode::hash() const { return NO_HASH; }
3284 bool MemBarNode::cmp( const Node &n ) const {
3285   return (&n == this);          // Always fail except on self
3286 }
3287 
3288 //------------------------------make-------------------------------------------
3289 MemBarNode* MemBarNode::make(Compile* C, int opcode, int atp, Node* pn) {
3290   switch (opcode) {
3291   case Op_MemBarAcquire:     return new MemBarAcquireNode(C, atp, pn);
3292   case Op_LoadFence:         return new LoadFenceNode(C, atp, pn);
3293   case Op_MemBarRelease:     return new MemBarReleaseNode(C, atp, pn);
3294   case Op_StoreFence:        return new StoreFenceNode(C, atp, pn);
3295   case Op_MemBarStoreStore:  return new MemBarStoreStoreNode(C, atp, pn);
3296   case Op_StoreStoreFence:   return new StoreStoreFenceNode(C, atp, pn);
3297   case Op_MemBarAcquireLock: return new MemBarAcquireLockNode(C, atp, pn);
3298   case Op_MemBarReleaseLock: return new MemBarReleaseLockNode(C, atp, pn);
3299   case Op_MemBarVolatile:    return new MemBarVolatileNode(C, atp, pn);
3300   case Op_MemBarCPUOrder:    return new MemBarCPUOrderNode(C, atp, pn);
3301   case Op_OnSpinWait:        return new OnSpinWaitNode(C, atp, pn);
3302   case Op_Initialize:        return new InitializeNode(C, atp, pn);
3303   default: ShouldNotReachHere(); return nullptr;
3304   }
3305 }
3306 
3307 void MemBarNode::remove(PhaseIterGVN *igvn) {
3308   if (outcnt() != 2) {
3309     assert(Opcode() == Op_Initialize, "Only seen when there are no use of init memory");
3310     assert(outcnt() == 1, "Only control then");
3311   }
3312   if (trailing_store() || trailing_load_store()) {
3313     MemBarNode* leading = leading_membar();
3314     if (leading != nullptr) {
3315       assert(leading->trailing_membar() == this, "inconsistent leading/trailing membars");
3316       leading->remove(igvn);
3317     }
3318   }
3319   if (proj_out_or_null(TypeFunc::Memory) != nullptr) {
3320     igvn->replace_node(proj_out(TypeFunc::Memory), in(TypeFunc::Memory));
3321   }
3322   if (proj_out_or_null(TypeFunc::Control) != nullptr) {
3323     igvn->replace_node(proj_out(TypeFunc::Control), in(TypeFunc::Control));
3324   }
3325 }
3326 
3327 //------------------------------Ideal------------------------------------------
3328 // Return a node which is more "ideal" than the current node.  Strip out
3329 // control copies
3330 Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) {
3331   if (remove_dead_region(phase, can_reshape)) return this;
3332   // Don't bother trying to transform a dead node
3333   if (in(0) && in(0)->is_top()) {
3334     return nullptr;
3335   }
3336 
3337   bool progress = false;
3338   // Eliminate volatile MemBars for scalar replaced objects.
3339   if (can_reshape && req() == (Precedent+1)) {
3340     bool eliminate = false;
3341     int opc = Opcode();
3342     if ((opc == Op_MemBarAcquire || opc == Op_MemBarVolatile)) {
3343       // Volatile field loads and stores.
3344       Node* my_mem = in(MemBarNode::Precedent);
3345       // The MembarAquire may keep an unused LoadNode alive through the Precedent edge
3346       if ((my_mem != nullptr) && (opc == Op_MemBarAcquire) && (my_mem->outcnt() == 1)) {
3347         // if the Precedent is a decodeN and its input (a Load) is used at more than one place,
3348         // replace this Precedent (decodeN) with the Load instead.
3349         if ((my_mem->Opcode() == Op_DecodeN) && (my_mem->in(1)->outcnt() > 1))  {
3350           Node* load_node = my_mem->in(1);
3351           set_req(MemBarNode::Precedent, load_node);
3352           phase->is_IterGVN()->_worklist.push(my_mem);
3353           my_mem = load_node;
3354         } else {
3355           assert(my_mem->unique_out() == this, "sanity");
3356           del_req(Precedent);
3357           phase->is_IterGVN()->_worklist.push(my_mem); // remove dead node later
3358           my_mem = nullptr;
3359         }
3360         progress = true;
3361       }
3362       if (my_mem != nullptr && my_mem->is_Mem()) {
3363         const TypeOopPtr* t_oop = my_mem->in(MemNode::Address)->bottom_type()->isa_oopptr();
3364         // Check for scalar replaced object reference.
3365         if( t_oop != nullptr && t_oop->is_known_instance_field() &&
3366             t_oop->offset() != Type::OffsetBot &&
3367             t_oop->offset() != Type::OffsetTop) {
3368           eliminate = true;
3369         }
3370       }
3371     } else if (opc == Op_MemBarRelease) {
3372       // Final field stores.
3373       Node* alloc = AllocateNode::Ideal_allocation(in(MemBarNode::Precedent), phase);
3374       if ((alloc != nullptr) && alloc->is_Allocate() &&
3375           alloc->as_Allocate()->does_not_escape_thread()) {
3376         // The allocated object does not escape.
3377         eliminate = true;
3378       }
3379     }
3380     if (eliminate) {
3381       // Replace MemBar projections by its inputs.
3382       PhaseIterGVN* igvn = phase->is_IterGVN();
3383       remove(igvn);
3384       // Must return either the original node (now dead) or a new node
3385       // (Do not return a top here, since that would break the uniqueness of top.)
3386       return new ConINode(TypeInt::ZERO);
3387     }
3388   }
3389   return progress ? this : nullptr;
3390 }
3391 
3392 //------------------------------Value------------------------------------------
3393 const Type* MemBarNode::Value(PhaseGVN* phase) const {
3394   if( !in(0) ) return Type::TOP;
3395   if( phase->type(in(0)) == Type::TOP )
3396     return Type::TOP;
3397   return TypeTuple::MEMBAR;
3398 }
3399 
3400 //------------------------------match------------------------------------------
3401 // Construct projections for memory.
3402 Node *MemBarNode::match( const ProjNode *proj, const Matcher *m ) {
3403   switch (proj->_con) {
3404   case TypeFunc::Control:
3405   case TypeFunc::Memory:
3406     return new MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
3407   }
3408   ShouldNotReachHere();
3409   return nullptr;
3410 }
3411 
3412 void MemBarNode::set_store_pair(MemBarNode* leading, MemBarNode* trailing) {
3413   trailing->_kind = TrailingStore;
3414   leading->_kind = LeadingStore;
3415 #ifdef ASSERT
3416   trailing->_pair_idx = leading->_idx;
3417   leading->_pair_idx = leading->_idx;
3418 #endif
3419 }
3420 
3421 void MemBarNode::set_load_store_pair(MemBarNode* leading, MemBarNode* trailing) {
3422   trailing->_kind = TrailingLoadStore;
3423   leading->_kind = LeadingLoadStore;
3424 #ifdef ASSERT
3425   trailing->_pair_idx = leading->_idx;
3426   leading->_pair_idx = leading->_idx;
3427 #endif
3428 }
3429 
3430 MemBarNode* MemBarNode::trailing_membar() const {
3431   ResourceMark rm;
3432   Node* trailing = (Node*)this;
3433   VectorSet seen;
3434   Node_Stack multis(0);
3435   do {
3436     Node* c = trailing;
3437     uint i = 0;
3438     do {
3439       trailing = nullptr;
3440       for (; i < c->outcnt(); i++) {
3441         Node* next = c->raw_out(i);
3442         if (next != c && next->is_CFG()) {
3443           if (c->is_MultiBranch()) {
3444             if (multis.node() == c) {
3445               multis.set_index(i+1);
3446             } else {
3447               multis.push(c, i+1);
3448             }
3449           }
3450           trailing = next;
3451           break;
3452         }
3453       }
3454       if (trailing != nullptr && !seen.test_set(trailing->_idx)) {
3455         break;
3456       }
3457       while (multis.size() > 0) {
3458         c = multis.node();
3459         i = multis.index();
3460         if (i < c->req()) {
3461           break;
3462         }
3463         multis.pop();
3464       }
3465     } while (multis.size() > 0);
3466   } while (!trailing->is_MemBar() || !trailing->as_MemBar()->trailing());
3467 
3468   MemBarNode* mb = trailing->as_MemBar();
3469   assert((mb->_kind == TrailingStore && _kind == LeadingStore) ||
3470          (mb->_kind == TrailingLoadStore && _kind == LeadingLoadStore), "bad trailing membar");
3471   assert(mb->_pair_idx == _pair_idx, "bad trailing membar");
3472   return mb;
3473 }
3474 
3475 MemBarNode* MemBarNode::leading_membar() const {
3476   ResourceMark rm;
3477   VectorSet seen;
3478   Node_Stack regions(0);
3479   Node* leading = in(0);
3480   while (leading != nullptr && (!leading->is_MemBar() || !leading->as_MemBar()->leading())) {
3481     while (leading == nullptr || leading->is_top() || seen.test_set(leading->_idx)) {
3482       leading = nullptr;
3483       while (regions.size() > 0 && leading == nullptr) {
3484         Node* r = regions.node();
3485         uint i = regions.index();
3486         if (i < r->req()) {
3487           leading = r->in(i);
3488           regions.set_index(i+1);
3489         } else {
3490           regions.pop();
3491         }
3492       }
3493       if (leading == nullptr) {
3494         assert(regions.size() == 0, "all paths should have been tried");
3495         return nullptr;
3496       }
3497     }
3498     if (leading->is_Region()) {
3499       regions.push(leading, 2);
3500       leading = leading->in(1);
3501     } else {
3502       leading = leading->in(0);
3503     }
3504   }
3505 #ifdef ASSERT
3506   Unique_Node_List wq;
3507   wq.push((Node*)this);
3508   uint found = 0;
3509   for (uint i = 0; i < wq.size(); i++) {
3510     Node* n = wq.at(i);
3511     if (n->is_Region()) {
3512       for (uint j = 1; j < n->req(); j++) {
3513         Node* in = n->in(j);
3514         if (in != nullptr && !in->is_top()) {
3515           wq.push(in);
3516         }
3517       }
3518     } else {
3519       if (n->is_MemBar() && n->as_MemBar()->leading()) {
3520         assert(n == leading, "consistency check failed");
3521         found++;
3522       } else {
3523         Node* in = n->in(0);
3524         if (in != nullptr && !in->is_top()) {
3525           wq.push(in);
3526         }
3527       }
3528     }
3529   }
3530   assert(found == 1 || (found == 0 && leading == nullptr), "consistency check failed");
3531 #endif
3532   if (leading == nullptr) {
3533     return nullptr;
3534   }
3535   MemBarNode* mb = leading->as_MemBar();
3536   assert((mb->_kind == LeadingStore && _kind == TrailingStore) ||
3537          (mb->_kind == LeadingLoadStore && _kind == TrailingLoadStore), "bad leading membar");
3538   assert(mb->_pair_idx == _pair_idx, "bad leading membar");
3539   return mb;
3540 }
3541 
3542 
3543 //===========================InitializeNode====================================
3544 // SUMMARY:
3545 // This node acts as a memory barrier on raw memory, after some raw stores.
3546 // The 'cooked' oop value feeds from the Initialize, not the Allocation.
3547 // The Initialize can 'capture' suitably constrained stores as raw inits.
3548 // It can coalesce related raw stores into larger units (called 'tiles').
3549 // It can avoid zeroing new storage for memory units which have raw inits.
3550 // At macro-expansion, it is marked 'complete', and does not optimize further.
3551 //
3552 // EXAMPLE:
3553 // The object 'new short[2]' occupies 16 bytes in a 32-bit machine.
3554 //   ctl = incoming control; mem* = incoming memory
3555 // (Note:  A star * on a memory edge denotes I/O and other standard edges.)
3556 // First allocate uninitialized memory and fill in the header:
3557 //   alloc = (Allocate ctl mem* 16 #short[].klass ...)
3558 //   ctl := alloc.Control; mem* := alloc.Memory*
3559 //   rawmem = alloc.Memory; rawoop = alloc.RawAddress
3560 // Then initialize to zero the non-header parts of the raw memory block:
3561 //   init = (Initialize alloc.Control alloc.Memory* alloc.RawAddress)
3562 //   ctl := init.Control; mem.SLICE(#short[*]) := init.Memory
3563 // After the initialize node executes, the object is ready for service:
3564 //   oop := (CheckCastPP init.Control alloc.RawAddress #short[])
3565 // Suppose its body is immediately initialized as {1,2}:
3566 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
3567 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
3568 //   mem.SLICE(#short[*]) := store2
3569 //
3570 // DETAILS:
3571 // An InitializeNode collects and isolates object initialization after
3572 // an AllocateNode and before the next possible safepoint.  As a
3573 // memory barrier (MemBarNode), it keeps critical stores from drifting
3574 // down past any safepoint or any publication of the allocation.
3575 // Before this barrier, a newly-allocated object may have uninitialized bits.
3576 // After this barrier, it may be treated as a real oop, and GC is allowed.
3577 //
3578 // The semantics of the InitializeNode include an implicit zeroing of
3579 // the new object from object header to the end of the object.
3580 // (The object header and end are determined by the AllocateNode.)
3581 //
3582 // Certain stores may be added as direct inputs to the InitializeNode.
3583 // These stores must update raw memory, and they must be to addresses
3584 // derived from the raw address produced by AllocateNode, and with
3585 // a constant offset.  They must be ordered by increasing offset.
3586 // The first one is at in(RawStores), the last at in(req()-1).
3587 // Unlike most memory operations, they are not linked in a chain,
3588 // but are displayed in parallel as users of the rawmem output of
3589 // the allocation.
3590 //
3591 // (See comments in InitializeNode::capture_store, which continue
3592 // the example given above.)
3593 //
3594 // When the associated Allocate is macro-expanded, the InitializeNode
3595 // may be rewritten to optimize collected stores.  A ClearArrayNode
3596 // may also be created at that point to represent any required zeroing.
3597 // The InitializeNode is then marked 'complete', prohibiting further
3598 // capturing of nearby memory operations.
3599 //
3600 // During macro-expansion, all captured initializations which store
3601 // constant values of 32 bits or smaller are coalesced (if advantageous)
3602 // into larger 'tiles' 32 or 64 bits.  This allows an object to be
3603 // initialized in fewer memory operations.  Memory words which are
3604 // covered by neither tiles nor non-constant stores are pre-zeroed
3605 // by explicit stores of zero.  (The code shape happens to do all
3606 // zeroing first, then all other stores, with both sequences occurring
3607 // in order of ascending offsets.)
3608 //
3609 // Alternatively, code may be inserted between an AllocateNode and its
3610 // InitializeNode, to perform arbitrary initialization of the new object.
3611 // E.g., the object copying intrinsics insert complex data transfers here.
3612 // The initialization must then be marked as 'complete' disable the
3613 // built-in zeroing semantics and the collection of initializing stores.
3614 //
3615 // While an InitializeNode is incomplete, reads from the memory state
3616 // produced by it are optimizable if they match the control edge and
3617 // new oop address associated with the allocation/initialization.
3618 // They return a stored value (if the offset matches) or else zero.
3619 // A write to the memory state, if it matches control and address,
3620 // and if it is to a constant offset, may be 'captured' by the
3621 // InitializeNode.  It is cloned as a raw memory operation and rewired
3622 // inside the initialization, to the raw oop produced by the allocation.
3623 // Operations on addresses which are provably distinct (e.g., to
3624 // other AllocateNodes) are allowed to bypass the initialization.
3625 //
3626 // The effect of all this is to consolidate object initialization
3627 // (both arrays and non-arrays, both piecewise and bulk) into a
3628 // single location, where it can be optimized as a unit.
3629 //
3630 // Only stores with an offset less than TrackedInitializationLimit words
3631 // will be considered for capture by an InitializeNode.  This puts a
3632 // reasonable limit on the complexity of optimized initializations.
3633 
3634 //---------------------------InitializeNode------------------------------------
3635 InitializeNode::InitializeNode(Compile* C, int adr_type, Node* rawoop)
3636   : MemBarNode(C, adr_type, rawoop),
3637     _is_complete(Incomplete), _does_not_escape(false)
3638 {
3639   init_class_id(Class_Initialize);
3640 
3641   assert(adr_type == Compile::AliasIdxRaw, "only valid atp");
3642   assert(in(RawAddress) == rawoop, "proper init");
3643   // Note:  allocation() can be null, for secondary initialization barriers
3644 }
3645 
3646 // Since this node is not matched, it will be processed by the
3647 // register allocator.  Declare that there are no constraints
3648 // on the allocation of the RawAddress edge.
3649 const RegMask &InitializeNode::in_RegMask(uint idx) const {
3650   // This edge should be set to top, by the set_complete.  But be conservative.
3651   if (idx == InitializeNode::RawAddress)
3652     return *(Compile::current()->matcher()->idealreg2spillmask[in(idx)->ideal_reg()]);
3653   return RegMask::Empty;
3654 }
3655 
3656 Node* InitializeNode::memory(uint alias_idx) {
3657   Node* mem = in(Memory);
3658   if (mem->is_MergeMem()) {
3659     return mem->as_MergeMem()->memory_at(alias_idx);
3660   } else {
3661     // incoming raw memory is not split
3662     return mem;
3663   }
3664 }
3665 
3666 bool InitializeNode::is_non_zero() {
3667   if (is_complete())  return false;
3668   remove_extra_zeroes();
3669   return (req() > RawStores);
3670 }
3671 
3672 void InitializeNode::set_complete(PhaseGVN* phase) {
3673   assert(!is_complete(), "caller responsibility");
3674   _is_complete = Complete;
3675 
3676   // After this node is complete, it contains a bunch of
3677   // raw-memory initializations.  There is no need for
3678   // it to have anything to do with non-raw memory effects.
3679   // Therefore, tell all non-raw users to re-optimize themselves,
3680   // after skipping the memory effects of this initialization.
3681   PhaseIterGVN* igvn = phase->is_IterGVN();
3682   if (igvn)  igvn->add_users_to_worklist(this);
3683 }
3684 
3685 // convenience function
3686 // return false if the init contains any stores already
3687 bool AllocateNode::maybe_set_complete(PhaseGVN* phase) {
3688   InitializeNode* init = initialization();
3689   if (init == nullptr || init->is_complete())  return false;
3690   init->remove_extra_zeroes();
3691   // for now, if this allocation has already collected any inits, bail:
3692   if (init->is_non_zero())  return false;
3693   init->set_complete(phase);
3694   return true;
3695 }
3696 
3697 void InitializeNode::remove_extra_zeroes() {
3698   if (req() == RawStores)  return;
3699   Node* zmem = zero_memory();
3700   uint fill = RawStores;
3701   for (uint i = fill; i < req(); i++) {
3702     Node* n = in(i);
3703     if (n->is_top() || n == zmem)  continue;  // skip
3704     if (fill < i)  set_req(fill, n);          // compact
3705     ++fill;
3706   }
3707   // delete any empty spaces created:
3708   while (fill < req()) {
3709     del_req(fill);
3710   }
3711 }
3712 
3713 // Helper for remembering which stores go with which offsets.
3714 intptr_t InitializeNode::get_store_offset(Node* st, PhaseTransform* phase) {
3715   if (!st->is_Store())  return -1;  // can happen to dead code via subsume_node
3716   intptr_t offset = -1;
3717   Node* base = AddPNode::Ideal_base_and_offset(st->in(MemNode::Address),
3718                                                phase, offset);
3719   if (base == nullptr)  return -1;  // something is dead,
3720   if (offset < 0)       return -1;  //        dead, dead
3721   return offset;
3722 }
3723 
3724 // Helper for proving that an initialization expression is
3725 // "simple enough" to be folded into an object initialization.
3726 // Attempts to prove that a store's initial value 'n' can be captured
3727 // within the initialization without creating a vicious cycle, such as:
3728 //     { Foo p = new Foo(); p.next = p; }
3729 // True for constants and parameters and small combinations thereof.
3730 bool InitializeNode::detect_init_independence(Node* value, PhaseGVN* phase) {
3731   ResourceMark rm;
3732   Unique_Node_List worklist;
3733   worklist.push(value);
3734 
3735   uint complexity_limit = 20;
3736   for (uint j = 0; j < worklist.size(); j++) {
3737     if (j >= complexity_limit) {
3738       return false;  // Bail out if processed too many nodes
3739     }
3740 
3741     Node* n = worklist.at(j);
3742     if (n == nullptr)   continue;   // (can this really happen?)
3743     if (n->is_Proj())   n = n->in(0);
3744     if (n == this)      return false;  // found a cycle
3745     if (n->is_Con())    continue;
3746     if (n->is_Start())  continue;   // params, etc., are OK
3747     if (n->is_Root())   continue;   // even better
3748 
3749     // There cannot be any dependency if 'n' is a CFG node that dominates the current allocation
3750     if (n->is_CFG() && phase->is_dominator(n, allocation())) {
3751       continue;
3752     }
3753 
3754     Node* ctl = n->in(0);
3755     if (ctl != nullptr && !ctl->is_top()) {
3756       if (ctl->is_Proj())  ctl = ctl->in(0);
3757       if (ctl == this)  return false;
3758 
3759       // If we already know that the enclosing memory op is pinned right after
3760       // the init, then any control flow that the store has picked up
3761       // must have preceded the init, or else be equal to the init.
3762       // Even after loop optimizations (which might change control edges)
3763       // a store is never pinned *before* the availability of its inputs.
3764       if (!MemNode::all_controls_dominate(n, this))
3765         return false;                  // failed to prove a good control
3766     }
3767 
3768     // Check data edges for possible dependencies on 'this'.
3769     for (uint i = 1; i < n->req(); i++) {
3770       Node* m = n->in(i);
3771       if (m == nullptr || m == n || m->is_top())  continue;
3772 
3773       // Only process data inputs once
3774       worklist.push(m);
3775     }
3776   }
3777 
3778   return true;
3779 }
3780 
3781 // Here are all the checks a Store must pass before it can be moved into
3782 // an initialization.  Returns zero if a check fails.
3783 // On success, returns the (constant) offset to which the store applies,
3784 // within the initialized memory.
3785 intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseGVN* phase, bool can_reshape) {
3786   const int FAIL = 0;
3787   if (st->req() != MemNode::ValueIn + 1)
3788     return FAIL;                // an inscrutable StoreNode (card mark?)
3789   Node* ctl = st->in(MemNode::Control);
3790   if (!(ctl != nullptr && ctl->is_Proj() && ctl->in(0) == this))
3791     return FAIL;                // must be unconditional after the initialization
3792   Node* mem = st->in(MemNode::Memory);
3793   if (!(mem->is_Proj() && mem->in(0) == this))
3794     return FAIL;                // must not be preceded by other stores
3795   Node* adr = st->in(MemNode::Address);
3796   intptr_t offset;
3797   AllocateNode* alloc = AllocateNode::Ideal_allocation(adr, phase, offset);
3798   if (alloc == nullptr)
3799     return FAIL;                // inscrutable address
3800   if (alloc != allocation())
3801     return FAIL;                // wrong allocation!  (store needs to float up)
3802   int size_in_bytes = st->memory_size();
3803   if ((size_in_bytes != 0) && (offset % size_in_bytes) != 0) {
3804     return FAIL;                // mismatched access
3805   }
3806   Node* val = st->in(MemNode::ValueIn);
3807 
3808   if (!detect_init_independence(val, phase))
3809     return FAIL;                // stored value must be 'simple enough'
3810 
3811   // The Store can be captured only if nothing after the allocation
3812   // and before the Store is using the memory location that the store
3813   // overwrites.
3814   bool failed = false;
3815   // If is_complete_with_arraycopy() is true the shape of the graph is
3816   // well defined and is safe so no need for extra checks.
3817   if (!is_complete_with_arraycopy()) {
3818     // We are going to look at each use of the memory state following
3819     // the allocation to make sure nothing reads the memory that the
3820     // Store writes.
3821     const TypePtr* t_adr = phase->type(adr)->isa_ptr();
3822     int alias_idx = phase->C->get_alias_index(t_adr);
3823     ResourceMark rm;
3824     Unique_Node_List mems;
3825     mems.push(mem);
3826     Node* unique_merge = nullptr;
3827     for (uint next = 0; next < mems.size(); ++next) {
3828       Node *m  = mems.at(next);
3829       for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
3830         Node *n = m->fast_out(j);
3831         if (n->outcnt() == 0) {
3832           continue;
3833         }
3834         if (n == st) {
3835           continue;
3836         } else if (n->in(0) != nullptr && n->in(0) != ctl) {
3837           // If the control of this use is different from the control
3838           // of the Store which is right after the InitializeNode then
3839           // this node cannot be between the InitializeNode and the
3840           // Store.
3841           continue;
3842         } else if (n->is_MergeMem()) {
3843           if (n->as_MergeMem()->memory_at(alias_idx) == m) {
3844             // We can hit a MergeMemNode (that will likely go away
3845             // later) that is a direct use of the memory state
3846             // following the InitializeNode on the same slice as the
3847             // store node that we'd like to capture. We need to check
3848             // the uses of the MergeMemNode.
3849             mems.push(n);
3850           }
3851         } else if (n->is_Mem()) {
3852           Node* other_adr = n->in(MemNode::Address);
3853           if (other_adr == adr) {
3854             failed = true;
3855             break;
3856           } else {
3857             const TypePtr* other_t_adr = phase->type(other_adr)->isa_ptr();
3858             if (other_t_adr != nullptr) {
3859               int other_alias_idx = phase->C->get_alias_index(other_t_adr);
3860               if (other_alias_idx == alias_idx) {
3861                 // A load from the same memory slice as the store right
3862                 // after the InitializeNode. We check the control of the
3863                 // object/array that is loaded from. If it's the same as
3864                 // the store control then we cannot capture the store.
3865                 assert(!n->is_Store(), "2 stores to same slice on same control?");
3866                 Node* base = other_adr;
3867                 assert(base->is_AddP(), "should be addp but is %s", base->Name());
3868                 base = base->in(AddPNode::Base);
3869                 if (base != nullptr) {
3870                   base = base->uncast();
3871                   if (base->is_Proj() && base->in(0) == alloc) {
3872                     failed = true;
3873                     break;
3874                   }
3875                 }
3876               }
3877             }
3878           }
3879         } else {
3880           failed = true;
3881           break;
3882         }
3883       }
3884     }
3885   }
3886   if (failed) {
3887     if (!can_reshape) {
3888       // We decided we couldn't capture the store during parsing. We
3889       // should try again during the next IGVN once the graph is
3890       // cleaner.
3891       phase->C->record_for_igvn(st);
3892     }
3893     return FAIL;
3894   }
3895 
3896   return offset;                // success
3897 }
3898 
3899 // Find the captured store in(i) which corresponds to the range
3900 // [start..start+size) in the initialized object.
3901 // If there is one, return its index i.  If there isn't, return the
3902 // negative of the index where it should be inserted.
3903 // Return 0 if the queried range overlaps an initialization boundary
3904 // or if dead code is encountered.
3905 // If size_in_bytes is zero, do not bother with overlap checks.
3906 int InitializeNode::captured_store_insertion_point(intptr_t start,
3907                                                    int size_in_bytes,
3908                                                    PhaseTransform* phase) {
3909   const int FAIL = 0, MAX_STORE = MAX2(BytesPerLong, (int)MaxVectorSize);
3910 
3911   if (is_complete())
3912     return FAIL;                // arraycopy got here first; punt
3913 
3914   assert(allocation() != nullptr, "must be present");
3915 
3916   // no negatives, no header fields:
3917   if (start < (intptr_t) allocation()->minimum_header_size())  return FAIL;
3918 
3919   // after a certain size, we bail out on tracking all the stores:
3920   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
3921   if (start >= ti_limit)  return FAIL;
3922 
3923   for (uint i = InitializeNode::RawStores, limit = req(); ; ) {
3924     if (i >= limit)  return -(int)i; // not found; here is where to put it
3925 
3926     Node*    st     = in(i);
3927     intptr_t st_off = get_store_offset(st, phase);
3928     if (st_off < 0) {
3929       if (st != zero_memory()) {
3930         return FAIL;            // bail out if there is dead garbage
3931       }
3932     } else if (st_off > start) {
3933       // ...we are done, since stores are ordered
3934       if (st_off < start + size_in_bytes) {
3935         return FAIL;            // the next store overlaps
3936       }
3937       return -(int)i;           // not found; here is where to put it
3938     } else if (st_off < start) {
3939       assert(st->as_Store()->memory_size() <= MAX_STORE, "");
3940       if (size_in_bytes != 0 &&
3941           start < st_off + MAX_STORE &&
3942           start < st_off + st->as_Store()->memory_size()) {
3943         return FAIL;            // the previous store overlaps
3944       }
3945     } else {
3946       if (size_in_bytes != 0 &&
3947           st->as_Store()->memory_size() != size_in_bytes) {
3948         return FAIL;            // mismatched store size
3949       }
3950       return i;
3951     }
3952 
3953     ++i;
3954   }
3955 }
3956 
3957 // Look for a captured store which initializes at the offset 'start'
3958 // with the given size.  If there is no such store, and no other
3959 // initialization interferes, then return zero_memory (the memory
3960 // projection of the AllocateNode).
3961 Node* InitializeNode::find_captured_store(intptr_t start, int size_in_bytes,
3962                                           PhaseTransform* phase) {
3963   assert(stores_are_sane(phase), "");
3964   int i = captured_store_insertion_point(start, size_in_bytes, phase);
3965   if (i == 0) {
3966     return nullptr;              // something is dead
3967   } else if (i < 0) {
3968     return zero_memory();       // just primordial zero bits here
3969   } else {
3970     Node* st = in(i);           // here is the store at this position
3971     assert(get_store_offset(st->as_Store(), phase) == start, "sanity");
3972     return st;
3973   }
3974 }
3975 
3976 // Create, as a raw pointer, an address within my new object at 'offset'.
3977 Node* InitializeNode::make_raw_address(intptr_t offset,
3978                                        PhaseTransform* phase) {
3979   Node* addr = in(RawAddress);
3980   if (offset != 0) {
3981     Compile* C = phase->C;
3982     addr = phase->transform( new AddPNode(C->top(), addr,
3983                                                  phase->MakeConX(offset)) );
3984   }
3985   return addr;
3986 }
3987 
3988 // Clone the given store, converting it into a raw store
3989 // initializing a field or element of my new object.
3990 // Caller is responsible for retiring the original store,
3991 // with subsume_node or the like.
3992 //
3993 // From the example above InitializeNode::InitializeNode,
3994 // here are the old stores to be captured:
3995 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
3996 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
3997 //
3998 // Here is the changed code; note the extra edges on init:
3999 //   alloc = (Allocate ...)
4000 //   rawoop = alloc.RawAddress
4001 //   rawstore1 = (StoreC alloc.Control alloc.Memory (+ rawoop 12) 1)
4002 //   rawstore2 = (StoreC alloc.Control alloc.Memory (+ rawoop 14) 2)
4003 //   init = (Initialize alloc.Control alloc.Memory rawoop
4004 //                      rawstore1 rawstore2)
4005 //
4006 Node* InitializeNode::capture_store(StoreNode* st, intptr_t start,
4007                                     PhaseGVN* phase, bool can_reshape) {
4008   assert(stores_are_sane(phase), "");
4009 
4010   if (start < 0)  return nullptr;
4011   assert(can_capture_store(st, phase, can_reshape) == start, "sanity");
4012 
4013   Compile* C = phase->C;
4014   int size_in_bytes = st->memory_size();
4015   int i = captured_store_insertion_point(start, size_in_bytes, phase);
4016   if (i == 0)  return nullptr;  // bail out
4017   Node* prev_mem = nullptr;     // raw memory for the captured store
4018   if (i > 0) {
4019     prev_mem = in(i);           // there is a pre-existing store under this one
4020     set_req(i, C->top());       // temporarily disconnect it
4021     // See StoreNode::Ideal 'st->outcnt() == 1' for the reason to disconnect.
4022   } else {
4023     i = -i;                     // no pre-existing store
4024     prev_mem = zero_memory();   // a slice of the newly allocated object
4025     if (i > InitializeNode::RawStores && in(i-1) == prev_mem)
4026       set_req(--i, C->top());   // reuse this edge; it has been folded away
4027     else
4028       ins_req(i, C->top());     // build a new edge
4029   }
4030   Node* new_st = st->clone();
4031   new_st->set_req(MemNode::Control, in(Control));
4032   new_st->set_req(MemNode::Memory,  prev_mem);
4033   new_st->set_req(MemNode::Address, make_raw_address(start, phase));
4034   new_st = phase->transform(new_st);
4035 
4036   // At this point, new_st might have swallowed a pre-existing store
4037   // at the same offset, or perhaps new_st might have disappeared,
4038   // if it redundantly stored the same value (or zero to fresh memory).
4039 
4040   // In any case, wire it in:
4041   PhaseIterGVN* igvn = phase->is_IterGVN();
4042   if (igvn) {
4043     igvn->rehash_node_delayed(this);
4044   }
4045   set_req(i, new_st);
4046 
4047   // The caller may now kill the old guy.
4048   DEBUG_ONLY(Node* check_st = find_captured_store(start, size_in_bytes, phase));
4049   assert(check_st == new_st || check_st == nullptr, "must be findable");
4050   assert(!is_complete(), "");
4051   return new_st;
4052 }
4053 
4054 static bool store_constant(jlong* tiles, int num_tiles,
4055                            intptr_t st_off, int st_size,
4056                            jlong con) {
4057   if ((st_off & (st_size-1)) != 0)
4058     return false;               // strange store offset (assume size==2**N)
4059   address addr = (address)tiles + st_off;
4060   assert(st_off >= 0 && addr+st_size <= (address)&tiles[num_tiles], "oob");
4061   switch (st_size) {
4062   case sizeof(jbyte):  *(jbyte*) addr = (jbyte) con; break;
4063   case sizeof(jchar):  *(jchar*) addr = (jchar) con; break;
4064   case sizeof(jint):   *(jint*)  addr = (jint)  con; break;
4065   case sizeof(jlong):  *(jlong*) addr = (jlong) con; break;
4066   default: return false;        // strange store size (detect size!=2**N here)
4067   }
4068   return true;                  // return success to caller
4069 }
4070 
4071 // Coalesce subword constants into int constants and possibly
4072 // into long constants.  The goal, if the CPU permits,
4073 // is to initialize the object with a small number of 64-bit tiles.
4074 // Also, convert floating-point constants to bit patterns.
4075 // Non-constants are not relevant to this pass.
4076 //
4077 // In terms of the running example on InitializeNode::InitializeNode
4078 // and InitializeNode::capture_store, here is the transformation
4079 // of rawstore1 and rawstore2 into rawstore12:
4080 //   alloc = (Allocate ...)
4081 //   rawoop = alloc.RawAddress
4082 //   tile12 = 0x00010002
4083 //   rawstore12 = (StoreI alloc.Control alloc.Memory (+ rawoop 12) tile12)
4084 //   init = (Initialize alloc.Control alloc.Memory rawoop rawstore12)
4085 //
4086 void
4087 InitializeNode::coalesce_subword_stores(intptr_t header_size,
4088                                         Node* size_in_bytes,
4089                                         PhaseGVN* phase) {
4090   Compile* C = phase->C;
4091 
4092   assert(stores_are_sane(phase), "");
4093   // Note:  After this pass, they are not completely sane,
4094   // since there may be some overlaps.
4095 
4096   int old_subword = 0, old_long = 0, new_int = 0, new_long = 0;
4097 
4098   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
4099   intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, ti_limit);
4100   size_limit = MIN2(size_limit, ti_limit);
4101   size_limit = align_up(size_limit, BytesPerLong);
4102   int num_tiles = size_limit / BytesPerLong;
4103 
4104   // allocate space for the tile map:
4105   const int small_len = DEBUG_ONLY(true ? 3 :) 30; // keep stack frames small
4106   jlong  tiles_buf[small_len];
4107   Node*  nodes_buf[small_len];
4108   jlong  inits_buf[small_len];
4109   jlong* tiles = ((num_tiles <= small_len) ? &tiles_buf[0]
4110                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
4111   Node** nodes = ((num_tiles <= small_len) ? &nodes_buf[0]
4112                   : NEW_RESOURCE_ARRAY(Node*, num_tiles));
4113   jlong* inits = ((num_tiles <= small_len) ? &inits_buf[0]
4114                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
4115   // tiles: exact bitwise model of all primitive constants
4116   // nodes: last constant-storing node subsumed into the tiles model
4117   // inits: which bytes (in each tile) are touched by any initializations
4118 
4119   //// Pass A: Fill in the tile model with any relevant stores.
4120 
4121   Copy::zero_to_bytes(tiles, sizeof(tiles[0]) * num_tiles);
4122   Copy::zero_to_bytes(nodes, sizeof(nodes[0]) * num_tiles);
4123   Copy::zero_to_bytes(inits, sizeof(inits[0]) * num_tiles);
4124   Node* zmem = zero_memory(); // initially zero memory state
4125   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
4126     Node* st = in(i);
4127     intptr_t st_off = get_store_offset(st, phase);
4128 
4129     // Figure out the store's offset and constant value:
4130     if (st_off < header_size)             continue; //skip (ignore header)
4131     if (st->in(MemNode::Memory) != zmem)  continue; //skip (odd store chain)
4132     int st_size = st->as_Store()->memory_size();
4133     if (st_off + st_size > size_limit)    break;
4134 
4135     // Record which bytes are touched, whether by constant or not.
4136     if (!store_constant(inits, num_tiles, st_off, st_size, (jlong) -1))
4137       continue;                 // skip (strange store size)
4138 
4139     const Type* val = phase->type(st->in(MemNode::ValueIn));
4140     if (!val->singleton())                continue; //skip (non-con store)
4141     BasicType type = val->basic_type();
4142 
4143     jlong con = 0;
4144     switch (type) {
4145     case T_INT:    con = val->is_int()->get_con();  break;
4146     case T_LONG:   con = val->is_long()->get_con(); break;
4147     case T_FLOAT:  con = jint_cast(val->getf());    break;
4148     case T_DOUBLE: con = jlong_cast(val->getd());   break;
4149     default:                              continue; //skip (odd store type)
4150     }
4151 
4152     if (type == T_LONG && Matcher::isSimpleConstant64(con) &&
4153         st->Opcode() == Op_StoreL) {
4154       continue;                 // This StoreL is already optimal.
4155     }
4156 
4157     // Store down the constant.
4158     store_constant(tiles, num_tiles, st_off, st_size, con);
4159 
4160     intptr_t j = st_off >> LogBytesPerLong;
4161 
4162     if (type == T_INT && st_size == BytesPerInt
4163         && (st_off & BytesPerInt) == BytesPerInt) {
4164       jlong lcon = tiles[j];
4165       if (!Matcher::isSimpleConstant64(lcon) &&
4166           st->Opcode() == Op_StoreI) {
4167         // This StoreI is already optimal by itself.
4168         jint* intcon = (jint*) &tiles[j];
4169         intcon[1] = 0;  // undo the store_constant()
4170 
4171         // If the previous store is also optimal by itself, back up and
4172         // undo the action of the previous loop iteration... if we can.
4173         // But if we can't, just let the previous half take care of itself.
4174         st = nodes[j];
4175         st_off -= BytesPerInt;
4176         con = intcon[0];
4177         if (con != 0 && st != nullptr && st->Opcode() == Op_StoreI) {
4178           assert(st_off >= header_size, "still ignoring header");
4179           assert(get_store_offset(st, phase) == st_off, "must be");
4180           assert(in(i-1) == zmem, "must be");
4181           DEBUG_ONLY(const Type* tcon = phase->type(st->in(MemNode::ValueIn)));
4182           assert(con == tcon->is_int()->get_con(), "must be");
4183           // Undo the effects of the previous loop trip, which swallowed st:
4184           intcon[0] = 0;        // undo store_constant()
4185           set_req(i-1, st);     // undo set_req(i, zmem)
4186           nodes[j] = nullptr;   // undo nodes[j] = st
4187           --old_subword;        // undo ++old_subword
4188         }
4189         continue;               // This StoreI is already optimal.
4190       }
4191     }
4192 
4193     // This store is not needed.
4194     set_req(i, zmem);
4195     nodes[j] = st;              // record for the moment
4196     if (st_size < BytesPerLong) // something has changed
4197           ++old_subword;        // includes int/float, but who's counting...
4198     else  ++old_long;
4199   }
4200 
4201   if ((old_subword + old_long) == 0)
4202     return;                     // nothing more to do
4203 
4204   //// Pass B: Convert any non-zero tiles into optimal constant stores.
4205   // Be sure to insert them before overlapping non-constant stores.
4206   // (E.g., byte[] x = { 1,2,y,4 }  =>  x[int 0] = 0x01020004, x[2]=y.)
4207   for (int j = 0; j < num_tiles; j++) {
4208     jlong con  = tiles[j];
4209     jlong init = inits[j];
4210     if (con == 0)  continue;
4211     jint con0,  con1;           // split the constant, address-wise
4212     jint init0, init1;          // split the init map, address-wise
4213     { union { jlong con; jint intcon[2]; } u;
4214       u.con = con;
4215       con0  = u.intcon[0];
4216       con1  = u.intcon[1];
4217       u.con = init;
4218       init0 = u.intcon[0];
4219       init1 = u.intcon[1];
4220     }
4221 
4222     Node* old = nodes[j];
4223     assert(old != nullptr, "need the prior store");
4224     intptr_t offset = (j * BytesPerLong);
4225 
4226     bool split = !Matcher::isSimpleConstant64(con);
4227 
4228     if (offset < header_size) {
4229       assert(offset + BytesPerInt >= header_size, "second int counts");
4230       assert(*(jint*)&tiles[j] == 0, "junk in header");
4231       split = true;             // only the second word counts
4232       // Example:  int a[] = { 42 ... }
4233     } else if (con0 == 0 && init0 == -1) {
4234       split = true;             // first word is covered by full inits
4235       // Example:  int a[] = { ... foo(), 42 ... }
4236     } else if (con1 == 0 && init1 == -1) {
4237       split = true;             // second word is covered by full inits
4238       // Example:  int a[] = { ... 42, foo() ... }
4239     }
4240 
4241     // Here's a case where init0 is neither 0 nor -1:
4242     //   byte a[] = { ... 0,0,foo(),0,  0,0,0,42 ... }
4243     // Assuming big-endian memory, init0, init1 are 0x0000FF00, 0x000000FF.
4244     // In this case the tile is not split; it is (jlong)42.
4245     // The big tile is stored down, and then the foo() value is inserted.
4246     // (If there were foo(),foo() instead of foo(),0, init0 would be -1.)
4247 
4248     Node* ctl = old->in(MemNode::Control);
4249     Node* adr = make_raw_address(offset, phase);
4250     const TypePtr* atp = TypeRawPtr::BOTTOM;
4251 
4252     // One or two coalesced stores to plop down.
4253     Node*    st[2];
4254     intptr_t off[2];
4255     int  nst = 0;
4256     if (!split) {
4257       ++new_long;
4258       off[nst] = offset;
4259       st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
4260                                   phase->longcon(con), T_LONG, MemNode::unordered);
4261     } else {
4262       // Omit either if it is a zero.
4263       if (con0 != 0) {
4264         ++new_int;
4265         off[nst]  = offset;
4266         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
4267                                     phase->intcon(con0), T_INT, MemNode::unordered);
4268       }
4269       if (con1 != 0) {
4270         ++new_int;
4271         offset += BytesPerInt;
4272         adr = make_raw_address(offset, phase);
4273         off[nst]  = offset;
4274         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
4275                                     phase->intcon(con1), T_INT, MemNode::unordered);
4276       }
4277     }
4278 
4279     // Insert second store first, then the first before the second.
4280     // Insert each one just before any overlapping non-constant stores.
4281     while (nst > 0) {
4282       Node* st1 = st[--nst];
4283       C->copy_node_notes_to(st1, old);
4284       st1 = phase->transform(st1);
4285       offset = off[nst];
4286       assert(offset >= header_size, "do not smash header");
4287       int ins_idx = captured_store_insertion_point(offset, /*size:*/0, phase);
4288       guarantee(ins_idx != 0, "must re-insert constant store");
4289       if (ins_idx < 0)  ins_idx = -ins_idx;  // never overlap
4290       if (ins_idx > InitializeNode::RawStores && in(ins_idx-1) == zmem)
4291         set_req(--ins_idx, st1);
4292       else
4293         ins_req(ins_idx, st1);
4294     }
4295   }
4296 
4297   if (PrintCompilation && WizardMode)
4298     tty->print_cr("Changed %d/%d subword/long constants into %d/%d int/long",
4299                   old_subword, old_long, new_int, new_long);
4300   if (C->log() != nullptr)
4301     C->log()->elem("comment that='%d/%d subword/long to %d/%d int/long'",
4302                    old_subword, old_long, new_int, new_long);
4303 
4304   // Clean up any remaining occurrences of zmem:
4305   remove_extra_zeroes();
4306 }
4307 
4308 // Explore forward from in(start) to find the first fully initialized
4309 // word, and return its offset.  Skip groups of subword stores which
4310 // together initialize full words.  If in(start) is itself part of a
4311 // fully initialized word, return the offset of in(start).  If there
4312 // are no following full-word stores, or if something is fishy, return
4313 // a negative value.
4314 intptr_t InitializeNode::find_next_fullword_store(uint start, PhaseGVN* phase) {
4315   int       int_map = 0;
4316   intptr_t  int_map_off = 0;
4317   const int FULL_MAP = right_n_bits(BytesPerInt);  // the int_map we hope for
4318 
4319   for (uint i = start, limit = req(); i < limit; i++) {
4320     Node* st = in(i);
4321 
4322     intptr_t st_off = get_store_offset(st, phase);
4323     if (st_off < 0)  break;  // return conservative answer
4324 
4325     int st_size = st->as_Store()->memory_size();
4326     if (st_size >= BytesPerInt && (st_off % BytesPerInt) == 0) {
4327       return st_off;            // we found a complete word init
4328     }
4329 
4330     // update the map:
4331 
4332     intptr_t this_int_off = align_down(st_off, BytesPerInt);
4333     if (this_int_off != int_map_off) {
4334       // reset the map:
4335       int_map = 0;
4336       int_map_off = this_int_off;
4337     }
4338 
4339     int subword_off = st_off - this_int_off;
4340     int_map |= right_n_bits(st_size) << subword_off;
4341     if ((int_map & FULL_MAP) == FULL_MAP) {
4342       return this_int_off;      // we found a complete word init
4343     }
4344 
4345     // Did this store hit or cross the word boundary?
4346     intptr_t next_int_off = align_down(st_off + st_size, BytesPerInt);
4347     if (next_int_off == this_int_off + BytesPerInt) {
4348       // We passed the current int, without fully initializing it.
4349       int_map_off = next_int_off;
4350       int_map >>= BytesPerInt;
4351     } else if (next_int_off > this_int_off + BytesPerInt) {
4352       // We passed the current and next int.
4353       return this_int_off + BytesPerInt;
4354     }
4355   }
4356 
4357   return -1;
4358 }
4359 
4360 
4361 // Called when the associated AllocateNode is expanded into CFG.
4362 // At this point, we may perform additional optimizations.
4363 // Linearize the stores by ascending offset, to make memory
4364 // activity as coherent as possible.
4365 Node* InitializeNode::complete_stores(Node* rawctl, Node* rawmem, Node* rawptr,
4366                                       intptr_t header_size,
4367                                       Node* size_in_bytes,
4368                                       PhaseIterGVN* phase) {
4369   assert(!is_complete(), "not already complete");
4370   assert(stores_are_sane(phase), "");
4371   assert(allocation() != nullptr, "must be present");
4372 
4373   remove_extra_zeroes();
4374 
4375   if (ReduceFieldZeroing || ReduceBulkZeroing)
4376     // reduce instruction count for common initialization patterns
4377     coalesce_subword_stores(header_size, size_in_bytes, phase);
4378 
4379   Node* zmem = zero_memory();   // initially zero memory state
4380   Node* inits = zmem;           // accumulating a linearized chain of inits
4381   #ifdef ASSERT
4382   intptr_t first_offset = allocation()->minimum_header_size();
4383   intptr_t last_init_off = first_offset;  // previous init offset
4384   intptr_t last_init_end = first_offset;  // previous init offset+size
4385   intptr_t last_tile_end = first_offset;  // previous tile offset+size
4386   #endif
4387   intptr_t zeroes_done = header_size;
4388 
4389   bool do_zeroing = true;       // we might give up if inits are very sparse
4390   int  big_init_gaps = 0;       // how many large gaps have we seen?
4391 
4392   if (UseTLAB && ZeroTLAB)  do_zeroing = false;
4393   if (!ReduceFieldZeroing && !ReduceBulkZeroing)  do_zeroing = false;
4394 
4395   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
4396     Node* st = in(i);
4397     intptr_t st_off = get_store_offset(st, phase);
4398     if (st_off < 0)
4399       break;                    // unknown junk in the inits
4400     if (st->in(MemNode::Memory) != zmem)
4401       break;                    // complicated store chains somehow in list
4402 
4403     int st_size = st->as_Store()->memory_size();
4404     intptr_t next_init_off = st_off + st_size;
4405 
4406     if (do_zeroing && zeroes_done < next_init_off) {
4407       // See if this store needs a zero before it or under it.
4408       intptr_t zeroes_needed = st_off;
4409 
4410       if (st_size < BytesPerInt) {
4411         // Look for subword stores which only partially initialize words.
4412         // If we find some, we must lay down some word-level zeroes first,
4413         // underneath the subword stores.
4414         //
4415         // Examples:
4416         //   byte[] a = { p,q,r,s }  =>  a[0]=p,a[1]=q,a[2]=r,a[3]=s
4417         //   byte[] a = { x,y,0,0 }  =>  a[0..3] = 0, a[0]=x,a[1]=y
4418         //   byte[] a = { 0,0,z,0 }  =>  a[0..3] = 0, a[2]=z
4419         //
4420         // Note:  coalesce_subword_stores may have already done this,
4421         // if it was prompted by constant non-zero subword initializers.
4422         // But this case can still arise with non-constant stores.
4423 
4424         intptr_t next_full_store = find_next_fullword_store(i, phase);
4425 
4426         // In the examples above:
4427         //   in(i)          p   q   r   s     x   y     z
4428         //   st_off        12  13  14  15    12  13    14
4429         //   st_size        1   1   1   1     1   1     1
4430         //   next_full_s.  12  16  16  16    16  16    16
4431         //   z's_done      12  16  16  16    12  16    12
4432         //   z's_needed    12  16  16  16    16  16    16
4433         //   zsize          0   0   0   0     4   0     4
4434         if (next_full_store < 0) {
4435           // Conservative tack:  Zero to end of current word.
4436           zeroes_needed = align_up(zeroes_needed, BytesPerInt);
4437         } else {
4438           // Zero to beginning of next fully initialized word.
4439           // Or, don't zero at all, if we are already in that word.
4440           assert(next_full_store >= zeroes_needed, "must go forward");
4441           assert((next_full_store & (BytesPerInt-1)) == 0, "even boundary");
4442           zeroes_needed = next_full_store;
4443         }
4444       }
4445 
4446       if (zeroes_needed > zeroes_done) {
4447         intptr_t zsize = zeroes_needed - zeroes_done;
4448         // Do some incremental zeroing on rawmem, in parallel with inits.
4449         zeroes_done = align_down(zeroes_done, BytesPerInt);
4450         rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
4451                                               zeroes_done, zeroes_needed,
4452                                               phase);
4453         zeroes_done = zeroes_needed;
4454         if (zsize > InitArrayShortSize && ++big_init_gaps > 2)
4455           do_zeroing = false;   // leave the hole, next time
4456       }
4457     }
4458 
4459     // Collect the store and move on:
4460     phase->replace_input_of(st, MemNode::Memory, inits);
4461     inits = st;                 // put it on the linearized chain
4462     set_req(i, zmem);           // unhook from previous position
4463 
4464     if (zeroes_done == st_off)
4465       zeroes_done = next_init_off;
4466 
4467     assert(!do_zeroing || zeroes_done >= next_init_off, "don't miss any");
4468 
4469     #ifdef ASSERT
4470     // Various order invariants.  Weaker than stores_are_sane because
4471     // a large constant tile can be filled in by smaller non-constant stores.
4472     assert(st_off >= last_init_off, "inits do not reverse");
4473     last_init_off = st_off;
4474     const Type* val = nullptr;
4475     if (st_size >= BytesPerInt &&
4476         (val = phase->type(st->in(MemNode::ValueIn)))->singleton() &&
4477         (int)val->basic_type() < (int)T_OBJECT) {
4478       assert(st_off >= last_tile_end, "tiles do not overlap");
4479       assert(st_off >= last_init_end, "tiles do not overwrite inits");
4480       last_tile_end = MAX2(last_tile_end, next_init_off);
4481     } else {
4482       intptr_t st_tile_end = align_up(next_init_off, BytesPerLong);
4483       assert(st_tile_end >= last_tile_end, "inits stay with tiles");
4484       assert(st_off      >= last_init_end, "inits do not overlap");
4485       last_init_end = next_init_off;  // it's a non-tile
4486     }
4487     #endif //ASSERT
4488   }
4489 
4490   remove_extra_zeroes();        // clear out all the zmems left over
4491   add_req(inits);
4492 
4493   if (!(UseTLAB && ZeroTLAB)) {
4494     // If anything remains to be zeroed, zero it all now.
4495     zeroes_done = align_down(zeroes_done, BytesPerInt);
4496     // if it is the last unused 4 bytes of an instance, forget about it
4497     intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, max_jint);
4498     if (zeroes_done + BytesPerLong >= size_limit) {
4499       AllocateNode* alloc = allocation();
4500       assert(alloc != nullptr, "must be present");
4501       if (alloc != nullptr && alloc->Opcode() == Op_Allocate) {
4502         Node* klass_node = alloc->in(AllocateNode::KlassNode);
4503         ciKlass* k = phase->type(klass_node)->is_klassptr()->klass();
4504         if (zeroes_done == k->layout_helper())
4505           zeroes_done = size_limit;
4506       }
4507     }
4508     if (zeroes_done < size_limit) {
4509       rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
4510                                             zeroes_done, size_in_bytes, phase);
4511     }
4512   }
4513 
4514   set_complete(phase);
4515   return rawmem;
4516 }
4517 
4518 
4519 #ifdef ASSERT
4520 bool InitializeNode::stores_are_sane(PhaseTransform* phase) {
4521   if (is_complete())
4522     return true;                // stores could be anything at this point
4523   assert(allocation() != nullptr, "must be present");
4524   intptr_t last_off = allocation()->minimum_header_size();
4525   for (uint i = InitializeNode::RawStores; i < req(); i++) {
4526     Node* st = in(i);
4527     intptr_t st_off = get_store_offset(st, phase);
4528     if (st_off < 0)  continue;  // ignore dead garbage
4529     if (last_off > st_off) {
4530       tty->print_cr("*** bad store offset at %d: " INTX_FORMAT " > " INTX_FORMAT, i, last_off, st_off);
4531       this->dump(2);
4532       assert(false, "ascending store offsets");
4533       return false;
4534     }
4535     last_off = st_off + st->as_Store()->memory_size();
4536   }
4537   return true;
4538 }
4539 #endif //ASSERT
4540 
4541 
4542 
4543 
4544 //============================MergeMemNode=====================================
4545 //
4546 // SEMANTICS OF MEMORY MERGES:  A MergeMem is a memory state assembled from several
4547 // contributing store or call operations.  Each contributor provides the memory
4548 // state for a particular "alias type" (see Compile::alias_type).  For example,
4549 // if a MergeMem has an input X for alias category #6, then any memory reference
4550 // to alias category #6 may use X as its memory state input, as an exact equivalent
4551 // to using the MergeMem as a whole.
4552 //   Load<6>( MergeMem(<6>: X, ...), p ) <==> Load<6>(X,p)
4553 //
4554 // (Here, the <N> notation gives the index of the relevant adr_type.)
4555 //
4556 // In one special case (and more cases in the future), alias categories overlap.
4557 // The special alias category "Bot" (Compile::AliasIdxBot) includes all memory
4558 // states.  Therefore, if a MergeMem has only one contributing input W for Bot,
4559 // it is exactly equivalent to that state W:
4560 //   MergeMem(<Bot>: W) <==> W
4561 //
4562 // Usually, the merge has more than one input.  In that case, where inputs
4563 // overlap (i.e., one is Bot), the narrower alias type determines the memory
4564 // state for that type, and the wider alias type (Bot) fills in everywhere else:
4565 //   Load<5>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<5>(W,p)
4566 //   Load<6>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<6>(X,p)
4567 //
4568 // A merge can take a "wide" memory state as one of its narrow inputs.
4569 // This simply means that the merge observes out only the relevant parts of
4570 // the wide input.  That is, wide memory states arriving at narrow merge inputs
4571 // are implicitly "filtered" or "sliced" as necessary.  (This is rare.)
4572 //
4573 // These rules imply that MergeMem nodes may cascade (via their <Bot> links),
4574 // and that memory slices "leak through":
4575 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y)) <==> MergeMem(<Bot>: W, <7>: Y)
4576 //
4577 // But, in such a cascade, repeated memory slices can "block the leak":
4578 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y), <7>: Y') <==> MergeMem(<Bot>: W, <7>: Y')
4579 //
4580 // In the last example, Y is not part of the combined memory state of the
4581 // outermost MergeMem.  The system must, of course, prevent unschedulable
4582 // memory states from arising, so you can be sure that the state Y is somehow
4583 // a precursor to state Y'.
4584 //
4585 //
4586 // REPRESENTATION OF MEMORY MERGES: The indexes used to address the Node::in array
4587 // of each MergeMemNode array are exactly the numerical alias indexes, including
4588 // but not limited to AliasIdxTop, AliasIdxBot, and AliasIdxRaw.  The functions
4589 // Compile::alias_type (and kin) produce and manage these indexes.
4590 //
4591 // By convention, the value of in(AliasIdxTop) (i.e., in(1)) is always the top node.
4592 // (Note that this provides quick access to the top node inside MergeMem methods,
4593 // without the need to reach out via TLS to Compile::current.)
4594 //
4595 // As a consequence of what was just described, a MergeMem that represents a full
4596 // memory state has an edge in(AliasIdxBot) which is a "wide" memory state,
4597 // containing all alias categories.
4598 //
4599 // MergeMem nodes never (?) have control inputs, so in(0) is null.
4600 //
4601 // All other edges in(N) (including in(AliasIdxRaw), which is in(3)) are either
4602 // a memory state for the alias type <N>, or else the top node, meaning that
4603 // there is no particular input for that alias type.  Note that the length of
4604 // a MergeMem is variable, and may be extended at any time to accommodate new
4605 // memory states at larger alias indexes.  When merges grow, they are of course
4606 // filled with "top" in the unused in() positions.
4607 //
4608 // This use of top is named "empty_memory()", or "empty_mem" (no-memory) as a variable.
4609 // (Top was chosen because it works smoothly with passes like GCM.)
4610 //
4611 // For convenience, we hardwire the alias index for TypeRawPtr::BOTTOM.  (It is
4612 // the type of random VM bits like TLS references.)  Since it is always the
4613 // first non-Bot memory slice, some low-level loops use it to initialize an
4614 // index variable:  for (i = AliasIdxRaw; i < req(); i++).
4615 //
4616 //
4617 // ACCESSORS:  There is a special accessor MergeMemNode::base_memory which returns
4618 // the distinguished "wide" state.  The accessor MergeMemNode::memory_at(N) returns
4619 // the memory state for alias type <N>, or (if there is no particular slice at <N>,
4620 // it returns the base memory.  To prevent bugs, memory_at does not accept <Top>
4621 // or <Bot> indexes.  The iterator MergeMemStream provides robust iteration over
4622 // MergeMem nodes or pairs of such nodes, ensuring that the non-top edges are visited.
4623 //
4624 // %%%% We may get rid of base_memory as a separate accessor at some point; it isn't
4625 // really that different from the other memory inputs.  An abbreviation called
4626 // "bot_memory()" for "memory_at(AliasIdxBot)" would keep code tidy.
4627 //
4628 //
4629 // PARTIAL MEMORY STATES:  During optimization, MergeMem nodes may arise that represent
4630 // partial memory states.  When a Phi splits through a MergeMem, the copy of the Phi
4631 // that "emerges though" the base memory will be marked as excluding the alias types
4632 // of the other (narrow-memory) copies which "emerged through" the narrow edges:
4633 //
4634 //   Phi<Bot>(U, MergeMem(<Bot>: W, <8>: Y))
4635 //     ==Ideal=>  MergeMem(<Bot>: Phi<Bot-8>(U, W), Phi<8>(U, Y))
4636 //
4637 // This strange "subtraction" effect is necessary to ensure IGVN convergence.
4638 // (It is currently unimplemented.)  As you can see, the resulting merge is
4639 // actually a disjoint union of memory states, rather than an overlay.
4640 //
4641 
4642 //------------------------------MergeMemNode-----------------------------------
4643 Node* MergeMemNode::make_empty_memory() {
4644   Node* empty_memory = (Node*) Compile::current()->top();
4645   assert(empty_memory->is_top(), "correct sentinel identity");
4646   return empty_memory;
4647 }
4648 
4649 MergeMemNode::MergeMemNode(Node *new_base) : Node(1+Compile::AliasIdxRaw) {
4650   init_class_id(Class_MergeMem);
4651   // all inputs are nullified in Node::Node(int)
4652   // set_input(0, nullptr);  // no control input
4653 
4654   // Initialize the edges uniformly to top, for starters.
4655   Node* empty_mem = make_empty_memory();
4656   for (uint i = Compile::AliasIdxTop; i < req(); i++) {
4657     init_req(i,empty_mem);
4658   }
4659   assert(empty_memory() == empty_mem, "");
4660 
4661   if( new_base != nullptr && new_base->is_MergeMem() ) {
4662     MergeMemNode* mdef = new_base->as_MergeMem();
4663     assert(mdef->empty_memory() == empty_mem, "consistent sentinels");
4664     for (MergeMemStream mms(this, mdef); mms.next_non_empty2(); ) {
4665       mms.set_memory(mms.memory2());
4666     }
4667     assert(base_memory() == mdef->base_memory(), "");
4668   } else {
4669     set_base_memory(new_base);
4670   }
4671 }
4672 
4673 // Make a new, untransformed MergeMem with the same base as 'mem'.
4674 // If mem is itself a MergeMem, populate the result with the same edges.
4675 MergeMemNode* MergeMemNode::make(Node* mem) {
4676   return new MergeMemNode(mem);
4677 }
4678 
4679 //------------------------------cmp--------------------------------------------
4680 uint MergeMemNode::hash() const { return NO_HASH; }
4681 bool MergeMemNode::cmp( const Node &n ) const {
4682   return (&n == this);          // Always fail except on self
4683 }
4684 
4685 //------------------------------Identity---------------------------------------
4686 Node* MergeMemNode::Identity(PhaseGVN* phase) {
4687   // Identity if this merge point does not record any interesting memory
4688   // disambiguations.
4689   Node* base_mem = base_memory();
4690   Node* empty_mem = empty_memory();
4691   if (base_mem != empty_mem) {  // Memory path is not dead?
4692     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4693       Node* mem = in(i);
4694       if (mem != empty_mem && mem != base_mem) {
4695         return this;            // Many memory splits; no change
4696       }
4697     }
4698   }
4699   return base_mem;              // No memory splits; ID on the one true input
4700 }
4701 
4702 //------------------------------Ideal------------------------------------------
4703 // This method is invoked recursively on chains of MergeMem nodes
4704 Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) {
4705   // Remove chain'd MergeMems
4706   //
4707   // This is delicate, because the each "in(i)" (i >= Raw) is interpreted
4708   // relative to the "in(Bot)".  Since we are patching both at the same time,
4709   // we have to be careful to read each "in(i)" relative to the old "in(Bot)",
4710   // but rewrite each "in(i)" relative to the new "in(Bot)".
4711   Node *progress = nullptr;
4712 
4713 
4714   Node* old_base = base_memory();
4715   Node* empty_mem = empty_memory();
4716   if (old_base == empty_mem)
4717     return nullptr; // Dead memory path.
4718 
4719   MergeMemNode* old_mbase;
4720   if (old_base != nullptr && old_base->is_MergeMem())
4721     old_mbase = old_base->as_MergeMem();
4722   else
4723     old_mbase = nullptr;
4724   Node* new_base = old_base;
4725 
4726   // simplify stacked MergeMems in base memory
4727   if (old_mbase)  new_base = old_mbase->base_memory();
4728 
4729   // the base memory might contribute new slices beyond my req()
4730   if (old_mbase)  grow_to_match(old_mbase);
4731 
4732   // Look carefully at the base node if it is a phi.
4733   PhiNode* phi_base;
4734   if (new_base != NULL && new_base->is_Phi())
4735     phi_base = new_base->as_Phi();
4736   else
4737     phi_base = NULL;
4738 
4739   Node*    phi_reg = NULL;
4740   uint     phi_len = (uint)-1;
4741   if (phi_base != NULL) {
4742     phi_reg = phi_base->region();
4743     phi_len = phi_base->req();
4744     // see if the phi is unfinished
4745     for (uint i = 1; i < phi_len; i++) {
4746       if (phi_base->in(i) == NULL) {
4747         // incomplete phi; do not look at it yet!
4748         phi_reg = NULL;
4749         phi_len = (uint)-1;
4750         break;
4751       }
4752     }
4753   }
4754 
4755   // Note:  We do not call verify_sparse on entry, because inputs
4756   // can normalize to the base_memory via subsume_node or similar
4757   // mechanisms.  This method repairs that damage.
4758 
4759   assert(!old_mbase || old_mbase->is_empty_memory(empty_mem), "consistent sentinels");
4760 
4761   // Look at each slice.
4762   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4763     Node* old_in = in(i);
4764     // calculate the old memory value
4765     Node* old_mem = old_in;
4766     if (old_mem == empty_mem)  old_mem = old_base;
4767     assert(old_mem == memory_at(i), "");
4768 
4769     // maybe update (reslice) the old memory value
4770 
4771     // simplify stacked MergeMems
4772     Node* new_mem = old_mem;
4773     MergeMemNode* old_mmem;
4774     if (old_mem != nullptr && old_mem->is_MergeMem())
4775       old_mmem = old_mem->as_MergeMem();
4776     else
4777       old_mmem = nullptr;
4778     if (old_mmem == this) {
4779       // This can happen if loops break up and safepoints disappear.
4780       // A merge of BotPtr (default) with a RawPtr memory derived from a
4781       // safepoint can be rewritten to a merge of the same BotPtr with
4782       // the BotPtr phi coming into the loop.  If that phi disappears
4783       // also, we can end up with a self-loop of the mergemem.
4784       // In general, if loops degenerate and memory effects disappear,
4785       // a mergemem can be left looking at itself.  This simply means
4786       // that the mergemem's default should be used, since there is
4787       // no longer any apparent effect on this slice.
4788       // Note: If a memory slice is a MergeMem cycle, it is unreachable
4789       //       from start.  Update the input to TOP.
4790       new_mem = (new_base == this || new_base == empty_mem)? empty_mem : new_base;
4791     }
4792     else if (old_mmem != nullptr) {
4793       new_mem = old_mmem->memory_at(i);
4794     }
4795     // else preceding memory was not a MergeMem
4796 
4797     // maybe store down a new value
4798     Node* new_in = new_mem;
4799     if (new_in == new_base)  new_in = empty_mem;
4800 
4801     if (new_in != old_in) {
4802       // Warning:  Do not combine this "if" with the previous "if"
4803       // A memory slice might have be be rewritten even if it is semantically
4804       // unchanged, if the base_memory value has changed.
4805       set_req_X(i, new_in, phase);
4806       progress = this;          // Report progress
4807     }
4808   }
4809 
4810   if (new_base != old_base) {
4811     set_req_X(Compile::AliasIdxBot, new_base, phase);
4812     // Don't use set_base_memory(new_base), because we need to update du.
4813     assert(base_memory() == new_base, "");
4814     progress = this;
4815   }
4816 
4817   if( base_memory() == this ) {
4818     // a self cycle indicates this memory path is dead
4819     set_req(Compile::AliasIdxBot, empty_mem);
4820   }
4821 
4822   // Resolve external cycles by calling Ideal on a MergeMem base_memory
4823   // Recursion must occur after the self cycle check above
4824   if( base_memory()->is_MergeMem() ) {
4825     MergeMemNode *new_mbase = base_memory()->as_MergeMem();
4826     Node *m = phase->transform(new_mbase);  // Rollup any cycles
4827     if( m != nullptr &&
4828         (m->is_top() ||
4829          (m->is_MergeMem() && m->as_MergeMem()->base_memory() == empty_mem)) ) {
4830       // propagate rollup of dead cycle to self
4831       set_req(Compile::AliasIdxBot, empty_mem);
4832     }
4833   }
4834 
4835   if( base_memory() == empty_mem ) {
4836     progress = this;
4837     // Cut inputs during Parse phase only.
4838     // During Optimize phase a dead MergeMem node will be subsumed by Top.
4839     if( !can_reshape ) {
4840       for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4841         if( in(i) != empty_mem ) { set_req(i, empty_mem); }
4842       }
4843     }
4844   }
4845 
4846   if( !progress && base_memory()->is_Phi() && can_reshape ) {
4847     // Check if PhiNode::Ideal's "Split phis through memory merges"
4848     // transform should be attempted. Look for this->phi->this cycle.
4849     uint merge_width = req();
4850     if (merge_width > Compile::AliasIdxRaw) {
4851       PhiNode* phi = base_memory()->as_Phi();
4852       for( uint i = 1; i < phi->req(); ++i ) {// For all paths in
4853         if (phi->in(i) == this) {
4854           phase->is_IterGVN()->_worklist.push(phi);
4855           break;
4856         }
4857       }
4858     }
4859   }
4860 
4861   assert(progress || verify_sparse(), "please, no dups of base");
4862   return progress;
4863 }
4864 
4865 //-------------------------set_base_memory-------------------------------------
4866 void MergeMemNode::set_base_memory(Node *new_base) {
4867   Node* empty_mem = empty_memory();
4868   set_req(Compile::AliasIdxBot, new_base);
4869   assert(memory_at(req()) == new_base, "must set default memory");
4870   // Clear out other occurrences of new_base:
4871   if (new_base != empty_mem) {
4872     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4873       if (in(i) == new_base)  set_req(i, empty_mem);
4874     }
4875   }
4876 }
4877 
4878 //------------------------------out_RegMask------------------------------------
4879 const RegMask &MergeMemNode::out_RegMask() const {
4880   return RegMask::Empty;
4881 }
4882 
4883 //------------------------------dump_spec--------------------------------------
4884 #ifndef PRODUCT
4885 void MergeMemNode::dump_spec(outputStream *st) const {
4886   st->print(" {");
4887   Node* base_mem = base_memory();
4888   for( uint i = Compile::AliasIdxRaw; i < req(); i++ ) {
4889     Node* mem = (in(i) != nullptr) ? memory_at(i) : base_mem;
4890     if (mem == base_mem) { st->print(" -"); continue; }
4891     st->print( " N%d:", mem->_idx );
4892     Compile::current()->get_adr_type(i)->dump_on(st);
4893   }
4894   st->print(" }");
4895 }
4896 #endif // !PRODUCT
4897 
4898 
4899 #ifdef ASSERT
4900 static bool might_be_same(Node* a, Node* b) {
4901   if (a == b)  return true;
4902   if (!(a->is_Phi() || b->is_Phi()))  return false;
4903   // phis shift around during optimization
4904   return true;  // pretty stupid...
4905 }
4906 
4907 // verify a narrow slice (either incoming or outgoing)
4908 static void verify_memory_slice(const MergeMemNode* m, int alias_idx, Node* n) {
4909   if (!VerifyAliases)                return;  // don't bother to verify unless requested
4910   if (VMError::is_error_reported())  return;  // muzzle asserts when debugging an error
4911   if (Node::in_dump())               return;  // muzzle asserts when printing
4912   assert(alias_idx >= Compile::AliasIdxRaw, "must not disturb base_memory or sentinel");
4913   assert(n != nullptr, "");
4914   // Elide intervening MergeMem's
4915   while (n->is_MergeMem()) {
4916     n = n->as_MergeMem()->memory_at(alias_idx);
4917   }
4918   Compile* C = Compile::current();
4919   const TypePtr* n_adr_type = n->adr_type();
4920   if (n == m->empty_memory()) {
4921     // Implicit copy of base_memory()
4922   } else if (n_adr_type != TypePtr::BOTTOM) {
4923     assert(n_adr_type != nullptr, "new memory must have a well-defined adr_type");
4924     assert(C->must_alias(n_adr_type, alias_idx), "new memory must match selected slice");
4925   } else {
4926     // A few places like make_runtime_call "know" that VM calls are narrow,
4927     // and can be used to update only the VM bits stored as TypeRawPtr::BOTTOM.
4928     bool expected_wide_mem = false;
4929     if (n == m->base_memory()) {
4930       expected_wide_mem = true;
4931     } else if (alias_idx == Compile::AliasIdxRaw ||
4932                n == m->memory_at(Compile::AliasIdxRaw)) {
4933       expected_wide_mem = true;
4934     } else if (!C->alias_type(alias_idx)->is_rewritable()) {
4935       // memory can "leak through" calls on channels that
4936       // are write-once.  Allow this also.
4937       expected_wide_mem = true;
4938     }
4939     assert(expected_wide_mem, "expected narrow slice replacement");
4940   }
4941 }
4942 #else // !ASSERT
4943 #define verify_memory_slice(m,i,n) (void)(0)  // PRODUCT version is no-op
4944 #endif
4945 
4946 
4947 //-----------------------------memory_at---------------------------------------
4948 Node* MergeMemNode::memory_at(uint alias_idx) const {
4949   assert(alias_idx >= Compile::AliasIdxRaw ||
4950          alias_idx == Compile::AliasIdxBot && Compile::current()->AliasLevel() == 0,
4951          "must avoid base_memory and AliasIdxTop");
4952 
4953   // Otherwise, it is a narrow slice.
4954   Node* n = alias_idx < req() ? in(alias_idx) : empty_memory();
4955   Compile *C = Compile::current();
4956   if (is_empty_memory(n)) {
4957     // the array is sparse; empty slots are the "top" node
4958     n = base_memory();
4959     assert(Node::in_dump()
4960            || n == nullptr || n->bottom_type() == Type::TOP
4961            || n->adr_type() == nullptr // address is TOP
4962            || n->adr_type() == TypePtr::BOTTOM
4963            || n->adr_type() == TypeRawPtr::BOTTOM
4964            || Compile::current()->AliasLevel() == 0,
4965            "must be a wide memory");
4966     // AliasLevel == 0 if we are organizing the memory states manually.
4967     // See verify_memory_slice for comments on TypeRawPtr::BOTTOM.
4968   } else {
4969     // make sure the stored slice is sane
4970     #ifdef ASSERT
4971     if (VMError::is_error_reported() || Node::in_dump()) {
4972     } else if (might_be_same(n, base_memory())) {
4973       // Give it a pass:  It is a mostly harmless repetition of the base.
4974       // This can arise normally from node subsumption during optimization.
4975     } else {
4976       verify_memory_slice(this, alias_idx, n);
4977     }
4978     #endif
4979   }
4980   return n;
4981 }
4982 
4983 //---------------------------set_memory_at-------------------------------------
4984 void MergeMemNode::set_memory_at(uint alias_idx, Node *n) {
4985   verify_memory_slice(this, alias_idx, n);
4986   Node* empty_mem = empty_memory();
4987   if (n == base_memory())  n = empty_mem;  // collapse default
4988   uint need_req = alias_idx+1;
4989   if (req() < need_req) {
4990     if (n == empty_mem)  return;  // already the default, so do not grow me
4991     // grow the sparse array
4992     do {
4993       add_req(empty_mem);
4994     } while (req() < need_req);
4995   }
4996   set_req( alias_idx, n );
4997 }
4998 
4999 
5000 
5001 //--------------------------iteration_setup------------------------------------
5002 void MergeMemNode::iteration_setup(const MergeMemNode* other) {
5003   if (other != nullptr) {
5004     grow_to_match(other);
5005     // invariant:  the finite support of mm2 is within mm->req()
5006     #ifdef ASSERT
5007     for (uint i = req(); i < other->req(); i++) {
5008       assert(other->is_empty_memory(other->in(i)), "slice left uncovered");
5009     }
5010     #endif
5011   }
5012   // Replace spurious copies of base_memory by top.
5013   Node* base_mem = base_memory();
5014   if (base_mem != nullptr && !base_mem->is_top()) {
5015     for (uint i = Compile::AliasIdxBot+1, imax = req(); i < imax; i++) {
5016       if (in(i) == base_mem)
5017         set_req(i, empty_memory());
5018     }
5019   }
5020 }
5021 
5022 //---------------------------grow_to_match-------------------------------------
5023 void MergeMemNode::grow_to_match(const MergeMemNode* other) {
5024   Node* empty_mem = empty_memory();
5025   assert(other->is_empty_memory(empty_mem), "consistent sentinels");
5026   // look for the finite support of the other memory
5027   for (uint i = other->req(); --i >= req(); ) {
5028     if (other->in(i) != empty_mem) {
5029       uint new_len = i+1;
5030       while (req() < new_len)  add_req(empty_mem);
5031       break;
5032     }
5033   }
5034 }
5035 
5036 //---------------------------verify_sparse-------------------------------------
5037 #ifndef PRODUCT
5038 bool MergeMemNode::verify_sparse() const {
5039   assert(is_empty_memory(make_empty_memory()), "sane sentinel");
5040   Node* base_mem = base_memory();
5041   // The following can happen in degenerate cases, since empty==top.
5042   if (is_empty_memory(base_mem))  return true;
5043   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
5044     assert(in(i) != nullptr, "sane slice");
5045     if (in(i) == base_mem)  return false;  // should have been the sentinel value!
5046   }
5047   return true;
5048 }
5049 
5050 bool MergeMemStream::match_memory(Node* mem, const MergeMemNode* mm, int idx) {
5051   Node* n;
5052   n = mm->in(idx);
5053   if (mem == n)  return true;  // might be empty_memory()
5054   n = (idx == Compile::AliasIdxBot)? mm->base_memory(): mm->memory_at(idx);
5055   if (mem == n)  return true;
5056   return false;
5057 }
5058 #endif // !PRODUCT