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