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