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