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