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