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