src/share/vm/opto/memnode.cpp

Mon, 19 Aug 2019 17:36:36 +0200

author
neliasso
date
Mon, 19 Aug 2019 17:36:36 +0200
changeset 9735
bd6ec847115e
parent 9686
025ce746a942
child 9756
2be326848943
child 9815
127e100fb80e
permissions
-rw-r--r--

8219517: assert(false) failed: infinite loop in PhaseIterGVN::optimize
Reviewed-by: kvn, thartmann

     1 /*
     2  * Copyright (c) 1997, 2017, 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  */
    25 #include "precompiled.hpp"
    26 #include "classfile/systemDictionary.hpp"
    27 #include "compiler/compileLog.hpp"
    28 #include "memory/allocation.inline.hpp"
    29 #include "oops/objArrayKlass.hpp"
    30 #include "opto/addnode.hpp"
    31 #include "opto/cfgnode.hpp"
    32 #include "opto/compile.hpp"
    33 #include "opto/connode.hpp"
    34 #include "opto/loopnode.hpp"
    35 #include "opto/machnode.hpp"
    36 #include "opto/matcher.hpp"
    37 #include "opto/memnode.hpp"
    38 #include "opto/mulnode.hpp"
    39 #include "opto/phaseX.hpp"
    40 #include "opto/regmask.hpp"
    42 // Portions of code courtesy of Clifford Click
    44 // Optimization - Graph Style
    46 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem,  const TypePtr *tp, const TypePtr *adr_check, outputStream *st);
    48 //=============================================================================
    49 uint MemNode::size_of() const { return sizeof(*this); }
    51 const TypePtr *MemNode::adr_type() const {
    52   Node* adr = in(Address);
    53   const TypePtr* cross_check = NULL;
    54   DEBUG_ONLY(cross_check = _adr_type);
    55   return calculate_adr_type(adr->bottom_type(), cross_check);
    56 }
    58 bool MemNode::check_if_adr_maybe_raw(Node* adr) {
    59   if (adr != NULL) {
    60     if (adr->bottom_type()->base() == Type::RawPtr || adr->bottom_type()->base() == Type::AnyPtr) {
    61       return true;
    62     }
    63   }
    64   return false;
    65 }
    67 #ifndef PRODUCT
    68 void MemNode::dump_spec(outputStream *st) const {
    69   if (in(Address) == NULL)  return; // node is dead
    70 #ifndef ASSERT
    71   // fake the missing field
    72   const TypePtr* _adr_type = NULL;
    73   if (in(Address) != NULL)
    74     _adr_type = in(Address)->bottom_type()->isa_ptr();
    75 #endif
    76   dump_adr_type(this, _adr_type, st);
    78   Compile* C = Compile::current();
    79   if (C->alias_type(_adr_type)->is_volatile()) {
    80     st->print(" Volatile!");
    81   }
    82   if (_unaligned_access) {
    83     st->print(" unaligned");
    84   }
    85   if (_mismatched_access) {
    86     st->print(" mismatched");
    87   }
    88 }
    90 void MemNode::dump_adr_type(const Node* mem, const TypePtr* adr_type, outputStream *st) {
    91   st->print(" @");
    92   if (adr_type == NULL) {
    93     st->print("NULL");
    94   } else {
    95     adr_type->dump_on(st);
    96     Compile* C = Compile::current();
    97     Compile::AliasType* atp = NULL;
    98     if (C->have_alias_type(adr_type))  atp = C->alias_type(adr_type);
    99     if (atp == NULL)
   100       st->print(", idx=?\?;");
   101     else if (atp->index() == Compile::AliasIdxBot)
   102       st->print(", idx=Bot;");
   103     else if (atp->index() == Compile::AliasIdxTop)
   104       st->print(", idx=Top;");
   105     else if (atp->index() == Compile::AliasIdxRaw)
   106       st->print(", idx=Raw;");
   107     else {
   108       ciField* field = atp->field();
   109       if (field) {
   110         st->print(", name=");
   111         field->print_name_on(st);
   112       }
   113       st->print(", idx=%d;", atp->index());
   114     }
   115   }
   116 }
   118 extern void print_alias_types();
   120 #endif
   122 Node *MemNode::optimize_simple_memory_chain(Node *mchain, const TypeOopPtr *t_oop, Node *load, PhaseGVN *phase) {
   123   assert((t_oop != NULL), "sanity");
   124   bool is_instance = t_oop->is_known_instance_field();
   125   bool is_boxed_value_load = t_oop->is_ptr_to_boxed_value() &&
   126                              (load != NULL) && load->is_Load() &&
   127                              (phase->is_IterGVN() != NULL);
   128   if (!(is_instance || is_boxed_value_load))
   129     return mchain;  // don't try to optimize non-instance types
   130   uint instance_id = t_oop->instance_id();
   131   Node *start_mem = phase->C->start()->proj_out(TypeFunc::Memory);
   132   Node *prev = NULL;
   133   Node *result = mchain;
   134   while (prev != result) {
   135     prev = result;
   136     if (result == start_mem)
   137       break;  // hit one of our sentinels
   138     // skip over a call which does not affect this memory slice
   139     if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
   140       Node *proj_in = result->in(0);
   141       if (proj_in->is_Allocate() && proj_in->_idx == instance_id) {
   142         break;  // hit one of our sentinels
   143       } else if (proj_in->is_Call()) {
   144         CallNode *call = proj_in->as_Call();
   145         if (!call->may_modify(t_oop, phase)) { // returns false for instances
   146           result = call->in(TypeFunc::Memory);
   147         }
   148       } else if (proj_in->is_Initialize()) {
   149         AllocateNode* alloc = proj_in->as_Initialize()->allocation();
   150         // Stop if this is the initialization for the object instance which
   151         // which contains this memory slice, otherwise skip over it.
   152         if ((alloc == NULL) || (alloc->_idx == instance_id)) {
   153           break;
   154         }
   155         if (is_instance) {
   156           result = proj_in->in(TypeFunc::Memory);
   157         } else if (is_boxed_value_load) {
   158           Node* klass = alloc->in(AllocateNode::KlassNode);
   159           const TypeKlassPtr* tklass = phase->type(klass)->is_klassptr();
   160           if (tklass->klass_is_exact() && !tklass->klass()->equals(t_oop->klass())) {
   161             result = proj_in->in(TypeFunc::Memory); // not related allocation
   162           }
   163         }
   164       } else if (proj_in->is_MemBar()) {
   165         result = proj_in->in(TypeFunc::Memory);
   166       } else {
   167         assert(false, "unexpected projection");
   168       }
   169     } else if (result->is_ClearArray()) {
   170       if (!is_instance || !ClearArrayNode::step_through(&result, instance_id, phase)) {
   171         // Can not bypass initialization of the instance
   172         // we are looking for.
   173         break;
   174       }
   175       // Otherwise skip it (the call updated 'result' value).
   176     } else if (result->is_MergeMem()) {
   177       result = step_through_mergemem(phase, result->as_MergeMem(), t_oop, NULL, tty);
   178     }
   179   }
   180   return result;
   181 }
   183 Node *MemNode::optimize_memory_chain(Node *mchain, const TypePtr *t_adr, Node *load, PhaseGVN *phase) {
   184   const TypeOopPtr* t_oop = t_adr->isa_oopptr();
   185   if (t_oop == NULL)
   186     return mchain;  // don't try to optimize non-oop types
   187   Node* result = optimize_simple_memory_chain(mchain, t_oop, load, phase);
   188   bool is_instance = t_oop->is_known_instance_field();
   189   PhaseIterGVN *igvn = phase->is_IterGVN();
   190   if (is_instance && igvn != NULL  && result->is_Phi()) {
   191     PhiNode *mphi = result->as_Phi();
   192     assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
   193     const TypePtr *t = mphi->adr_type();
   194     if (t == TypePtr::BOTTOM || t == TypeRawPtr::BOTTOM ||
   195         t->isa_oopptr() && !t->is_oopptr()->is_known_instance() &&
   196         t->is_oopptr()->cast_to_exactness(true)
   197          ->is_oopptr()->cast_to_ptr_type(t_oop->ptr())
   198          ->is_oopptr()->cast_to_instance_id(t_oop->instance_id()) == t_oop) {
   199       // clone the Phi with our address type
   200       result = mphi->split_out_instance(t_adr, igvn);
   201     } else {
   202       assert(phase->C->get_alias_index(t) == phase->C->get_alias_index(t_adr), "correct memory chain");
   203     }
   204   }
   205   return result;
   206 }
   208 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem,  const TypePtr *tp, const TypePtr *adr_check, outputStream *st) {
   209   uint alias_idx = phase->C->get_alias_index(tp);
   210   Node *mem = mmem;
   211 #ifdef ASSERT
   212   {
   213     // Check that current type is consistent with the alias index used during graph construction
   214     assert(alias_idx >= Compile::AliasIdxRaw, "must not be a bad alias_idx");
   215     bool consistent =  adr_check == NULL || adr_check->empty() ||
   216                        phase->C->must_alias(adr_check, alias_idx );
   217     // Sometimes dead array references collapse to a[-1], a[-2], or a[-3]
   218     if( !consistent && adr_check != NULL && !adr_check->empty() &&
   219                tp->isa_aryptr() &&        tp->offset() == Type::OffsetBot &&
   220         adr_check->isa_aryptr() && adr_check->offset() != Type::OffsetBot &&
   221         ( adr_check->offset() == arrayOopDesc::length_offset_in_bytes() ||
   222           adr_check->offset() == oopDesc::klass_offset_in_bytes() ||
   223           adr_check->offset() == oopDesc::mark_offset_in_bytes() ) ) {
   224       // don't assert if it is dead code.
   225       consistent = true;
   226     }
   227     if( !consistent ) {
   228       st->print("alias_idx==%d, adr_check==", alias_idx);
   229       if( adr_check == NULL ) {
   230         st->print("NULL");
   231       } else {
   232         adr_check->dump();
   233       }
   234       st->cr();
   235       print_alias_types();
   236       assert(consistent, "adr_check must match alias idx");
   237     }
   238   }
   239 #endif
   240   // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally
   241   // means an array I have not precisely typed yet.  Do not do any
   242   // alias stuff with it any time soon.
   243   const TypeOopPtr *toop = tp->isa_oopptr();
   244   if( tp->base() != Type::AnyPtr &&
   245       !(toop &&
   246         toop->klass() != NULL &&
   247         toop->klass()->is_java_lang_Object() &&
   248         toop->offset() == Type::OffsetBot) ) {
   249     // compress paths and change unreachable cycles to TOP
   250     // If not, we can update the input infinitely along a MergeMem cycle
   251     // Equivalent code in PhiNode::Ideal
   252     Node* m  = phase->transform(mmem);
   253     // If transformed to a MergeMem, get the desired slice
   254     // Otherwise the returned node represents memory for every slice
   255     mem = (m->is_MergeMem())? m->as_MergeMem()->memory_at(alias_idx) : m;
   256     // Update input if it is progress over what we have now
   257   }
   258   return mem;
   259 }
   261 //--------------------------Ideal_common---------------------------------------
   262 // Look for degenerate control and memory inputs.  Bypass MergeMem inputs.
   263 // Unhook non-raw memories from complete (macro-expanded) initializations.
   264 Node *MemNode::Ideal_common(PhaseGVN *phase, bool can_reshape) {
   265   // If our control input is a dead region, kill all below the region
   266   Node *ctl = in(MemNode::Control);
   267   if (ctl && remove_dead_region(phase, can_reshape))
   268     return this;
   269   ctl = in(MemNode::Control);
   270   // Don't bother trying to transform a dead node
   271   if (ctl && ctl->is_top())  return NodeSentinel;
   273   PhaseIterGVN *igvn = phase->is_IterGVN();
   274   // Wait if control on the worklist.
   275   if (ctl && can_reshape && igvn != NULL) {
   276     Node* bol = NULL;
   277     Node* cmp = NULL;
   278     if (ctl->in(0)->is_If()) {
   279       assert(ctl->is_IfTrue() || ctl->is_IfFalse(), "sanity");
   280       bol = ctl->in(0)->in(1);
   281       if (bol->is_Bool())
   282         cmp = ctl->in(0)->in(1)->in(1);
   283     }
   284     if (igvn->_worklist.member(ctl) ||
   285         (bol != NULL && igvn->_worklist.member(bol)) ||
   286         (cmp != NULL && igvn->_worklist.member(cmp)) ) {
   287       // This control path may be dead.
   288       // Delay this memory node transformation until the control is processed.
   289       phase->is_IterGVN()->_worklist.push(this);
   290       return NodeSentinel; // caller will return NULL
   291     }
   292   }
   293   // Ignore if memory is dead, or self-loop
   294   Node *mem = in(MemNode::Memory);
   295   if (phase->type( mem ) == Type::TOP) return NodeSentinel; // caller will return NULL
   296   assert(mem != this, "dead loop in MemNode::Ideal");
   298   if (can_reshape && igvn != NULL && igvn->_worklist.member(mem)) {
   299     // This memory slice may be dead.
   300     // Delay this mem node transformation until the memory is processed.
   301     phase->is_IterGVN()->_worklist.push(this);
   302     return NodeSentinel; // caller will return NULL
   303   }
   305   Node *address = in(MemNode::Address);
   306   const Type *t_adr = phase->type(address);
   307   if (t_adr == Type::TOP)              return NodeSentinel; // caller will return NULL
   309   if (can_reshape && igvn != NULL &&
   310       (igvn->_worklist.member(address) ||
   311        igvn->_worklist.size() > 0 && (t_adr != adr_type())) ) {
   312     // The address's base and type may change when the address is processed.
   313     // Delay this mem node transformation until the address is processed.
   314     phase->is_IterGVN()->_worklist.push(this);
   315     return NodeSentinel; // caller will return NULL
   316   }
   318   // Do NOT remove or optimize the next lines: ensure a new alias index
   319   // is allocated for an oop pointer type before Escape Analysis.
   320   // Note: C++ will not remove it since the call has side effect.
   321   if (t_adr->isa_oopptr()) {
   322     int alias_idx = phase->C->get_alias_index(t_adr->is_ptr());
   323   }
   325   Node* base = NULL;
   326   if (address->is_AddP()) {
   327     base = address->in(AddPNode::Base);
   328   }
   329   if (base != NULL && phase->type(base)->higher_equal(TypePtr::NULL_PTR) &&
   330       !t_adr->isa_rawptr()) {
   331     // Note: raw address has TOP base and top->higher_equal(TypePtr::NULL_PTR) is true.
   332     // Skip this node optimization if its address has TOP base.
   333     return NodeSentinel; // caller will return NULL
   334   }
   336   // Avoid independent memory operations
   337   Node* old_mem = mem;
   339   // The code which unhooks non-raw memories from complete (macro-expanded)
   340   // initializations was removed. After macro-expansion all stores catched
   341   // by Initialize node became raw stores and there is no information
   342   // which memory slices they modify. So it is unsafe to move any memory
   343   // operation above these stores. Also in most cases hooked non-raw memories
   344   // were already unhooked by using information from detect_ptr_independence()
   345   // and find_previous_store().
   347   if (mem->is_MergeMem()) {
   348     MergeMemNode* mmem = mem->as_MergeMem();
   349     const TypePtr *tp = t_adr->is_ptr();
   351     mem = step_through_mergemem(phase, mmem, tp, adr_type(), tty);
   352   }
   354   if (mem != old_mem) {
   355     set_req(MemNode::Memory, mem);
   356     if (can_reshape && old_mem->outcnt() == 0) {
   357         igvn->_worklist.push(old_mem);
   358     }
   359     if (phase->type( mem ) == Type::TOP) return NodeSentinel;
   360     return this;
   361   }
   363   // let the subclass continue analyzing...
   364   return NULL;
   365 }
   367 // Helper function for proving some simple control dominations.
   368 // Attempt to prove that all control inputs of 'dom' dominate 'sub'.
   369 // Already assumes that 'dom' is available at 'sub', and that 'sub'
   370 // is not a constant (dominated by the method's StartNode).
   371 // Used by MemNode::find_previous_store to prove that the
   372 // control input of a memory operation predates (dominates)
   373 // an allocation it wants to look past.
   374 bool MemNode::all_controls_dominate(Node* dom, Node* sub) {
   375   if (dom == NULL || dom->is_top() || sub == NULL || sub->is_top())
   376     return false; // Conservative answer for dead code
   378   // Check 'dom'. Skip Proj and CatchProj nodes.
   379   dom = dom->find_exact_control(dom);
   380   if (dom == NULL || dom->is_top())
   381     return false; // Conservative answer for dead code
   383   if (dom == sub) {
   384     // For the case when, for example, 'sub' is Initialize and the original
   385     // 'dom' is Proj node of the 'sub'.
   386     return false;
   387   }
   389   if (dom->is_Con() || dom->is_Start() || dom->is_Root() || dom == sub)
   390     return true;
   392   // 'dom' dominates 'sub' if its control edge and control edges
   393   // of all its inputs dominate or equal to sub's control edge.
   395   // Currently 'sub' is either Allocate, Initialize or Start nodes.
   396   // Or Region for the check in LoadNode::Ideal();
   397   // 'sub' should have sub->in(0) != NULL.
   398   assert(sub->is_Allocate() || sub->is_Initialize() || sub->is_Start() ||
   399          sub->is_Region() || sub->is_Call(), "expecting only these nodes");
   401   // Get control edge of 'sub'.
   402   Node* orig_sub = sub;
   403   sub = sub->find_exact_control(sub->in(0));
   404   if (sub == NULL || sub->is_top())
   405     return false; // Conservative answer for dead code
   407   assert(sub->is_CFG(), "expecting control");
   409   if (sub == dom)
   410     return true;
   412   if (sub->is_Start() || sub->is_Root())
   413     return false;
   415   {
   416     // Check all control edges of 'dom'.
   418     ResourceMark rm;
   419     Arena* arena = Thread::current()->resource_area();
   420     Node_List nlist(arena);
   421     Unique_Node_List dom_list(arena);
   423     dom_list.push(dom);
   424     bool only_dominating_controls = false;
   426     for (uint next = 0; next < dom_list.size(); next++) {
   427       Node* n = dom_list.at(next);
   428       if (n == orig_sub)
   429         return false; // One of dom's inputs dominated by sub.
   430       if (!n->is_CFG() && n->pinned()) {
   431         // Check only own control edge for pinned non-control nodes.
   432         n = n->find_exact_control(n->in(0));
   433         if (n == NULL || n->is_top())
   434           return false; // Conservative answer for dead code
   435         assert(n->is_CFG(), "expecting control");
   436         dom_list.push(n);
   437       } else if (n->is_Con() || n->is_Start() || n->is_Root()) {
   438         only_dominating_controls = true;
   439       } else if (n->is_CFG()) {
   440         if (n->dominates(sub, nlist))
   441           only_dominating_controls = true;
   442         else
   443           return false;
   444       } else {
   445         // First, own control edge.
   446         Node* m = n->find_exact_control(n->in(0));
   447         if (m != NULL) {
   448           if (m->is_top())
   449             return false; // Conservative answer for dead code
   450           dom_list.push(m);
   451         }
   452         // Now, the rest of edges.
   453         uint cnt = n->req();
   454         for (uint i = 1; i < cnt; i++) {
   455           m = n->find_exact_control(n->in(i));
   456           if (m == NULL || m->is_top())
   457             continue;
   458           dom_list.push(m);
   459         }
   460       }
   461     }
   462     return only_dominating_controls;
   463   }
   464 }
   466 //---------------------detect_ptr_independence---------------------------------
   467 // Used by MemNode::find_previous_store to prove that two base
   468 // pointers are never equal.
   469 // The pointers are accompanied by their associated allocations,
   470 // if any, which have been previously discovered by the caller.
   471 bool MemNode::detect_ptr_independence(Node* p1, AllocateNode* a1,
   472                                       Node* p2, AllocateNode* a2,
   473                                       PhaseTransform* phase) {
   474   // Attempt to prove that these two pointers cannot be aliased.
   475   // They may both manifestly be allocations, and they should differ.
   476   // Or, if they are not both allocations, they can be distinct constants.
   477   // Otherwise, one is an allocation and the other a pre-existing value.
   478   if (a1 == NULL && a2 == NULL) {           // neither an allocation
   479     return (p1 != p2) && p1->is_Con() && p2->is_Con();
   480   } else if (a1 != NULL && a2 != NULL) {    // both allocations
   481     return (a1 != a2);
   482   } else if (a1 != NULL) {                  // one allocation a1
   483     // (Note:  p2->is_Con implies p2->in(0)->is_Root, which dominates.)
   484     return all_controls_dominate(p2, a1);
   485   } else { //(a2 != NULL)                   // one allocation a2
   486     return all_controls_dominate(p1, a2);
   487   }
   488   return false;
   489 }
   492 // The logic for reordering loads and stores uses four steps:
   493 // (a) Walk carefully past stores and initializations which we
   494 //     can prove are independent of this load.
   495 // (b) Observe that the next memory state makes an exact match
   496 //     with self (load or store), and locate the relevant store.
   497 // (c) Ensure that, if we were to wire self directly to the store,
   498 //     the optimizer would fold it up somehow.
   499 // (d) Do the rewiring, and return, depending on some other part of
   500 //     the optimizer to fold up the load.
   501 // This routine handles steps (a) and (b).  Steps (c) and (d) are
   502 // specific to loads and stores, so they are handled by the callers.
   503 // (Currently, only LoadNode::Ideal has steps (c), (d).  More later.)
   504 //
   505 Node* MemNode::find_previous_store(PhaseTransform* phase) {
   506   Node*         ctrl   = in(MemNode::Control);
   507   Node*         adr    = in(MemNode::Address);
   508   intptr_t      offset = 0;
   509   Node*         base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
   510   AllocateNode* alloc  = AllocateNode::Ideal_allocation(base, phase);
   512   if (offset == Type::OffsetBot)
   513     return NULL;            // cannot unalias unless there are precise offsets
   515   const bool adr_maybe_raw = check_if_adr_maybe_raw(adr);
   516   const TypeOopPtr *addr_t = adr->bottom_type()->isa_oopptr();
   518   intptr_t size_in_bytes = memory_size();
   520   Node* mem = in(MemNode::Memory);   // start searching here...
   522   int cnt = 50;             // Cycle limiter
   523   for (;;) {                // While we can dance past unrelated stores...
   524     if (--cnt < 0)  break;  // Caught in cycle or a complicated dance?
   526     if (mem->is_Store()) {
   527       Node* st_adr = mem->in(MemNode::Address);
   528       intptr_t st_offset = 0;
   529       Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_offset);
   530       if (st_base == NULL)
   531         break;              // inscrutable pointer
   533       // For raw accesses it's not enough to prove that constant offsets don't intersect.
   534       // We need the bases to be the equal in order for the offset check to make sense.
   535       if ((adr_maybe_raw || check_if_adr_maybe_raw(st_adr)) && st_base != base) {
   536         break;
   537       }
   539       if (st_offset != offset && st_offset != Type::OffsetBot) {
   540         const int MAX_STORE = BytesPerLong;
   541         if (st_offset >= offset + size_in_bytes ||
   542             st_offset <= offset - MAX_STORE ||
   543             st_offset <= offset - mem->as_Store()->memory_size()) {
   544           // Success:  The offsets are provably independent.
   545           // (You may ask, why not just test st_offset != offset and be done?
   546           // The answer is that stores of different sizes can co-exist
   547           // in the same sequence of RawMem effects.  We sometimes initialize
   548           // a whole 'tile' of array elements with a single jint or jlong.)
   549           mem = mem->in(MemNode::Memory);
   550           continue;           // (a) advance through independent store memory
   551         }
   552       }
   553       if (st_base != base &&
   554           detect_ptr_independence(base, alloc,
   555                                   st_base,
   556                                   AllocateNode::Ideal_allocation(st_base, phase),
   557                                   phase)) {
   558         // Success:  The bases are provably independent.
   559         mem = mem->in(MemNode::Memory);
   560         continue;           // (a) advance through independent store memory
   561       }
   563       // (b) At this point, if the bases or offsets do not agree, we lose,
   564       // since we have not managed to prove 'this' and 'mem' independent.
   565       if (st_base == base && st_offset == offset) {
   566         return mem;         // let caller handle steps (c), (d)
   567       }
   569     } else if (mem->is_Proj() && mem->in(0)->is_Initialize()) {
   570       InitializeNode* st_init = mem->in(0)->as_Initialize();
   571       AllocateNode*  st_alloc = st_init->allocation();
   572       if (st_alloc == NULL)
   573         break;              // something degenerated
   574       bool known_identical = false;
   575       bool known_independent = false;
   576       if (alloc == st_alloc)
   577         known_identical = true;
   578       else if (alloc != NULL)
   579         known_independent = true;
   580       else if (all_controls_dominate(this, st_alloc))
   581         known_independent = true;
   583       if (known_independent) {
   584         // The bases are provably independent: Either they are
   585         // manifestly distinct allocations, or else the control
   586         // of this load dominates the store's allocation.
   587         int alias_idx = phase->C->get_alias_index(adr_type());
   588         if (alias_idx == Compile::AliasIdxRaw) {
   589           mem = st_alloc->in(TypeFunc::Memory);
   590         } else {
   591           mem = st_init->memory(alias_idx);
   592         }
   593         continue;           // (a) advance through independent store memory
   594       }
   596       // (b) at this point, if we are not looking at a store initializing
   597       // the same allocation we are loading from, we lose.
   598       if (known_identical) {
   599         // From caller, can_see_stored_value will consult find_captured_store.
   600         return mem;         // let caller handle steps (c), (d)
   601       }
   603     } else if (addr_t != NULL && addr_t->is_known_instance_field()) {
   604       // Can't use optimize_simple_memory_chain() since it needs PhaseGVN.
   605       if (mem->is_Proj() && mem->in(0)->is_Call()) {
   606         CallNode *call = mem->in(0)->as_Call();
   607         if (!call->may_modify(addr_t, phase)) {
   608           mem = call->in(TypeFunc::Memory);
   609           continue;         // (a) advance through independent call memory
   610         }
   611       } else if (mem->is_Proj() && mem->in(0)->is_MemBar()) {
   612         mem = mem->in(0)->in(TypeFunc::Memory);
   613         continue;           // (a) advance through independent MemBar memory
   614       } else if (mem->is_ClearArray()) {
   615         if (ClearArrayNode::step_through(&mem, (uint)addr_t->instance_id(), phase)) {
   616           // (the call updated 'mem' value)
   617           continue;         // (a) advance through independent allocation memory
   618         } else {
   619           // Can not bypass initialization of the instance
   620           // we are looking for.
   621           return mem;
   622         }
   623       } else if (mem->is_MergeMem()) {
   624         int alias_idx = phase->C->get_alias_index(adr_type());
   625         mem = mem->as_MergeMem()->memory_at(alias_idx);
   626         continue;           // (a) advance through independent MergeMem memory
   627       }
   628     }
   630     // Unless there is an explicit 'continue', we must bail out here,
   631     // because 'mem' is an inscrutable memory state (e.g., a call).
   632     break;
   633   }
   635   return NULL;              // bail out
   636 }
   638 //----------------------calculate_adr_type-------------------------------------
   639 // Helper function.  Notices when the given type of address hits top or bottom.
   640 // Also, asserts a cross-check of the type against the expected address type.
   641 const TypePtr* MemNode::calculate_adr_type(const Type* t, const TypePtr* cross_check) {
   642   if (t == Type::TOP)  return NULL; // does not touch memory any more?
   643   #ifdef PRODUCT
   644   cross_check = NULL;
   645   #else
   646   if (!VerifyAliases || is_error_reported() || Node::in_dump())  cross_check = NULL;
   647   #endif
   648   const TypePtr* tp = t->isa_ptr();
   649   if (tp == NULL) {
   650     assert(cross_check == NULL || cross_check == TypePtr::BOTTOM, "expected memory type must be wide");
   651     return TypePtr::BOTTOM;           // touches lots of memory
   652   } else {
   653     #ifdef ASSERT
   654     // %%%% [phh] We don't check the alias index if cross_check is
   655     //            TypeRawPtr::BOTTOM.  Needs to be investigated.
   656     if (cross_check != NULL &&
   657         cross_check != TypePtr::BOTTOM &&
   658         cross_check != TypeRawPtr::BOTTOM) {
   659       // Recheck the alias index, to see if it has changed (due to a bug).
   660       Compile* C = Compile::current();
   661       assert(C->get_alias_index(cross_check) == C->get_alias_index(tp),
   662              "must stay in the original alias category");
   663       // The type of the address must be contained in the adr_type,
   664       // disregarding "null"-ness.
   665       // (We make an exception for TypeRawPtr::BOTTOM, which is a bit bucket.)
   666       const TypePtr* tp_notnull = tp->join(TypePtr::NOTNULL)->is_ptr();
   667       assert(cross_check->meet(tp_notnull) == cross_check->remove_speculative(),
   668              "real address must not escape from expected memory type");
   669     }
   670     #endif
   671     return tp;
   672   }
   673 }
   675 //------------------------adr_phi_is_loop_invariant----------------------------
   676 // A helper function for Ideal_DU_postCCP to check if a Phi in a counted
   677 // loop is loop invariant. Make a quick traversal of Phi and associated
   678 // CastPP nodes, looking to see if they are a closed group within the loop.
   679 bool MemNode::adr_phi_is_loop_invariant(Node* adr_phi, Node* cast) {
   680   // The idea is that the phi-nest must boil down to only CastPP nodes
   681   // with the same data. This implies that any path into the loop already
   682   // includes such a CastPP, and so the original cast, whatever its input,
   683   // must be covered by an equivalent cast, with an earlier control input.
   684   ResourceMark rm;
   686   // The loop entry input of the phi should be the unique dominating
   687   // node for every Phi/CastPP in the loop.
   688   Unique_Node_List closure;
   689   closure.push(adr_phi->in(LoopNode::EntryControl));
   691   // Add the phi node and the cast to the worklist.
   692   Unique_Node_List worklist;
   693   worklist.push(adr_phi);
   694   if( cast != NULL ){
   695     if( !cast->is_ConstraintCast() ) return false;
   696     worklist.push(cast);
   697   }
   699   // Begin recursive walk of phi nodes.
   700   while( worklist.size() ){
   701     // Take a node off the worklist
   702     Node *n = worklist.pop();
   703     if( !closure.member(n) ){
   704       // Add it to the closure.
   705       closure.push(n);
   706       // Make a sanity check to ensure we don't waste too much time here.
   707       if( closure.size() > 20) return false;
   708       // This node is OK if:
   709       //  - it is a cast of an identical value
   710       //  - or it is a phi node (then we add its inputs to the worklist)
   711       // Otherwise, the node is not OK, and we presume the cast is not invariant
   712       if( n->is_ConstraintCast() ){
   713         worklist.push(n->in(1));
   714       } else if( n->is_Phi() ) {
   715         for( uint i = 1; i < n->req(); i++ ) {
   716           worklist.push(n->in(i));
   717         }
   718       } else {
   719         return false;
   720       }
   721     }
   722   }
   724   // Quit when the worklist is empty, and we've found no offending nodes.
   725   return true;
   726 }
   728 //------------------------------Ideal_DU_postCCP-------------------------------
   729 // Find any cast-away of null-ness and keep its control.  Null cast-aways are
   730 // going away in this pass and we need to make this memory op depend on the
   731 // gating null check.
   732 Node *MemNode::Ideal_DU_postCCP( PhaseCCP *ccp ) {
   733   return Ideal_common_DU_postCCP(ccp, this, in(MemNode::Address));
   734 }
   736 // I tried to leave the CastPP's in.  This makes the graph more accurate in
   737 // some sense; we get to keep around the knowledge that an oop is not-null
   738 // after some test.  Alas, the CastPP's interfere with GVN (some values are
   739 // the regular oop, some are the CastPP of the oop, all merge at Phi's which
   740 // cannot collapse, etc).  This cost us 10% on SpecJVM, even when I removed
   741 // some of the more trivial cases in the optimizer.  Removing more useless
   742 // Phi's started allowing Loads to illegally float above null checks.  I gave
   743 // up on this approach.  CNC 10/20/2000
   744 // This static method may be called not from MemNode (EncodePNode calls it).
   745 // Only the control edge of the node 'n' might be updated.
   746 Node *MemNode::Ideal_common_DU_postCCP( PhaseCCP *ccp, Node* n, Node* adr ) {
   747   Node *skipped_cast = NULL;
   748   // Need a null check?  Regular static accesses do not because they are
   749   // from constant addresses.  Array ops are gated by the range check (which
   750   // always includes a NULL check).  Just check field ops.
   751   if( n->in(MemNode::Control) == NULL ) {
   752     // Scan upwards for the highest location we can place this memory op.
   753     while( true ) {
   754       switch( adr->Opcode() ) {
   756       case Op_AddP:             // No change to NULL-ness, so peek thru AddP's
   757         adr = adr->in(AddPNode::Base);
   758         continue;
   760       case Op_DecodeN:         // No change to NULL-ness, so peek thru
   761       case Op_DecodeNKlass:
   762         adr = adr->in(1);
   763         continue;
   765       case Op_EncodeP:
   766       case Op_EncodePKlass:
   767         // EncodeP node's control edge could be set by this method
   768         // when EncodeP node depends on CastPP node.
   769         //
   770         // Use its control edge for memory op because EncodeP may go away
   771         // later when it is folded with following or preceding DecodeN node.
   772         if (adr->in(0) == NULL) {
   773           // Keep looking for cast nodes.
   774           adr = adr->in(1);
   775           continue;
   776         }
   777         ccp->hash_delete(n);
   778         n->set_req(MemNode::Control, adr->in(0));
   779         ccp->hash_insert(n);
   780         return n;
   782       case Op_CastPP:
   783         // If the CastPP is useless, just peek on through it.
   784         if( ccp->type(adr) == ccp->type(adr->in(1)) ) {
   785           // Remember the cast that we've peeked though. If we peek
   786           // through more than one, then we end up remembering the highest
   787           // one, that is, if in a loop, the one closest to the top.
   788           skipped_cast = adr;
   789           adr = adr->in(1);
   790           continue;
   791         }
   792         // CastPP is going away in this pass!  We need this memory op to be
   793         // control-dependent on the test that is guarding the CastPP.
   794         ccp->hash_delete(n);
   795         n->set_req(MemNode::Control, adr->in(0));
   796         ccp->hash_insert(n);
   797         return n;
   799       case Op_Phi:
   800         // Attempt to float above a Phi to some dominating point.
   801         if (adr->in(0) != NULL && adr->in(0)->is_CountedLoop()) {
   802           // If we've already peeked through a Cast (which could have set the
   803           // control), we can't float above a Phi, because the skipped Cast
   804           // may not be loop invariant.
   805           if (adr_phi_is_loop_invariant(adr, skipped_cast)) {
   806             adr = adr->in(1);
   807             continue;
   808           }
   809         }
   811         // Intentional fallthrough!
   813         // No obvious dominating point.  The mem op is pinned below the Phi
   814         // by the Phi itself.  If the Phi goes away (no true value is merged)
   815         // then the mem op can float, but not indefinitely.  It must be pinned
   816         // behind the controls leading to the Phi.
   817       case Op_CheckCastPP:
   818         // These usually stick around to change address type, however a
   819         // useless one can be elided and we still need to pick up a control edge
   820         if (adr->in(0) == NULL) {
   821           // This CheckCastPP node has NO control and is likely useless. But we
   822           // need check further up the ancestor chain for a control input to keep
   823           // the node in place. 4959717.
   824           skipped_cast = adr;
   825           adr = adr->in(1);
   826           continue;
   827         }
   828         ccp->hash_delete(n);
   829         n->set_req(MemNode::Control, adr->in(0));
   830         ccp->hash_insert(n);
   831         return n;
   833         // List of "safe" opcodes; those that implicitly block the memory
   834         // op below any null check.
   835       case Op_CastX2P:          // no null checks on native pointers
   836       case Op_Parm:             // 'this' pointer is not null
   837       case Op_LoadP:            // Loading from within a klass
   838       case Op_LoadN:            // Loading from within a klass
   839       case Op_LoadKlass:        // Loading from within a klass
   840       case Op_LoadNKlass:       // Loading from within a klass
   841       case Op_ConP:             // Loading from a klass
   842       case Op_ConN:             // Loading from a klass
   843       case Op_ConNKlass:        // Loading from a klass
   844       case Op_CreateEx:         // Sucking up the guts of an exception oop
   845       case Op_Con:              // Reading from TLS
   846       case Op_CMoveP:           // CMoveP is pinned
   847       case Op_CMoveN:           // CMoveN is pinned
   848         break;                  // No progress
   850       case Op_Proj:             // Direct call to an allocation routine
   851       case Op_SCMemProj:        // Memory state from store conditional ops
   852 #ifdef ASSERT
   853         {
   854           assert(adr->as_Proj()->_con == TypeFunc::Parms, "must be return value");
   855           const Node* call = adr->in(0);
   856           if (call->is_CallJava()) {
   857             const CallJavaNode* call_java = call->as_CallJava();
   858             const TypeTuple *r = call_java->tf()->range();
   859             assert(r->cnt() > TypeFunc::Parms, "must return value");
   860             const Type* ret_type = r->field_at(TypeFunc::Parms);
   861             assert(ret_type && ret_type->isa_ptr(), "must return pointer");
   862             // We further presume that this is one of
   863             // new_instance_Java, new_array_Java, or
   864             // the like, but do not assert for this.
   865           } else if (call->is_Allocate()) {
   866             // similar case to new_instance_Java, etc.
   867           } else if (!call->is_CallLeaf()) {
   868             // Projections from fetch_oop (OSR) are allowed as well.
   869             ShouldNotReachHere();
   870           }
   871         }
   872 #endif
   873         break;
   874       default:
   875         ShouldNotReachHere();
   876       }
   877       break;
   878     }
   879   }
   881   return  NULL;               // No progress
   882 }
   885 //=============================================================================
   886 // Should LoadNode::Ideal() attempt to remove control edges?
   887 bool LoadNode::can_remove_control() const {
   888   return true;
   889 }
   890 uint LoadNode::size_of() const { return sizeof(*this); }
   891 uint LoadNode::cmp( const Node &n ) const
   892 { return !Type::cmp( _type, ((LoadNode&)n)._type ); }
   893 const Type *LoadNode::bottom_type() const { return _type; }
   894 uint LoadNode::ideal_reg() const {
   895   return _type->ideal_reg();
   896 }
   898 #ifndef PRODUCT
   899 void LoadNode::dump_spec(outputStream *st) const {
   900   MemNode::dump_spec(st);
   901   if( !Verbose && !WizardMode ) {
   902     // standard dump does this in Verbose and WizardMode
   903     st->print(" #"); _type->dump_on(st);
   904   }
   905   if (!_depends_only_on_test) {
   906     st->print(" (does not depend only on test)");
   907   }
   908 }
   909 #endif
   911 #ifdef ASSERT
   912 //----------------------------is_immutable_value-------------------------------
   913 // Helper function to allow a raw load without control edge for some cases
   914 bool LoadNode::is_immutable_value(Node* adr) {
   915   return (adr->is_AddP() && adr->in(AddPNode::Base)->is_top() &&
   916           adr->in(AddPNode::Address)->Opcode() == Op_ThreadLocal &&
   917           (adr->in(AddPNode::Offset)->find_intptr_t_con(-1) ==
   918            in_bytes(JavaThread::osthread_offset())));
   919 }
   920 #endif
   922 //----------------------------LoadNode::make-----------------------------------
   923 // Polymorphic factory method:
   924 Node *LoadNode::make(PhaseGVN& gvn, Node *ctl, Node *mem, Node *adr, const TypePtr* adr_type, const Type *rt, BasicType bt, MemOrd mo, ControlDependency control_dependency) {
   925   Compile* C = gvn.C;
   927   // sanity check the alias category against the created node type
   928   assert(!(adr_type->isa_oopptr() &&
   929            adr_type->offset() == oopDesc::klass_offset_in_bytes()),
   930          "use LoadKlassNode instead");
   931   assert(!(adr_type->isa_aryptr() &&
   932            adr_type->offset() == arrayOopDesc::length_offset_in_bytes()),
   933          "use LoadRangeNode instead");
   934   // Check control edge of raw loads
   935   assert( ctl != NULL || C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
   936           // oop will be recorded in oop map if load crosses safepoint
   937           rt->isa_oopptr() || is_immutable_value(adr),
   938           "raw memory operations should have control edge");
   939   switch (bt) {
   940   case T_BOOLEAN: return new (C) LoadUBNode(ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency);
   941   case T_BYTE:    return new (C) LoadBNode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency);
   942   case T_INT:     return new (C) LoadINode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency);
   943   case T_CHAR:    return new (C) LoadUSNode(ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency);
   944   case T_SHORT:   return new (C) LoadSNode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency);
   945   case T_LONG:    return new (C) LoadLNode (ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency);
   946   case T_FLOAT:   return new (C) LoadFNode (ctl, mem, adr, adr_type, rt,            mo, control_dependency);
   947   case T_DOUBLE:  return new (C) LoadDNode (ctl, mem, adr, adr_type, rt,            mo, control_dependency);
   948   case T_ADDRESS: return new (C) LoadPNode (ctl, mem, adr, adr_type, rt->is_ptr(),  mo, control_dependency);
   949   case T_OBJECT:
   950 #ifdef _LP64
   951     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
   952       Node* load  = gvn.transform(new (C) LoadNNode(ctl, mem, adr, adr_type, rt->make_narrowoop(), mo, control_dependency));
   953       return new (C) DecodeNNode(load, load->bottom_type()->make_ptr());
   954     } else
   955 #endif
   956     {
   957       assert(!adr->bottom_type()->is_ptr_to_narrowoop() && !adr->bottom_type()->is_ptr_to_narrowklass(), "should have got back a narrow oop");
   958       return new (C) LoadPNode(ctl, mem, adr, adr_type, rt->is_oopptr(), mo, control_dependency);
   959     }
   960   }
   961   ShouldNotReachHere();
   962   return (LoadNode*)NULL;
   963 }
   965 LoadLNode* LoadLNode::make_atomic(Compile *C, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, MemOrd mo, ControlDependency control_dependency) {
   966   bool require_atomic = true;
   967   return new (C) LoadLNode(ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency, require_atomic);
   968 }
   970 LoadDNode* LoadDNode::make_atomic(Compile *C, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, MemOrd mo, ControlDependency control_dependency) {
   971   bool require_atomic = true;
   972   return new (C) LoadDNode(ctl, mem, adr, adr_type, rt, mo, control_dependency, require_atomic);
   973 }
   977 //------------------------------hash-------------------------------------------
   978 uint LoadNode::hash() const {
   979   // unroll addition of interesting fields
   980   return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address);
   981 }
   983 static bool skip_through_membars(Compile::AliasType* atp, const TypeInstPtr* tp, bool eliminate_boxing) {
   984   if ((atp != NULL) && (atp->index() >= Compile::AliasIdxRaw)) {
   985     bool non_volatile = (atp->field() != NULL) && !atp->field()->is_volatile();
   986     bool is_stable_ary = FoldStableValues &&
   987                          (tp != NULL) && (tp->isa_aryptr() != NULL) &&
   988                          tp->isa_aryptr()->is_stable();
   990     return (eliminate_boxing && non_volatile) || is_stable_ary;
   991   }
   993   return false;
   994 }
   996 //---------------------------can_see_stored_value------------------------------
   997 // This routine exists to make sure this set of tests is done the same
   998 // everywhere.  We need to make a coordinated change: first LoadNode::Ideal
   999 // will change the graph shape in a way which makes memory alive twice at the
  1000 // same time (uses the Oracle model of aliasing), then some
  1001 // LoadXNode::Identity will fold things back to the equivalence-class model
  1002 // of aliasing.
  1003 Node* MemNode::can_see_stored_value(Node* st, PhaseTransform* phase) const {
  1004   Node* ld_adr = in(MemNode::Address);
  1005   intptr_t ld_off = 0;
  1006   AllocateNode* ld_alloc = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off);
  1007   const TypeInstPtr* tp = phase->type(ld_adr)->isa_instptr();
  1008   Compile::AliasType* atp = (tp != NULL) ? phase->C->alias_type(tp) : NULL;
  1009   // This is more general than load from boxing objects.
  1010   if (skip_through_membars(atp, tp, phase->C->eliminate_boxing())) {
  1011     uint alias_idx = atp->index();
  1012     bool final = !atp->is_rewritable();
  1013     Node* result = NULL;
  1014     Node* current = st;
  1015     // Skip through chains of MemBarNodes checking the MergeMems for
  1016     // new states for the slice of this load.  Stop once any other
  1017     // kind of node is encountered.  Loads from final memory can skip
  1018     // through any kind of MemBar but normal loads shouldn't skip
  1019     // through MemBarAcquire since the could allow them to move out of
  1020     // a synchronized region.
  1021     while (current->is_Proj()) {
  1022       int opc = current->in(0)->Opcode();
  1023       if ((final && (opc == Op_MemBarAcquire ||
  1024                      opc == Op_MemBarAcquireLock ||
  1025                      opc == Op_LoadFence)) ||
  1026           opc == Op_MemBarRelease ||
  1027           opc == Op_StoreFence ||
  1028           opc == Op_MemBarReleaseLock ||
  1029           opc == Op_MemBarCPUOrder) {
  1030         Node* mem = current->in(0)->in(TypeFunc::Memory);
  1031         if (mem->is_MergeMem()) {
  1032           MergeMemNode* merge = mem->as_MergeMem();
  1033           Node* new_st = merge->memory_at(alias_idx);
  1034           if (new_st == merge->base_memory()) {
  1035             // Keep searching
  1036             current = new_st;
  1037             continue;
  1039           // Save the new memory state for the slice and fall through
  1040           // to exit.
  1041           result = new_st;
  1044       break;
  1046     if (result != NULL) {
  1047       st = result;
  1051   // Loop around twice in the case Load -> Initialize -> Store.
  1052   // (See PhaseIterGVN::add_users_to_worklist, which knows about this case.)
  1053   for (int trip = 0; trip <= 1; trip++) {
  1055     if (st->is_Store()) {
  1056       Node* st_adr = st->in(MemNode::Address);
  1057       if (!phase->eqv(st_adr, ld_adr)) {
  1058         // Try harder before giving up...  Match raw and non-raw pointers.
  1059         intptr_t st_off = 0;
  1060         AllocateNode* alloc = AllocateNode::Ideal_allocation(st_adr, phase, st_off);
  1061         if (alloc == NULL)       return NULL;
  1062         if (alloc != ld_alloc)   return NULL;
  1063         if (ld_off != st_off)    return NULL;
  1064         // At this point we have proven something like this setup:
  1065         //  A = Allocate(...)
  1066         //  L = LoadQ(,  AddP(CastPP(, A.Parm),, #Off))
  1067         //  S = StoreQ(, AddP(,        A.Parm  , #Off), V)
  1068         // (Actually, we haven't yet proven the Q's are the same.)
  1069         // In other words, we are loading from a casted version of
  1070         // the same pointer-and-offset that we stored to.
  1071         // Thus, we are able to replace L by V.
  1073       // Now prove that we have a LoadQ matched to a StoreQ, for some Q.
  1074       if (store_Opcode() != st->Opcode())
  1075         return NULL;
  1076       return st->in(MemNode::ValueIn);
  1079     // A load from a freshly-created object always returns zero.
  1080     // (This can happen after LoadNode::Ideal resets the load's memory input
  1081     // to find_captured_store, which returned InitializeNode::zero_memory.)
  1082     if (st->is_Proj() && st->in(0)->is_Allocate() &&
  1083         (st->in(0) == ld_alloc) &&
  1084         (ld_off >= st->in(0)->as_Allocate()->minimum_header_size())) {
  1085       // return a zero value for the load's basic type
  1086       // (This is one of the few places where a generic PhaseTransform
  1087       // can create new nodes.  Think of it as lazily manifesting
  1088       // virtually pre-existing constants.)
  1089       return phase->zerocon(memory_type());
  1092     // A load from an initialization barrier can match a captured store.
  1093     if (st->is_Proj() && st->in(0)->is_Initialize()) {
  1094       InitializeNode* init = st->in(0)->as_Initialize();
  1095       AllocateNode* alloc = init->allocation();
  1096       if ((alloc != NULL) && (alloc == ld_alloc)) {
  1097         // examine a captured store value
  1098         st = init->find_captured_store(ld_off, memory_size(), phase);
  1099         if (st != NULL)
  1100           continue;             // take one more trip around
  1104     // Load boxed value from result of valueOf() call is input parameter.
  1105     if (this->is_Load() && ld_adr->is_AddP() &&
  1106         (tp != NULL) && tp->is_ptr_to_boxed_value()) {
  1107       intptr_t ignore = 0;
  1108       Node* base = AddPNode::Ideal_base_and_offset(ld_adr, phase, ignore);
  1109       if (base != NULL && base->is_Proj() &&
  1110           base->as_Proj()->_con == TypeFunc::Parms &&
  1111           base->in(0)->is_CallStaticJava() &&
  1112           base->in(0)->as_CallStaticJava()->is_boxing_method()) {
  1113         return base->in(0)->in(TypeFunc::Parms);
  1117     break;
  1120   return NULL;
  1123 //----------------------is_instance_field_load_with_local_phi------------------
  1124 bool LoadNode::is_instance_field_load_with_local_phi(Node* ctrl) {
  1125   if( in(Memory)->is_Phi() && in(Memory)->in(0) == ctrl &&
  1126       in(Address)->is_AddP() ) {
  1127     const TypeOopPtr* t_oop = in(Address)->bottom_type()->isa_oopptr();
  1128     // Only instances and boxed values.
  1129     if( t_oop != NULL &&
  1130         (t_oop->is_ptr_to_boxed_value() ||
  1131          t_oop->is_known_instance_field()) &&
  1132         t_oop->offset() != Type::OffsetBot &&
  1133         t_oop->offset() != Type::OffsetTop) {
  1134       return true;
  1137   return false;
  1140 //------------------------------Identity---------------------------------------
  1141 // Loads are identity if previous store is to same address
  1142 Node *LoadNode::Identity( PhaseTransform *phase ) {
  1143   // If the previous store-maker is the right kind of Store, and the store is
  1144   // to the same address, then we are equal to the value stored.
  1145   Node* mem = in(Memory);
  1146   Node* value = can_see_stored_value(mem, phase);
  1147   if( value ) {
  1148     // byte, short & char stores truncate naturally.
  1149     // A load has to load the truncated value which requires
  1150     // some sort of masking operation and that requires an
  1151     // Ideal call instead of an Identity call.
  1152     if (memory_size() < BytesPerInt) {
  1153       // If the input to the store does not fit with the load's result type,
  1154       // it must be truncated via an Ideal call.
  1155       if (!phase->type(value)->higher_equal(phase->type(this)))
  1156         return this;
  1158     // (This works even when value is a Con, but LoadNode::Value
  1159     // usually runs first, producing the singleton type of the Con.)
  1160     return value;
  1163   // Search for an existing data phi which was generated before for the same
  1164   // instance's field to avoid infinite generation of phis in a loop.
  1165   Node *region = mem->in(0);
  1166   if (is_instance_field_load_with_local_phi(region)) {
  1167     const TypeOopPtr *addr_t = in(Address)->bottom_type()->isa_oopptr();
  1168     int this_index  = phase->C->get_alias_index(addr_t);
  1169     int this_offset = addr_t->offset();
  1170     int this_iid    = addr_t->instance_id();
  1171     if (!addr_t->is_known_instance() &&
  1172          addr_t->is_ptr_to_boxed_value()) {
  1173       // Use _idx of address base (could be Phi node) for boxed values.
  1174       intptr_t   ignore = 0;
  1175       Node*      base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore);
  1176       if (base == NULL) {
  1177         return this;
  1179       this_iid = base->_idx;
  1181     const Type* this_type = bottom_type();
  1182     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
  1183       Node* phi = region->fast_out(i);
  1184       if (phi->is_Phi() && phi != mem &&
  1185           phi->as_Phi()->is_same_inst_field(this_type, (int)mem->_idx, this_iid, this_index, this_offset)) {
  1186         return phi;
  1191   return this;
  1194 // We're loading from an object which has autobox behaviour.
  1195 // If this object is result of a valueOf call we'll have a phi
  1196 // merging a newly allocated object and a load from the cache.
  1197 // We want to replace this load with the original incoming
  1198 // argument to the valueOf call.
  1199 Node* LoadNode::eliminate_autobox(PhaseGVN* phase) {
  1200   assert(phase->C->eliminate_boxing(), "sanity");
  1201   intptr_t ignore = 0;
  1202   Node* base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore);
  1203   if ((base == NULL) || base->is_Phi()) {
  1204     // Push the loads from the phi that comes from valueOf up
  1205     // through it to allow elimination of the loads and the recovery
  1206     // of the original value. It is done in split_through_phi().
  1207     return NULL;
  1208   } else if (base->is_Load() ||
  1209              base->is_DecodeN() && base->in(1)->is_Load()) {
  1210     // Eliminate the load of boxed value for integer types from the cache
  1211     // array by deriving the value from the index into the array.
  1212     // Capture the offset of the load and then reverse the computation.
  1214     // Get LoadN node which loads a boxing object from 'cache' array.
  1215     if (base->is_DecodeN()) {
  1216       base = base->in(1);
  1218     if (!base->in(Address)->is_AddP()) {
  1219       return NULL; // Complex address
  1221     AddPNode* address = base->in(Address)->as_AddP();
  1222     Node* cache_base = address->in(AddPNode::Base);
  1223     if ((cache_base != NULL) && cache_base->is_DecodeN()) {
  1224       // Get ConP node which is static 'cache' field.
  1225       cache_base = cache_base->in(1);
  1227     if ((cache_base != NULL) && cache_base->is_Con()) {
  1228       const TypeAryPtr* base_type = cache_base->bottom_type()->isa_aryptr();
  1229       if ((base_type != NULL) && base_type->is_autobox_cache()) {
  1230         Node* elements[4];
  1231         int shift = exact_log2(type2aelembytes(T_OBJECT));
  1232         int count = address->unpack_offsets(elements, ARRAY_SIZE(elements));
  1233         if ((count >  0) && elements[0]->is_Con() &&
  1234             ((count == 1) ||
  1235              (count == 2) && elements[1]->Opcode() == Op_LShiftX &&
  1236                              elements[1]->in(2) == phase->intcon(shift))) {
  1237           ciObjArray* array = base_type->const_oop()->as_obj_array();
  1238           // Fetch the box object cache[0] at the base of the array and get its value
  1239           ciInstance* box = array->obj_at(0)->as_instance();
  1240           ciInstanceKlass* ik = box->klass()->as_instance_klass();
  1241           assert(ik->is_box_klass(), "sanity");
  1242           assert(ik->nof_nonstatic_fields() == 1, "change following code");
  1243           if (ik->nof_nonstatic_fields() == 1) {
  1244             // This should be true nonstatic_field_at requires calling
  1245             // nof_nonstatic_fields so check it anyway
  1246             ciConstant c = box->field_value(ik->nonstatic_field_at(0));
  1247             BasicType bt = c.basic_type();
  1248             // Only integer types have boxing cache.
  1249             assert(bt == T_BOOLEAN || bt == T_CHAR  ||
  1250                    bt == T_BYTE    || bt == T_SHORT ||
  1251                    bt == T_INT     || bt == T_LONG, err_msg_res("wrong type = %s", type2name(bt)));
  1252             jlong cache_low = (bt == T_LONG) ? c.as_long() : c.as_int();
  1253             if (cache_low != (int)cache_low) {
  1254               return NULL; // should not happen since cache is array indexed by value
  1256             jlong offset = arrayOopDesc::base_offset_in_bytes(T_OBJECT) - (cache_low << shift);
  1257             if (offset != (int)offset) {
  1258               return NULL; // should not happen since cache is array indexed by value
  1260            // Add up all the offsets making of the address of the load
  1261             Node* result = elements[0];
  1262             for (int i = 1; i < count; i++) {
  1263               result = phase->transform(new (phase->C) AddXNode(result, elements[i]));
  1265             // Remove the constant offset from the address and then
  1266             result = phase->transform(new (phase->C) AddXNode(result, phase->MakeConX(-(int)offset)));
  1267             // remove the scaling of the offset to recover the original index.
  1268             if (result->Opcode() == Op_LShiftX && result->in(2) == phase->intcon(shift)) {
  1269               // Peel the shift off directly but wrap it in a dummy node
  1270               // since Ideal can't return existing nodes
  1271               result = new (phase->C) RShiftXNode(result->in(1), phase->intcon(0));
  1272             } else if (result->is_Add() && result->in(2)->is_Con() &&
  1273                        result->in(1)->Opcode() == Op_LShiftX &&
  1274                        result->in(1)->in(2) == phase->intcon(shift)) {
  1275               // We can't do general optimization: ((X<<Z) + Y) >> Z ==> X + (Y>>Z)
  1276               // but for boxing cache access we know that X<<Z will not overflow
  1277               // (there is range check) so we do this optimizatrion by hand here.
  1278               Node* add_con = new (phase->C) RShiftXNode(result->in(2), phase->intcon(shift));
  1279               result = new (phase->C) AddXNode(result->in(1)->in(1), phase->transform(add_con));
  1280             } else {
  1281               result = new (phase->C) RShiftXNode(result, phase->intcon(shift));
  1283 #ifdef _LP64
  1284             if (bt != T_LONG) {
  1285               result = new (phase->C) ConvL2INode(phase->transform(result));
  1287 #else
  1288             if (bt == T_LONG) {
  1289               result = new (phase->C) ConvI2LNode(phase->transform(result));
  1291 #endif
  1292             // Boxing/unboxing can be done from signed & unsigned loads (e.g. LoadUB -> ... -> LoadB pair).
  1293             // Need to preserve unboxing load type if it is unsigned.
  1294             switch(this->Opcode()) {
  1295               case Op_LoadUB:
  1296                 result = new (phase->C) AndINode(phase->transform(result), phase->intcon(0xFF));
  1297                 break;
  1298               case Op_LoadUS:
  1299                 result = new (phase->C) AndINode(phase->transform(result), phase->intcon(0xFFFF));
  1300                 break;
  1302             return result;
  1308   return NULL;
  1311 static bool stable_phi(PhiNode* phi, PhaseGVN *phase) {
  1312   Node* region = phi->in(0);
  1313   if (region == NULL) {
  1314     return false; // Wait stable graph
  1316   uint cnt = phi->req();
  1317   for (uint i = 1; i < cnt; i++) {
  1318     Node* rc = region->in(i);
  1319     if (rc == NULL || phase->type(rc) == Type::TOP)
  1320       return false; // Wait stable graph
  1321     Node* in = phi->in(i);
  1322     if (in == NULL || phase->type(in) == Type::TOP)
  1323       return false; // Wait stable graph
  1325   return true;
  1327 //------------------------------split_through_phi------------------------------
  1328 // Split instance or boxed field load through Phi.
  1329 Node *LoadNode::split_through_phi(PhaseGVN *phase) {
  1330   Node* mem     = in(Memory);
  1331   Node* address = in(Address);
  1332   const TypeOopPtr *t_oop = phase->type(address)->isa_oopptr();
  1334   assert((t_oop != NULL) &&
  1335          (t_oop->is_known_instance_field() ||
  1336           t_oop->is_ptr_to_boxed_value()), "invalide conditions");
  1338   Compile* C = phase->C;
  1339   intptr_t ignore = 0;
  1340   Node*    base = AddPNode::Ideal_base_and_offset(address, phase, ignore);
  1341   bool base_is_phi = (base != NULL) && base->is_Phi();
  1342   bool load_boxed_values = t_oop->is_ptr_to_boxed_value() && C->aggressive_unboxing() &&
  1343                            (base != NULL) && (base == address->in(AddPNode::Base)) &&
  1344                            phase->type(base)->higher_equal(TypePtr::NOTNULL);
  1346   if (!((mem->is_Phi() || base_is_phi) &&
  1347         (load_boxed_values || t_oop->is_known_instance_field()))) {
  1348     return NULL; // memory is not Phi
  1351   if (mem->is_Phi()) {
  1352     if (!stable_phi(mem->as_Phi(), phase)) {
  1353       return NULL; // Wait stable graph
  1355     uint cnt = mem->req();
  1356     // Check for loop invariant memory.
  1357     if (cnt == 3) {
  1358       for (uint i = 1; i < cnt; i++) {
  1359         Node* in = mem->in(i);
  1360         Node*  m = optimize_memory_chain(in, t_oop, this, phase);
  1361         if (m == mem) {
  1362           if (i == 1) {
  1363             // if the first edge was a loop, check second edge too.
  1364             // If both are replaceable - we are in an infinite loop
  1365             Node *n = optimize_memory_chain(mem->in(2), t_oop, this, phase);
  1366             if (n == mem) {
  1367               break;
  1370           set_req(Memory, mem->in(cnt - i));
  1371           return this; // made change
  1376   if (base_is_phi) {
  1377     if (!stable_phi(base->as_Phi(), phase)) {
  1378       return NULL; // Wait stable graph
  1380     uint cnt = base->req();
  1381     // Check for loop invariant memory.
  1382     if (cnt == 3) {
  1383       for (uint i = 1; i < cnt; i++) {
  1384         if (base->in(i) == base) {
  1385           return NULL; // Wait stable graph
  1391   bool load_boxed_phi = load_boxed_values && base_is_phi && (base->in(0) == mem->in(0));
  1393   // Split through Phi (see original code in loopopts.cpp).
  1394   assert(C->have_alias_type(t_oop), "instance should have alias type");
  1396   // Do nothing here if Identity will find a value
  1397   // (to avoid infinite chain of value phis generation).
  1398   if (!phase->eqv(this, this->Identity(phase)))
  1399     return NULL;
  1401   // Select Region to split through.
  1402   Node* region;
  1403   if (!base_is_phi) {
  1404     assert(mem->is_Phi(), "sanity");
  1405     region = mem->in(0);
  1406     // Skip if the region dominates some control edge of the address.
  1407     if (!MemNode::all_controls_dominate(address, region))
  1408       return NULL;
  1409   } else if (!mem->is_Phi()) {
  1410     assert(base_is_phi, "sanity");
  1411     region = base->in(0);
  1412     // Skip if the region dominates some control edge of the memory.
  1413     if (!MemNode::all_controls_dominate(mem, region))
  1414       return NULL;
  1415   } else if (base->in(0) != mem->in(0)) {
  1416     assert(base_is_phi && mem->is_Phi(), "sanity");
  1417     if (MemNode::all_controls_dominate(mem, base->in(0))) {
  1418       region = base->in(0);
  1419     } else if (MemNode::all_controls_dominate(address, mem->in(0))) {
  1420       region = mem->in(0);
  1421     } else {
  1422       return NULL; // complex graph
  1424   } else {
  1425     assert(base->in(0) == mem->in(0), "sanity");
  1426     region = mem->in(0);
  1429   const Type* this_type = this->bottom_type();
  1430   int this_index  = C->get_alias_index(t_oop);
  1431   int this_offset = t_oop->offset();
  1432   int this_iid    = t_oop->instance_id();
  1433   if (!t_oop->is_known_instance() && load_boxed_values) {
  1434     // Use _idx of address base for boxed values.
  1435     this_iid = base->_idx;
  1437   PhaseIterGVN* igvn = phase->is_IterGVN();
  1438   Node* phi = new (C) PhiNode(region, this_type, NULL, mem->_idx, this_iid, this_index, this_offset);
  1439   for (uint i = 1; i < region->req(); i++) {
  1440     Node* x;
  1441     Node* the_clone = NULL;
  1442     if (region->in(i) == C->top()) {
  1443       x = C->top();      // Dead path?  Use a dead data op
  1444     } else {
  1445       x = this->clone();        // Else clone up the data op
  1446       the_clone = x;            // Remember for possible deletion.
  1447       // Alter data node to use pre-phi inputs
  1448       if (this->in(0) == region) {
  1449         x->set_req(0, region->in(i));
  1450       } else {
  1451         x->set_req(0, NULL);
  1453       if (mem->is_Phi() && (mem->in(0) == region)) {
  1454         x->set_req(Memory, mem->in(i)); // Use pre-Phi input for the clone.
  1456       if (address->is_Phi() && address->in(0) == region) {
  1457         x->set_req(Address, address->in(i)); // Use pre-Phi input for the clone
  1459       if (base_is_phi && (base->in(0) == region)) {
  1460         Node* base_x = base->in(i); // Clone address for loads from boxed objects.
  1461         Node* adr_x = phase->transform(new (C) AddPNode(base_x,base_x,address->in(AddPNode::Offset)));
  1462         x->set_req(Address, adr_x);
  1465     // Check for a 'win' on some paths
  1466     const Type *t = x->Value(igvn);
  1468     bool singleton = t->singleton();
  1470     // See comments in PhaseIdealLoop::split_thru_phi().
  1471     if (singleton && t == Type::TOP) {
  1472       singleton &= region->is_Loop() && (i != LoopNode::EntryControl);
  1475     if (singleton) {
  1476       x = igvn->makecon(t);
  1477     } else {
  1478       // We now call Identity to try to simplify the cloned node.
  1479       // Note that some Identity methods call phase->type(this).
  1480       // Make sure that the type array is big enough for
  1481       // our new node, even though we may throw the node away.
  1482       // (This tweaking with igvn only works because x is a new node.)
  1483       igvn->set_type(x, t);
  1484       // If x is a TypeNode, capture any more-precise type permanently into Node
  1485       // otherwise it will be not updated during igvn->transform since
  1486       // igvn->type(x) is set to x->Value() already.
  1487       x->raise_bottom_type(t);
  1488       Node *y = x->Identity(igvn);
  1489       if (y != x) {
  1490         x = y;
  1491       } else {
  1492         y = igvn->hash_find_insert(x);
  1493         if (y) {
  1494           x = y;
  1495         } else {
  1496           // Else x is a new node we are keeping
  1497           // We do not need register_new_node_with_optimizer
  1498           // because set_type has already been called.
  1499           igvn->_worklist.push(x);
  1503     if (x != the_clone && the_clone != NULL) {
  1504       igvn->remove_dead_node(the_clone);
  1506     phi->set_req(i, x);
  1508   // Record Phi
  1509   igvn->register_new_node_with_optimizer(phi);
  1510   return phi;
  1513 //------------------------------Ideal------------------------------------------
  1514 // If the load is from Field memory and the pointer is non-null, it might be possible to
  1515 // zero out the control input.
  1516 // If the offset is constant and the base is an object allocation,
  1517 // try to hook me up to the exact initializing store.
  1518 Node *LoadNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  1519   Node* p = MemNode::Ideal_common(phase, can_reshape);
  1520   if (p)  return (p == NodeSentinel) ? NULL : p;
  1522   Node* ctrl    = in(MemNode::Control);
  1523   Node* address = in(MemNode::Address);
  1525   bool addr_mark = ((phase->type(address)->isa_oopptr() || phase->type(address)->isa_narrowoop()) &&
  1526          phase->type(address)->is_ptr()->offset() == oopDesc::mark_offset_in_bytes());
  1528   // Skip up past a SafePoint control.  Cannot do this for Stores because
  1529   // pointer stores & cardmarks must stay on the same side of a SafePoint.
  1530   if( ctrl != NULL && ctrl->Opcode() == Op_SafePoint &&
  1531       phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw  &&
  1532       !addr_mark ) {
  1533     ctrl = ctrl->in(0);
  1534     set_req(MemNode::Control,ctrl);
  1537   intptr_t ignore = 0;
  1538   Node*    base   = AddPNode::Ideal_base_and_offset(address, phase, ignore);
  1539   if (base != NULL
  1540       && phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw) {
  1541     // Check for useless control edge in some common special cases
  1542     if (in(MemNode::Control) != NULL
  1543         && can_remove_control()
  1544         && phase->type(base)->higher_equal(TypePtr::NOTNULL)
  1545         && all_controls_dominate(base, phase->C->start())) {
  1546       // A method-invariant, non-null address (constant or 'this' argument).
  1547       set_req(MemNode::Control, NULL);
  1551   Node* mem = in(MemNode::Memory);
  1552   const TypePtr *addr_t = phase->type(address)->isa_ptr();
  1554   if (can_reshape && (addr_t != NULL)) {
  1555     // try to optimize our memory input
  1556     Node* opt_mem = MemNode::optimize_memory_chain(mem, addr_t, this, phase);
  1557     if (opt_mem != mem) {
  1558       set_req(MemNode::Memory, opt_mem);
  1559       if (phase->type( opt_mem ) == Type::TOP) return NULL;
  1560       return this;
  1562     const TypeOopPtr *t_oop = addr_t->isa_oopptr();
  1563     if ((t_oop != NULL) &&
  1564         (t_oop->is_known_instance_field() ||
  1565          t_oop->is_ptr_to_boxed_value())) {
  1566       PhaseIterGVN *igvn = phase->is_IterGVN();
  1567       if (igvn != NULL && igvn->_worklist.member(opt_mem)) {
  1568         // Delay this transformation until memory Phi is processed.
  1569         phase->is_IterGVN()->_worklist.push(this);
  1570         return NULL;
  1572       // Split instance field load through Phi.
  1573       Node* result = split_through_phi(phase);
  1574       if (result != NULL) return result;
  1576       if (t_oop->is_ptr_to_boxed_value()) {
  1577         Node* result = eliminate_autobox(phase);
  1578         if (result != NULL) return result;
  1583   // Check for prior store with a different base or offset; make Load
  1584   // independent.  Skip through any number of them.  Bail out if the stores
  1585   // are in an endless dead cycle and report no progress.  This is a key
  1586   // transform for Reflection.  However, if after skipping through the Stores
  1587   // we can't then fold up against a prior store do NOT do the transform as
  1588   // this amounts to using the 'Oracle' model of aliasing.  It leaves the same
  1589   // array memory alive twice: once for the hoisted Load and again after the
  1590   // bypassed Store.  This situation only works if EVERYBODY who does
  1591   // anti-dependence work knows how to bypass.  I.e. we need all
  1592   // anti-dependence checks to ask the same Oracle.  Right now, that Oracle is
  1593   // the alias index stuff.  So instead, peek through Stores and IFF we can
  1594   // fold up, do so.
  1595   Node* prev_mem = find_previous_store(phase);
  1596   // Steps (a), (b):  Walk past independent stores to find an exact match.
  1597   if (prev_mem != NULL && prev_mem != in(MemNode::Memory)) {
  1598     // (c) See if we can fold up on the spot, but don't fold up here.
  1599     // Fold-up might require truncation (for LoadB/LoadS/LoadUS) or
  1600     // just return a prior value, which is done by Identity calls.
  1601     if (can_see_stored_value(prev_mem, phase)) {
  1602       // Make ready for step (d):
  1603       set_req(MemNode::Memory, prev_mem);
  1604       return this;
  1608   return NULL;                  // No further progress
  1611 // Helper to recognize certain Klass fields which are invariant across
  1612 // some group of array types (e.g., int[] or all T[] where T < Object).
  1613 const Type*
  1614 LoadNode::load_array_final_field(const TypeKlassPtr *tkls,
  1615                                  ciKlass* klass) const {
  1616   if (tkls->offset() == in_bytes(Klass::modifier_flags_offset())) {
  1617     // The field is Klass::_modifier_flags.  Return its (constant) value.
  1618     // (Folds up the 2nd indirection in aClassConstant.getModifiers().)
  1619     assert(this->Opcode() == Op_LoadI, "must load an int from _modifier_flags");
  1620     return TypeInt::make(klass->modifier_flags());
  1622   if (tkls->offset() == in_bytes(Klass::access_flags_offset())) {
  1623     // The field is Klass::_access_flags.  Return its (constant) value.
  1624     // (Folds up the 2nd indirection in Reflection.getClassAccessFlags(aClassConstant).)
  1625     assert(this->Opcode() == Op_LoadI, "must load an int from _access_flags");
  1626     return TypeInt::make(klass->access_flags());
  1628   if (tkls->offset() == in_bytes(Klass::layout_helper_offset())) {
  1629     // The field is Klass::_layout_helper.  Return its constant value if known.
  1630     assert(this->Opcode() == Op_LoadI, "must load an int from _layout_helper");
  1631     return TypeInt::make(klass->layout_helper());
  1634   // No match.
  1635   return NULL;
  1638 // Try to constant-fold a stable array element.
  1639 static const Type* fold_stable_ary_elem(const TypeAryPtr* ary, int off, BasicType loadbt) {
  1640   assert(ary->const_oop(), "array should be constant");
  1641   assert(ary->is_stable(), "array should be stable");
  1643   // Decode the results of GraphKit::array_element_address.
  1644   ciArray* aobj = ary->const_oop()->as_array();
  1645   ciConstant con = aobj->element_value_by_offset(off);
  1647   if (con.basic_type() != T_ILLEGAL && !con.is_null_or_zero()) {
  1648     const Type* con_type = Type::make_from_constant(con);
  1649     if (con_type != NULL) {
  1650       if (con_type->isa_aryptr()) {
  1651         // Join with the array element type, in case it is also stable.
  1652         int dim = ary->stable_dimension();
  1653         con_type = con_type->is_aryptr()->cast_to_stable(true, dim-1);
  1655       if (loadbt == T_NARROWOOP && con_type->isa_oopptr()) {
  1656         con_type = con_type->make_narrowoop();
  1658 #ifndef PRODUCT
  1659       if (TraceIterativeGVN) {
  1660         tty->print("FoldStableValues: array element [off=%d]: con_type=", off);
  1661         con_type->dump(); tty->cr();
  1663 #endif //PRODUCT
  1664       return con_type;
  1667   return NULL;
  1670 //------------------------------Value-----------------------------------------
  1671 const Type *LoadNode::Value( PhaseTransform *phase ) const {
  1672   // Either input is TOP ==> the result is TOP
  1673   Node* mem = in(MemNode::Memory);
  1674   const Type *t1 = phase->type(mem);
  1675   if (t1 == Type::TOP)  return Type::TOP;
  1676   Node* adr = in(MemNode::Address);
  1677   const TypePtr* tp = phase->type(adr)->isa_ptr();
  1678   if (tp == NULL || tp->empty())  return Type::TOP;
  1679   int off = tp->offset();
  1680   assert(off != Type::OffsetTop, "case covered by TypePtr::empty");
  1681   Compile* C = phase->C;
  1683   // Try to guess loaded type from pointer type
  1684   if (tp->isa_aryptr()) {
  1685     const TypeAryPtr* ary = tp->is_aryptr();
  1686     const Type* t = ary->elem();
  1688     // Determine whether the reference is beyond the header or not, by comparing
  1689     // the offset against the offset of the start of the array's data.
  1690     // Different array types begin at slightly different offsets (12 vs. 16).
  1691     // We choose T_BYTE as an example base type that is least restrictive
  1692     // as to alignment, which will therefore produce the smallest
  1693     // possible base offset.
  1694     const int min_base_off = arrayOopDesc::base_offset_in_bytes(T_BYTE);
  1695     const bool off_beyond_header = ((uint)off >= (uint)min_base_off);
  1697     // Try to constant-fold a stable array element.
  1698     if (FoldStableValues && ary->is_stable() && ary->const_oop() != NULL) {
  1699       // Make sure the reference is not into the header and the offset is constant
  1700       if (off_beyond_header && adr->is_AddP() && off != Type::OffsetBot) {
  1701         const Type* con_type = fold_stable_ary_elem(ary, off, memory_type());
  1702         if (con_type != NULL) {
  1703           return con_type;
  1708     // Don't do this for integer types. There is only potential profit if
  1709     // the element type t is lower than _type; that is, for int types, if _type is
  1710     // more restrictive than t.  This only happens here if one is short and the other
  1711     // char (both 16 bits), and in those cases we've made an intentional decision
  1712     // to use one kind of load over the other. See AndINode::Ideal and 4965907.
  1713     // Also, do not try to narrow the type for a LoadKlass, regardless of offset.
  1714     //
  1715     // Yes, it is possible to encounter an expression like (LoadKlass p1:(AddP x x 8))
  1716     // where the _gvn.type of the AddP is wider than 8.  This occurs when an earlier
  1717     // copy p0 of (AddP x x 8) has been proven equal to p1, and the p0 has been
  1718     // subsumed by p1.  If p1 is on the worklist but has not yet been re-transformed,
  1719     // it is possible that p1 will have a type like Foo*[int+]:NotNull*+any.
  1720     // In fact, that could have been the original type of p1, and p1 could have
  1721     // had an original form like p1:(AddP x x (LShiftL quux 3)), where the
  1722     // expression (LShiftL quux 3) independently optimized to the constant 8.
  1723     if ((t->isa_int() == NULL) && (t->isa_long() == NULL)
  1724         && (_type->isa_vect() == NULL)
  1725         && Opcode() != Op_LoadKlass && Opcode() != Op_LoadNKlass) {
  1726       // t might actually be lower than _type, if _type is a unique
  1727       // concrete subclass of abstract class t.
  1728       if (off_beyond_header) {  // is the offset beyond the header?
  1729         const Type* jt = t->join_speculative(_type);
  1730         // In any case, do not allow the join, per se, to empty out the type.
  1731         if (jt->empty() && !t->empty()) {
  1732           // This can happen if a interface-typed array narrows to a class type.
  1733           jt = _type;
  1735 #ifdef ASSERT
  1736         if (phase->C->eliminate_boxing() && adr->is_AddP()) {
  1737           // The pointers in the autobox arrays are always non-null
  1738           Node* base = adr->in(AddPNode::Base);
  1739           if ((base != NULL) && base->is_DecodeN()) {
  1740             // Get LoadN node which loads IntegerCache.cache field
  1741             base = base->in(1);
  1743           if ((base != NULL) && base->is_Con()) {
  1744             const TypeAryPtr* base_type = base->bottom_type()->isa_aryptr();
  1745             if ((base_type != NULL) && base_type->is_autobox_cache()) {
  1746               // It could be narrow oop
  1747               assert(jt->make_ptr()->ptr() == TypePtr::NotNull,"sanity");
  1751 #endif
  1752         return jt;
  1755   } else if (tp->base() == Type::InstPtr) {
  1756     ciEnv* env = C->env();
  1757     const TypeInstPtr* tinst = tp->is_instptr();
  1758     ciKlass* klass = tinst->klass();
  1759     assert( off != Type::OffsetBot ||
  1760             // arrays can be cast to Objects
  1761             tp->is_oopptr()->klass()->is_java_lang_Object() ||
  1762             // unsafe field access may not have a constant offset
  1763             C->has_unsafe_access(),
  1764             "Field accesses must be precise" );
  1765     // For oop loads, we expect the _type to be precise
  1766     if (klass == env->String_klass() &&
  1767         adr->is_AddP() && off != Type::OffsetBot) {
  1768       // For constant Strings treat the final fields as compile time constants.
  1769       Node* base = adr->in(AddPNode::Base);
  1770       const TypeOopPtr* t = phase->type(base)->isa_oopptr();
  1771       if (t != NULL && t->singleton()) {
  1772         ciField* field = env->String_klass()->get_field_by_offset(off, false);
  1773         if (field != NULL && field->is_final()) {
  1774           ciObject* string = t->const_oop();
  1775           ciConstant constant = string->as_instance()->field_value(field);
  1776           if (constant.basic_type() == T_INT) {
  1777             return TypeInt::make(constant.as_int());
  1778           } else if (constant.basic_type() == T_ARRAY) {
  1779             if (adr->bottom_type()->is_ptr_to_narrowoop()) {
  1780               return TypeNarrowOop::make_from_constant(constant.as_object(), true);
  1781             } else {
  1782               return TypeOopPtr::make_from_constant(constant.as_object(), true);
  1788     // Optimizations for constant objects
  1789     ciObject* const_oop = tinst->const_oop();
  1790     if (const_oop != NULL) {
  1791       // For constant Boxed value treat the target field as a compile time constant.
  1792       if (tinst->is_ptr_to_boxed_value()) {
  1793         return tinst->get_const_boxed_value();
  1794       } else
  1795       // For constant CallSites treat the target field as a compile time constant.
  1796       if (const_oop->is_call_site()) {
  1797         ciCallSite* call_site = const_oop->as_call_site();
  1798         ciField* field = call_site->klass()->as_instance_klass()->get_field_by_offset(off, /*is_static=*/ false);
  1799         if (field != NULL && field->is_call_site_target()) {
  1800           ciMethodHandle* target = call_site->get_target();
  1801           if (target != NULL) {  // just in case
  1802             ciConstant constant(T_OBJECT, target);
  1803             const Type* t;
  1804             if (adr->bottom_type()->is_ptr_to_narrowoop()) {
  1805               t = TypeNarrowOop::make_from_constant(constant.as_object(), true);
  1806             } else {
  1807               t = TypeOopPtr::make_from_constant(constant.as_object(), true);
  1809             // Add a dependence for invalidation of the optimization.
  1810             if (!call_site->is_constant_call_site()) {
  1811               C->dependencies()->assert_call_site_target_value(call_site, target);
  1813             return t;
  1818   } else if (tp->base() == Type::KlassPtr) {
  1819     assert( off != Type::OffsetBot ||
  1820             // arrays can be cast to Objects
  1821             tp->is_klassptr()->klass()->is_java_lang_Object() ||
  1822             // also allow array-loading from the primary supertype
  1823             // array during subtype checks
  1824             Opcode() == Op_LoadKlass,
  1825             "Field accesses must be precise" );
  1826     // For klass/static loads, we expect the _type to be precise
  1829   const TypeKlassPtr *tkls = tp->isa_klassptr();
  1830   if (tkls != NULL && !StressReflectiveCode) {
  1831     ciKlass* klass = tkls->klass();
  1832     if (klass->is_loaded() && tkls->klass_is_exact()) {
  1833       // We are loading a field from a Klass metaobject whose identity
  1834       // is known at compile time (the type is "exact" or "precise").
  1835       // Check for fields we know are maintained as constants by the VM.
  1836       if (tkls->offset() == in_bytes(Klass::super_check_offset_offset())) {
  1837         // The field is Klass::_super_check_offset.  Return its (constant) value.
  1838         // (Folds up type checking code.)
  1839         assert(Opcode() == Op_LoadI, "must load an int from _super_check_offset");
  1840         return TypeInt::make(klass->super_check_offset());
  1842       // Compute index into primary_supers array
  1843       juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
  1844       // Check for overflowing; use unsigned compare to handle the negative case.
  1845       if( depth < ciKlass::primary_super_limit() ) {
  1846         // The field is an element of Klass::_primary_supers.  Return its (constant) value.
  1847         // (Folds up type checking code.)
  1848         assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
  1849         ciKlass *ss = klass->super_of_depth(depth);
  1850         return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
  1852       const Type* aift = load_array_final_field(tkls, klass);
  1853       if (aift != NULL)  return aift;
  1854       if (tkls->offset() == in_bytes(ArrayKlass::component_mirror_offset())
  1855           && klass->is_array_klass()) {
  1856         // The field is ArrayKlass::_component_mirror.  Return its (constant) value.
  1857         // (Folds up aClassConstant.getComponentType, common in Arrays.copyOf.)
  1858         assert(Opcode() == Op_LoadP, "must load an oop from _component_mirror");
  1859         return TypeInstPtr::make(klass->as_array_klass()->component_mirror());
  1861       if (tkls->offset() == in_bytes(Klass::java_mirror_offset())) {
  1862         // The field is Klass::_java_mirror.  Return its (constant) value.
  1863         // (Folds up the 2nd indirection in anObjConstant.getClass().)
  1864         assert(Opcode() == Op_LoadP, "must load an oop from _java_mirror");
  1865         return TypeInstPtr::make(klass->java_mirror());
  1869     // We can still check if we are loading from the primary_supers array at a
  1870     // shallow enough depth.  Even though the klass is not exact, entries less
  1871     // than or equal to its super depth are correct.
  1872     if (klass->is_loaded() ) {
  1873       ciType *inner = klass;
  1874       while( inner->is_obj_array_klass() )
  1875         inner = inner->as_obj_array_klass()->base_element_type();
  1876       if( inner->is_instance_klass() &&
  1877           !inner->as_instance_klass()->flags().is_interface() ) {
  1878         // Compute index into primary_supers array
  1879         juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
  1880         // Check for overflowing; use unsigned compare to handle the negative case.
  1881         if( depth < ciKlass::primary_super_limit() &&
  1882             depth <= klass->super_depth() ) { // allow self-depth checks to handle self-check case
  1883           // The field is an element of Klass::_primary_supers.  Return its (constant) value.
  1884           // (Folds up type checking code.)
  1885           assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
  1886           ciKlass *ss = klass->super_of_depth(depth);
  1887           return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
  1892     // If the type is enough to determine that the thing is not an array,
  1893     // we can give the layout_helper a positive interval type.
  1894     // This will help short-circuit some reflective code.
  1895     if (tkls->offset() == in_bytes(Klass::layout_helper_offset())
  1896         && !klass->is_array_klass() // not directly typed as an array
  1897         && !klass->is_interface()  // specifically not Serializable & Cloneable
  1898         && !klass->is_java_lang_Object()   // not the supertype of all T[]
  1899         ) {
  1900       // Note:  When interfaces are reliable, we can narrow the interface
  1901       // test to (klass != Serializable && klass != Cloneable).
  1902       assert(Opcode() == Op_LoadI, "must load an int from _layout_helper");
  1903       jint min_size = Klass::instance_layout_helper(oopDesc::header_size(), false);
  1904       // The key property of this type is that it folds up tests
  1905       // for array-ness, since it proves that the layout_helper is positive.
  1906       // Thus, a generic value like the basic object layout helper works fine.
  1907       return TypeInt::make(min_size, max_jint, Type::WidenMin);
  1911   // If we are loading from a freshly-allocated object, produce a zero,
  1912   // if the load is provably beyond the header of the object.
  1913   // (Also allow a variable load from a fresh array to produce zero.)
  1914   const TypeOopPtr *tinst = tp->isa_oopptr();
  1915   bool is_instance = (tinst != NULL) && tinst->is_known_instance_field();
  1916   bool is_boxed_value = (tinst != NULL) && tinst->is_ptr_to_boxed_value();
  1917   if (ReduceFieldZeroing || is_instance || is_boxed_value) {
  1918     Node* value = can_see_stored_value(mem,phase);
  1919     if (value != NULL && value->is_Con()) {
  1920       assert(value->bottom_type()->higher_equal(_type),"sanity");
  1921       return value->bottom_type();
  1925   if (is_instance) {
  1926     // If we have an instance type and our memory input is the
  1927     // programs's initial memory state, there is no matching store,
  1928     // so just return a zero of the appropriate type
  1929     Node *mem = in(MemNode::Memory);
  1930     if (mem->is_Parm() && mem->in(0)->is_Start()) {
  1931       assert(mem->as_Parm()->_con == TypeFunc::Memory, "must be memory Parm");
  1932       return Type::get_zero_type(_type->basic_type());
  1935   return _type;
  1938 //------------------------------match_edge-------------------------------------
  1939 // Do we Match on this edge index or not?  Match only the address.
  1940 uint LoadNode::match_edge(uint idx) const {
  1941   return idx == MemNode::Address;
  1944 //--------------------------LoadBNode::Ideal--------------------------------------
  1945 //
  1946 //  If the previous store is to the same address as this load,
  1947 //  and the value stored was larger than a byte, replace this load
  1948 //  with the value stored truncated to a byte.  If no truncation is
  1949 //  needed, the replacement is done in LoadNode::Identity().
  1950 //
  1951 Node *LoadBNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  1952   Node* mem = in(MemNode::Memory);
  1953   Node* value = can_see_stored_value(mem,phase);
  1954   if( value && !phase->type(value)->higher_equal( _type ) ) {
  1955     Node *result = phase->transform( new (phase->C) LShiftINode(value, phase->intcon(24)) );
  1956     return new (phase->C) RShiftINode(result, phase->intcon(24));
  1958   // Identity call will handle the case where truncation is not needed.
  1959   return LoadNode::Ideal(phase, can_reshape);
  1962 const Type* LoadBNode::Value(PhaseTransform *phase) const {
  1963   Node* mem = in(MemNode::Memory);
  1964   Node* value = can_see_stored_value(mem,phase);
  1965   if (value != NULL && value->is_Con() &&
  1966       !value->bottom_type()->higher_equal(_type)) {
  1967     // If the input to the store does not fit with the load's result type,
  1968     // it must be truncated. We can't delay until Ideal call since
  1969     // a singleton Value is needed for split_thru_phi optimization.
  1970     int con = value->get_int();
  1971     return TypeInt::make((con << 24) >> 24);
  1973   return LoadNode::Value(phase);
  1976 //--------------------------LoadUBNode::Ideal-------------------------------------
  1977 //
  1978 //  If the previous store is to the same address as this load,
  1979 //  and the value stored was larger than a byte, replace this load
  1980 //  with the value stored truncated to a byte.  If no truncation is
  1981 //  needed, the replacement is done in LoadNode::Identity().
  1982 //
  1983 Node* LoadUBNode::Ideal(PhaseGVN* phase, bool can_reshape) {
  1984   Node* mem = in(MemNode::Memory);
  1985   Node* value = can_see_stored_value(mem, phase);
  1986   if (value && !phase->type(value)->higher_equal(_type))
  1987     return new (phase->C) AndINode(value, phase->intcon(0xFF));
  1988   // Identity call will handle the case where truncation is not needed.
  1989   return LoadNode::Ideal(phase, can_reshape);
  1992 const Type* LoadUBNode::Value(PhaseTransform *phase) const {
  1993   Node* mem = in(MemNode::Memory);
  1994   Node* value = can_see_stored_value(mem,phase);
  1995   if (value != NULL && value->is_Con() &&
  1996       !value->bottom_type()->higher_equal(_type)) {
  1997     // If the input to the store does not fit with the load's result type,
  1998     // it must be truncated. We can't delay until Ideal call since
  1999     // a singleton Value is needed for split_thru_phi optimization.
  2000     int con = value->get_int();
  2001     return TypeInt::make(con & 0xFF);
  2003   return LoadNode::Value(phase);
  2006 //--------------------------LoadUSNode::Ideal-------------------------------------
  2007 //
  2008 //  If the previous store is to the same address as this load,
  2009 //  and the value stored was larger than a char, replace this load
  2010 //  with the value stored truncated to a char.  If no truncation is
  2011 //  needed, the replacement is done in LoadNode::Identity().
  2012 //
  2013 Node *LoadUSNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  2014   Node* mem = in(MemNode::Memory);
  2015   Node* value = can_see_stored_value(mem,phase);
  2016   if( value && !phase->type(value)->higher_equal( _type ) )
  2017     return new (phase->C) AndINode(value,phase->intcon(0xFFFF));
  2018   // Identity call will handle the case where truncation is not needed.
  2019   return LoadNode::Ideal(phase, can_reshape);
  2022 const Type* LoadUSNode::Value(PhaseTransform *phase) const {
  2023   Node* mem = in(MemNode::Memory);
  2024   Node* value = can_see_stored_value(mem,phase);
  2025   if (value != NULL && value->is_Con() &&
  2026       !value->bottom_type()->higher_equal(_type)) {
  2027     // If the input to the store does not fit with the load's result type,
  2028     // it must be truncated. We can't delay until Ideal call since
  2029     // a singleton Value is needed for split_thru_phi optimization.
  2030     int con = value->get_int();
  2031     return TypeInt::make(con & 0xFFFF);
  2033   return LoadNode::Value(phase);
  2036 //--------------------------LoadSNode::Ideal--------------------------------------
  2037 //
  2038 //  If the previous store is to the same address as this load,
  2039 //  and the value stored was larger than a short, replace this load
  2040 //  with the value stored truncated to a short.  If no truncation is
  2041 //  needed, the replacement is done in LoadNode::Identity().
  2042 //
  2043 Node *LoadSNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  2044   Node* mem = in(MemNode::Memory);
  2045   Node* value = can_see_stored_value(mem,phase);
  2046   if( value && !phase->type(value)->higher_equal( _type ) ) {
  2047     Node *result = phase->transform( new (phase->C) LShiftINode(value, phase->intcon(16)) );
  2048     return new (phase->C) RShiftINode(result, phase->intcon(16));
  2050   // Identity call will handle the case where truncation is not needed.
  2051   return LoadNode::Ideal(phase, can_reshape);
  2054 const Type* LoadSNode::Value(PhaseTransform *phase) const {
  2055   Node* mem = in(MemNode::Memory);
  2056   Node* value = can_see_stored_value(mem,phase);
  2057   if (value != NULL && value->is_Con() &&
  2058       !value->bottom_type()->higher_equal(_type)) {
  2059     // If the input to the store does not fit with the load's result type,
  2060     // it must be truncated. We can't delay until Ideal call since
  2061     // a singleton Value is needed for split_thru_phi optimization.
  2062     int con = value->get_int();
  2063     return TypeInt::make((con << 16) >> 16);
  2065   return LoadNode::Value(phase);
  2068 //=============================================================================
  2069 //----------------------------LoadKlassNode::make------------------------------
  2070 // Polymorphic factory method:
  2071 Node* LoadKlassNode::make(PhaseGVN& gvn, Node* ctl, Node *mem, Node *adr, const TypePtr* at, const TypeKlassPtr *tk) {
  2072   Compile* C = gvn.C;
  2073   // sanity check the alias category against the created node type
  2074   const TypePtr *adr_type = adr->bottom_type()->isa_ptr();
  2075   assert(adr_type != NULL, "expecting TypeKlassPtr");
  2076 #ifdef _LP64
  2077   if (adr_type->is_ptr_to_narrowklass()) {
  2078     assert(UseCompressedClassPointers, "no compressed klasses");
  2079     Node* load_klass = gvn.transform(new (C) LoadNKlassNode(ctl, mem, adr, at, tk->make_narrowklass(), MemNode::unordered));
  2080     return new (C) DecodeNKlassNode(load_klass, load_klass->bottom_type()->make_ptr());
  2082 #endif
  2083   assert(!adr_type->is_ptr_to_narrowklass() && !adr_type->is_ptr_to_narrowoop(), "should have got back a narrow oop");
  2084   return new (C) LoadKlassNode(ctl, mem, adr, at, tk, MemNode::unordered);
  2087 //------------------------------Value------------------------------------------
  2088 const Type *LoadKlassNode::Value( PhaseTransform *phase ) const {
  2089   return klass_value_common(phase);
  2092 // In most cases, LoadKlassNode does not have the control input set. If the control
  2093 // input is set, it must not be removed (by LoadNode::Ideal()).
  2094 bool LoadKlassNode::can_remove_control() const {
  2095   return false;
  2098 const Type *LoadNode::klass_value_common( PhaseTransform *phase ) const {
  2099   // Either input is TOP ==> the result is TOP
  2100   const Type *t1 = phase->type( in(MemNode::Memory) );
  2101   if (t1 == Type::TOP)  return Type::TOP;
  2102   Node *adr = in(MemNode::Address);
  2103   const Type *t2 = phase->type( adr );
  2104   if (t2 == Type::TOP)  return Type::TOP;
  2105   const TypePtr *tp = t2->is_ptr();
  2106   if (TypePtr::above_centerline(tp->ptr()) ||
  2107       tp->ptr() == TypePtr::Null)  return Type::TOP;
  2109   // Return a more precise klass, if possible
  2110   const TypeInstPtr *tinst = tp->isa_instptr();
  2111   if (tinst != NULL) {
  2112     ciInstanceKlass* ik = tinst->klass()->as_instance_klass();
  2113     int offset = tinst->offset();
  2114     if (ik == phase->C->env()->Class_klass()
  2115         && (offset == java_lang_Class::klass_offset_in_bytes() ||
  2116             offset == java_lang_Class::array_klass_offset_in_bytes())) {
  2117       // We are loading a special hidden field from a Class mirror object,
  2118       // the field which points to the VM's Klass metaobject.
  2119       ciType* t = tinst->java_mirror_type();
  2120       // java_mirror_type returns non-null for compile-time Class constants.
  2121       if (t != NULL) {
  2122         // constant oop => constant klass
  2123         if (offset == java_lang_Class::array_klass_offset_in_bytes()) {
  2124           if (t->is_void()) {
  2125             // We cannot create a void array.  Since void is a primitive type return null
  2126             // klass.  Users of this result need to do a null check on the returned klass.
  2127             return TypePtr::NULL_PTR;
  2129           return TypeKlassPtr::make(ciArrayKlass::make(t));
  2131         if (!t->is_klass()) {
  2132           // a primitive Class (e.g., int.class) has NULL for a klass field
  2133           return TypePtr::NULL_PTR;
  2135         // (Folds up the 1st indirection in aClassConstant.getModifiers().)
  2136         return TypeKlassPtr::make(t->as_klass());
  2138       // non-constant mirror, so we can't tell what's going on
  2140     if( !ik->is_loaded() )
  2141       return _type;             // Bail out if not loaded
  2142     if (offset == oopDesc::klass_offset_in_bytes()) {
  2143       if (tinst->klass_is_exact()) {
  2144         return TypeKlassPtr::make(ik);
  2146       // See if we can become precise: no subklasses and no interface
  2147       // (Note:  We need to support verified interfaces.)
  2148       if (!ik->is_interface() && !ik->has_subklass()) {
  2149         //assert(!UseExactTypes, "this code should be useless with exact types");
  2150         // Add a dependence; if any subclass added we need to recompile
  2151         if (!ik->is_final()) {
  2152           // %%% should use stronger assert_unique_concrete_subtype instead
  2153           phase->C->dependencies()->assert_leaf_type(ik);
  2155         // Return precise klass
  2156         return TypeKlassPtr::make(ik);
  2159       // Return root of possible klass
  2160       return TypeKlassPtr::make(TypePtr::NotNull, ik, 0/*offset*/);
  2164   // Check for loading klass from an array
  2165   const TypeAryPtr *tary = tp->isa_aryptr();
  2166   if( tary != NULL ) {
  2167     ciKlass *tary_klass = tary->klass();
  2168     if (tary_klass != NULL   // can be NULL when at BOTTOM or TOP
  2169         && tary->offset() == oopDesc::klass_offset_in_bytes()) {
  2170       if (tary->klass_is_exact()) {
  2171         return TypeKlassPtr::make(tary_klass);
  2173       ciArrayKlass *ak = tary->klass()->as_array_klass();
  2174       // If the klass is an object array, we defer the question to the
  2175       // array component klass.
  2176       if( ak->is_obj_array_klass() ) {
  2177         assert( ak->is_loaded(), "" );
  2178         ciKlass *base_k = ak->as_obj_array_klass()->base_element_klass();
  2179         if( base_k->is_loaded() && base_k->is_instance_klass() ) {
  2180           ciInstanceKlass* ik = base_k->as_instance_klass();
  2181           // See if we can become precise: no subklasses and no interface
  2182           if (!ik->is_interface() && !ik->has_subklass()) {
  2183             //assert(!UseExactTypes, "this code should be useless with exact types");
  2184             // Add a dependence; if any subclass added we need to recompile
  2185             if (!ik->is_final()) {
  2186               phase->C->dependencies()->assert_leaf_type(ik);
  2188             // Return precise array klass
  2189             return TypeKlassPtr::make(ak);
  2192         return TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
  2193       } else {                  // Found a type-array?
  2194         //assert(!UseExactTypes, "this code should be useless with exact types");
  2195         assert( ak->is_type_array_klass(), "" );
  2196         return TypeKlassPtr::make(ak); // These are always precise
  2201   // Check for loading klass from an array klass
  2202   const TypeKlassPtr *tkls = tp->isa_klassptr();
  2203   if (tkls != NULL && !StressReflectiveCode) {
  2204     ciKlass* klass = tkls->klass();
  2205     if( !klass->is_loaded() )
  2206       return _type;             // Bail out if not loaded
  2207     if( klass->is_obj_array_klass() &&
  2208         tkls->offset() == in_bytes(ObjArrayKlass::element_klass_offset())) {
  2209       ciKlass* elem = klass->as_obj_array_klass()->element_klass();
  2210       // // Always returning precise element type is incorrect,
  2211       // // e.g., element type could be object and array may contain strings
  2212       // return TypeKlassPtr::make(TypePtr::Constant, elem, 0);
  2214       // The array's TypeKlassPtr was declared 'precise' or 'not precise'
  2215       // according to the element type's subclassing.
  2216       return TypeKlassPtr::make(tkls->ptr(), elem, 0/*offset*/);
  2218     if( klass->is_instance_klass() && tkls->klass_is_exact() &&
  2219         tkls->offset() == in_bytes(Klass::super_offset())) {
  2220       ciKlass* sup = klass->as_instance_klass()->super();
  2221       // The field is Klass::_super.  Return its (constant) value.
  2222       // (Folds up the 2nd indirection in aClassConstant.getSuperClass().)
  2223       return sup ? TypeKlassPtr::make(sup) : TypePtr::NULL_PTR;
  2227   // Bailout case
  2228   return LoadNode::Value(phase);
  2231 //------------------------------Identity---------------------------------------
  2232 // To clean up reflective code, simplify k.java_mirror.as_klass to plain k.
  2233 // Also feed through the klass in Allocate(...klass...)._klass.
  2234 Node* LoadKlassNode::Identity( PhaseTransform *phase ) {
  2235   return klass_identity_common(phase);
  2238 Node* LoadNode::klass_identity_common(PhaseTransform *phase ) {
  2239   Node* x = LoadNode::Identity(phase);
  2240   if (x != this)  return x;
  2242   // Take apart the address into an oop and and offset.
  2243   // Return 'this' if we cannot.
  2244   Node*    adr    = in(MemNode::Address);
  2245   intptr_t offset = 0;
  2246   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
  2247   if (base == NULL)     return this;
  2248   const TypeOopPtr* toop = phase->type(adr)->isa_oopptr();
  2249   if (toop == NULL)     return this;
  2251   // We can fetch the klass directly through an AllocateNode.
  2252   // This works even if the klass is not constant (clone or newArray).
  2253   if (offset == oopDesc::klass_offset_in_bytes()) {
  2254     Node* allocated_klass = AllocateNode::Ideal_klass(base, phase);
  2255     if (allocated_klass != NULL) {
  2256       return allocated_klass;
  2260   // Simplify k.java_mirror.as_klass to plain k, where k is a Klass*.
  2261   // Simplify ak.component_mirror.array_klass to plain ak, ak an ArrayKlass.
  2262   // See inline_native_Class_query for occurrences of these patterns.
  2263   // Java Example:  x.getClass().isAssignableFrom(y)
  2264   // Java Example:  Array.newInstance(x.getClass().getComponentType(), n)
  2265   //
  2266   // This improves reflective code, often making the Class
  2267   // mirror go completely dead.  (Current exception:  Class
  2268   // mirrors may appear in debug info, but we could clean them out by
  2269   // introducing a new debug info operator for Klass*.java_mirror).
  2270   if (toop->isa_instptr() && toop->klass() == phase->C->env()->Class_klass()
  2271       && (offset == java_lang_Class::klass_offset_in_bytes() ||
  2272           offset == java_lang_Class::array_klass_offset_in_bytes())) {
  2273     // We are loading a special hidden field from a Class mirror,
  2274     // the field which points to its Klass or ArrayKlass metaobject.
  2275     if (base->is_Load()) {
  2276       Node* adr2 = base->in(MemNode::Address);
  2277       const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
  2278       if (tkls != NULL && !tkls->empty()
  2279           && (tkls->klass()->is_instance_klass() ||
  2280               tkls->klass()->is_array_klass())
  2281           && adr2->is_AddP()
  2282           ) {
  2283         int mirror_field = in_bytes(Klass::java_mirror_offset());
  2284         if (offset == java_lang_Class::array_klass_offset_in_bytes()) {
  2285           mirror_field = in_bytes(ArrayKlass::component_mirror_offset());
  2287         if (tkls->offset() == mirror_field) {
  2288           return adr2->in(AddPNode::Base);
  2294   return this;
  2298 //------------------------------Value------------------------------------------
  2299 const Type *LoadNKlassNode::Value( PhaseTransform *phase ) const {
  2300   const Type *t = klass_value_common(phase);
  2301   if (t == Type::TOP)
  2302     return t;
  2304   return t->make_narrowklass();
  2307 //------------------------------Identity---------------------------------------
  2308 // To clean up reflective code, simplify k.java_mirror.as_klass to narrow k.
  2309 // Also feed through the klass in Allocate(...klass...)._klass.
  2310 Node* LoadNKlassNode::Identity( PhaseTransform *phase ) {
  2311   Node *x = klass_identity_common(phase);
  2313   const Type *t = phase->type( x );
  2314   if( t == Type::TOP ) return x;
  2315   if( t->isa_narrowklass()) return x;
  2316   assert (!t->isa_narrowoop(), "no narrow oop here");
  2318   return phase->transform(new (phase->C) EncodePKlassNode(x, t->make_narrowklass()));
  2321 //------------------------------Value-----------------------------------------
  2322 const Type *LoadRangeNode::Value( PhaseTransform *phase ) const {
  2323   // Either input is TOP ==> the result is TOP
  2324   const Type *t1 = phase->type( in(MemNode::Memory) );
  2325   if( t1 == Type::TOP ) return Type::TOP;
  2326   Node *adr = in(MemNode::Address);
  2327   const Type *t2 = phase->type( adr );
  2328   if( t2 == Type::TOP ) return Type::TOP;
  2329   const TypePtr *tp = t2->is_ptr();
  2330   if (TypePtr::above_centerline(tp->ptr()))  return Type::TOP;
  2331   const TypeAryPtr *tap = tp->isa_aryptr();
  2332   if( !tap ) return _type;
  2333   return tap->size();
  2336 //-------------------------------Ideal---------------------------------------
  2337 // Feed through the length in AllocateArray(...length...)._length.
  2338 Node *LoadRangeNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  2339   Node* p = MemNode::Ideal_common(phase, can_reshape);
  2340   if (p)  return (p == NodeSentinel) ? NULL : p;
  2342   // Take apart the address into an oop and and offset.
  2343   // Return 'this' if we cannot.
  2344   Node*    adr    = in(MemNode::Address);
  2345   intptr_t offset = 0;
  2346   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase,  offset);
  2347   if (base == NULL)     return NULL;
  2348   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
  2349   if (tary == NULL)     return NULL;
  2351   // We can fetch the length directly through an AllocateArrayNode.
  2352   // This works even if the length is not constant (clone or newArray).
  2353   if (offset == arrayOopDesc::length_offset_in_bytes()) {
  2354     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
  2355     if (alloc != NULL) {
  2356       Node* allocated_length = alloc->Ideal_length();
  2357       Node* len = alloc->make_ideal_length(tary, phase);
  2358       if (allocated_length != len) {
  2359         // New CastII improves on this.
  2360         return len;
  2365   return NULL;
  2368 //------------------------------Identity---------------------------------------
  2369 // Feed through the length in AllocateArray(...length...)._length.
  2370 Node* LoadRangeNode::Identity( PhaseTransform *phase ) {
  2371   Node* x = LoadINode::Identity(phase);
  2372   if (x != this)  return x;
  2374   // Take apart the address into an oop and and offset.
  2375   // Return 'this' if we cannot.
  2376   Node*    adr    = in(MemNode::Address);
  2377   intptr_t offset = 0;
  2378   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
  2379   if (base == NULL)     return this;
  2380   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
  2381   if (tary == NULL)     return this;
  2383   // We can fetch the length directly through an AllocateArrayNode.
  2384   // This works even if the length is not constant (clone or newArray).
  2385   if (offset == arrayOopDesc::length_offset_in_bytes()) {
  2386     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
  2387     if (alloc != NULL) {
  2388       Node* allocated_length = alloc->Ideal_length();
  2389       // Do not allow make_ideal_length to allocate a CastII node.
  2390       Node* len = alloc->make_ideal_length(tary, phase, false);
  2391       if (allocated_length == len) {
  2392         // Return allocated_length only if it would not be improved by a CastII.
  2393         return allocated_length;
  2398   return this;
  2402 //=============================================================================
  2403 //---------------------------StoreNode::make-----------------------------------
  2404 // Polymorphic factory method:
  2405 StoreNode* StoreNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, BasicType bt, MemOrd mo) {
  2406   assert((mo == unordered || mo == release), "unexpected");
  2407   Compile* C = gvn.C;
  2408   assert(C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
  2409          ctl != NULL, "raw memory operations should have control edge");
  2411   switch (bt) {
  2412   case T_BOOLEAN: val = gvn.transform(new (C) AndINode(val, gvn.intcon(0x1))); // Fall through to T_BYTE case
  2413   case T_BYTE:    return new (C) StoreBNode(ctl, mem, adr, adr_type, val, mo);
  2414   case T_INT:     return new (C) StoreINode(ctl, mem, adr, adr_type, val, mo);
  2415   case T_CHAR:
  2416   case T_SHORT:   return new (C) StoreCNode(ctl, mem, adr, adr_type, val, mo);
  2417   case T_LONG:    return new (C) StoreLNode(ctl, mem, adr, adr_type, val, mo);
  2418   case T_FLOAT:   return new (C) StoreFNode(ctl, mem, adr, adr_type, val, mo);
  2419   case T_DOUBLE:  return new (C) StoreDNode(ctl, mem, adr, adr_type, val, mo);
  2420   case T_METADATA:
  2421   case T_ADDRESS:
  2422   case T_OBJECT:
  2423 #ifdef _LP64
  2424     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
  2425       val = gvn.transform(new (C) EncodePNode(val, val->bottom_type()->make_narrowoop()));
  2426       return new (C) StoreNNode(ctl, mem, adr, adr_type, val, mo);
  2427     } else if (adr->bottom_type()->is_ptr_to_narrowklass() ||
  2428                (UseCompressedClassPointers && val->bottom_type()->isa_klassptr() &&
  2429                 adr->bottom_type()->isa_rawptr())) {
  2430       val = gvn.transform(new (C) EncodePKlassNode(val, val->bottom_type()->make_narrowklass()));
  2431       return new (C) StoreNKlassNode(ctl, mem, adr, adr_type, val, mo);
  2433 #endif
  2435       return new (C) StorePNode(ctl, mem, adr, adr_type, val, mo);
  2438   ShouldNotReachHere();
  2439   return (StoreNode*)NULL;
  2442 StoreLNode* StoreLNode::make_atomic(Compile *C, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, MemOrd mo) {
  2443   bool require_atomic = true;
  2444   return new (C) StoreLNode(ctl, mem, adr, adr_type, val, mo, require_atomic);
  2447 StoreDNode* StoreDNode::make_atomic(Compile *C, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, MemOrd mo) {
  2448   bool require_atomic = true;
  2449   return new (C) StoreDNode(ctl, mem, adr, adr_type, val, mo, require_atomic);
  2453 //--------------------------bottom_type----------------------------------------
  2454 const Type *StoreNode::bottom_type() const {
  2455   return Type::MEMORY;
  2458 //------------------------------hash-------------------------------------------
  2459 uint StoreNode::hash() const {
  2460   // unroll addition of interesting fields
  2461   //return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address) + (uintptr_t)in(ValueIn);
  2463   // Since they are not commoned, do not hash them:
  2464   return NO_HASH;
  2467 //------------------------------Ideal------------------------------------------
  2468 // Change back-to-back Store(, p, x) -> Store(m, p, y) to Store(m, p, x).
  2469 // When a store immediately follows a relevant allocation/initialization,
  2470 // try to capture it into the initialization, or hoist it above.
  2471 Node *StoreNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  2472   Node* p = MemNode::Ideal_common(phase, can_reshape);
  2473   if (p)  return (p == NodeSentinel) ? NULL : p;
  2475   Node* mem     = in(MemNode::Memory);
  2476   Node* address = in(MemNode::Address);
  2478   // Back-to-back stores to same address?  Fold em up.  Generally
  2479   // unsafe if I have intervening uses...  Also disallowed for StoreCM
  2480   // since they must follow each StoreP operation.  Redundant StoreCMs
  2481   // are eliminated just before matching in final_graph_reshape.
  2482   if (mem->is_Store() && mem->in(MemNode::Address)->eqv_uncast(address) &&
  2483       mem->Opcode() != Op_StoreCM) {
  2484     // Looking at a dead closed cycle of memory?
  2485     assert(mem != mem->in(MemNode::Memory), "dead loop in StoreNode::Ideal");
  2487     assert(Opcode() == mem->Opcode() ||
  2488            phase->C->get_alias_index(adr_type()) == Compile::AliasIdxRaw,
  2489            "no mismatched stores, except on raw memory");
  2491     if (mem->outcnt() == 1 &&           // check for intervening uses
  2492         mem->as_Store()->memory_size() <= this->memory_size()) {
  2493       // If anybody other than 'this' uses 'mem', we cannot fold 'mem' away.
  2494       // For example, 'mem' might be the final state at a conditional return.
  2495       // Or, 'mem' might be used by some node which is live at the same time
  2496       // 'this' is live, which might be unschedulable.  So, require exactly
  2497       // ONE user, the 'this' store, until such time as we clone 'mem' for
  2498       // each of 'mem's uses (thus making the exactly-1-user-rule hold true).
  2499       if (can_reshape) {  // (%%% is this an anachronism?)
  2500         set_req_X(MemNode::Memory, mem->in(MemNode::Memory),
  2501                   phase->is_IterGVN());
  2502       } else {
  2503         // It's OK to do this in the parser, since DU info is always accurate,
  2504         // and the parser always refers to nodes via SafePointNode maps.
  2505         set_req(MemNode::Memory, mem->in(MemNode::Memory));
  2507       return this;
  2511   // Capture an unaliased, unconditional, simple store into an initializer.
  2512   // Or, if it is independent of the allocation, hoist it above the allocation.
  2513   if (ReduceFieldZeroing && /*can_reshape &&*/
  2514       mem->is_Proj() && mem->in(0)->is_Initialize()) {
  2515     InitializeNode* init = mem->in(0)->as_Initialize();
  2516     intptr_t offset = init->can_capture_store(this, phase, can_reshape);
  2517     if (offset > 0) {
  2518       Node* moved = init->capture_store(this, offset, phase, can_reshape);
  2519       // If the InitializeNode captured me, it made a raw copy of me,
  2520       // and I need to disappear.
  2521       if (moved != NULL) {
  2522         // %%% hack to ensure that Ideal returns a new node:
  2523         mem = MergeMemNode::make(phase->C, mem);
  2524         return mem;             // fold me away
  2529   return NULL;                  // No further progress
  2532 //------------------------------Value-----------------------------------------
  2533 const Type *StoreNode::Value( PhaseTransform *phase ) const {
  2534   // Either input is TOP ==> the result is TOP
  2535   const Type *t1 = phase->type( in(MemNode::Memory) );
  2536   if( t1 == Type::TOP ) return Type::TOP;
  2537   const Type *t2 = phase->type( in(MemNode::Address) );
  2538   if( t2 == Type::TOP ) return Type::TOP;
  2539   const Type *t3 = phase->type( in(MemNode::ValueIn) );
  2540   if( t3 == Type::TOP ) return Type::TOP;
  2541   return Type::MEMORY;
  2544 //------------------------------Identity---------------------------------------
  2545 // Remove redundant stores:
  2546 //   Store(m, p, Load(m, p)) changes to m.
  2547 //   Store(, p, x) -> Store(m, p, x) changes to Store(m, p, x).
  2548 Node *StoreNode::Identity( PhaseTransform *phase ) {
  2549   Node* mem = in(MemNode::Memory);
  2550   Node* adr = in(MemNode::Address);
  2551   Node* val = in(MemNode::ValueIn);
  2553   // Load then Store?  Then the Store is useless
  2554   if (val->is_Load() &&
  2555       val->in(MemNode::Address)->eqv_uncast(adr) &&
  2556       val->in(MemNode::Memory )->eqv_uncast(mem) &&
  2557       val->as_Load()->store_Opcode() == Opcode()) {
  2558     return mem;
  2561   // Two stores in a row of the same value?
  2562   if (mem->is_Store() &&
  2563       mem->in(MemNode::Address)->eqv_uncast(adr) &&
  2564       mem->in(MemNode::ValueIn)->eqv_uncast(val) &&
  2565       mem->Opcode() == Opcode()) {
  2566     return mem;
  2569   // Store of zero anywhere into a freshly-allocated object?
  2570   // Then the store is useless.
  2571   // (It must already have been captured by the InitializeNode.)
  2572   if (ReduceFieldZeroing && phase->type(val)->is_zero_type()) {
  2573     // a newly allocated object is already all-zeroes everywhere
  2574     if (mem->is_Proj() && mem->in(0)->is_Allocate()) {
  2575       return mem;
  2578     // the store may also apply to zero-bits in an earlier object
  2579     Node* prev_mem = find_previous_store(phase);
  2580     // Steps (a), (b):  Walk past independent stores to find an exact match.
  2581     if (prev_mem != NULL) {
  2582       Node* prev_val = can_see_stored_value(prev_mem, phase);
  2583       if (prev_val != NULL && phase->eqv(prev_val, val)) {
  2584         // prev_val and val might differ by a cast; it would be good
  2585         // to keep the more informative of the two.
  2586         return mem;
  2591   return this;
  2594 //------------------------------match_edge-------------------------------------
  2595 // Do we Match on this edge index or not?  Match only memory & value
  2596 uint StoreNode::match_edge(uint idx) const {
  2597   return idx == MemNode::Address || idx == MemNode::ValueIn;
  2600 //------------------------------cmp--------------------------------------------
  2601 // Do not common stores up together.  They generally have to be split
  2602 // back up anyways, so do not bother.
  2603 uint StoreNode::cmp( const Node &n ) const {
  2604   return (&n == this);          // Always fail except on self
  2607 //------------------------------Ideal_masked_input-----------------------------
  2608 // Check for a useless mask before a partial-word store
  2609 // (StoreB ... (AndI valIn conIa) )
  2610 // If (conIa & mask == mask) this simplifies to
  2611 // (StoreB ... (valIn) )
  2612 Node *StoreNode::Ideal_masked_input(PhaseGVN *phase, uint mask) {
  2613   Node *val = in(MemNode::ValueIn);
  2614   if( val->Opcode() == Op_AndI ) {
  2615     const TypeInt *t = phase->type( val->in(2) )->isa_int();
  2616     if( t && t->is_con() && (t->get_con() & mask) == mask ) {
  2617       set_req(MemNode::ValueIn, val->in(1));
  2618       return this;
  2621   return NULL;
  2625 //------------------------------Ideal_sign_extended_input----------------------
  2626 // Check for useless sign-extension before a partial-word store
  2627 // (StoreB ... (RShiftI _ (LShiftI _ valIn conIL ) conIR) )
  2628 // If (conIL == conIR && conIR <= num_bits)  this simplifies to
  2629 // (StoreB ... (valIn) )
  2630 Node *StoreNode::Ideal_sign_extended_input(PhaseGVN *phase, int num_bits) {
  2631   Node *val = in(MemNode::ValueIn);
  2632   if( val->Opcode() == Op_RShiftI ) {
  2633     const TypeInt *t = phase->type( val->in(2) )->isa_int();
  2634     if( t && t->is_con() && (t->get_con() <= num_bits) ) {
  2635       Node *shl = val->in(1);
  2636       if( shl->Opcode() == Op_LShiftI ) {
  2637         const TypeInt *t2 = phase->type( shl->in(2) )->isa_int();
  2638         if( t2 && t2->is_con() && (t2->get_con() == t->get_con()) ) {
  2639           set_req(MemNode::ValueIn, shl->in(1));
  2640           return this;
  2645   return NULL;
  2648 //------------------------------value_never_loaded-----------------------------------
  2649 // Determine whether there are any possible loads of the value stored.
  2650 // For simplicity, we actually check if there are any loads from the
  2651 // address stored to, not just for loads of the value stored by this node.
  2652 //
  2653 bool StoreNode::value_never_loaded( PhaseTransform *phase) const {
  2654   Node *adr = in(Address);
  2655   const TypeOopPtr *adr_oop = phase->type(adr)->isa_oopptr();
  2656   if (adr_oop == NULL)
  2657     return false;
  2658   if (!adr_oop->is_known_instance_field())
  2659     return false; // if not a distinct instance, there may be aliases of the address
  2660   for (DUIterator_Fast imax, i = adr->fast_outs(imax); i < imax; i++) {
  2661     Node *use = adr->fast_out(i);
  2662     int opc = use->Opcode();
  2663     if (use->is_Load() || use->is_LoadStore()) {
  2664       return false;
  2667   return true;
  2670 //=============================================================================
  2671 //------------------------------Ideal------------------------------------------
  2672 // If the store is from an AND mask that leaves the low bits untouched, then
  2673 // we can skip the AND operation.  If the store is from a sign-extension
  2674 // (a left shift, then right shift) we can skip both.
  2675 Node *StoreBNode::Ideal(PhaseGVN *phase, bool can_reshape){
  2676   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFF);
  2677   if( progress != NULL ) return progress;
  2679   progress = StoreNode::Ideal_sign_extended_input(phase, 24);
  2680   if( progress != NULL ) return progress;
  2682   // Finally check the default case
  2683   return StoreNode::Ideal(phase, can_reshape);
  2686 //=============================================================================
  2687 //------------------------------Ideal------------------------------------------
  2688 // If the store is from an AND mask that leaves the low bits untouched, then
  2689 // we can skip the AND operation
  2690 Node *StoreCNode::Ideal(PhaseGVN *phase, bool can_reshape){
  2691   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFFFF);
  2692   if( progress != NULL ) return progress;
  2694   progress = StoreNode::Ideal_sign_extended_input(phase, 16);
  2695   if( progress != NULL ) return progress;
  2697   // Finally check the default case
  2698   return StoreNode::Ideal(phase, can_reshape);
  2701 //=============================================================================
  2702 //------------------------------Identity---------------------------------------
  2703 Node *StoreCMNode::Identity( PhaseTransform *phase ) {
  2704   // No need to card mark when storing a null ptr
  2705   Node* my_store = in(MemNode::OopStore);
  2706   if (my_store->is_Store()) {
  2707     const Type *t1 = phase->type( my_store->in(MemNode::ValueIn) );
  2708     if( t1 == TypePtr::NULL_PTR ) {
  2709       return in(MemNode::Memory);
  2712   return this;
  2715 //=============================================================================
  2716 //------------------------------Ideal---------------------------------------
  2717 Node *StoreCMNode::Ideal(PhaseGVN *phase, bool can_reshape){
  2718   Node* progress = StoreNode::Ideal(phase, can_reshape);
  2719   if (progress != NULL) return progress;
  2721   Node* my_store = in(MemNode::OopStore);
  2722   if (my_store->is_MergeMem()) {
  2723     Node* mem = my_store->as_MergeMem()->memory_at(oop_alias_idx());
  2724     set_req(MemNode::OopStore, mem);
  2725     return this;
  2728   return NULL;
  2731 //------------------------------Value-----------------------------------------
  2732 const Type *StoreCMNode::Value( PhaseTransform *phase ) const {
  2733   // Either input is TOP ==> the result is TOP
  2734   const Type *t = phase->type( in(MemNode::Memory) );
  2735   if( t == Type::TOP ) return Type::TOP;
  2736   t = phase->type( in(MemNode::Address) );
  2737   if( t == Type::TOP ) return Type::TOP;
  2738   t = phase->type( in(MemNode::ValueIn) );
  2739   if( t == Type::TOP ) return Type::TOP;
  2740   // If extra input is TOP ==> the result is TOP
  2741   t = phase->type( in(MemNode::OopStore) );
  2742   if( t == Type::TOP ) return Type::TOP;
  2744   return StoreNode::Value( phase );
  2748 //=============================================================================
  2749 //----------------------------------SCMemProjNode------------------------------
  2750 const Type * SCMemProjNode::Value( PhaseTransform *phase ) const
  2752   return bottom_type();
  2755 //=============================================================================
  2756 //----------------------------------LoadStoreNode------------------------------
  2757 LoadStoreNode::LoadStoreNode( Node *c, Node *mem, Node *adr, Node *val, const TypePtr* at, const Type* rt, uint required )
  2758   : Node(required),
  2759     _type(rt),
  2760     _adr_type(at)
  2762   init_req(MemNode::Control, c  );
  2763   init_req(MemNode::Memory , mem);
  2764   init_req(MemNode::Address, adr);
  2765   init_req(MemNode::ValueIn, val);
  2766   init_class_id(Class_LoadStore);
  2769 uint LoadStoreNode::ideal_reg() const {
  2770   return _type->ideal_reg();
  2773 bool LoadStoreNode::result_not_used() const {
  2774   for( DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++ ) {
  2775     Node *x = fast_out(i);
  2776     if (x->Opcode() == Op_SCMemProj) continue;
  2777     return false;
  2779   return true;
  2782 uint LoadStoreNode::size_of() const { return sizeof(*this); }
  2784 //=============================================================================
  2785 //----------------------------------LoadStoreConditionalNode--------------------
  2786 LoadStoreConditionalNode::LoadStoreConditionalNode( Node *c, Node *mem, Node *adr, Node *val, Node *ex ) : LoadStoreNode(c, mem, adr, val, NULL, TypeInt::BOOL, 5) {
  2787   init_req(ExpectedIn, ex );
  2790 //=============================================================================
  2791 //-------------------------------adr_type--------------------------------------
  2792 // Do we Match on this edge index or not?  Do not match memory
  2793 const TypePtr* ClearArrayNode::adr_type() const {
  2794   Node *adr = in(3);
  2795   return MemNode::calculate_adr_type(adr->bottom_type());
  2798 //------------------------------match_edge-------------------------------------
  2799 // Do we Match on this edge index or not?  Do not match memory
  2800 uint ClearArrayNode::match_edge(uint idx) const {
  2801   return idx > 1;
  2804 //------------------------------Identity---------------------------------------
  2805 // Clearing a zero length array does nothing
  2806 Node *ClearArrayNode::Identity( PhaseTransform *phase ) {
  2807   return phase->type(in(2))->higher_equal(TypeX::ZERO)  ? in(1) : this;
  2810 //------------------------------Idealize---------------------------------------
  2811 // Clearing a short array is faster with stores
  2812 Node *ClearArrayNode::Ideal(PhaseGVN *phase, bool can_reshape){
  2813   const int unit = BytesPerLong;
  2814   const TypeX* t = phase->type(in(2))->isa_intptr_t();
  2815   if (!t)  return NULL;
  2816   if (!t->is_con())  return NULL;
  2817   intptr_t raw_count = t->get_con();
  2818   intptr_t size = raw_count;
  2819   if (!Matcher::init_array_count_is_in_bytes) size *= unit;
  2820   // Clearing nothing uses the Identity call.
  2821   // Negative clears are possible on dead ClearArrays
  2822   // (see jck test stmt114.stmt11402.val).
  2823   if (size <= 0 || size % unit != 0)  return NULL;
  2824   intptr_t count = size / unit;
  2825   // Length too long; use fast hardware clear
  2826   if (size > Matcher::init_array_short_size)  return NULL;
  2827   Node *mem = in(1);
  2828   if( phase->type(mem)==Type::TOP ) return NULL;
  2829   Node *adr = in(3);
  2830   const Type* at = phase->type(adr);
  2831   if( at==Type::TOP ) return NULL;
  2832   const TypePtr* atp = at->isa_ptr();
  2833   // adjust atp to be the correct array element address type
  2834   if (atp == NULL)  atp = TypePtr::BOTTOM;
  2835   else              atp = atp->add_offset(Type::OffsetBot);
  2836   // Get base for derived pointer purposes
  2837   if( adr->Opcode() != Op_AddP ) Unimplemented();
  2838   Node *base = adr->in(1);
  2840   Node *zero = phase->makecon(TypeLong::ZERO);
  2841   Node *off  = phase->MakeConX(BytesPerLong);
  2842   mem = new (phase->C) StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
  2843   count--;
  2844   while( count-- ) {
  2845     mem = phase->transform(mem);
  2846     adr = phase->transform(new (phase->C) AddPNode(base,adr,off));
  2847     mem = new (phase->C) StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
  2849   return mem;
  2852 //----------------------------step_through----------------------------------
  2853 // Return allocation input memory edge if it is different instance
  2854 // or itself if it is the one we are looking for.
  2855 bool ClearArrayNode::step_through(Node** np, uint instance_id, PhaseTransform* phase) {
  2856   Node* n = *np;
  2857   assert(n->is_ClearArray(), "sanity");
  2858   intptr_t offset;
  2859   AllocateNode* alloc = AllocateNode::Ideal_allocation(n->in(3), phase, offset);
  2860   // This method is called only before Allocate nodes are expanded during
  2861   // macro nodes expansion. Before that ClearArray nodes are only generated
  2862   // in LibraryCallKit::generate_arraycopy() which follows allocations.
  2863   assert(alloc != NULL, "should have allocation");
  2864   if (alloc->_idx == instance_id) {
  2865     // Can not bypass initialization of the instance we are looking for.
  2866     return false;
  2868   // Otherwise skip it.
  2869   InitializeNode* init = alloc->initialization();
  2870   if (init != NULL)
  2871     *np = init->in(TypeFunc::Memory);
  2872   else
  2873     *np = alloc->in(TypeFunc::Memory);
  2874   return true;
  2877 //----------------------------clear_memory-------------------------------------
  2878 // Generate code to initialize object storage to zero.
  2879 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
  2880                                    intptr_t start_offset,
  2881                                    Node* end_offset,
  2882                                    PhaseGVN* phase) {
  2883   Compile* C = phase->C;
  2884   intptr_t offset = start_offset;
  2886   int unit = BytesPerLong;
  2887   if ((offset % unit) != 0) {
  2888     Node* adr = new (C) AddPNode(dest, dest, phase->MakeConX(offset));
  2889     adr = phase->transform(adr);
  2890     const TypePtr* atp = TypeRawPtr::BOTTOM;
  2891     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
  2892     mem = phase->transform(mem);
  2893     offset += BytesPerInt;
  2895   assert((offset % unit) == 0, "");
  2897   // Initialize the remaining stuff, if any, with a ClearArray.
  2898   return clear_memory(ctl, mem, dest, phase->MakeConX(offset), end_offset, phase);
  2901 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
  2902                                    Node* start_offset,
  2903                                    Node* end_offset,
  2904                                    PhaseGVN* phase) {
  2905   if (start_offset == end_offset) {
  2906     // nothing to do
  2907     return mem;
  2910   Compile* C = phase->C;
  2911   int unit = BytesPerLong;
  2912   Node* zbase = start_offset;
  2913   Node* zend  = end_offset;
  2915   // Scale to the unit required by the CPU:
  2916   if (!Matcher::init_array_count_is_in_bytes) {
  2917     Node* shift = phase->intcon(exact_log2(unit));
  2918     zbase = phase->transform( new(C) URShiftXNode(zbase, shift) );
  2919     zend  = phase->transform( new(C) URShiftXNode(zend,  shift) );
  2922   // Bulk clear double-words
  2923   Node* zsize = phase->transform( new(C) SubXNode(zend, zbase) );
  2924   Node* adr = phase->transform( new(C) AddPNode(dest, dest, start_offset) );
  2925   mem = new (C) ClearArrayNode(ctl, mem, zsize, adr);
  2926   return phase->transform(mem);
  2929 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
  2930                                    intptr_t start_offset,
  2931                                    intptr_t end_offset,
  2932                                    PhaseGVN* phase) {
  2933   if (start_offset == end_offset) {
  2934     // nothing to do
  2935     return mem;
  2938   Compile* C = phase->C;
  2939   assert((end_offset % BytesPerInt) == 0, "odd end offset");
  2940   intptr_t done_offset = end_offset;
  2941   if ((done_offset % BytesPerLong) != 0) {
  2942     done_offset -= BytesPerInt;
  2944   if (done_offset > start_offset) {
  2945     mem = clear_memory(ctl, mem, dest,
  2946                        start_offset, phase->MakeConX(done_offset), phase);
  2948   if (done_offset < end_offset) { // emit the final 32-bit store
  2949     Node* adr = new (C) AddPNode(dest, dest, phase->MakeConX(done_offset));
  2950     adr = phase->transform(adr);
  2951     const TypePtr* atp = TypeRawPtr::BOTTOM;
  2952     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
  2953     mem = phase->transform(mem);
  2954     done_offset += BytesPerInt;
  2956   assert(done_offset == end_offset, "");
  2957   return mem;
  2960 //=============================================================================
  2961 // Do not match memory edge.
  2962 uint StrIntrinsicNode::match_edge(uint idx) const {
  2963   return idx == 2 || idx == 3;
  2966 //------------------------------Ideal------------------------------------------
  2967 // Return a node which is more "ideal" than the current node.  Strip out
  2968 // control copies
  2969 Node *StrIntrinsicNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  2970   if (remove_dead_region(phase, can_reshape)) return this;
  2971   // Don't bother trying to transform a dead node
  2972   if (in(0) && in(0)->is_top())  return NULL;
  2974   if (can_reshape) {
  2975     Node* mem = phase->transform(in(MemNode::Memory));
  2976     // If transformed to a MergeMem, get the desired slice
  2977     uint alias_idx = phase->C->get_alias_index(adr_type());
  2978     mem = mem->is_MergeMem() ? mem->as_MergeMem()->memory_at(alias_idx) : mem;
  2979     if (mem != in(MemNode::Memory)) {
  2980       set_req(MemNode::Memory, mem);
  2981       return this;
  2984   return NULL;
  2987 //------------------------------Value------------------------------------------
  2988 const Type *StrIntrinsicNode::Value( PhaseTransform *phase ) const {
  2989   if (in(0) && phase->type(in(0)) == Type::TOP) return Type::TOP;
  2990   return bottom_type();
  2993 //=============================================================================
  2994 //------------------------------match_edge-------------------------------------
  2995 // Do not match memory edge
  2996 uint EncodeISOArrayNode::match_edge(uint idx) const {
  2997   return idx == 2 || idx == 3; // EncodeISOArray src (Binary dst len)
  3000 //------------------------------Ideal------------------------------------------
  3001 // Return a node which is more "ideal" than the current node.  Strip out
  3002 // control copies
  3003 Node *EncodeISOArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  3004   return remove_dead_region(phase, can_reshape) ? this : NULL;
  3007 //------------------------------Value------------------------------------------
  3008 const Type *EncodeISOArrayNode::Value(PhaseTransform *phase) const {
  3009   if (in(0) && phase->type(in(0)) == Type::TOP) return Type::TOP;
  3010   return bottom_type();
  3013 //=============================================================================
  3014 MemBarNode::MemBarNode(Compile* C, int alias_idx, Node* precedent)
  3015   : MultiNode(TypeFunc::Parms + (precedent == NULL? 0: 1)),
  3016     _adr_type(C->get_adr_type(alias_idx))
  3018   init_class_id(Class_MemBar);
  3019   Node* top = C->top();
  3020   init_req(TypeFunc::I_O,top);
  3021   init_req(TypeFunc::FramePtr,top);
  3022   init_req(TypeFunc::ReturnAdr,top);
  3023   if (precedent != NULL)
  3024     init_req(TypeFunc::Parms, precedent);
  3027 //------------------------------cmp--------------------------------------------
  3028 uint MemBarNode::hash() const { return NO_HASH; }
  3029 uint MemBarNode::cmp( const Node &n ) const {
  3030   return (&n == this);          // Always fail except on self
  3033 //------------------------------make-------------------------------------------
  3034 MemBarNode* MemBarNode::make(Compile* C, int opcode, int atp, Node* pn) {
  3035   switch (opcode) {
  3036   case Op_MemBarAcquire:     return new(C) MemBarAcquireNode(C, atp, pn);
  3037   case Op_LoadFence:         return new(C) LoadFenceNode(C, atp, pn);
  3038   case Op_MemBarRelease:     return new(C) MemBarReleaseNode(C, atp, pn);
  3039   case Op_StoreFence:        return new(C) StoreFenceNode(C, atp, pn);
  3040   case Op_MemBarAcquireLock: return new(C) MemBarAcquireLockNode(C, atp, pn);
  3041   case Op_MemBarReleaseLock: return new(C) MemBarReleaseLockNode(C, atp, pn);
  3042   case Op_MemBarVolatile:    return new(C) MemBarVolatileNode(C, atp, pn);
  3043   case Op_MemBarCPUOrder:    return new(C) MemBarCPUOrderNode(C, atp, pn);
  3044   case Op_Initialize:        return new(C) InitializeNode(C, atp, pn);
  3045   case Op_MemBarStoreStore:  return new(C) MemBarStoreStoreNode(C, atp, pn);
  3046   default: ShouldNotReachHere(); return NULL;
  3050 //------------------------------Ideal------------------------------------------
  3051 // Return a node which is more "ideal" than the current node.  Strip out
  3052 // control copies
  3053 Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  3054   if (remove_dead_region(phase, can_reshape)) return this;
  3055   // Don't bother trying to transform a dead node
  3056   if (in(0) && in(0)->is_top()) {
  3057     return NULL;
  3060   // Eliminate volatile MemBars for scalar replaced objects.
  3061   if (can_reshape && req() == (Precedent+1)) {
  3062     bool eliminate = false;
  3063     int opc = Opcode();
  3064     if ((opc == Op_MemBarAcquire || opc == Op_MemBarVolatile)) {
  3065       // Volatile field loads and stores.
  3066       Node* my_mem = in(MemBarNode::Precedent);
  3067       // The MembarAquire may keep an unused LoadNode alive through the Precedent edge
  3068       if ((my_mem != NULL) && (opc == Op_MemBarAcquire) && (my_mem->outcnt() == 1)) {
  3069         // if the Precedent is a decodeN and its input (a Load) is used at more than one place,
  3070         // replace this Precedent (decodeN) with the Load instead.
  3071         if ((my_mem->Opcode() == Op_DecodeN) && (my_mem->in(1)->outcnt() > 1))  {
  3072           Node* load_node = my_mem->in(1);
  3073           set_req(MemBarNode::Precedent, load_node);
  3074           phase->is_IterGVN()->_worklist.push(my_mem);
  3075           my_mem = load_node;
  3076         } else {
  3077           assert(my_mem->unique_out() == this, "sanity");
  3078           del_req(Precedent);
  3079           phase->is_IterGVN()->_worklist.push(my_mem); // remove dead node later
  3080           my_mem = NULL;
  3083       if (my_mem != NULL && my_mem->is_Mem()) {
  3084         const TypeOopPtr* t_oop = my_mem->in(MemNode::Address)->bottom_type()->isa_oopptr();
  3085         // Check for scalar replaced object reference.
  3086         if( t_oop != NULL && t_oop->is_known_instance_field() &&
  3087             t_oop->offset() != Type::OffsetBot &&
  3088             t_oop->offset() != Type::OffsetTop) {
  3089           eliminate = true;
  3092     } else if (opc == Op_MemBarRelease) {
  3093       // Final field stores.
  3094       Node* alloc = AllocateNode::Ideal_allocation(in(MemBarNode::Precedent), phase);
  3095       if ((alloc != NULL) && alloc->is_Allocate() &&
  3096           alloc->as_Allocate()->_is_non_escaping) {
  3097         // The allocated object does not escape.
  3098         eliminate = true;
  3101     if (eliminate) {
  3102       // Replace MemBar projections by its inputs.
  3103       PhaseIterGVN* igvn = phase->is_IterGVN();
  3104       igvn->replace_node(proj_out(TypeFunc::Memory), in(TypeFunc::Memory));
  3105       igvn->replace_node(proj_out(TypeFunc::Control), in(TypeFunc::Control));
  3106       // Must return either the original node (now dead) or a new node
  3107       // (Do not return a top here, since that would break the uniqueness of top.)
  3108       return new (phase->C) ConINode(TypeInt::ZERO);
  3111   return NULL;
  3114 //------------------------------Value------------------------------------------
  3115 const Type *MemBarNode::Value( PhaseTransform *phase ) const {
  3116   if( !in(0) ) return Type::TOP;
  3117   if( phase->type(in(0)) == Type::TOP )
  3118     return Type::TOP;
  3119   return TypeTuple::MEMBAR;
  3122 //------------------------------match------------------------------------------
  3123 // Construct projections for memory.
  3124 Node *MemBarNode::match( const ProjNode *proj, const Matcher *m ) {
  3125   switch (proj->_con) {
  3126   case TypeFunc::Control:
  3127   case TypeFunc::Memory:
  3128     return new (m->C) MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
  3130   ShouldNotReachHere();
  3131   return NULL;
  3134 //===========================InitializeNode====================================
  3135 // SUMMARY:
  3136 // This node acts as a memory barrier on raw memory, after some raw stores.
  3137 // The 'cooked' oop value feeds from the Initialize, not the Allocation.
  3138 // The Initialize can 'capture' suitably constrained stores as raw inits.
  3139 // It can coalesce related raw stores into larger units (called 'tiles').
  3140 // It can avoid zeroing new storage for memory units which have raw inits.
  3141 // At macro-expansion, it is marked 'complete', and does not optimize further.
  3142 //
  3143 // EXAMPLE:
  3144 // The object 'new short[2]' occupies 16 bytes in a 32-bit machine.
  3145 //   ctl = incoming control; mem* = incoming memory
  3146 // (Note:  A star * on a memory edge denotes I/O and other standard edges.)
  3147 // First allocate uninitialized memory and fill in the header:
  3148 //   alloc = (Allocate ctl mem* 16 #short[].klass ...)
  3149 //   ctl := alloc.Control; mem* := alloc.Memory*
  3150 //   rawmem = alloc.Memory; rawoop = alloc.RawAddress
  3151 // Then initialize to zero the non-header parts of the raw memory block:
  3152 //   init = (Initialize alloc.Control alloc.Memory* alloc.RawAddress)
  3153 //   ctl := init.Control; mem.SLICE(#short[*]) := init.Memory
  3154 // After the initialize node executes, the object is ready for service:
  3155 //   oop := (CheckCastPP init.Control alloc.RawAddress #short[])
  3156 // Suppose its body is immediately initialized as {1,2}:
  3157 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
  3158 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
  3159 //   mem.SLICE(#short[*]) := store2
  3160 //
  3161 // DETAILS:
  3162 // An InitializeNode collects and isolates object initialization after
  3163 // an AllocateNode and before the next possible safepoint.  As a
  3164 // memory barrier (MemBarNode), it keeps critical stores from drifting
  3165 // down past any safepoint or any publication of the allocation.
  3166 // Before this barrier, a newly-allocated object may have uninitialized bits.
  3167 // After this barrier, it may be treated as a real oop, and GC is allowed.
  3168 //
  3169 // The semantics of the InitializeNode include an implicit zeroing of
  3170 // the new object from object header to the end of the object.
  3171 // (The object header and end are determined by the AllocateNode.)
  3172 //
  3173 // Certain stores may be added as direct inputs to the InitializeNode.
  3174 // These stores must update raw memory, and they must be to addresses
  3175 // derived from the raw address produced by AllocateNode, and with
  3176 // a constant offset.  They must be ordered by increasing offset.
  3177 // The first one is at in(RawStores), the last at in(req()-1).
  3178 // Unlike most memory operations, they are not linked in a chain,
  3179 // but are displayed in parallel as users of the rawmem output of
  3180 // the allocation.
  3181 //
  3182 // (See comments in InitializeNode::capture_store, which continue
  3183 // the example given above.)
  3184 //
  3185 // When the associated Allocate is macro-expanded, the InitializeNode
  3186 // may be rewritten to optimize collected stores.  A ClearArrayNode
  3187 // may also be created at that point to represent any required zeroing.
  3188 // The InitializeNode is then marked 'complete', prohibiting further
  3189 // capturing of nearby memory operations.
  3190 //
  3191 // During macro-expansion, all captured initializations which store
  3192 // constant values of 32 bits or smaller are coalesced (if advantageous)
  3193 // into larger 'tiles' 32 or 64 bits.  This allows an object to be
  3194 // initialized in fewer memory operations.  Memory words which are
  3195 // covered by neither tiles nor non-constant stores are pre-zeroed
  3196 // by explicit stores of zero.  (The code shape happens to do all
  3197 // zeroing first, then all other stores, with both sequences occurring
  3198 // in order of ascending offsets.)
  3199 //
  3200 // Alternatively, code may be inserted between an AllocateNode and its
  3201 // InitializeNode, to perform arbitrary initialization of the new object.
  3202 // E.g., the object copying intrinsics insert complex data transfers here.
  3203 // The initialization must then be marked as 'complete' disable the
  3204 // built-in zeroing semantics and the collection of initializing stores.
  3205 //
  3206 // While an InitializeNode is incomplete, reads from the memory state
  3207 // produced by it are optimizable if they match the control edge and
  3208 // new oop address associated with the allocation/initialization.
  3209 // They return a stored value (if the offset matches) or else zero.
  3210 // A write to the memory state, if it matches control and address,
  3211 // and if it is to a constant offset, may be 'captured' by the
  3212 // InitializeNode.  It is cloned as a raw memory operation and rewired
  3213 // inside the initialization, to the raw oop produced by the allocation.
  3214 // Operations on addresses which are provably distinct (e.g., to
  3215 // other AllocateNodes) are allowed to bypass the initialization.
  3216 //
  3217 // The effect of all this is to consolidate object initialization
  3218 // (both arrays and non-arrays, both piecewise and bulk) into a
  3219 // single location, where it can be optimized as a unit.
  3220 //
  3221 // Only stores with an offset less than TrackedInitializationLimit words
  3222 // will be considered for capture by an InitializeNode.  This puts a
  3223 // reasonable limit on the complexity of optimized initializations.
  3225 //---------------------------InitializeNode------------------------------------
  3226 InitializeNode::InitializeNode(Compile* C, int adr_type, Node* rawoop)
  3227   : _is_complete(Incomplete), _does_not_escape(false),
  3228     MemBarNode(C, adr_type, rawoop)
  3230   init_class_id(Class_Initialize);
  3232   assert(adr_type == Compile::AliasIdxRaw, "only valid atp");
  3233   assert(in(RawAddress) == rawoop, "proper init");
  3234   // Note:  allocation() can be NULL, for secondary initialization barriers
  3237 // Since this node is not matched, it will be processed by the
  3238 // register allocator.  Declare that there are no constraints
  3239 // on the allocation of the RawAddress edge.
  3240 const RegMask &InitializeNode::in_RegMask(uint idx) const {
  3241   // This edge should be set to top, by the set_complete.  But be conservative.
  3242   if (idx == InitializeNode::RawAddress)
  3243     return *(Compile::current()->matcher()->idealreg2spillmask[in(idx)->ideal_reg()]);
  3244   return RegMask::Empty;
  3247 Node* InitializeNode::memory(uint alias_idx) {
  3248   Node* mem = in(Memory);
  3249   if (mem->is_MergeMem()) {
  3250     return mem->as_MergeMem()->memory_at(alias_idx);
  3251   } else {
  3252     // incoming raw memory is not split
  3253     return mem;
  3257 bool InitializeNode::is_non_zero() {
  3258   if (is_complete())  return false;
  3259   remove_extra_zeroes();
  3260   return (req() > RawStores);
  3263 void InitializeNode::set_complete(PhaseGVN* phase) {
  3264   assert(!is_complete(), "caller responsibility");
  3265   _is_complete = Complete;
  3267   // After this node is complete, it contains a bunch of
  3268   // raw-memory initializations.  There is no need for
  3269   // it to have anything to do with non-raw memory effects.
  3270   // Therefore, tell all non-raw users to re-optimize themselves,
  3271   // after skipping the memory effects of this initialization.
  3272   PhaseIterGVN* igvn = phase->is_IterGVN();
  3273   if (igvn)  igvn->add_users_to_worklist(this);
  3276 // convenience function
  3277 // return false if the init contains any stores already
  3278 bool AllocateNode::maybe_set_complete(PhaseGVN* phase) {
  3279   InitializeNode* init = initialization();
  3280   if (init == NULL || init->is_complete())  return false;
  3281   init->remove_extra_zeroes();
  3282   // for now, if this allocation has already collected any inits, bail:
  3283   if (init->is_non_zero())  return false;
  3284   init->set_complete(phase);
  3285   return true;
  3288 void InitializeNode::remove_extra_zeroes() {
  3289   if (req() == RawStores)  return;
  3290   Node* zmem = zero_memory();
  3291   uint fill = RawStores;
  3292   for (uint i = fill; i < req(); i++) {
  3293     Node* n = in(i);
  3294     if (n->is_top() || n == zmem)  continue;  // skip
  3295     if (fill < i)  set_req(fill, n);          // compact
  3296     ++fill;
  3298   // delete any empty spaces created:
  3299   while (fill < req()) {
  3300     del_req(fill);
  3304 // Helper for remembering which stores go with which offsets.
  3305 intptr_t InitializeNode::get_store_offset(Node* st, PhaseTransform* phase) {
  3306   if (!st->is_Store())  return -1;  // can happen to dead code via subsume_node
  3307   intptr_t offset = -1;
  3308   Node* base = AddPNode::Ideal_base_and_offset(st->in(MemNode::Address),
  3309                                                phase, offset);
  3310   if (base == NULL)     return -1;  // something is dead,
  3311   if (offset < 0)       return -1;  //        dead, dead
  3312   return offset;
  3315 // Helper for proving that an initialization expression is
  3316 // "simple enough" to be folded into an object initialization.
  3317 // Attempts to prove that a store's initial value 'n' can be captured
  3318 // within the initialization without creating a vicious cycle, such as:
  3319 //     { Foo p = new Foo(); p.next = p; }
  3320 // True for constants and parameters and small combinations thereof.
  3321 bool InitializeNode::detect_init_independence(Node* n, int& count) {
  3322   if (n == NULL)      return true;   // (can this really happen?)
  3323   if (n->is_Proj())   n = n->in(0);
  3324   if (n == this)      return false;  // found a cycle
  3325   if (n->is_Con())    return true;
  3326   if (n->is_Start())  return true;   // params, etc., are OK
  3327   if (n->is_Root())   return true;   // even better
  3329   Node* ctl = n->in(0);
  3330   if (ctl != NULL && !ctl->is_top()) {
  3331     if (ctl->is_Proj())  ctl = ctl->in(0);
  3332     if (ctl == this)  return false;
  3334     // If we already know that the enclosing memory op is pinned right after
  3335     // the init, then any control flow that the store has picked up
  3336     // must have preceded the init, or else be equal to the init.
  3337     // Even after loop optimizations (which might change control edges)
  3338     // a store is never pinned *before* the availability of its inputs.
  3339     if (!MemNode::all_controls_dominate(n, this))
  3340       return false;                  // failed to prove a good control
  3343   // Check data edges for possible dependencies on 'this'.
  3344   if ((count += 1) > 20)  return false;  // complexity limit
  3345   for (uint i = 1; i < n->req(); i++) {
  3346     Node* m = n->in(i);
  3347     if (m == NULL || m == n || m->is_top())  continue;
  3348     uint first_i = n->find_edge(m);
  3349     if (i != first_i)  continue;  // process duplicate edge just once
  3350     if (!detect_init_independence(m, count)) {
  3351       return false;
  3355   return true;
  3358 // Here are all the checks a Store must pass before it can be moved into
  3359 // an initialization.  Returns zero if a check fails.
  3360 // On success, returns the (constant) offset to which the store applies,
  3361 // within the initialized memory.
  3362 intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseTransform* phase, bool can_reshape) {
  3363   const int FAIL = 0;
  3364   if (st->req() != MemNode::ValueIn + 1)
  3365     return FAIL;                // an inscrutable StoreNode (card mark?)
  3366   Node* ctl = st->in(MemNode::Control);
  3367   if (!(ctl != NULL && ctl->is_Proj() && ctl->in(0) == this))
  3368     return FAIL;                // must be unconditional after the initialization
  3369   Node* mem = st->in(MemNode::Memory);
  3370   if (!(mem->is_Proj() && mem->in(0) == this))
  3371     return FAIL;                // must not be preceded by other stores
  3372   Node* adr = st->in(MemNode::Address);
  3373   intptr_t offset;
  3374   AllocateNode* alloc = AllocateNode::Ideal_allocation(adr, phase, offset);
  3375   if (alloc == NULL)
  3376     return FAIL;                // inscrutable address
  3377   if (alloc != allocation())
  3378     return FAIL;                // wrong allocation!  (store needs to float up)
  3379   int size_in_bytes = st->memory_size();
  3380   if ((size_in_bytes != 0) && (offset % size_in_bytes) != 0) {
  3381     return FAIL;                // mismatched access
  3383   Node* val = st->in(MemNode::ValueIn);
  3384   int complexity_count = 0;
  3385   if (!detect_init_independence(val, complexity_count))
  3386     return FAIL;                // stored value must be 'simple enough'
  3388   // The Store can be captured only if nothing after the allocation
  3389   // and before the Store is using the memory location that the store
  3390   // overwrites.
  3391   bool failed = false;
  3392   // If is_complete_with_arraycopy() is true the shape of the graph is
  3393   // well defined and is safe so no need for extra checks.
  3394   if (!is_complete_with_arraycopy()) {
  3395     // We are going to look at each use of the memory state following
  3396     // the allocation to make sure nothing reads the memory that the
  3397     // Store writes.
  3398     const TypePtr* t_adr = phase->type(adr)->isa_ptr();
  3399     int alias_idx = phase->C->get_alias_index(t_adr);
  3400     ResourceMark rm;
  3401     Unique_Node_List mems;
  3402     mems.push(mem);
  3403     Node* unique_merge = NULL;
  3404     for (uint next = 0; next < mems.size(); ++next) {
  3405       Node *m  = mems.at(next);
  3406       for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
  3407         Node *n = m->fast_out(j);
  3408         if (n->outcnt() == 0) {
  3409           continue;
  3411         if (n == st) {
  3412           continue;
  3413         } else if (n->in(0) != NULL && n->in(0) != ctl) {
  3414           // If the control of this use is different from the control
  3415           // of the Store which is right after the InitializeNode then
  3416           // this node cannot be between the InitializeNode and the
  3417           // Store.
  3418           continue;
  3419         } else if (n->is_MergeMem()) {
  3420           if (n->as_MergeMem()->memory_at(alias_idx) == m) {
  3421             // We can hit a MergeMemNode (that will likely go away
  3422             // later) that is a direct use of the memory state
  3423             // following the InitializeNode on the same slice as the
  3424             // store node that we'd like to capture. We need to check
  3425             // the uses of the MergeMemNode.
  3426             mems.push(n);
  3428         } else if (n->is_Mem()) {
  3429           Node* other_adr = n->in(MemNode::Address);
  3430           if (other_adr == adr) {
  3431             failed = true;
  3432             break;
  3433           } else {
  3434             const TypePtr* other_t_adr = phase->type(other_adr)->isa_ptr();
  3435             if (other_t_adr != NULL) {
  3436               int other_alias_idx = phase->C->get_alias_index(other_t_adr);
  3437               if (other_alias_idx == alias_idx) {
  3438                 // A load from the same memory slice as the store right
  3439                 // after the InitializeNode. We check the control of the
  3440                 // object/array that is loaded from. If it's the same as
  3441                 // the store control then we cannot capture the store.
  3442                 assert(!n->is_Store(), "2 stores to same slice on same control?");
  3443                 Node* base = other_adr;
  3444                 assert(base->is_AddP(), err_msg_res("should be addp but is %s", base->Name()));
  3445                 base = base->in(AddPNode::Base);
  3446                 if (base != NULL) {
  3447                   base = base->uncast();
  3448                   if (base->is_Proj() && base->in(0) == alloc) {
  3449                     failed = true;
  3450                     break;
  3456         } else {
  3457           failed = true;
  3458           break;
  3463   if (failed) {
  3464     if (!can_reshape) {
  3465       // We decided we couldn't capture the store during parsing. We
  3466       // should try again during the next IGVN once the graph is
  3467       // cleaner.
  3468       phase->C->record_for_igvn(st);
  3470     return FAIL;
  3473   return offset;                // success
  3476 // Find the captured store in(i) which corresponds to the range
  3477 // [start..start+size) in the initialized object.
  3478 // If there is one, return its index i.  If there isn't, return the
  3479 // negative of the index where it should be inserted.
  3480 // Return 0 if the queried range overlaps an initialization boundary
  3481 // or if dead code is encountered.
  3482 // If size_in_bytes is zero, do not bother with overlap checks.
  3483 int InitializeNode::captured_store_insertion_point(intptr_t start,
  3484                                                    int size_in_bytes,
  3485                                                    PhaseTransform* phase) {
  3486   const int FAIL = 0, MAX_STORE = BytesPerLong;
  3488   if (is_complete())
  3489     return FAIL;                // arraycopy got here first; punt
  3491   assert(allocation() != NULL, "must be present");
  3493   // no negatives, no header fields:
  3494   if (start < (intptr_t) allocation()->minimum_header_size())  return FAIL;
  3496   // after a certain size, we bail out on tracking all the stores:
  3497   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
  3498   if (start >= ti_limit)  return FAIL;
  3500   for (uint i = InitializeNode::RawStores, limit = req(); ; ) {
  3501     if (i >= limit)  return -(int)i; // not found; here is where to put it
  3503     Node*    st     = in(i);
  3504     intptr_t st_off = get_store_offset(st, phase);
  3505     if (st_off < 0) {
  3506       if (st != zero_memory()) {
  3507         return FAIL;            // bail out if there is dead garbage
  3509     } else if (st_off > start) {
  3510       // ...we are done, since stores are ordered
  3511       if (st_off < start + size_in_bytes) {
  3512         return FAIL;            // the next store overlaps
  3514       return -(int)i;           // not found; here is where to put it
  3515     } else if (st_off < start) {
  3516       if (size_in_bytes != 0 &&
  3517           start < st_off + MAX_STORE &&
  3518           start < st_off + st->as_Store()->memory_size()) {
  3519         return FAIL;            // the previous store overlaps
  3521     } else {
  3522       if (size_in_bytes != 0 &&
  3523           st->as_Store()->memory_size() != size_in_bytes) {
  3524         return FAIL;            // mismatched store size
  3526       return i;
  3529     ++i;
  3533 // Look for a captured store which initializes at the offset 'start'
  3534 // with the given size.  If there is no such store, and no other
  3535 // initialization interferes, then return zero_memory (the memory
  3536 // projection of the AllocateNode).
  3537 Node* InitializeNode::find_captured_store(intptr_t start, int size_in_bytes,
  3538                                           PhaseTransform* phase) {
  3539   assert(stores_are_sane(phase), "");
  3540   int i = captured_store_insertion_point(start, size_in_bytes, phase);
  3541   if (i == 0) {
  3542     return NULL;                // something is dead
  3543   } else if (i < 0) {
  3544     return zero_memory();       // just primordial zero bits here
  3545   } else {
  3546     Node* st = in(i);           // here is the store at this position
  3547     assert(get_store_offset(st->as_Store(), phase) == start, "sanity");
  3548     return st;
  3552 // Create, as a raw pointer, an address within my new object at 'offset'.
  3553 Node* InitializeNode::make_raw_address(intptr_t offset,
  3554                                        PhaseTransform* phase) {
  3555   Node* addr = in(RawAddress);
  3556   if (offset != 0) {
  3557     Compile* C = phase->C;
  3558     addr = phase->transform( new (C) AddPNode(C->top(), addr,
  3559                                                  phase->MakeConX(offset)) );
  3561   return addr;
  3564 // Clone the given store, converting it into a raw store
  3565 // initializing a field or element of my new object.
  3566 // Caller is responsible for retiring the original store,
  3567 // with subsume_node or the like.
  3568 //
  3569 // From the example above InitializeNode::InitializeNode,
  3570 // here are the old stores to be captured:
  3571 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
  3572 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
  3573 //
  3574 // Here is the changed code; note the extra edges on init:
  3575 //   alloc = (Allocate ...)
  3576 //   rawoop = alloc.RawAddress
  3577 //   rawstore1 = (StoreC alloc.Control alloc.Memory (+ rawoop 12) 1)
  3578 //   rawstore2 = (StoreC alloc.Control alloc.Memory (+ rawoop 14) 2)
  3579 //   init = (Initialize alloc.Control alloc.Memory rawoop
  3580 //                      rawstore1 rawstore2)
  3581 //
  3582 Node* InitializeNode::capture_store(StoreNode* st, intptr_t start,
  3583                                     PhaseTransform* phase, bool can_reshape) {
  3584   assert(stores_are_sane(phase), "");
  3586   if (start < 0)  return NULL;
  3587   assert(can_capture_store(st, phase, can_reshape) == start, "sanity");
  3589   Compile* C = phase->C;
  3590   int size_in_bytes = st->memory_size();
  3591   int i = captured_store_insertion_point(start, size_in_bytes, phase);
  3592   if (i == 0)  return NULL;     // bail out
  3593   Node* prev_mem = NULL;        // raw memory for the captured store
  3594   if (i > 0) {
  3595     prev_mem = in(i);           // there is a pre-existing store under this one
  3596     set_req(i, C->top());       // temporarily disconnect it
  3597     // See StoreNode::Ideal 'st->outcnt() == 1' for the reason to disconnect.
  3598   } else {
  3599     i = -i;                     // no pre-existing store
  3600     prev_mem = zero_memory();   // a slice of the newly allocated object
  3601     if (i > InitializeNode::RawStores && in(i-1) == prev_mem)
  3602       set_req(--i, C->top());   // reuse this edge; it has been folded away
  3603     else
  3604       ins_req(i, C->top());     // build a new edge
  3606   Node* new_st = st->clone();
  3607   new_st->set_req(MemNode::Control, in(Control));
  3608   new_st->set_req(MemNode::Memory,  prev_mem);
  3609   new_st->set_req(MemNode::Address, make_raw_address(start, phase));
  3610   new_st = phase->transform(new_st);
  3612   // At this point, new_st might have swallowed a pre-existing store
  3613   // at the same offset, or perhaps new_st might have disappeared,
  3614   // if it redundantly stored the same value (or zero to fresh memory).
  3616   // In any case, wire it in:
  3617   set_req(i, new_st);
  3619   // The caller may now kill the old guy.
  3620   DEBUG_ONLY(Node* check_st = find_captured_store(start, size_in_bytes, phase));
  3621   assert(check_st == new_st || check_st == NULL, "must be findable");
  3622   assert(!is_complete(), "");
  3623   return new_st;
  3626 static bool store_constant(jlong* tiles, int num_tiles,
  3627                            intptr_t st_off, int st_size,
  3628                            jlong con) {
  3629   if ((st_off & (st_size-1)) != 0)
  3630     return false;               // strange store offset (assume size==2**N)
  3631   address addr = (address)tiles + st_off;
  3632   assert(st_off >= 0 && addr+st_size <= (address)&tiles[num_tiles], "oob");
  3633   switch (st_size) {
  3634   case sizeof(jbyte):  *(jbyte*) addr = (jbyte) con; break;
  3635   case sizeof(jchar):  *(jchar*) addr = (jchar) con; break;
  3636   case sizeof(jint):   *(jint*)  addr = (jint)  con; break;
  3637   case sizeof(jlong):  *(jlong*) addr = (jlong) con; break;
  3638   default: return false;        // strange store size (detect size!=2**N here)
  3640   return true;                  // return success to caller
  3643 // Coalesce subword constants into int constants and possibly
  3644 // into long constants.  The goal, if the CPU permits,
  3645 // is to initialize the object with a small number of 64-bit tiles.
  3646 // Also, convert floating-point constants to bit patterns.
  3647 // Non-constants are not relevant to this pass.
  3648 //
  3649 // In terms of the running example on InitializeNode::InitializeNode
  3650 // and InitializeNode::capture_store, here is the transformation
  3651 // of rawstore1 and rawstore2 into rawstore12:
  3652 //   alloc = (Allocate ...)
  3653 //   rawoop = alloc.RawAddress
  3654 //   tile12 = 0x00010002
  3655 //   rawstore12 = (StoreI alloc.Control alloc.Memory (+ rawoop 12) tile12)
  3656 //   init = (Initialize alloc.Control alloc.Memory rawoop rawstore12)
  3657 //
  3658 void
  3659 InitializeNode::coalesce_subword_stores(intptr_t header_size,
  3660                                         Node* size_in_bytes,
  3661                                         PhaseGVN* phase) {
  3662   Compile* C = phase->C;
  3664   assert(stores_are_sane(phase), "");
  3665   // Note:  After this pass, they are not completely sane,
  3666   // since there may be some overlaps.
  3668   int old_subword = 0, old_long = 0, new_int = 0, new_long = 0;
  3670   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
  3671   intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, ti_limit);
  3672   size_limit = MIN2(size_limit, ti_limit);
  3673   size_limit = align_size_up(size_limit, BytesPerLong);
  3674   int num_tiles = size_limit / BytesPerLong;
  3676   // allocate space for the tile map:
  3677   const int small_len = DEBUG_ONLY(true ? 3 :) 30; // keep stack frames small
  3678   jlong  tiles_buf[small_len];
  3679   Node*  nodes_buf[small_len];
  3680   jlong  inits_buf[small_len];
  3681   jlong* tiles = ((num_tiles <= small_len) ? &tiles_buf[0]
  3682                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
  3683   Node** nodes = ((num_tiles <= small_len) ? &nodes_buf[0]
  3684                   : NEW_RESOURCE_ARRAY(Node*, num_tiles));
  3685   jlong* inits = ((num_tiles <= small_len) ? &inits_buf[0]
  3686                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
  3687   // tiles: exact bitwise model of all primitive constants
  3688   // nodes: last constant-storing node subsumed into the tiles model
  3689   // inits: which bytes (in each tile) are touched by any initializations
  3691   //// Pass A: Fill in the tile model with any relevant stores.
  3693   Copy::zero_to_bytes(tiles, sizeof(tiles[0]) * num_tiles);
  3694   Copy::zero_to_bytes(nodes, sizeof(nodes[0]) * num_tiles);
  3695   Copy::zero_to_bytes(inits, sizeof(inits[0]) * num_tiles);
  3696   Node* zmem = zero_memory(); // initially zero memory state
  3697   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
  3698     Node* st = in(i);
  3699     intptr_t st_off = get_store_offset(st, phase);
  3701     // Figure out the store's offset and constant value:
  3702     if (st_off < header_size)             continue; //skip (ignore header)
  3703     if (st->in(MemNode::Memory) != zmem)  continue; //skip (odd store chain)
  3704     int st_size = st->as_Store()->memory_size();
  3705     if (st_off + st_size > size_limit)    break;
  3707     // Record which bytes are touched, whether by constant or not.
  3708     if (!store_constant(inits, num_tiles, st_off, st_size, (jlong) -1))
  3709       continue;                 // skip (strange store size)
  3711     const Type* val = phase->type(st->in(MemNode::ValueIn));
  3712     if (!val->singleton())                continue; //skip (non-con store)
  3713     BasicType type = val->basic_type();
  3715     jlong con = 0;
  3716     switch (type) {
  3717     case T_INT:    con = val->is_int()->get_con();  break;
  3718     case T_LONG:   con = val->is_long()->get_con(); break;
  3719     case T_FLOAT:  con = jint_cast(val->getf());    break;
  3720     case T_DOUBLE: con = jlong_cast(val->getd());   break;
  3721     default:                              continue; //skip (odd store type)
  3724     if (type == T_LONG && Matcher::isSimpleConstant64(con) &&
  3725         st->Opcode() == Op_StoreL) {
  3726       continue;                 // This StoreL is already optimal.
  3729     // Store down the constant.
  3730     store_constant(tiles, num_tiles, st_off, st_size, con);
  3732     intptr_t j = st_off >> LogBytesPerLong;
  3734     if (type == T_INT && st_size == BytesPerInt
  3735         && (st_off & BytesPerInt) == BytesPerInt) {
  3736       jlong lcon = tiles[j];
  3737       if (!Matcher::isSimpleConstant64(lcon) &&
  3738           st->Opcode() == Op_StoreI) {
  3739         // This StoreI is already optimal by itself.
  3740         jint* intcon = (jint*) &tiles[j];
  3741         intcon[1] = 0;  // undo the store_constant()
  3743         // If the previous store is also optimal by itself, back up and
  3744         // undo the action of the previous loop iteration... if we can.
  3745         // But if we can't, just let the previous half take care of itself.
  3746         st = nodes[j];
  3747         st_off -= BytesPerInt;
  3748         con = intcon[0];
  3749         if (con != 0 && st != NULL && st->Opcode() == Op_StoreI) {
  3750           assert(st_off >= header_size, "still ignoring header");
  3751           assert(get_store_offset(st, phase) == st_off, "must be");
  3752           assert(in(i-1) == zmem, "must be");
  3753           DEBUG_ONLY(const Type* tcon = phase->type(st->in(MemNode::ValueIn)));
  3754           assert(con == tcon->is_int()->get_con(), "must be");
  3755           // Undo the effects of the previous loop trip, which swallowed st:
  3756           intcon[0] = 0;        // undo store_constant()
  3757           set_req(i-1, st);     // undo set_req(i, zmem)
  3758           nodes[j] = NULL;      // undo nodes[j] = st
  3759           --old_subword;        // undo ++old_subword
  3761         continue;               // This StoreI is already optimal.
  3765     // This store is not needed.
  3766     set_req(i, zmem);
  3767     nodes[j] = st;              // record for the moment
  3768     if (st_size < BytesPerLong) // something has changed
  3769           ++old_subword;        // includes int/float, but who's counting...
  3770     else  ++old_long;
  3773   if ((old_subword + old_long) == 0)
  3774     return;                     // nothing more to do
  3776   //// Pass B: Convert any non-zero tiles into optimal constant stores.
  3777   // Be sure to insert them before overlapping non-constant stores.
  3778   // (E.g., byte[] x = { 1,2,y,4 }  =>  x[int 0] = 0x01020004, x[2]=y.)
  3779   for (int j = 0; j < num_tiles; j++) {
  3780     jlong con  = tiles[j];
  3781     jlong init = inits[j];
  3782     if (con == 0)  continue;
  3783     jint con0,  con1;           // split the constant, address-wise
  3784     jint init0, init1;          // split the init map, address-wise
  3785     { union { jlong con; jint intcon[2]; } u;
  3786       u.con = con;
  3787       con0  = u.intcon[0];
  3788       con1  = u.intcon[1];
  3789       u.con = init;
  3790       init0 = u.intcon[0];
  3791       init1 = u.intcon[1];
  3794     Node* old = nodes[j];
  3795     assert(old != NULL, "need the prior store");
  3796     intptr_t offset = (j * BytesPerLong);
  3798     bool split = !Matcher::isSimpleConstant64(con);
  3800     if (offset < header_size) {
  3801       assert(offset + BytesPerInt >= header_size, "second int counts");
  3802       assert(*(jint*)&tiles[j] == 0, "junk in header");
  3803       split = true;             // only the second word counts
  3804       // Example:  int a[] = { 42 ... }
  3805     } else if (con0 == 0 && init0 == -1) {
  3806       split = true;             // first word is covered by full inits
  3807       // Example:  int a[] = { ... foo(), 42 ... }
  3808     } else if (con1 == 0 && init1 == -1) {
  3809       split = true;             // second word is covered by full inits
  3810       // Example:  int a[] = { ... 42, foo() ... }
  3813     // Here's a case where init0 is neither 0 nor -1:
  3814     //   byte a[] = { ... 0,0,foo(),0,  0,0,0,42 ... }
  3815     // Assuming big-endian memory, init0, init1 are 0x0000FF00, 0x000000FF.
  3816     // In this case the tile is not split; it is (jlong)42.
  3817     // The big tile is stored down, and then the foo() value is inserted.
  3818     // (If there were foo(),foo() instead of foo(),0, init0 would be -1.)
  3820     Node* ctl = old->in(MemNode::Control);
  3821     Node* adr = make_raw_address(offset, phase);
  3822     const TypePtr* atp = TypeRawPtr::BOTTOM;
  3824     // One or two coalesced stores to plop down.
  3825     Node*    st[2];
  3826     intptr_t off[2];
  3827     int  nst = 0;
  3828     if (!split) {
  3829       ++new_long;
  3830       off[nst] = offset;
  3831       st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
  3832                                   phase->longcon(con), T_LONG, MemNode::unordered);
  3833     } else {
  3834       // Omit either if it is a zero.
  3835       if (con0 != 0) {
  3836         ++new_int;
  3837         off[nst]  = offset;
  3838         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
  3839                                     phase->intcon(con0), T_INT, MemNode::unordered);
  3841       if (con1 != 0) {
  3842         ++new_int;
  3843         offset += BytesPerInt;
  3844         adr = make_raw_address(offset, phase);
  3845         off[nst]  = offset;
  3846         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
  3847                                     phase->intcon(con1), T_INT, MemNode::unordered);
  3851     // Insert second store first, then the first before the second.
  3852     // Insert each one just before any overlapping non-constant stores.
  3853     while (nst > 0) {
  3854       Node* st1 = st[--nst];
  3855       C->copy_node_notes_to(st1, old);
  3856       st1 = phase->transform(st1);
  3857       offset = off[nst];
  3858       assert(offset >= header_size, "do not smash header");
  3859       int ins_idx = captured_store_insertion_point(offset, /*size:*/0, phase);
  3860       guarantee(ins_idx != 0, "must re-insert constant store");
  3861       if (ins_idx < 0)  ins_idx = -ins_idx;  // never overlap
  3862       if (ins_idx > InitializeNode::RawStores && in(ins_idx-1) == zmem)
  3863         set_req(--ins_idx, st1);
  3864       else
  3865         ins_req(ins_idx, st1);
  3869   if (PrintCompilation && WizardMode)
  3870     tty->print_cr("Changed %d/%d subword/long constants into %d/%d int/long",
  3871                   old_subword, old_long, new_int, new_long);
  3872   if (C->log() != NULL)
  3873     C->log()->elem("comment that='%d/%d subword/long to %d/%d int/long'",
  3874                    old_subword, old_long, new_int, new_long);
  3876   // Clean up any remaining occurrences of zmem:
  3877   remove_extra_zeroes();
  3880 // Explore forward from in(start) to find the first fully initialized
  3881 // word, and return its offset.  Skip groups of subword stores which
  3882 // together initialize full words.  If in(start) is itself part of a
  3883 // fully initialized word, return the offset of in(start).  If there
  3884 // are no following full-word stores, or if something is fishy, return
  3885 // a negative value.
  3886 intptr_t InitializeNode::find_next_fullword_store(uint start, PhaseGVN* phase) {
  3887   int       int_map = 0;
  3888   intptr_t  int_map_off = 0;
  3889   const int FULL_MAP = right_n_bits(BytesPerInt);  // the int_map we hope for
  3891   for (uint i = start, limit = req(); i < limit; i++) {
  3892     Node* st = in(i);
  3894     intptr_t st_off = get_store_offset(st, phase);
  3895     if (st_off < 0)  break;  // return conservative answer
  3897     int st_size = st->as_Store()->memory_size();
  3898     if (st_size >= BytesPerInt && (st_off % BytesPerInt) == 0) {
  3899       return st_off;            // we found a complete word init
  3902     // update the map:
  3904     intptr_t this_int_off = align_size_down(st_off, BytesPerInt);
  3905     if (this_int_off != int_map_off) {
  3906       // reset the map:
  3907       int_map = 0;
  3908       int_map_off = this_int_off;
  3911     int subword_off = st_off - this_int_off;
  3912     int_map |= right_n_bits(st_size) << subword_off;
  3913     if ((int_map & FULL_MAP) == FULL_MAP) {
  3914       return this_int_off;      // we found a complete word init
  3917     // Did this store hit or cross the word boundary?
  3918     intptr_t next_int_off = align_size_down(st_off + st_size, BytesPerInt);
  3919     if (next_int_off == this_int_off + BytesPerInt) {
  3920       // We passed the current int, without fully initializing it.
  3921       int_map_off = next_int_off;
  3922       int_map >>= BytesPerInt;
  3923     } else if (next_int_off > this_int_off + BytesPerInt) {
  3924       // We passed the current and next int.
  3925       return this_int_off + BytesPerInt;
  3929   return -1;
  3933 // Called when the associated AllocateNode is expanded into CFG.
  3934 // At this point, we may perform additional optimizations.
  3935 // Linearize the stores by ascending offset, to make memory
  3936 // activity as coherent as possible.
  3937 Node* InitializeNode::complete_stores(Node* rawctl, Node* rawmem, Node* rawptr,
  3938                                       intptr_t header_size,
  3939                                       Node* size_in_bytes,
  3940                                       PhaseGVN* phase) {
  3941   assert(!is_complete(), "not already complete");
  3942   assert(stores_are_sane(phase), "");
  3943   assert(allocation() != NULL, "must be present");
  3945   remove_extra_zeroes();
  3947   if (ReduceFieldZeroing || ReduceBulkZeroing)
  3948     // reduce instruction count for common initialization patterns
  3949     coalesce_subword_stores(header_size, size_in_bytes, phase);
  3951   Node* zmem = zero_memory();   // initially zero memory state
  3952   Node* inits = zmem;           // accumulating a linearized chain of inits
  3953   #ifdef ASSERT
  3954   intptr_t first_offset = allocation()->minimum_header_size();
  3955   intptr_t last_init_off = first_offset;  // previous init offset
  3956   intptr_t last_init_end = first_offset;  // previous init offset+size
  3957   intptr_t last_tile_end = first_offset;  // previous tile offset+size
  3958   #endif
  3959   intptr_t zeroes_done = header_size;
  3961   bool do_zeroing = true;       // we might give up if inits are very sparse
  3962   int  big_init_gaps = 0;       // how many large gaps have we seen?
  3964   if (ZeroTLAB)  do_zeroing = false;
  3965   if (!ReduceFieldZeroing && !ReduceBulkZeroing)  do_zeroing = false;
  3967   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
  3968     Node* st = in(i);
  3969     intptr_t st_off = get_store_offset(st, phase);
  3970     if (st_off < 0)
  3971       break;                    // unknown junk in the inits
  3972     if (st->in(MemNode::Memory) != zmem)
  3973       break;                    // complicated store chains somehow in list
  3975     int st_size = st->as_Store()->memory_size();
  3976     intptr_t next_init_off = st_off + st_size;
  3978     if (do_zeroing && zeroes_done < next_init_off) {
  3979       // See if this store needs a zero before it or under it.
  3980       intptr_t zeroes_needed = st_off;
  3982       if (st_size < BytesPerInt) {
  3983         // Look for subword stores which only partially initialize words.
  3984         // If we find some, we must lay down some word-level zeroes first,
  3985         // underneath the subword stores.
  3986         //
  3987         // Examples:
  3988         //   byte[] a = { p,q,r,s }  =>  a[0]=p,a[1]=q,a[2]=r,a[3]=s
  3989         //   byte[] a = { x,y,0,0 }  =>  a[0..3] = 0, a[0]=x,a[1]=y
  3990         //   byte[] a = { 0,0,z,0 }  =>  a[0..3] = 0, a[2]=z
  3991         //
  3992         // Note:  coalesce_subword_stores may have already done this,
  3993         // if it was prompted by constant non-zero subword initializers.
  3994         // But this case can still arise with non-constant stores.
  3996         intptr_t next_full_store = find_next_fullword_store(i, phase);
  3998         // In the examples above:
  3999         //   in(i)          p   q   r   s     x   y     z
  4000         //   st_off        12  13  14  15    12  13    14
  4001         //   st_size        1   1   1   1     1   1     1
  4002         //   next_full_s.  12  16  16  16    16  16    16
  4003         //   z's_done      12  16  16  16    12  16    12
  4004         //   z's_needed    12  16  16  16    16  16    16
  4005         //   zsize          0   0   0   0     4   0     4
  4006         if (next_full_store < 0) {
  4007           // Conservative tack:  Zero to end of current word.
  4008           zeroes_needed = align_size_up(zeroes_needed, BytesPerInt);
  4009         } else {
  4010           // Zero to beginning of next fully initialized word.
  4011           // Or, don't zero at all, if we are already in that word.
  4012           assert(next_full_store >= zeroes_needed, "must go forward");
  4013           assert((next_full_store & (BytesPerInt-1)) == 0, "even boundary");
  4014           zeroes_needed = next_full_store;
  4018       if (zeroes_needed > zeroes_done) {
  4019         intptr_t zsize = zeroes_needed - zeroes_done;
  4020         // Do some incremental zeroing on rawmem, in parallel with inits.
  4021         zeroes_done = align_size_down(zeroes_done, BytesPerInt);
  4022         rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
  4023                                               zeroes_done, zeroes_needed,
  4024                                               phase);
  4025         zeroes_done = zeroes_needed;
  4026         if (zsize > Matcher::init_array_short_size && ++big_init_gaps > 2)
  4027           do_zeroing = false;   // leave the hole, next time
  4031     // Collect the store and move on:
  4032     st->set_req(MemNode::Memory, inits);
  4033     inits = st;                 // put it on the linearized chain
  4034     set_req(i, zmem);           // unhook from previous position
  4036     if (zeroes_done == st_off)
  4037       zeroes_done = next_init_off;
  4039     assert(!do_zeroing || zeroes_done >= next_init_off, "don't miss any");
  4041     #ifdef ASSERT
  4042     // Various order invariants.  Weaker than stores_are_sane because
  4043     // a large constant tile can be filled in by smaller non-constant stores.
  4044     assert(st_off >= last_init_off, "inits do not reverse");
  4045     last_init_off = st_off;
  4046     const Type* val = NULL;
  4047     if (st_size >= BytesPerInt &&
  4048         (val = phase->type(st->in(MemNode::ValueIn)))->singleton() &&
  4049         (int)val->basic_type() < (int)T_OBJECT) {
  4050       assert(st_off >= last_tile_end, "tiles do not overlap");
  4051       assert(st_off >= last_init_end, "tiles do not overwrite inits");
  4052       last_tile_end = MAX2(last_tile_end, next_init_off);
  4053     } else {
  4054       intptr_t st_tile_end = align_size_up(next_init_off, BytesPerLong);
  4055       assert(st_tile_end >= last_tile_end, "inits stay with tiles");
  4056       assert(st_off      >= last_init_end, "inits do not overlap");
  4057       last_init_end = next_init_off;  // it's a non-tile
  4059     #endif //ASSERT
  4062   remove_extra_zeroes();        // clear out all the zmems left over
  4063   add_req(inits);
  4065   if (!ZeroTLAB) {
  4066     // If anything remains to be zeroed, zero it all now.
  4067     zeroes_done = align_size_down(zeroes_done, BytesPerInt);
  4068     // if it is the last unused 4 bytes of an instance, forget about it
  4069     intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, max_jint);
  4070     if (zeroes_done + BytesPerLong >= size_limit) {
  4071       AllocateNode* alloc = allocation();
  4072       assert(alloc != NULL, "must be present");
  4073       if (alloc != NULL && alloc->Opcode() == Op_Allocate) {
  4074         Node* klass_node = alloc->in(AllocateNode::KlassNode);
  4075         ciKlass* k = phase->type(klass_node)->is_klassptr()->klass();
  4076         if (zeroes_done == k->layout_helper())
  4077           zeroes_done = size_limit;
  4080     if (zeroes_done < size_limit) {
  4081       rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
  4082                                             zeroes_done, size_in_bytes, phase);
  4086   set_complete(phase);
  4087   return rawmem;
  4091 #ifdef ASSERT
  4092 bool InitializeNode::stores_are_sane(PhaseTransform* phase) {
  4093   if (is_complete())
  4094     return true;                // stores could be anything at this point
  4095   assert(allocation() != NULL, "must be present");
  4096   intptr_t last_off = allocation()->minimum_header_size();
  4097   for (uint i = InitializeNode::RawStores; i < req(); i++) {
  4098     Node* st = in(i);
  4099     intptr_t st_off = get_store_offset(st, phase);
  4100     if (st_off < 0)  continue;  // ignore dead garbage
  4101     if (last_off > st_off) {
  4102       tty->print_cr("*** bad store offset at %d: " INTX_FORMAT " > " INTX_FORMAT, i, last_off, st_off);
  4103       this->dump(2);
  4104       assert(false, "ascending store offsets");
  4105       return false;
  4107     last_off = st_off + st->as_Store()->memory_size();
  4109   return true;
  4111 #endif //ASSERT
  4116 //============================MergeMemNode=====================================
  4117 //
  4118 // SEMANTICS OF MEMORY MERGES:  A MergeMem is a memory state assembled from several
  4119 // contributing store or call operations.  Each contributor provides the memory
  4120 // state for a particular "alias type" (see Compile::alias_type).  For example,
  4121 // if a MergeMem has an input X for alias category #6, then any memory reference
  4122 // to alias category #6 may use X as its memory state input, as an exact equivalent
  4123 // to using the MergeMem as a whole.
  4124 //   Load<6>( MergeMem(<6>: X, ...), p ) <==> Load<6>(X,p)
  4125 //
  4126 // (Here, the <N> notation gives the index of the relevant adr_type.)
  4127 //
  4128 // In one special case (and more cases in the future), alias categories overlap.
  4129 // The special alias category "Bot" (Compile::AliasIdxBot) includes all memory
  4130 // states.  Therefore, if a MergeMem has only one contributing input W for Bot,
  4131 // it is exactly equivalent to that state W:
  4132 //   MergeMem(<Bot>: W) <==> W
  4133 //
  4134 // Usually, the merge has more than one input.  In that case, where inputs
  4135 // overlap (i.e., one is Bot), the narrower alias type determines the memory
  4136 // state for that type, and the wider alias type (Bot) fills in everywhere else:
  4137 //   Load<5>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<5>(W,p)
  4138 //   Load<6>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<6>(X,p)
  4139 //
  4140 // A merge can take a "wide" memory state as one of its narrow inputs.
  4141 // This simply means that the merge observes out only the relevant parts of
  4142 // the wide input.  That is, wide memory states arriving at narrow merge inputs
  4143 // are implicitly "filtered" or "sliced" as necessary.  (This is rare.)
  4144 //
  4145 // These rules imply that MergeMem nodes may cascade (via their <Bot> links),
  4146 // and that memory slices "leak through":
  4147 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y)) <==> MergeMem(<Bot>: W, <7>: Y)
  4148 //
  4149 // But, in such a cascade, repeated memory slices can "block the leak":
  4150 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y), <7>: Y') <==> MergeMem(<Bot>: W, <7>: Y')
  4151 //
  4152 // In the last example, Y is not part of the combined memory state of the
  4153 // outermost MergeMem.  The system must, of course, prevent unschedulable
  4154 // memory states from arising, so you can be sure that the state Y is somehow
  4155 // a precursor to state Y'.
  4156 //
  4157 //
  4158 // REPRESENTATION OF MEMORY MERGES: The indexes used to address the Node::in array
  4159 // of each MergeMemNode array are exactly the numerical alias indexes, including
  4160 // but not limited to AliasIdxTop, AliasIdxBot, and AliasIdxRaw.  The functions
  4161 // Compile::alias_type (and kin) produce and manage these indexes.
  4162 //
  4163 // By convention, the value of in(AliasIdxTop) (i.e., in(1)) is always the top node.
  4164 // (Note that this provides quick access to the top node inside MergeMem methods,
  4165 // without the need to reach out via TLS to Compile::current.)
  4166 //
  4167 // As a consequence of what was just described, a MergeMem that represents a full
  4168 // memory state has an edge in(AliasIdxBot) which is a "wide" memory state,
  4169 // containing all alias categories.
  4170 //
  4171 // MergeMem nodes never (?) have control inputs, so in(0) is NULL.
  4172 //
  4173 // All other edges in(N) (including in(AliasIdxRaw), which is in(3)) are either
  4174 // a memory state for the alias type <N>, or else the top node, meaning that
  4175 // there is no particular input for that alias type.  Note that the length of
  4176 // a MergeMem is variable, and may be extended at any time to accommodate new
  4177 // memory states at larger alias indexes.  When merges grow, they are of course
  4178 // filled with "top" in the unused in() positions.
  4179 //
  4180 // This use of top is named "empty_memory()", or "empty_mem" (no-memory) as a variable.
  4181 // (Top was chosen because it works smoothly with passes like GCM.)
  4182 //
  4183 // For convenience, we hardwire the alias index for TypeRawPtr::BOTTOM.  (It is
  4184 // the type of random VM bits like TLS references.)  Since it is always the
  4185 // first non-Bot memory slice, some low-level loops use it to initialize an
  4186 // index variable:  for (i = AliasIdxRaw; i < req(); i++).
  4187 //
  4188 //
  4189 // ACCESSORS:  There is a special accessor MergeMemNode::base_memory which returns
  4190 // the distinguished "wide" state.  The accessor MergeMemNode::memory_at(N) returns
  4191 // the memory state for alias type <N>, or (if there is no particular slice at <N>,
  4192 // it returns the base memory.  To prevent bugs, memory_at does not accept <Top>
  4193 // or <Bot> indexes.  The iterator MergeMemStream provides robust iteration over
  4194 // MergeMem nodes or pairs of such nodes, ensuring that the non-top edges are visited.
  4195 //
  4196 // %%%% We may get rid of base_memory as a separate accessor at some point; it isn't
  4197 // really that different from the other memory inputs.  An abbreviation called
  4198 // "bot_memory()" for "memory_at(AliasIdxBot)" would keep code tidy.
  4199 //
  4200 //
  4201 // PARTIAL MEMORY STATES:  During optimization, MergeMem nodes may arise that represent
  4202 // partial memory states.  When a Phi splits through a MergeMem, the copy of the Phi
  4203 // that "emerges though" the base memory will be marked as excluding the alias types
  4204 // of the other (narrow-memory) copies which "emerged through" the narrow edges:
  4205 //
  4206 //   Phi<Bot>(U, MergeMem(<Bot>: W, <8>: Y))
  4207 //     ==Ideal=>  MergeMem(<Bot>: Phi<Bot-8>(U, W), Phi<8>(U, Y))
  4208 //
  4209 // This strange "subtraction" effect is necessary to ensure IGVN convergence.
  4210 // (It is currently unimplemented.)  As you can see, the resulting merge is
  4211 // actually a disjoint union of memory states, rather than an overlay.
  4212 //
  4214 //------------------------------MergeMemNode-----------------------------------
  4215 Node* MergeMemNode::make_empty_memory() {
  4216   Node* empty_memory = (Node*) Compile::current()->top();
  4217   assert(empty_memory->is_top(), "correct sentinel identity");
  4218   return empty_memory;
  4221 MergeMemNode::MergeMemNode(Node *new_base) : Node(1+Compile::AliasIdxRaw) {
  4222   init_class_id(Class_MergeMem);
  4223   // all inputs are nullified in Node::Node(int)
  4224   // set_input(0, NULL);  // no control input
  4226   // Initialize the edges uniformly to top, for starters.
  4227   Node* empty_mem = make_empty_memory();
  4228   for (uint i = Compile::AliasIdxTop; i < req(); i++) {
  4229     init_req(i,empty_mem);
  4231   assert(empty_memory() == empty_mem, "");
  4233   if( new_base != NULL && new_base->is_MergeMem() ) {
  4234     MergeMemNode* mdef = new_base->as_MergeMem();
  4235     assert(mdef->empty_memory() == empty_mem, "consistent sentinels");
  4236     for (MergeMemStream mms(this, mdef); mms.next_non_empty2(); ) {
  4237       mms.set_memory(mms.memory2());
  4239     assert(base_memory() == mdef->base_memory(), "");
  4240   } else {
  4241     set_base_memory(new_base);
  4245 // Make a new, untransformed MergeMem with the same base as 'mem'.
  4246 // If mem is itself a MergeMem, populate the result with the same edges.
  4247 MergeMemNode* MergeMemNode::make(Compile* C, Node* mem) {
  4248   return new(C) MergeMemNode(mem);
  4251 //------------------------------cmp--------------------------------------------
  4252 uint MergeMemNode::hash() const { return NO_HASH; }
  4253 uint MergeMemNode::cmp( const Node &n ) const {
  4254   return (&n == this);          // Always fail except on self
  4257 //------------------------------Identity---------------------------------------
  4258 Node* MergeMemNode::Identity(PhaseTransform *phase) {
  4259   // Identity if this merge point does not record any interesting memory
  4260   // disambiguations.
  4261   Node* base_mem = base_memory();
  4262   Node* empty_mem = empty_memory();
  4263   if (base_mem != empty_mem) {  // Memory path is not dead?
  4264     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
  4265       Node* mem = in(i);
  4266       if (mem != empty_mem && mem != base_mem) {
  4267         return this;            // Many memory splits; no change
  4271   return base_mem;              // No memory splits; ID on the one true input
  4274 //------------------------------Ideal------------------------------------------
  4275 // This method is invoked recursively on chains of MergeMem nodes
  4276 Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  4277   // Remove chain'd MergeMems
  4278   //
  4279   // This is delicate, because the each "in(i)" (i >= Raw) is interpreted
  4280   // relative to the "in(Bot)".  Since we are patching both at the same time,
  4281   // we have to be careful to read each "in(i)" relative to the old "in(Bot)",
  4282   // but rewrite each "in(i)" relative to the new "in(Bot)".
  4283   Node *progress = NULL;
  4286   Node* old_base = base_memory();
  4287   Node* empty_mem = empty_memory();
  4288   if (old_base == empty_mem)
  4289     return NULL; // Dead memory path.
  4291   MergeMemNode* old_mbase;
  4292   if (old_base != NULL && old_base->is_MergeMem())
  4293     old_mbase = old_base->as_MergeMem();
  4294   else
  4295     old_mbase = NULL;
  4296   Node* new_base = old_base;
  4298   // simplify stacked MergeMems in base memory
  4299   if (old_mbase)  new_base = old_mbase->base_memory();
  4301   // the base memory might contribute new slices beyond my req()
  4302   if (old_mbase)  grow_to_match(old_mbase);
  4304   // Look carefully at the base node if it is a phi.
  4305   PhiNode* phi_base;
  4306   if (new_base != NULL && new_base->is_Phi())
  4307     phi_base = new_base->as_Phi();
  4308   else
  4309     phi_base = NULL;
  4311   Node*    phi_reg = NULL;
  4312   uint     phi_len = (uint)-1;
  4313   if (phi_base != NULL && !phi_base->is_copy()) {
  4314     // do not examine phi if degraded to a copy
  4315     phi_reg = phi_base->region();
  4316     phi_len = phi_base->req();
  4317     // see if the phi is unfinished
  4318     for (uint i = 1; i < phi_len; i++) {
  4319       if (phi_base->in(i) == NULL) {
  4320         // incomplete phi; do not look at it yet!
  4321         phi_reg = NULL;
  4322         phi_len = (uint)-1;
  4323         break;
  4328   // Note:  We do not call verify_sparse on entry, because inputs
  4329   // can normalize to the base_memory via subsume_node or similar
  4330   // mechanisms.  This method repairs that damage.
  4332   assert(!old_mbase || old_mbase->is_empty_memory(empty_mem), "consistent sentinels");
  4334   // Look at each slice.
  4335   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
  4336     Node* old_in = in(i);
  4337     // calculate the old memory value
  4338     Node* old_mem = old_in;
  4339     if (old_mem == empty_mem)  old_mem = old_base;
  4340     assert(old_mem == memory_at(i), "");
  4342     // maybe update (reslice) the old memory value
  4344     // simplify stacked MergeMems
  4345     Node* new_mem = old_mem;
  4346     MergeMemNode* old_mmem;
  4347     if (old_mem != NULL && old_mem->is_MergeMem())
  4348       old_mmem = old_mem->as_MergeMem();
  4349     else
  4350       old_mmem = NULL;
  4351     if (old_mmem == this) {
  4352       // This can happen if loops break up and safepoints disappear.
  4353       // A merge of BotPtr (default) with a RawPtr memory derived from a
  4354       // safepoint can be rewritten to a merge of the same BotPtr with
  4355       // the BotPtr phi coming into the loop.  If that phi disappears
  4356       // also, we can end up with a self-loop of the mergemem.
  4357       // In general, if loops degenerate and memory effects disappear,
  4358       // a mergemem can be left looking at itself.  This simply means
  4359       // that the mergemem's default should be used, since there is
  4360       // no longer any apparent effect on this slice.
  4361       // Note: If a memory slice is a MergeMem cycle, it is unreachable
  4362       //       from start.  Update the input to TOP.
  4363       new_mem = (new_base == this || new_base == empty_mem)? empty_mem : new_base;
  4365     else if (old_mmem != NULL) {
  4366       new_mem = old_mmem->memory_at(i);
  4368     // else preceding memory was not a MergeMem
  4370     // replace equivalent phis (unfortunately, they do not GVN together)
  4371     if (new_mem != NULL && new_mem != new_base &&
  4372         new_mem->req() == phi_len && new_mem->in(0) == phi_reg) {
  4373       if (new_mem->is_Phi()) {
  4374         PhiNode* phi_mem = new_mem->as_Phi();
  4375         for (uint i = 1; i < phi_len; i++) {
  4376           if (phi_base->in(i) != phi_mem->in(i)) {
  4377             phi_mem = NULL;
  4378             break;
  4381         if (phi_mem != NULL) {
  4382           // equivalent phi nodes; revert to the def
  4383           new_mem = new_base;
  4388     // maybe store down a new value
  4389     Node* new_in = new_mem;
  4390     if (new_in == new_base)  new_in = empty_mem;
  4392     if (new_in != old_in) {
  4393       // Warning:  Do not combine this "if" with the previous "if"
  4394       // A memory slice might have be be rewritten even if it is semantically
  4395       // unchanged, if the base_memory value has changed.
  4396       set_req(i, new_in);
  4397       progress = this;          // Report progress
  4401   if (new_base != old_base) {
  4402     set_req(Compile::AliasIdxBot, new_base);
  4403     // Don't use set_base_memory(new_base), because we need to update du.
  4404     assert(base_memory() == new_base, "");
  4405     progress = this;
  4408   if( base_memory() == this ) {
  4409     // a self cycle indicates this memory path is dead
  4410     set_req(Compile::AliasIdxBot, empty_mem);
  4413   // Resolve external cycles by calling Ideal on a MergeMem base_memory
  4414   // Recursion must occur after the self cycle check above
  4415   if( base_memory()->is_MergeMem() ) {
  4416     MergeMemNode *new_mbase = base_memory()->as_MergeMem();
  4417     Node *m = phase->transform(new_mbase);  // Rollup any cycles
  4418     if( m != NULL && (m->is_top() ||
  4419         m->is_MergeMem() && m->as_MergeMem()->base_memory() == empty_mem) ) {
  4420       // propagate rollup of dead cycle to self
  4421       set_req(Compile::AliasIdxBot, empty_mem);
  4425   if( base_memory() == empty_mem ) {
  4426     progress = this;
  4427     // Cut inputs during Parse phase only.
  4428     // During Optimize phase a dead MergeMem node will be subsumed by Top.
  4429     if( !can_reshape ) {
  4430       for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
  4431         if( in(i) != empty_mem ) { set_req(i, empty_mem); }
  4436   if( !progress && base_memory()->is_Phi() && can_reshape ) {
  4437     // Check if PhiNode::Ideal's "Split phis through memory merges"
  4438     // transform should be attempted. Look for this->phi->this cycle.
  4439     uint merge_width = req();
  4440     if (merge_width > Compile::AliasIdxRaw) {
  4441       PhiNode* phi = base_memory()->as_Phi();
  4442       for( uint i = 1; i < phi->req(); ++i ) {// For all paths in
  4443         if (phi->in(i) == this) {
  4444           phase->is_IterGVN()->_worklist.push(phi);
  4445           break;
  4451   assert(progress || verify_sparse(), "please, no dups of base");
  4452   return progress;
  4455 //-------------------------set_base_memory-------------------------------------
  4456 void MergeMemNode::set_base_memory(Node *new_base) {
  4457   Node* empty_mem = empty_memory();
  4458   set_req(Compile::AliasIdxBot, new_base);
  4459   assert(memory_at(req()) == new_base, "must set default memory");
  4460   // Clear out other occurrences of new_base:
  4461   if (new_base != empty_mem) {
  4462     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
  4463       if (in(i) == new_base)  set_req(i, empty_mem);
  4468 //------------------------------out_RegMask------------------------------------
  4469 const RegMask &MergeMemNode::out_RegMask() const {
  4470   return RegMask::Empty;
  4473 //------------------------------dump_spec--------------------------------------
  4474 #ifndef PRODUCT
  4475 void MergeMemNode::dump_spec(outputStream *st) const {
  4476   st->print(" {");
  4477   Node* base_mem = base_memory();
  4478   for( uint i = Compile::AliasIdxRaw; i < req(); i++ ) {
  4479     Node* mem = memory_at(i);
  4480     if (mem == base_mem) { st->print(" -"); continue; }
  4481     st->print( " N%d:", mem->_idx );
  4482     Compile::current()->get_adr_type(i)->dump_on(st);
  4484   st->print(" }");
  4486 #endif // !PRODUCT
  4489 #ifdef ASSERT
  4490 static bool might_be_same(Node* a, Node* b) {
  4491   if (a == b)  return true;
  4492   if (!(a->is_Phi() || b->is_Phi()))  return false;
  4493   // phis shift around during optimization
  4494   return true;  // pretty stupid...
  4497 // verify a narrow slice (either incoming or outgoing)
  4498 static void verify_memory_slice(const MergeMemNode* m, int alias_idx, Node* n) {
  4499   if (!VerifyAliases)       return;  // don't bother to verify unless requested
  4500   if (is_error_reported())  return;  // muzzle asserts when debugging an error
  4501   if (Node::in_dump())      return;  // muzzle asserts when printing
  4502   assert(alias_idx >= Compile::AliasIdxRaw, "must not disturb base_memory or sentinel");
  4503   assert(n != NULL, "");
  4504   // Elide intervening MergeMem's
  4505   while (n->is_MergeMem()) {
  4506     n = n->as_MergeMem()->memory_at(alias_idx);
  4508   Compile* C = Compile::current();
  4509   const TypePtr* n_adr_type = n->adr_type();
  4510   if (n == m->empty_memory()) {
  4511     // Implicit copy of base_memory()
  4512   } else if (n_adr_type != TypePtr::BOTTOM) {
  4513     assert(n_adr_type != NULL, "new memory must have a well-defined adr_type");
  4514     assert(C->must_alias(n_adr_type, alias_idx), "new memory must match selected slice");
  4515   } else {
  4516     // A few places like make_runtime_call "know" that VM calls are narrow,
  4517     // and can be used to update only the VM bits stored as TypeRawPtr::BOTTOM.
  4518     bool expected_wide_mem = false;
  4519     if (n == m->base_memory()) {
  4520       expected_wide_mem = true;
  4521     } else if (alias_idx == Compile::AliasIdxRaw ||
  4522                n == m->memory_at(Compile::AliasIdxRaw)) {
  4523       expected_wide_mem = true;
  4524     } else if (!C->alias_type(alias_idx)->is_rewritable()) {
  4525       // memory can "leak through" calls on channels that
  4526       // are write-once.  Allow this also.
  4527       expected_wide_mem = true;
  4529     assert(expected_wide_mem, "expected narrow slice replacement");
  4532 #else // !ASSERT
  4533 #define verify_memory_slice(m,i,n) (void)(0)  // PRODUCT version is no-op
  4534 #endif
  4537 //-----------------------------memory_at---------------------------------------
  4538 Node* MergeMemNode::memory_at(uint alias_idx) const {
  4539   assert(alias_idx >= Compile::AliasIdxRaw ||
  4540          alias_idx == Compile::AliasIdxBot && Compile::current()->AliasLevel() == 0,
  4541          "must avoid base_memory and AliasIdxTop");
  4543   // Otherwise, it is a narrow slice.
  4544   Node* n = alias_idx < req() ? in(alias_idx) : empty_memory();
  4545   Compile *C = Compile::current();
  4546   if (is_empty_memory(n)) {
  4547     // the array is sparse; empty slots are the "top" node
  4548     n = base_memory();
  4549     assert(Node::in_dump()
  4550            || n == NULL || n->bottom_type() == Type::TOP
  4551            || n->adr_type() == NULL // address is TOP
  4552            || n->adr_type() == TypePtr::BOTTOM
  4553            || n->adr_type() == TypeRawPtr::BOTTOM
  4554            || Compile::current()->AliasLevel() == 0,
  4555            "must be a wide memory");
  4556     // AliasLevel == 0 if we are organizing the memory states manually.
  4557     // See verify_memory_slice for comments on TypeRawPtr::BOTTOM.
  4558   } else {
  4559     // make sure the stored slice is sane
  4560     #ifdef ASSERT
  4561     if (is_error_reported() || Node::in_dump()) {
  4562     } else if (might_be_same(n, base_memory())) {
  4563       // Give it a pass:  It is a mostly harmless repetition of the base.
  4564       // This can arise normally from node subsumption during optimization.
  4565     } else {
  4566       verify_memory_slice(this, alias_idx, n);
  4568     #endif
  4570   return n;
  4573 //---------------------------set_memory_at-------------------------------------
  4574 void MergeMemNode::set_memory_at(uint alias_idx, Node *n) {
  4575   verify_memory_slice(this, alias_idx, n);
  4576   Node* empty_mem = empty_memory();
  4577   if (n == base_memory())  n = empty_mem;  // collapse default
  4578   uint need_req = alias_idx+1;
  4579   if (req() < need_req) {
  4580     if (n == empty_mem)  return;  // already the default, so do not grow me
  4581     // grow the sparse array
  4582     do {
  4583       add_req(empty_mem);
  4584     } while (req() < need_req);
  4586   set_req( alias_idx, n );
  4591 //--------------------------iteration_setup------------------------------------
  4592 void MergeMemNode::iteration_setup(const MergeMemNode* other) {
  4593   if (other != NULL) {
  4594     grow_to_match(other);
  4595     // invariant:  the finite support of mm2 is within mm->req()
  4596     #ifdef ASSERT
  4597     for (uint i = req(); i < other->req(); i++) {
  4598       assert(other->is_empty_memory(other->in(i)), "slice left uncovered");
  4600     #endif
  4602   // Replace spurious copies of base_memory by top.
  4603   Node* base_mem = base_memory();
  4604   if (base_mem != NULL && !base_mem->is_top()) {
  4605     for (uint i = Compile::AliasIdxBot+1, imax = req(); i < imax; i++) {
  4606       if (in(i) == base_mem)
  4607         set_req(i, empty_memory());
  4612 //---------------------------grow_to_match-------------------------------------
  4613 void MergeMemNode::grow_to_match(const MergeMemNode* other) {
  4614   Node* empty_mem = empty_memory();
  4615   assert(other->is_empty_memory(empty_mem), "consistent sentinels");
  4616   // look for the finite support of the other memory
  4617   for (uint i = other->req(); --i >= req(); ) {
  4618     if (other->in(i) != empty_mem) {
  4619       uint new_len = i+1;
  4620       while (req() < new_len)  add_req(empty_mem);
  4621       break;
  4626 //---------------------------verify_sparse-------------------------------------
  4627 #ifndef PRODUCT
  4628 bool MergeMemNode::verify_sparse() const {
  4629   assert(is_empty_memory(make_empty_memory()), "sane sentinel");
  4630   Node* base_mem = base_memory();
  4631   // The following can happen in degenerate cases, since empty==top.
  4632   if (is_empty_memory(base_mem))  return true;
  4633   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
  4634     assert(in(i) != NULL, "sane slice");
  4635     if (in(i) == base_mem)  return false;  // should have been the sentinel value!
  4637   return true;
  4640 bool MergeMemStream::match_memory(Node* mem, const MergeMemNode* mm, int idx) {
  4641   Node* n;
  4642   n = mm->in(idx);
  4643   if (mem == n)  return true;  // might be empty_memory()
  4644   n = (idx == Compile::AliasIdxBot)? mm->base_memory(): mm->memory_at(idx);
  4645   if (mem == n)  return true;
  4646   while (n->is_Phi() && (n = n->as_Phi()->is_copy()) != NULL) {
  4647     if (mem == n)  return true;
  4648     if (n == NULL)  break;
  4650   return false;
  4652 #endif // !PRODUCT

mercurial