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