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