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