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