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