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