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