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