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