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