1 /*
   2  * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "libadt/vectset.hpp"
  27 #include "memory/allocation.inline.hpp"
  28 #include "opto/cfgnode.hpp"
  29 #include "opto/connode.hpp"
  30 #include "opto/loopnode.hpp"
  31 #include "opto/machnode.hpp"
  32 #include "opto/matcher.hpp"
  33 #include "opto/node.hpp"
  34 #include "opto/opcodes.hpp"
  35 #include "opto/regmask.hpp"
  36 #include "opto/type.hpp"
  37 #include "utilities/copy.hpp"
  38 
  39 class RegMask;
  40 // #include "phase.hpp"
  41 class PhaseTransform;
  42 class PhaseGVN;
  43 
  44 // Arena we are currently building Nodes in
  45 const uint Node::NotAMachineReg = 0xffff0000;
  46 
  47 #ifndef PRODUCT
  48 extern int nodes_created;
  49 #endif
  50 
  51 #ifdef ASSERT
  52 
  53 //-------------------------- construct_node------------------------------------
  54 // Set a breakpoint here to identify where a particular node index is built.
  55 void Node::verify_construction() {
  56   _debug_orig = NULL;
  57   int old_debug_idx = Compile::debug_idx();
  58   int new_debug_idx = old_debug_idx+1;
  59   if (new_debug_idx > 0) {
  60     // Arrange that the lowest five decimal digits of _debug_idx
  61     // will repeat those of _idx. In case this is somehow pathological,
  62     // we continue to assign negative numbers (!) consecutively.
  63     const int mod = 100000;
  64     int bump = (int)(_idx - new_debug_idx) % mod;
  65     if (bump < 0)  bump += mod;
  66     assert(bump >= 0 && bump < mod, "");
  67     new_debug_idx += bump;
  68   }
  69   Compile::set_debug_idx(new_debug_idx);
  70   set_debug_idx( new_debug_idx );
  71   assert(Compile::current()->unique() < (INT_MAX - 1), "Node limit exceeded INT_MAX");
  72   assert(Compile::current()->live_nodes() < Compile::current()->max_node_limit(), "Live Node limit exceeded limit");
  73   if (BreakAtNode != 0 && (_debug_idx == BreakAtNode || (int)_idx == BreakAtNode)) {
  74     tty->print_cr("BreakAtNode: _idx=%d _debug_idx=%d", _idx, _debug_idx);
  75     BREAKPOINT;
  76   }
  77 #if OPTO_DU_ITERATOR_ASSERT
  78   _last_del = NULL;
  79   _del_tick = 0;
  80 #endif
  81   _hash_lock = 0;
  82 }
  83 
  84 
  85 // #ifdef ASSERT ...
  86 
  87 #if OPTO_DU_ITERATOR_ASSERT
  88 void DUIterator_Common::sample(const Node* node) {
  89   _vdui     = VerifyDUIterators;
  90   _node     = node;
  91   _outcnt   = node->_outcnt;
  92   _del_tick = node->_del_tick;
  93   _last     = NULL;
  94 }
  95 
  96 void DUIterator_Common::verify(const Node* node, bool at_end_ok) {
  97   assert(_node     == node, "consistent iterator source");
  98   assert(_del_tick == node->_del_tick, "no unexpected deletions allowed");
  99 }
 100 
 101 void DUIterator_Common::verify_resync() {
 102   // Ensure that the loop body has just deleted the last guy produced.
 103   const Node* node = _node;
 104   // Ensure that at least one copy of the last-seen edge was deleted.
 105   // Note:  It is OK to delete multiple copies of the last-seen edge.
 106   // Unfortunately, we have no way to verify that all the deletions delete
 107   // that same edge.  On this point we must use the Honor System.
 108   assert(node->_del_tick >= _del_tick+1, "must have deleted an edge");
 109   assert(node->_last_del == _last, "must have deleted the edge just produced");
 110   // We liked this deletion, so accept the resulting outcnt and tick.
 111   _outcnt   = node->_outcnt;
 112   _del_tick = node->_del_tick;
 113 }
 114 
 115 void DUIterator_Common::reset(const DUIterator_Common& that) {
 116   if (this == &that)  return;  // ignore assignment to self
 117   if (!_vdui) {
 118     // We need to initialize everything, overwriting garbage values.
 119     _last = that._last;
 120     _vdui = that._vdui;
 121   }
 122   // Note:  It is legal (though odd) for an iterator over some node x
 123   // to be reassigned to iterate over another node y.  Some doubly-nested
 124   // progress loops depend on being able to do this.
 125   const Node* node = that._node;
 126   // Re-initialize everything, except _last.
 127   _node     = node;
 128   _outcnt   = node->_outcnt;
 129   _del_tick = node->_del_tick;
 130 }
 131 
 132 void DUIterator::sample(const Node* node) {
 133   DUIterator_Common::sample(node);      // Initialize the assertion data.
 134   _refresh_tick = 0;                    // No refreshes have happened, as yet.
 135 }
 136 
 137 void DUIterator::verify(const Node* node, bool at_end_ok) {
 138   DUIterator_Common::verify(node, at_end_ok);
 139   assert(_idx      <  node->_outcnt + (uint)at_end_ok, "idx in range");
 140 }
 141 
 142 void DUIterator::verify_increment() {
 143   if (_refresh_tick & 1) {
 144     // We have refreshed the index during this loop.
 145     // Fix up _idx to meet asserts.
 146     if (_idx > _outcnt)  _idx = _outcnt;
 147   }
 148   verify(_node, true);
 149 }
 150 
 151 void DUIterator::verify_resync() {
 152   // Note:  We do not assert on _outcnt, because insertions are OK here.
 153   DUIterator_Common::verify_resync();
 154   // Make sure we are still in sync, possibly with no more out-edges:
 155   verify(_node, true);
 156 }
 157 
 158 void DUIterator::reset(const DUIterator& that) {
 159   if (this == &that)  return;  // self assignment is always a no-op
 160   assert(that._refresh_tick == 0, "assign only the result of Node::outs()");
 161   assert(that._idx          == 0, "assign only the result of Node::outs()");
 162   assert(_idx               == that._idx, "already assigned _idx");
 163   if (!_vdui) {
 164     // We need to initialize everything, overwriting garbage values.
 165     sample(that._node);
 166   } else {
 167     DUIterator_Common::reset(that);
 168     if (_refresh_tick & 1) {
 169       _refresh_tick++;                  // Clear the "was refreshed" flag.
 170     }
 171     assert(_refresh_tick < 2*100000, "DU iteration must converge quickly");
 172   }
 173 }
 174 
 175 void DUIterator::refresh() {
 176   DUIterator_Common::sample(_node);     // Re-fetch assertion data.
 177   _refresh_tick |= 1;                   // Set the "was refreshed" flag.
 178 }
 179 
 180 void DUIterator::verify_finish() {
 181   // If the loop has killed the node, do not require it to re-run.
 182   if (_node->_outcnt == 0)  _refresh_tick &= ~1;
 183   // If this assert triggers, it means that a loop used refresh_out_pos
 184   // to re-synch an iteration index, but the loop did not correctly
 185   // re-run itself, using a "while (progress)" construct.
 186   // This iterator enforces the rule that you must keep trying the loop
 187   // until it "runs clean" without any need for refreshing.
 188   assert(!(_refresh_tick & 1), "the loop must run once with no refreshing");
 189 }
 190 
 191 
 192 void DUIterator_Fast::verify(const Node* node, bool at_end_ok) {
 193   DUIterator_Common::verify(node, at_end_ok);
 194   Node** out    = node->_out;
 195   uint   cnt    = node->_outcnt;
 196   assert(cnt == _outcnt, "no insertions allowed");
 197   assert(_outp >= out && _outp <= out + cnt - !at_end_ok, "outp in range");
 198   // This last check is carefully designed to work for NO_OUT_ARRAY.
 199 }
 200 
 201 void DUIterator_Fast::verify_limit() {
 202   const Node* node = _node;
 203   verify(node, true);
 204   assert(_outp == node->_out + node->_outcnt, "limit still correct");
 205 }
 206 
 207 void DUIterator_Fast::verify_resync() {
 208   const Node* node = _node;
 209   if (_outp == node->_out + _outcnt) {
 210     // Note that the limit imax, not the pointer i, gets updated with the
 211     // exact count of deletions.  (For the pointer it's always "--i".)
 212     assert(node->_outcnt+node->_del_tick == _outcnt+_del_tick, "no insertions allowed with deletion(s)");
 213     // This is a limit pointer, with a name like "imax".
 214     // Fudge the _last field so that the common assert will be happy.
 215     _last = (Node*) node->_last_del;
 216     DUIterator_Common::verify_resync();
 217   } else {
 218     assert(node->_outcnt < _outcnt, "no insertions allowed with deletion(s)");
 219     // A normal internal pointer.
 220     DUIterator_Common::verify_resync();
 221     // Make sure we are still in sync, possibly with no more out-edges:
 222     verify(node, true);
 223   }
 224 }
 225 
 226 void DUIterator_Fast::verify_relimit(uint n) {
 227   const Node* node = _node;
 228   assert((int)n > 0, "use imax -= n only with a positive count");
 229   // This must be a limit pointer, with a name like "imax".
 230   assert(_outp == node->_out + node->_outcnt, "apply -= only to a limit (imax)");
 231   // The reported number of deletions must match what the node saw.
 232   assert(node->_del_tick == _del_tick + n, "must have deleted n edges");
 233   // Fudge the _last field so that the common assert will be happy.
 234   _last = (Node*) node->_last_del;
 235   DUIterator_Common::verify_resync();
 236 }
 237 
 238 void DUIterator_Fast::reset(const DUIterator_Fast& that) {
 239   assert(_outp              == that._outp, "already assigned _outp");
 240   DUIterator_Common::reset(that);
 241 }
 242 
 243 void DUIterator_Last::verify(const Node* node, bool at_end_ok) {
 244   // at_end_ok means the _outp is allowed to underflow by 1
 245   _outp += at_end_ok;
 246   DUIterator_Fast::verify(node, at_end_ok);  // check _del_tick, etc.
 247   _outp -= at_end_ok;
 248   assert(_outp == (node->_out + node->_outcnt) - 1, "pointer must point to end of nodes");
 249 }
 250 
 251 void DUIterator_Last::verify_limit() {
 252   // Do not require the limit address to be resynched.
 253   //verify(node, true);
 254   assert(_outp == _node->_out, "limit still correct");
 255 }
 256 
 257 void DUIterator_Last::verify_step(uint num_edges) {
 258   assert((int)num_edges > 0, "need non-zero edge count for loop progress");
 259   _outcnt   -= num_edges;
 260   _del_tick += num_edges;
 261   // Make sure we are still in sync, possibly with no more out-edges:
 262   const Node* node = _node;
 263   verify(node, true);
 264   assert(node->_last_del == _last, "must have deleted the edge just produced");
 265 }
 266 
 267 #endif //OPTO_DU_ITERATOR_ASSERT
 268 
 269 
 270 #endif //ASSERT
 271 
 272 
 273 // This constant used to initialize _out may be any non-null value.
 274 // The value NULL is reserved for the top node only.
 275 #define NO_OUT_ARRAY ((Node**)-1)
 276 
 277 // Out-of-line code from node constructors.
 278 // Executed only when extra debug info. is being passed around.
 279 static void init_node_notes(Compile* C, int idx, Node_Notes* nn) {
 280   C->set_node_notes_at(idx, nn);
 281 }
 282 
 283 // Shared initialization code.
 284 inline int Node::Init(int req) {
 285   Compile* C = Compile::current();
 286   int idx = C->next_unique();
 287 
 288   // Allocate memory for the necessary number of edges.
 289   if (req > 0) {
 290     // Allocate space for _in array to have double alignment.
 291     _in = (Node **) ((char *) (C->node_arena()->Amalloc_D(req * sizeof(void*))));
 292 #ifdef ASSERT
 293     _in[req-1] = this; // magic cookie for assertion check
 294 #endif
 295   }
 296   // If there are default notes floating around, capture them:
 297   Node_Notes* nn = C->default_node_notes();
 298   if (nn != NULL)  init_node_notes(C, idx, nn);
 299 
 300   // Note:  At this point, C is dead,
 301   // and we begin to initialize the new Node.
 302 
 303   _cnt = _max = req;
 304   _outcnt = _outmax = 0;
 305   _class_id = Class_Node;
 306   _flags = 0;
 307   _out = NO_OUT_ARRAY;
 308   return idx;
 309 }
 310 
 311 //------------------------------Node-------------------------------------------
 312 // Create a Node, with a given number of required edges.
 313 Node::Node(uint req)
 314   : _idx(Init(req))
 315 {
 316   assert( req < Compile::current()->max_node_limit() - NodeLimitFudgeFactor, "Input limit exceeded" );
 317   debug_only( verify_construction() );
 318   NOT_PRODUCT(nodes_created++);
 319   if (req == 0) {
 320     assert( _in == (Node**)this, "Must not pass arg count to 'new'" );
 321     _in = NULL;
 322   } else {
 323     assert( _in[req-1] == this, "Must pass arg count to 'new'" );
 324     Node** to = _in;
 325     for(uint i = 0; i < req; i++) {
 326       to[i] = NULL;
 327     }
 328   }
 329 }
 330 
 331 //------------------------------Node-------------------------------------------
 332 Node::Node(Node *n0)
 333   : _idx(Init(1))
 334 {
 335   debug_only( verify_construction() );
 336   NOT_PRODUCT(nodes_created++);
 337   // Assert we allocated space for input array already
 338   assert( _in[0] == this, "Must pass arg count to 'new'" );
 339   assert( is_not_dead(n0), "can not use dead node");
 340   _in[0] = n0; if (n0 != NULL) n0->add_out((Node *)this);
 341 }
 342 
 343 //------------------------------Node-------------------------------------------
 344 Node::Node(Node *n0, Node *n1)
 345   : _idx(Init(2))
 346 {
 347   debug_only( verify_construction() );
 348   NOT_PRODUCT(nodes_created++);
 349   // Assert we allocated space for input array already
 350   assert( _in[1] == this, "Must pass arg count to 'new'" );
 351   assert( is_not_dead(n0), "can not use dead node");
 352   assert( is_not_dead(n1), "can not use dead node");
 353   _in[0] = n0; if (n0 != NULL) n0->add_out((Node *)this);
 354   _in[1] = n1; if (n1 != NULL) n1->add_out((Node *)this);
 355 }
 356 
 357 //------------------------------Node-------------------------------------------
 358 Node::Node(Node *n0, Node *n1, Node *n2)
 359   : _idx(Init(3))
 360 {
 361   debug_only( verify_construction() );
 362   NOT_PRODUCT(nodes_created++);
 363   // Assert we allocated space for input array already
 364   assert( _in[2] == this, "Must pass arg count to 'new'" );
 365   assert( is_not_dead(n0), "can not use dead node");
 366   assert( is_not_dead(n1), "can not use dead node");
 367   assert( is_not_dead(n2), "can not use dead node");
 368   _in[0] = n0; if (n0 != NULL) n0->add_out((Node *)this);
 369   _in[1] = n1; if (n1 != NULL) n1->add_out((Node *)this);
 370   _in[2] = n2; if (n2 != NULL) n2->add_out((Node *)this);
 371 }
 372 
 373 //------------------------------Node-------------------------------------------
 374 Node::Node(Node *n0, Node *n1, Node *n2, Node *n3)
 375   : _idx(Init(4))
 376 {
 377   debug_only( verify_construction() );
 378   NOT_PRODUCT(nodes_created++);
 379   // Assert we allocated space for input array already
 380   assert( _in[3] == this, "Must pass arg count to 'new'" );
 381   assert( is_not_dead(n0), "can not use dead node");
 382   assert( is_not_dead(n1), "can not use dead node");
 383   assert( is_not_dead(n2), "can not use dead node");
 384   assert( is_not_dead(n3), "can not use dead node");
 385   _in[0] = n0; if (n0 != NULL) n0->add_out((Node *)this);
 386   _in[1] = n1; if (n1 != NULL) n1->add_out((Node *)this);
 387   _in[2] = n2; if (n2 != NULL) n2->add_out((Node *)this);
 388   _in[3] = n3; if (n3 != NULL) n3->add_out((Node *)this);
 389 }
 390 
 391 //------------------------------Node-------------------------------------------
 392 Node::Node(Node *n0, Node *n1, Node *n2, Node *n3, Node *n4)
 393   : _idx(Init(5))
 394 {
 395   debug_only( verify_construction() );
 396   NOT_PRODUCT(nodes_created++);
 397   // Assert we allocated space for input array already
 398   assert( _in[4] == this, "Must pass arg count to 'new'" );
 399   assert( is_not_dead(n0), "can not use dead node");
 400   assert( is_not_dead(n1), "can not use dead node");
 401   assert( is_not_dead(n2), "can not use dead node");
 402   assert( is_not_dead(n3), "can not use dead node");
 403   assert( is_not_dead(n4), "can not use dead node");
 404   _in[0] = n0; if (n0 != NULL) n0->add_out((Node *)this);
 405   _in[1] = n1; if (n1 != NULL) n1->add_out((Node *)this);
 406   _in[2] = n2; if (n2 != NULL) n2->add_out((Node *)this);
 407   _in[3] = n3; if (n3 != NULL) n3->add_out((Node *)this);
 408   _in[4] = n4; if (n4 != NULL) n4->add_out((Node *)this);
 409 }
 410 
 411 //------------------------------Node-------------------------------------------
 412 Node::Node(Node *n0, Node *n1, Node *n2, Node *n3,
 413                      Node *n4, Node *n5)
 414   : _idx(Init(6))
 415 {
 416   debug_only( verify_construction() );
 417   NOT_PRODUCT(nodes_created++);
 418   // Assert we allocated space for input array already
 419   assert( _in[5] == this, "Must pass arg count to 'new'" );
 420   assert( is_not_dead(n0), "can not use dead node");
 421   assert( is_not_dead(n1), "can not use dead node");
 422   assert( is_not_dead(n2), "can not use dead node");
 423   assert( is_not_dead(n3), "can not use dead node");
 424   assert( is_not_dead(n4), "can not use dead node");
 425   assert( is_not_dead(n5), "can not use dead node");
 426   _in[0] = n0; if (n0 != NULL) n0->add_out((Node *)this);
 427   _in[1] = n1; if (n1 != NULL) n1->add_out((Node *)this);
 428   _in[2] = n2; if (n2 != NULL) n2->add_out((Node *)this);
 429   _in[3] = n3; if (n3 != NULL) n3->add_out((Node *)this);
 430   _in[4] = n4; if (n4 != NULL) n4->add_out((Node *)this);
 431   _in[5] = n5; if (n5 != NULL) n5->add_out((Node *)this);
 432 }
 433 
 434 //------------------------------Node-------------------------------------------
 435 Node::Node(Node *n0, Node *n1, Node *n2, Node *n3,
 436                      Node *n4, Node *n5, Node *n6)
 437   : _idx(Init(7))
 438 {
 439   debug_only( verify_construction() );
 440   NOT_PRODUCT(nodes_created++);
 441   // Assert we allocated space for input array already
 442   assert( _in[6] == this, "Must pass arg count to 'new'" );
 443   assert( is_not_dead(n0), "can not use dead node");
 444   assert( is_not_dead(n1), "can not use dead node");
 445   assert( is_not_dead(n2), "can not use dead node");
 446   assert( is_not_dead(n3), "can not use dead node");
 447   assert( is_not_dead(n4), "can not use dead node");
 448   assert( is_not_dead(n5), "can not use dead node");
 449   assert( is_not_dead(n6), "can not use dead node");
 450   _in[0] = n0; if (n0 != NULL) n0->add_out((Node *)this);
 451   _in[1] = n1; if (n1 != NULL) n1->add_out((Node *)this);
 452   _in[2] = n2; if (n2 != NULL) n2->add_out((Node *)this);
 453   _in[3] = n3; if (n3 != NULL) n3->add_out((Node *)this);
 454   _in[4] = n4; if (n4 != NULL) n4->add_out((Node *)this);
 455   _in[5] = n5; if (n5 != NULL) n5->add_out((Node *)this);
 456   _in[6] = n6; if (n6 != NULL) n6->add_out((Node *)this);
 457 }
 458 
 459 
 460 //------------------------------clone------------------------------------------
 461 // Clone a Node.
 462 Node *Node::clone() const {
 463   Compile* C = Compile::current();
 464   uint s = size_of();           // Size of inherited Node
 465   Node *n = (Node*)C->node_arena()->Amalloc_D(size_of() + _max*sizeof(Node*));
 466   Copy::conjoint_words_to_lower((HeapWord*)this, (HeapWord*)n, s);
 467   // Set the new input pointer array
 468   n->_in = (Node**)(((char*)n)+s);
 469   // Cannot share the old output pointer array, so kill it
 470   n->_out = NO_OUT_ARRAY;
 471   // And reset the counters to 0
 472   n->_outcnt = 0;
 473   n->_outmax = 0;
 474   // Unlock this guy, since he is not in any hash table.
 475   debug_only(n->_hash_lock = 0);
 476   // Walk the old node's input list to duplicate its edges
 477   uint i;
 478   for( i = 0; i < len(); i++ ) {
 479     Node *x = in(i);
 480     n->_in[i] = x;
 481     if (x != NULL) x->add_out(n);
 482   }
 483   if (is_macro())
 484     C->add_macro_node(n);
 485   if (is_expensive())
 486     C->add_expensive_node(n);
 487 
 488   n->set_idx(C->next_unique()); // Get new unique index as well
 489   debug_only( n->verify_construction() );
 490   NOT_PRODUCT(nodes_created++);
 491   // Do not patch over the debug_idx of a clone, because it makes it
 492   // impossible to break on the clone's moment of creation.
 493   //debug_only( n->set_debug_idx( debug_idx() ) );
 494 
 495   C->copy_node_notes_to(n, (Node*) this);
 496 
 497   // MachNode clone
 498   uint nopnds;
 499   if (this->is_Mach() && (nopnds = this->as_Mach()->num_opnds()) > 0) {
 500     MachNode *mach  = n->as_Mach();
 501     MachNode *mthis = this->as_Mach();
 502     // Get address of _opnd_array.
 503     // It should be the same offset since it is the clone of this node.
 504     MachOper **from = mthis->_opnds;
 505     MachOper **to = (MachOper **)((size_t)(&mach->_opnds) +
 506                     pointer_delta((const void*)from,
 507                                   (const void*)(&mthis->_opnds), 1));
 508     mach->_opnds = to;
 509     for ( uint i = 0; i < nopnds; ++i ) {
 510       to[i] = from[i]->clone();
 511     }
 512   }
 513   // cloning CallNode may need to clone JVMState
 514   if (n->is_Call()) {
 515     n->as_Call()->clone_jvms(C);
 516   }
 517   if (n->is_SafePoint()) {
 518     n->as_SafePoint()->clone_replaced_nodes();
 519   }
 520   return n;                     // Return the clone
 521 }
 522 
 523 //---------------------------setup_is_top--------------------------------------
 524 // Call this when changing the top node, to reassert the invariants
 525 // required by Node::is_top.  See Compile::set_cached_top_node.
 526 void Node::setup_is_top() {
 527   if (this == (Node*)Compile::current()->top()) {
 528     // This node has just become top.  Kill its out array.
 529     _outcnt = _outmax = 0;
 530     _out = NULL;                           // marker value for top
 531     assert(is_top(), "must be top");
 532   } else {
 533     if (_out == NULL)  _out = NO_OUT_ARRAY;
 534     assert(!is_top(), "must not be top");
 535   }
 536 }
 537 
 538 
 539 //------------------------------~Node------------------------------------------
 540 // Fancy destructor; eagerly attempt to reclaim Node numberings and storage
 541 extern int reclaim_idx ;
 542 extern int reclaim_in  ;
 543 extern int reclaim_node;
 544 void Node::destruct() {
 545   // Eagerly reclaim unique Node numberings
 546   Compile* compile = Compile::current();
 547   if ((uint)_idx+1 == compile->unique()) {
 548     compile->set_unique(compile->unique()-1);
 549 #ifdef ASSERT
 550     reclaim_idx++;
 551 #endif
 552   }
 553   // Clear debug info:
 554   Node_Notes* nn = compile->node_notes_at(_idx);
 555   if (nn != NULL)  nn->clear();
 556   // Walk the input array, freeing the corresponding output edges
 557   _cnt = _max;  // forget req/prec distinction
 558   uint i;
 559   for( i = 0; i < _max; i++ ) {
 560     set_req(i, NULL);
 561     //assert(def->out(def->outcnt()-1) == (Node *)this,"bad def-use hacking in reclaim");
 562   }
 563   assert(outcnt() == 0, "deleting a node must not leave a dangling use");
 564   // See if the input array was allocated just prior to the object
 565   int edge_size = _max*sizeof(void*);
 566   int out_edge_size = _outmax*sizeof(void*);
 567   char *edge_end = ((char*)_in) + edge_size;
 568   char *out_array = (char*)(_out == NO_OUT_ARRAY? NULL: _out);
 569   char *out_edge_end = out_array + out_edge_size;
 570   int node_size = size_of();
 571 
 572   // Free the output edge array
 573   if (out_edge_size > 0) {
 574 #ifdef ASSERT
 575     if( out_edge_end == compile->node_arena()->hwm() )
 576       reclaim_in  += out_edge_size;  // count reclaimed out edges with in edges
 577 #endif
 578     compile->node_arena()->Afree(out_array, out_edge_size);
 579   }
 580 
 581   // Free the input edge array and the node itself
 582   if( edge_end == (char*)this ) {
 583 #ifdef ASSERT
 584     if( edge_end+node_size == compile->node_arena()->hwm() ) {
 585       reclaim_in  += edge_size;
 586       reclaim_node+= node_size;
 587     }
 588 #else
 589     // It was; free the input array and object all in one hit
 590     compile->node_arena()->Afree(_in,edge_size+node_size);
 591 #endif
 592   } else {
 593 
 594     // Free just the input array
 595 #ifdef ASSERT
 596     if( edge_end == compile->node_arena()->hwm() )
 597       reclaim_in  += edge_size;
 598 #endif
 599     compile->node_arena()->Afree(_in,edge_size);
 600 
 601     // Free just the object
 602 #ifdef ASSERT
 603     if( ((char*)this) + node_size == compile->node_arena()->hwm() )
 604       reclaim_node+= node_size;
 605 #else
 606     compile->node_arena()->Afree(this,node_size);
 607 #endif
 608   }
 609   if (is_macro()) {
 610     compile->remove_macro_node(this);
 611   }
 612   if (is_expensive()) {
 613     compile->remove_expensive_node(this);
 614   }
 615   if (is_SafePoint()) {
 616     as_SafePoint()->delete_replaced_nodes();
 617   }
 618 #ifdef ASSERT
 619   // We will not actually delete the storage, but we'll make the node unusable.
 620   *(address*)this = badAddress;  // smash the C++ vtbl, probably
 621   _in = _out = (Node**) badAddress;
 622   _max = _cnt = _outmax = _outcnt = 0;
 623   compile->remove_modified_node(this);
 624 #endif
 625 }
 626 
 627 //------------------------------grow-------------------------------------------
 628 // Grow the input array, making space for more edges
 629 void Node::grow( uint len ) {
 630   Arena* arena = Compile::current()->node_arena();
 631   uint new_max = _max;
 632   if( new_max == 0 ) {
 633     _max = 4;
 634     _in = (Node**)arena->Amalloc(4*sizeof(Node*));
 635     Node** to = _in;
 636     to[0] = NULL;
 637     to[1] = NULL;
 638     to[2] = NULL;
 639     to[3] = NULL;
 640     return;
 641   }
 642   while( new_max <= len ) new_max <<= 1; // Find next power-of-2
 643   // Trimming to limit allows a uint8 to handle up to 255 edges.
 644   // Previously I was using only powers-of-2 which peaked at 128 edges.
 645   //if( new_max >= limit ) new_max = limit-1;
 646   _in = (Node**)arena->Arealloc(_in, _max*sizeof(Node*), new_max*sizeof(Node*));
 647   Copy::zero_to_bytes(&_in[_max], (new_max-_max)*sizeof(Node*)); // NULL all new space
 648   _max = new_max;               // Record new max length
 649   // This assertion makes sure that Node::_max is wide enough to
 650   // represent the numerical value of new_max.
 651   assert(_max == new_max && _max > len, "int width of _max is too small");
 652 }
 653 
 654 //-----------------------------out_grow----------------------------------------
 655 // Grow the input array, making space for more edges
 656 void Node::out_grow( uint len ) {
 657   assert(!is_top(), "cannot grow a top node's out array");
 658   Arena* arena = Compile::current()->node_arena();
 659   uint new_max = _outmax;
 660   if( new_max == 0 ) {
 661     _outmax = 4;
 662     _out = (Node **)arena->Amalloc(4*sizeof(Node*));
 663     return;
 664   }
 665   while( new_max <= len ) new_max <<= 1; // Find next power-of-2
 666   // Trimming to limit allows a uint8 to handle up to 255 edges.
 667   // Previously I was using only powers-of-2 which peaked at 128 edges.
 668   //if( new_max >= limit ) new_max = limit-1;
 669   assert(_out != NULL && _out != NO_OUT_ARRAY, "out must have sensible value");
 670   _out = (Node**)arena->Arealloc(_out,_outmax*sizeof(Node*),new_max*sizeof(Node*));
 671   //Copy::zero_to_bytes(&_out[_outmax], (new_max-_outmax)*sizeof(Node*)); // NULL all new space
 672   _outmax = new_max;               // Record new max length
 673   // This assertion makes sure that Node::_max is wide enough to
 674   // represent the numerical value of new_max.
 675   assert(_outmax == new_max && _outmax > len, "int width of _outmax is too small");
 676 }
 677 
 678 #ifdef ASSERT
 679 //------------------------------is_dead----------------------------------------
 680 bool Node::is_dead() const {
 681   // Mach and pinch point nodes may look like dead.
 682   if( is_top() || is_Mach() || (Opcode() == Op_Node && _outcnt > 0) )
 683     return false;
 684   for( uint i = 0; i < _max; i++ )
 685     if( _in[i] != NULL )
 686       return false;
 687   dump();
 688   return true;
 689 }
 690 #endif
 691 
 692 
 693 //------------------------------is_unreachable---------------------------------
 694 bool Node::is_unreachable(PhaseIterGVN &igvn) const {
 695   assert(!is_Mach(), "doesn't work with MachNodes");
 696   return outcnt() == 0 || igvn.type(this) == Type::TOP || in(0)->is_top();
 697 }
 698 
 699 //------------------------------add_req----------------------------------------
 700 // Add a new required input at the end
 701 void Node::add_req( Node *n ) {
 702   assert( is_not_dead(n), "can not use dead node");
 703 
 704   // Look to see if I can move precedence down one without reallocating
 705   if( (_cnt >= _max) || (in(_max-1) != NULL) )
 706     grow( _max+1 );
 707 
 708   // Find a precedence edge to move
 709   if( in(_cnt) != NULL ) {       // Next precedence edge is busy?
 710     uint i;
 711     for( i=_cnt; i<_max; i++ )
 712       if( in(i) == NULL )       // Find the NULL at end of prec edge list
 713         break;                  // There must be one, since we grew the array
 714     _in[i] = in(_cnt);          // Move prec over, making space for req edge
 715   }
 716   _in[_cnt++] = n;            // Stuff over old prec edge
 717   if (n != NULL) n->add_out((Node *)this);
 718 }
 719 
 720 //---------------------------add_req_batch-------------------------------------
 721 // Add a new required input at the end
 722 void Node::add_req_batch( Node *n, uint m ) {
 723   assert( is_not_dead(n), "can not use dead node");
 724   // check various edge cases
 725   if ((int)m <= 1) {
 726     assert((int)m >= 0, "oob");
 727     if (m != 0)  add_req(n);
 728     return;
 729   }
 730 
 731   // Look to see if I can move precedence down one without reallocating
 732   if( (_cnt+m) > _max || _in[_max-m] )
 733     grow( _max+m );
 734 
 735   // Find a precedence edge to move
 736   if( _in[_cnt] != NULL ) {     // Next precedence edge is busy?
 737     uint i;
 738     for( i=_cnt; i<_max; i++ )
 739       if( _in[i] == NULL )      // Find the NULL at end of prec edge list
 740         break;                  // There must be one, since we grew the array
 741     // Slide all the precs over by m positions (assume #prec << m).
 742     Copy::conjoint_words_to_higher((HeapWord*)&_in[_cnt], (HeapWord*)&_in[_cnt+m], ((i-_cnt)*sizeof(Node*)));
 743   }
 744 
 745   // Stuff over the old prec edges
 746   for(uint i=0; i<m; i++ ) {
 747     _in[_cnt++] = n;
 748   }
 749 
 750   // Insert multiple out edges on the node.
 751   if (n != NULL && !n->is_top()) {
 752     for(uint i=0; i<m; i++ ) {
 753       n->add_out((Node *)this);
 754     }
 755   }
 756 }
 757 
 758 //------------------------------del_req----------------------------------------
 759 // Delete the required edge and compact the edge array
 760 void Node::del_req( uint idx ) {
 761   assert( idx < _cnt, "oob");
 762   assert( !VerifyHashTableKeys || _hash_lock == 0,
 763           "remove node from hash table before modifying it");
 764   // First remove corresponding def-use edge
 765   Node *n = in(idx);
 766   if (n != NULL) n->del_out((Node *)this);
 767   _in[idx] = in(--_cnt);  // Compact the array
 768   _in[_cnt] = NULL;       // NULL out emptied slot
 769   Compile::current()->record_modified_node(this);
 770 }
 771 
 772 //------------------------------del_req_ordered--------------------------------
 773 // Delete the required edge and compact the edge array with preserved order
 774 void Node::del_req_ordered( uint idx ) {
 775   assert( idx < _cnt, "oob");
 776   assert( !VerifyHashTableKeys || _hash_lock == 0,
 777           "remove node from hash table before modifying it");
 778   // First remove corresponding def-use edge
 779   Node *n = in(idx);
 780   if (n != NULL) n->del_out((Node *)this);
 781   if (idx < _cnt - 1) { // Not last edge ?
 782     Copy::conjoint_words_to_lower((HeapWord*)&_in[idx+1], (HeapWord*)&_in[idx], ((_cnt-idx-1)*sizeof(Node*)));
 783   }
 784   _in[--_cnt] = NULL;   // NULL out emptied slot
 785   Compile::current()->record_modified_node(this);
 786 }
 787 
 788 //------------------------------ins_req----------------------------------------
 789 // Insert a new required input at the end
 790 void Node::ins_req( uint idx, Node *n ) {
 791   assert( is_not_dead(n), "can not use dead node");
 792   add_req(NULL);                // Make space
 793   assert( idx < _max, "Must have allocated enough space");
 794   // Slide over
 795   if(_cnt-idx-1 > 0) {
 796     Copy::conjoint_words_to_higher((HeapWord*)&_in[idx], (HeapWord*)&_in[idx+1], ((_cnt-idx-1)*sizeof(Node*)));
 797   }
 798   _in[idx] = n;                            // Stuff over old required edge
 799   if (n != NULL) n->add_out((Node *)this); // Add reciprocal def-use edge
 800 }
 801 
 802 //-----------------------------find_edge---------------------------------------
 803 int Node::find_edge(Node* n) {
 804   for (uint i = 0; i < len(); i++) {
 805     if (_in[i] == n)  return i;
 806   }
 807   return -1;
 808 }
 809 
 810 //----------------------------replace_edge-------------------------------------
 811 int Node::replace_edge(Node* old, Node* neww) {
 812   if (old == neww)  return 0;  // nothing to do
 813   uint nrep = 0;
 814   for (uint i = 0; i < len(); i++) {
 815     if (in(i) == old) {
 816       if (i < req())
 817         set_req(i, neww);
 818       else
 819         set_prec(i, neww);
 820       nrep++;
 821     }
 822   }
 823   return nrep;
 824 }
 825 
 826 /**
 827  * Replace input edges in the range pointing to 'old' node.
 828  */
 829 int Node::replace_edges_in_range(Node* old, Node* neww, int start, int end) {
 830   if (old == neww)  return 0;  // nothing to do
 831   uint nrep = 0;
 832   for (int i = start; i < end; i++) {
 833     if (in(i) == old) {
 834       set_req(i, neww);
 835       nrep++;
 836     }
 837   }
 838   return nrep;
 839 }
 840 
 841 //-------------------------disconnect_inputs-----------------------------------
 842 // NULL out all inputs to eliminate incoming Def-Use edges.
 843 // Return the number of edges between 'n' and 'this'
 844 int Node::disconnect_inputs(Node *n, Compile* C) {
 845   int edges_to_n = 0;
 846 
 847   uint cnt = req();
 848   for( uint i = 0; i < cnt; ++i ) {
 849     if( in(i) == 0 ) continue;
 850     if( in(i) == n ) ++edges_to_n;
 851     set_req(i, NULL);
 852   }
 853   // Remove precedence edges if any exist
 854   // Note: Safepoints may have precedence edges, even during parsing
 855   if( (req() != len()) && (in(req()) != NULL) ) {
 856     uint max = len();
 857     for( uint i = 0; i < max; ++i ) {
 858       if( in(i) == 0 ) continue;
 859       if( in(i) == n ) ++edges_to_n;
 860       set_prec(i, NULL);
 861     }
 862   }
 863 
 864   // Node::destruct requires all out edges be deleted first
 865   // debug_only(destruct();)   // no reuse benefit expected
 866   if (edges_to_n == 0) {
 867     C->record_dead_node(_idx);
 868   }
 869   return edges_to_n;
 870 }
 871 
 872 //-----------------------------uncast---------------------------------------
 873 // %%% Temporary, until we sort out CheckCastPP vs. CastPP.
 874 // Strip away casting.  (It is depth-limited.)
 875 Node* Node::uncast() const {
 876   // Should be inline:
 877   //return is_ConstraintCast() ? uncast_helper(this) : (Node*) this;
 878   if (is_ConstraintCast() || is_CheckCastPP())
 879     return uncast_helper(this);
 880   else
 881     return (Node*) this;
 882 }
 883 
 884 //---------------------------uncast_helper-------------------------------------
 885 Node* Node::uncast_helper(const Node* p) {
 886 #ifdef ASSERT
 887   uint depth_count = 0;
 888   const Node* orig_p = p;
 889 #endif
 890 
 891   while (true) {
 892 #ifdef ASSERT
 893     if (depth_count >= K) {
 894       orig_p->dump(4);
 895       if (p != orig_p)
 896         p->dump(1);
 897     }
 898     assert(depth_count++ < K, "infinite loop in Node::uncast_helper");
 899 #endif
 900     if (p == NULL || p->req() != 2) {
 901       break;
 902     } else if (p->is_ConstraintCast()) {
 903       p = p->in(1);
 904     } else if (p->is_CheckCastPP()) {
 905       p = p->in(1);
 906     } else {
 907       break;
 908     }
 909   }
 910   return (Node*) p;
 911 }
 912 
 913 //------------------------------add_prec---------------------------------------
 914 // Add a new precedence input.  Precedence inputs are unordered, with
 915 // duplicates removed and NULLs packed down at the end.
 916 void Node::add_prec( Node *n ) {
 917   assert( is_not_dead(n), "can not use dead node");
 918 
 919   // Check for NULL at end
 920   if( _cnt >= _max || in(_max-1) )
 921     grow( _max+1 );
 922 
 923   // Find a precedence edge to move
 924   uint i = _cnt;
 925   while( in(i) != NULL ) i++;
 926   _in[i] = n;                                // Stuff prec edge over NULL
 927   if ( n != NULL) n->add_out((Node *)this);  // Add mirror edge
 928 }
 929 
 930 //------------------------------rm_prec----------------------------------------
 931 // Remove a precedence input.  Precedence inputs are unordered, with
 932 // duplicates removed and NULLs packed down at the end.
 933 void Node::rm_prec( uint j ) {
 934 
 935   // Find end of precedence list to pack NULLs
 936   uint i;
 937   for( i=j; i<_max; i++ )
 938     if( !_in[i] )               // Find the NULL at end of prec edge list
 939       break;
 940   if (_in[j] != NULL) _in[j]->del_out((Node *)this);
 941   _in[j] = _in[--i];            // Move last element over removed guy
 942   _in[i] = NULL;                // NULL out last element
 943 }
 944 
 945 //------------------------------size_of----------------------------------------
 946 uint Node::size_of() const { return sizeof(*this); }
 947 
 948 //------------------------------ideal_reg--------------------------------------
 949 uint Node::ideal_reg() const { return 0; }
 950 
 951 //------------------------------jvms-------------------------------------------
 952 JVMState* Node::jvms() const { return NULL; }
 953 
 954 #ifdef ASSERT
 955 //------------------------------jvms-------------------------------------------
 956 bool Node::verify_jvms(const JVMState* using_jvms) const {
 957   for (JVMState* jvms = this->jvms(); jvms != NULL; jvms = jvms->caller()) {
 958     if (jvms == using_jvms)  return true;
 959   }
 960   return false;
 961 }
 962 
 963 //------------------------------init_NodeProperty------------------------------
 964 void Node::init_NodeProperty() {
 965   assert(_max_classes <= max_jushort, "too many NodeProperty classes");
 966   assert(_max_flags <= max_jushort, "too many NodeProperty flags");
 967 }
 968 #endif
 969 
 970 //------------------------------format-----------------------------------------
 971 // Print as assembly
 972 void Node::format( PhaseRegAlloc *, outputStream *st ) const {}
 973 //------------------------------emit-------------------------------------------
 974 // Emit bytes starting at parameter 'ptr'.
 975 void Node::emit(CodeBuffer &cbuf, PhaseRegAlloc *ra_) const {}
 976 //------------------------------size-------------------------------------------
 977 // Size of instruction in bytes
 978 uint Node::size(PhaseRegAlloc *ra_) const { return 0; }
 979 
 980 //------------------------------CFG Construction-------------------------------
 981 // Nodes that end basic blocks, e.g. IfTrue/IfFalse, JumpProjNode, Root,
 982 // Goto and Return.
 983 const Node *Node::is_block_proj() const { return 0; }
 984 
 985 // Minimum guaranteed type
 986 const Type *Node::bottom_type() const { return Type::BOTTOM; }
 987 
 988 
 989 //------------------------------raise_bottom_type------------------------------
 990 // Get the worst-case Type output for this Node.
 991 void Node::raise_bottom_type(const Type* new_type) {
 992   if (is_Type()) {
 993     TypeNode *n = this->as_Type();
 994     if (VerifyAliases) {
 995       assert(new_type->higher_equal_speculative(n->type()), "new type must refine old type");
 996     }
 997     n->set_type(new_type);
 998   } else if (is_Load()) {
 999     LoadNode *n = this->as_Load();
1000     if (VerifyAliases) {
1001       assert(new_type->higher_equal_speculative(n->type()), "new type must refine old type");
1002     }
1003     n->set_type(new_type);
1004   }
1005 }
1006 
1007 //------------------------------Identity---------------------------------------
1008 // Return a node that the given node is equivalent to.
1009 Node *Node::Identity( PhaseTransform * ) {
1010   return this;                  // Default to no identities
1011 }
1012 
1013 //------------------------------Value------------------------------------------
1014 // Compute a new Type for a node using the Type of the inputs.
1015 const Type *Node::Value( PhaseTransform * ) const {
1016   return bottom_type();         // Default to worst-case Type
1017 }
1018 
1019 //------------------------------Ideal------------------------------------------
1020 //
1021 // 'Idealize' the graph rooted at this Node.
1022 //
1023 // In order to be efficient and flexible there are some subtle invariants
1024 // these Ideal calls need to hold.  Running with '+VerifyIterativeGVN' checks
1025 // these invariants, although its too slow to have on by default.  If you are
1026 // hacking an Ideal call, be sure to test with +VerifyIterativeGVN!
1027 //
1028 // The Ideal call almost arbitrarily reshape the graph rooted at the 'this'
1029 // pointer.  If ANY change is made, it must return the root of the reshaped
1030 // graph - even if the root is the same Node.  Example: swapping the inputs
1031 // to an AddINode gives the same answer and same root, but you still have to
1032 // return the 'this' pointer instead of NULL.
1033 //
1034 // You cannot return an OLD Node, except for the 'this' pointer.  Use the
1035 // Identity call to return an old Node; basically if Identity can find
1036 // another Node have the Ideal call make no change and return NULL.
1037 // Example: AddINode::Ideal must check for add of zero; in this case it
1038 // returns NULL instead of doing any graph reshaping.
1039 //
1040 // You cannot modify any old Nodes except for the 'this' pointer.  Due to
1041 // sharing there may be other users of the old Nodes relying on their current
1042 // semantics.  Modifying them will break the other users.
1043 // Example: when reshape "(X+3)+4" into "X+7" you must leave the Node for
1044 // "X+3" unchanged in case it is shared.
1045 //
1046 // If you modify the 'this' pointer's inputs, you should use
1047 // 'set_req'.  If you are making a new Node (either as the new root or
1048 // some new internal piece) you may use 'init_req' to set the initial
1049 // value.  You can make a new Node with either 'new' or 'clone'.  In
1050 // either case, def-use info is correctly maintained.
1051 //
1052 // Example: reshape "(X+3)+4" into "X+7":
1053 //    set_req(1, in(1)->in(1));
1054 //    set_req(2, phase->intcon(7));
1055 //    return this;
1056 // Example: reshape "X*4" into "X<<2"
1057 //    return new LShiftINode(in(1), phase->intcon(2));
1058 //
1059 // You must call 'phase->transform(X)' on any new Nodes X you make, except
1060 // for the returned root node.  Example: reshape "X*31" with "(X<<5)-X".
1061 //    Node *shift=phase->transform(new LShiftINode(in(1),phase->intcon(5)));
1062 //    return new AddINode(shift, in(1));
1063 //
1064 // When making a Node for a constant use 'phase->makecon' or 'phase->intcon'.
1065 // These forms are faster than 'phase->transform(new ConNode())' and Do
1066 // The Right Thing with def-use info.
1067 //
1068 // You cannot bury the 'this' Node inside of a graph reshape.  If the reshaped
1069 // graph uses the 'this' Node it must be the root.  If you want a Node with
1070 // the same Opcode as the 'this' pointer use 'clone'.
1071 //
1072 Node *Node::Ideal(PhaseGVN *phase, bool can_reshape) {
1073   return NULL;                  // Default to being Ideal already
1074 }
1075 
1076 // Some nodes have specific Ideal subgraph transformations only if they are
1077 // unique users of specific nodes. Such nodes should be put on IGVN worklist
1078 // for the transformations to happen.
1079 bool Node::has_special_unique_user() const {
1080   assert(outcnt() == 1, "match only for unique out");
1081   Node* n = unique_out();
1082   int op  = Opcode();
1083   if( this->is_Store() ) {
1084     // Condition for back-to-back stores folding.
1085     return n->Opcode() == op && n->in(MemNode::Memory) == this;
1086   } else if (this->is_Load()) {
1087     // Condition for removing an unused LoadNode from the MemBarAcquire precedence input
1088     return n->Opcode() == Op_MemBarAcquire;
1089   } else if( op == Op_AddL ) {
1090     // Condition for convL2I(addL(x,y)) ==> addI(convL2I(x),convL2I(y))
1091     return n->Opcode() == Op_ConvL2I && n->in(1) == this;
1092   } else if( op == Op_SubI || op == Op_SubL ) {
1093     // Condition for subI(x,subI(y,z)) ==> subI(addI(x,z),y)
1094     return n->Opcode() == op && n->in(2) == this;
1095   }
1096   return false;
1097 };
1098 
1099 //--------------------------find_exact_control---------------------------------
1100 // Skip Proj and CatchProj nodes chains. Check for Null and Top.
1101 Node* Node::find_exact_control(Node* ctrl) {
1102   if (ctrl == NULL && this->is_Region())
1103     ctrl = this->as_Region()->is_copy();
1104 
1105   if (ctrl != NULL && ctrl->is_CatchProj()) {
1106     if (ctrl->as_CatchProj()->_con == CatchProjNode::fall_through_index)
1107       ctrl = ctrl->in(0);
1108     if (ctrl != NULL && !ctrl->is_top())
1109       ctrl = ctrl->in(0);
1110   }
1111 
1112   if (ctrl != NULL && ctrl->is_Proj())
1113     ctrl = ctrl->in(0);
1114 
1115   return ctrl;
1116 }
1117 
1118 //--------------------------dominates------------------------------------------
1119 // Helper function for MemNode::all_controls_dominate().
1120 // Check if 'this' control node dominates or equal to 'sub' control node.
1121 // We already know that if any path back to Root or Start reaches 'this',
1122 // then all paths so, so this is a simple search for one example,
1123 // not an exhaustive search for a counterexample.
1124 bool Node::dominates(Node* sub, Node_List &nlist) {
1125   assert(this->is_CFG(), "expecting control");
1126   assert(sub != NULL && sub->is_CFG(), "expecting control");
1127 
1128   // detect dead cycle without regions
1129   int iterations_without_region_limit = DominatorSearchLimit;
1130 
1131   Node* orig_sub = sub;
1132   Node* dom      = this;
1133   bool  met_dom  = false;
1134   nlist.clear();
1135 
1136   // Walk 'sub' backward up the chain to 'dom', watching for regions.
1137   // After seeing 'dom', continue up to Root or Start.
1138   // If we hit a region (backward split point), it may be a loop head.
1139   // Keep going through one of the region's inputs.  If we reach the
1140   // same region again, go through a different input.  Eventually we
1141   // will either exit through the loop head, or give up.
1142   // (If we get confused, break out and return a conservative 'false'.)
1143   while (sub != NULL) {
1144     if (sub->is_top())  break; // Conservative answer for dead code.
1145     if (sub == dom) {
1146       if (nlist.size() == 0) {
1147         // No Region nodes except loops were visited before and the EntryControl
1148         // path was taken for loops: it did not walk in a cycle.
1149         return true;
1150       } else if (met_dom) {
1151         break;          // already met before: walk in a cycle
1152       } else {
1153         // Region nodes were visited. Continue walk up to Start or Root
1154         // to make sure that it did not walk in a cycle.
1155         met_dom = true; // first time meet
1156         iterations_without_region_limit = DominatorSearchLimit; // Reset
1157      }
1158     }
1159     if (sub->is_Start() || sub->is_Root()) {
1160       // Success if we met 'dom' along a path to Start or Root.
1161       // We assume there are no alternative paths that avoid 'dom'.
1162       // (This assumption is up to the caller to ensure!)
1163       return met_dom;
1164     }
1165     Node* up = sub->in(0);
1166     // Normalize simple pass-through regions and projections:
1167     up = sub->find_exact_control(up);
1168     // If sub == up, we found a self-loop.  Try to push past it.
1169     if (sub == up && sub->is_Loop()) {
1170       // Take loop entry path on the way up to 'dom'.
1171       up = sub->in(1); // in(LoopNode::EntryControl);
1172     } else if (sub == up && sub->is_Region() && sub->req() != 3) {
1173       // Always take in(1) path on the way up to 'dom' for clone regions
1174       // (with only one input) or regions which merge > 2 paths
1175       // (usually used to merge fast/slow paths).
1176       up = sub->in(1);
1177     } else if (sub == up && sub->is_Region()) {
1178       // Try both paths for Regions with 2 input paths (it may be a loop head).
1179       // It could give conservative 'false' answer without information
1180       // which region's input is the entry path.
1181       iterations_without_region_limit = DominatorSearchLimit; // Reset
1182 
1183       bool region_was_visited_before = false;
1184       // Was this Region node visited before?
1185       // If so, we have reached it because we accidentally took a
1186       // loop-back edge from 'sub' back into the body of the loop,
1187       // and worked our way up again to the loop header 'sub'.
1188       // So, take the first unexplored path on the way up to 'dom'.
1189       for (int j = nlist.size() - 1; j >= 0; j--) {
1190         intptr_t ni = (intptr_t)nlist.at(j);
1191         Node* visited = (Node*)(ni & ~1);
1192         bool  visited_twice_already = ((ni & 1) != 0);
1193         if (visited == sub) {
1194           if (visited_twice_already) {
1195             // Visited 2 paths, but still stuck in loop body.  Give up.
1196             return false;
1197           }
1198           // The Region node was visited before only once.
1199           // (We will repush with the low bit set, below.)
1200           nlist.remove(j);
1201           // We will find a new edge and re-insert.
1202           region_was_visited_before = true;
1203           break;
1204         }
1205       }
1206 
1207       // Find an incoming edge which has not been seen yet; walk through it.
1208       assert(up == sub, "");
1209       uint skip = region_was_visited_before ? 1 : 0;
1210       for (uint i = 1; i < sub->req(); i++) {
1211         Node* in = sub->in(i);
1212         if (in != NULL && !in->is_top() && in != sub) {
1213           if (skip == 0) {
1214             up = in;
1215             break;
1216           }
1217           --skip;               // skip this nontrivial input
1218         }
1219       }
1220 
1221       // Set 0 bit to indicate that both paths were taken.
1222       nlist.push((Node*)((intptr_t)sub + (region_was_visited_before ? 1 : 0)));
1223     }
1224 
1225     if (up == sub) {
1226       break;    // some kind of tight cycle
1227     }
1228     if (up == orig_sub && met_dom) {
1229       // returned back after visiting 'dom'
1230       break;    // some kind of cycle
1231     }
1232     if (--iterations_without_region_limit < 0) {
1233       break;    // dead cycle
1234     }
1235     sub = up;
1236   }
1237 
1238   // Did not meet Root or Start node in pred. chain.
1239   // Conservative answer for dead code.
1240   return false;
1241 }
1242 
1243 //------------------------------remove_dead_region-----------------------------
1244 // This control node is dead.  Follow the subgraph below it making everything
1245 // using it dead as well.  This will happen normally via the usual IterGVN
1246 // worklist but this call is more efficient.  Do not update use-def info
1247 // inside the dead region, just at the borders.
1248 static void kill_dead_code( Node *dead, PhaseIterGVN *igvn ) {
1249   // Con's are a popular node to re-hit in the hash table again.
1250   if( dead->is_Con() ) return;
1251 
1252   // Can't put ResourceMark here since igvn->_worklist uses the same arena
1253   // for verify pass with +VerifyOpto and we add/remove elements in it here.
1254   Node_List  nstack(Thread::current()->resource_area());
1255 
1256   Node *top = igvn->C->top();
1257   nstack.push(dead);
1258   bool has_irreducible_loop = igvn->C->has_irreducible_loop();
1259 
1260   while (nstack.size() > 0) {
1261     dead = nstack.pop();
1262     if (dead->outcnt() > 0) {
1263       // Keep dead node on stack until all uses are processed.
1264       nstack.push(dead);
1265       // For all Users of the Dead...    ;-)
1266       for (DUIterator_Last kmin, k = dead->last_outs(kmin); k >= kmin; ) {
1267         Node* use = dead->last_out(k);
1268         igvn->hash_delete(use);       // Yank from hash table prior to mod
1269         if (use->in(0) == dead) {     // Found another dead node
1270           assert (!use->is_Con(), "Control for Con node should be Root node.");
1271           use->set_req(0, top);       // Cut dead edge to prevent processing
1272           nstack.push(use);           // the dead node again.
1273         } else if (!has_irreducible_loop && // Backedge could be alive in irreducible loop
1274                    use->is_Loop() && !use->is_Root() &&       // Don't kill Root (RootNode extends LoopNode)
1275                    use->in(LoopNode::EntryControl) == dead) { // Dead loop if its entry is dead
1276           use->set_req(LoopNode::EntryControl, top);          // Cut dead edge to prevent processing
1277           use->set_req(0, top);       // Cut self edge
1278           nstack.push(use);
1279         } else {                      // Else found a not-dead user
1280           // Dead if all inputs are top or null
1281           bool dead_use = !use->is_Root(); // Keep empty graph alive
1282           for (uint j = 1; j < use->req(); j++) {
1283             Node* in = use->in(j);
1284             if (in == dead) {         // Turn all dead inputs into TOP
1285               use->set_req(j, top);
1286             } else if (in != NULL && !in->is_top()) {
1287               dead_use = false;
1288             }
1289           }
1290           if (dead_use) {
1291             if (use->is_Region()) {
1292               use->set_req(0, top);   // Cut self edge
1293             }
1294             nstack.push(use);
1295           } else {
1296             igvn->_worklist.push(use);
1297           }
1298         }
1299         // Refresh the iterator, since any number of kills might have happened.
1300         k = dead->last_outs(kmin);
1301       }
1302     } else { // (dead->outcnt() == 0)
1303       // Done with outputs.
1304       igvn->hash_delete(dead);
1305       igvn->_worklist.remove(dead);
1306       igvn->C->remove_modified_node(dead);
1307       igvn->set_type(dead, Type::TOP);
1308       if (dead->is_macro()) {
1309         igvn->C->remove_macro_node(dead);
1310       }
1311       if (dead->is_expensive()) {
1312         igvn->C->remove_expensive_node(dead);
1313       }
1314       igvn->C->record_dead_node(dead->_idx);
1315       // Kill all inputs to the dead guy
1316       for (uint i=0; i < dead->req(); i++) {
1317         Node *n = dead->in(i);      // Get input to dead guy
1318         if (n != NULL && !n->is_top()) { // Input is valid?
1319           dead->set_req(i, top);    // Smash input away
1320           if (n->outcnt() == 0) {   // Input also goes dead?
1321             if (!n->is_Con())
1322               nstack.push(n);       // Clear it out as well
1323           } else if (n->outcnt() == 1 &&
1324                      n->has_special_unique_user()) {
1325             igvn->add_users_to_worklist( n );
1326           } else if (n->outcnt() <= 2 && n->is_Store()) {
1327             // Push store's uses on worklist to enable folding optimization for
1328             // store/store and store/load to the same address.
1329             // The restriction (outcnt() <= 2) is the same as in set_req_X()
1330             // and remove_globally_dead_node().
1331             igvn->add_users_to_worklist( n );
1332           }
1333         }
1334       }
1335     } // (dead->outcnt() == 0)
1336   }   // while (nstack.size() > 0) for outputs
1337   return;
1338 }
1339 
1340 //------------------------------remove_dead_region-----------------------------
1341 bool Node::remove_dead_region(PhaseGVN *phase, bool can_reshape) {
1342   Node *n = in(0);
1343   if( !n ) return false;
1344   // Lost control into this guy?  I.e., it became unreachable?
1345   // Aggressively kill all unreachable code.
1346   if (can_reshape && n->is_top()) {
1347     kill_dead_code(this, phase->is_IterGVN());
1348     return false; // Node is dead.
1349   }
1350 
1351   if( n->is_Region() && n->as_Region()->is_copy() ) {
1352     Node *m = n->nonnull_req();
1353     set_req(0, m);
1354     return true;
1355   }
1356   return false;
1357 }
1358 
1359 //------------------------------Ideal_DU_postCCP-------------------------------
1360 // Idealize graph, using DU info.  Must clone result into new-space
1361 Node *Node::Ideal_DU_postCCP( PhaseCCP * ) {
1362   return NULL;                 // Default to no change
1363 }
1364 
1365 //------------------------------hash-------------------------------------------
1366 // Hash function over Nodes.
1367 uint Node::hash() const {
1368   uint sum = 0;
1369   for( uint i=0; i<_cnt; i++ )  // Add in all inputs
1370     sum = (sum<<1)-(uintptr_t)in(i);        // Ignore embedded NULLs
1371   return (sum>>2) + _cnt + Opcode();
1372 }
1373 
1374 //------------------------------cmp--------------------------------------------
1375 // Compare special parts of simple Nodes
1376 uint Node::cmp( const Node &n ) const {
1377   return 1;                     // Must be same
1378 }
1379 
1380 //------------------------------rematerialize-----------------------------------
1381 // Should we clone rather than spill this instruction?
1382 bool Node::rematerialize() const {
1383   if ( is_Mach() )
1384     return this->as_Mach()->rematerialize();
1385   else
1386     return (_flags & Flag_rematerialize) != 0;
1387 }
1388 
1389 //------------------------------needs_anti_dependence_check---------------------
1390 // Nodes which use memory without consuming it, hence need antidependences.
1391 bool Node::needs_anti_dependence_check() const {
1392   if( req() < 2 || (_flags & Flag_needs_anti_dependence_check) == 0 )
1393     return false;
1394   else
1395     return in(1)->bottom_type()->has_memory();
1396 }
1397 
1398 
1399 // Get an integer constant from a ConNode (or CastIINode).
1400 // Return a default value if there is no apparent constant here.
1401 const TypeInt* Node::find_int_type() const {
1402   if (this->is_Type()) {
1403     return this->as_Type()->type()->isa_int();
1404   } else if (this->is_Con()) {
1405     assert(is_Mach(), "should be ConNode(TypeNode) or else a MachNode");
1406     return this->bottom_type()->isa_int();
1407   }
1408   return NULL;
1409 }
1410 
1411 // Get a pointer constant from a ConstNode.
1412 // Returns the constant if it is a pointer ConstNode
1413 intptr_t Node::get_ptr() const {
1414   assert( Opcode() == Op_ConP, "" );
1415   return ((ConPNode*)this)->type()->is_ptr()->get_con();
1416 }
1417 
1418 // Get a narrow oop constant from a ConNNode.
1419 intptr_t Node::get_narrowcon() const {
1420   assert( Opcode() == Op_ConN, "" );
1421   return ((ConNNode*)this)->type()->is_narrowoop()->get_con();
1422 }
1423 
1424 // Get a long constant from a ConNode.
1425 // Return a default value if there is no apparent constant here.
1426 const TypeLong* Node::find_long_type() const {
1427   if (this->is_Type()) {
1428     return this->as_Type()->type()->isa_long();
1429   } else if (this->is_Con()) {
1430     assert(is_Mach(), "should be ConNode(TypeNode) or else a MachNode");
1431     return this->bottom_type()->isa_long();
1432   }
1433   return NULL;
1434 }
1435 
1436 
1437 /**
1438  * Return a ptr type for nodes which should have it.
1439  */
1440 const TypePtr* Node::get_ptr_type() const {
1441   const TypePtr* tp = this->bottom_type()->make_ptr();
1442 #ifdef ASSERT
1443   if (tp == NULL) {
1444     this->dump(1);
1445     assert((tp != NULL), "unexpected node type");
1446   }
1447 #endif
1448   return tp;
1449 }
1450 
1451 // Get a double constant from a ConstNode.
1452 // Returns the constant if it is a double ConstNode
1453 jdouble Node::getd() const {
1454   assert( Opcode() == Op_ConD, "" );
1455   return ((ConDNode*)this)->type()->is_double_constant()->getd();
1456 }
1457 
1458 // Get a float constant from a ConstNode.
1459 // Returns the constant if it is a float ConstNode
1460 jfloat Node::getf() const {
1461   assert( Opcode() == Op_ConF, "" );
1462   return ((ConFNode*)this)->type()->is_float_constant()->getf();
1463 }
1464 
1465 #ifndef PRODUCT
1466 
1467 //----------------------------NotANode----------------------------------------
1468 // Used in debugging code to avoid walking across dead or uninitialized edges.
1469 static inline bool NotANode(const Node* n) {
1470   if (n == NULL)                   return true;
1471   if (((intptr_t)n & 1) != 0)      return true;  // uninitialized, etc.
1472   if (*(address*)n == badAddress)  return true;  // kill by Node::destruct
1473   return false;
1474 }
1475 
1476 
1477 //------------------------------find------------------------------------------
1478 // Find a neighbor of this Node with the given _idx
1479 // If idx is negative, find its absolute value, following both _in and _out.
1480 static void find_recur(Compile* C,  Node* &result, Node *n, int idx, bool only_ctrl,
1481                         VectorSet* old_space, VectorSet* new_space ) {
1482   int node_idx = (idx >= 0) ? idx : -idx;
1483   if (NotANode(n))  return;  // Gracefully handle NULL, -1, 0xabababab, etc.
1484   // Contained in new_space or old_space?   Check old_arena first since it's mostly empty.
1485   VectorSet *v = C->old_arena()->contains(n) ? old_space : new_space;
1486   if( v->test(n->_idx) ) return;
1487   if( (int)n->_idx == node_idx
1488       debug_only(|| n->debug_idx() == node_idx) ) {
1489     if (result != NULL)
1490       tty->print("find: " INTPTR_FORMAT " and " INTPTR_FORMAT " both have idx==%d\n",
1491                  (uintptr_t)result, (uintptr_t)n, node_idx);
1492     result = n;
1493   }
1494   v->set(n->_idx);
1495   for( uint i=0; i<n->len(); i++ ) {
1496     if( only_ctrl && !(n->is_Region()) && (n->Opcode() != Op_Root) && (i != TypeFunc::Control) ) continue;
1497     find_recur(C, result, n->in(i), idx, only_ctrl, old_space, new_space );
1498   }
1499   // Search along forward edges also:
1500   if (idx < 0 && !only_ctrl) {
1501     for( uint j=0; j<n->outcnt(); j++ ) {
1502       find_recur(C, result, n->raw_out(j), idx, only_ctrl, old_space, new_space );
1503     }
1504   }
1505 #ifdef ASSERT
1506   // Search along debug_orig edges last, checking for cycles
1507   Node* orig = n->debug_orig();
1508   if (orig != NULL) {
1509     do {
1510       if (NotANode(orig))  break;
1511       find_recur(C, result, orig, idx, only_ctrl, old_space, new_space );
1512       orig = orig->debug_orig();
1513     } while (orig != NULL && orig != n->debug_orig());
1514   }
1515 #endif //ASSERT
1516 }
1517 
1518 // call this from debugger:
1519 Node* find_node(Node* n, int idx) {
1520   return n->find(idx);
1521 }
1522 
1523 //------------------------------find-------------------------------------------
1524 Node* Node::find(int idx) const {
1525   ResourceArea *area = Thread::current()->resource_area();
1526   VectorSet old_space(area), new_space(area);
1527   Node* result = NULL;
1528   find_recur(Compile::current(), result, (Node*) this, idx, false, &old_space, &new_space );
1529   return result;
1530 }
1531 
1532 //------------------------------find_ctrl--------------------------------------
1533 // Find an ancestor to this node in the control history with given _idx
1534 Node* Node::find_ctrl(int idx) const {
1535   ResourceArea *area = Thread::current()->resource_area();
1536   VectorSet old_space(area), new_space(area);
1537   Node* result = NULL;
1538   find_recur(Compile::current(), result, (Node*) this, idx, true, &old_space, &new_space );
1539   return result;
1540 }
1541 #endif
1542 
1543 
1544 
1545 #ifndef PRODUCT
1546 
1547 // -----------------------------Name-------------------------------------------
1548 extern const char *NodeClassNames[];
1549 const char *Node::Name() const { return NodeClassNames[Opcode()]; }
1550 
1551 static bool is_disconnected(const Node* n) {
1552   for (uint i = 0; i < n->req(); i++) {
1553     if (n->in(i) != NULL)  return false;
1554   }
1555   return true;
1556 }
1557 
1558 #ifdef ASSERT
1559 static void dump_orig(Node* orig, outputStream *st) {
1560   Compile* C = Compile::current();
1561   if (NotANode(orig)) orig = NULL;
1562   if (orig != NULL && !C->node_arena()->contains(orig)) orig = NULL;
1563   if (orig == NULL) return;
1564   st->print(" !orig=");
1565   Node* fast = orig->debug_orig(); // tortoise & hare algorithm to detect loops
1566   if (NotANode(fast)) fast = NULL;
1567   while (orig != NULL) {
1568     bool discon = is_disconnected(orig);  // if discon, print [123] else 123
1569     if (discon) st->print("[");
1570     if (!Compile::current()->node_arena()->contains(orig))
1571       st->print("o");
1572     st->print("%d", orig->_idx);
1573     if (discon) st->print("]");
1574     orig = orig->debug_orig();
1575     if (NotANode(orig)) orig = NULL;
1576     if (orig != NULL && !C->node_arena()->contains(orig)) orig = NULL;
1577     if (orig != NULL) st->print(",");
1578     if (fast != NULL) {
1579       // Step fast twice for each single step of orig:
1580       fast = fast->debug_orig();
1581       if (NotANode(fast)) fast = NULL;
1582       if (fast != NULL && fast != orig) {
1583         fast = fast->debug_orig();
1584         if (NotANode(fast)) fast = NULL;
1585       }
1586       if (fast == orig) {
1587         st->print("...");
1588         break;
1589       }
1590     }
1591   }
1592 }
1593 
1594 void Node::set_debug_orig(Node* orig) {
1595   _debug_orig = orig;
1596   if (BreakAtNode == 0)  return;
1597   if (NotANode(orig))  orig = NULL;
1598   int trip = 10;
1599   while (orig != NULL) {
1600     if (orig->debug_idx() == BreakAtNode || (int)orig->_idx == BreakAtNode) {
1601       tty->print_cr("BreakAtNode: _idx=%d _debug_idx=%d orig._idx=%d orig._debug_idx=%d",
1602                     this->_idx, this->debug_idx(), orig->_idx, orig->debug_idx());
1603       BREAKPOINT;
1604     }
1605     orig = orig->debug_orig();
1606     if (NotANode(orig))  orig = NULL;
1607     if (trip-- <= 0)  break;
1608   }
1609 }
1610 #endif //ASSERT
1611 
1612 //------------------------------dump------------------------------------------
1613 // Dump a Node
1614 void Node::dump(const char* suffix, outputStream *st) const {
1615   Compile* C = Compile::current();
1616   bool is_new = C->node_arena()->contains(this);
1617   C->_in_dump_cnt++;
1618   st->print("%c%d\t%s\t=== ", is_new ? ' ' : 'o', _idx, Name());
1619 
1620   // Dump the required and precedence inputs
1621   dump_req(st);
1622   dump_prec(st);
1623   // Dump the outputs
1624   dump_out(st);
1625 
1626   if (is_disconnected(this)) {
1627 #ifdef ASSERT
1628     st->print("  [%d]",debug_idx());
1629     dump_orig(debug_orig(), st);
1630 #endif
1631     st->cr();
1632     C->_in_dump_cnt--;
1633     return;                     // don't process dead nodes
1634   }
1635 
1636   // Dump node-specific info
1637   dump_spec(st);
1638 #ifdef ASSERT
1639   // Dump the non-reset _debug_idx
1640   if (Verbose && WizardMode) {
1641     st->print("  [%d]",debug_idx());
1642   }
1643 #endif
1644 
1645   const Type *t = bottom_type();
1646 
1647   if (t != NULL && (t->isa_instptr() || t->isa_klassptr())) {
1648     const TypeInstPtr  *toop = t->isa_instptr();
1649     const TypeKlassPtr *tkls = t->isa_klassptr();
1650     ciKlass*           klass = toop ? toop->klass() : (tkls ? tkls->klass() : NULL );
1651     if (klass && klass->is_loaded() && klass->is_interface()) {
1652       st->print("  Interface:");
1653     } else if (toop) {
1654       st->print("  Oop:");
1655     } else if (tkls) {
1656       st->print("  Klass:");
1657     }
1658     t->dump_on(st);
1659   } else if (t == Type::MEMORY) {
1660     st->print("  Memory:");
1661     MemNode::dump_adr_type(this, adr_type(), st);
1662   } else if (Verbose || WizardMode) {
1663     st->print("  Type:");
1664     if (t) {
1665       t->dump_on(st);
1666     } else {
1667       st->print("no type");
1668     }
1669   } else if (t->isa_vect() && this->is_MachSpillCopy()) {
1670     // Dump MachSpillcopy vector type.
1671     t->dump_on(st);
1672   }
1673   if (is_new) {
1674     debug_only(dump_orig(debug_orig(), st));
1675     Node_Notes* nn = C->node_notes_at(_idx);
1676     if (nn != NULL && !nn->is_clear()) {
1677       if (nn->jvms() != NULL) {
1678         st->print(" !jvms:");
1679         nn->jvms()->dump_spec(st);
1680       }
1681     }
1682   }
1683   if (suffix) st->print("%s", suffix);
1684   C->_in_dump_cnt--;
1685 }
1686 
1687 //------------------------------dump_req--------------------------------------
1688 void Node::dump_req(outputStream *st) const {
1689   // Dump the required input edges
1690   for (uint i = 0; i < req(); i++) {    // For all required inputs
1691     Node* d = in(i);
1692     if (d == NULL) {
1693       st->print("_ ");
1694     } else if (NotANode(d)) {
1695       st->print("NotANode ");  // uninitialized, sentinel, garbage, etc.
1696     } else {
1697       st->print("%c%d ", Compile::current()->node_arena()->contains(d) ? ' ' : 'o', d->_idx);
1698     }
1699   }
1700 }
1701 
1702 
1703 //------------------------------dump_prec-------------------------------------
1704 void Node::dump_prec(outputStream *st) const {
1705   // Dump the precedence edges
1706   int any_prec = 0;
1707   for (uint i = req(); i < len(); i++) {       // For all precedence inputs
1708     Node* p = in(i);
1709     if (p != NULL) {
1710       if (!any_prec++) st->print(" |");
1711       if (NotANode(p)) { st->print("NotANode "); continue; }
1712       st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);
1713     }
1714   }
1715 }
1716 
1717 //------------------------------dump_out--------------------------------------
1718 void Node::dump_out(outputStream *st) const {
1719   // Delimit the output edges
1720   st->print(" [[");
1721   // Dump the output edges
1722   for (uint i = 0; i < _outcnt; i++) {    // For all outputs
1723     Node* u = _out[i];
1724     if (u == NULL) {
1725       st->print("_ ");
1726     } else if (NotANode(u)) {
1727       st->print("NotANode ");
1728     } else {
1729       st->print("%c%d ", Compile::current()->node_arena()->contains(u) ? ' ' : 'o', u->_idx);
1730     }
1731   }
1732   st->print("]] ");
1733 }
1734 
1735 //------------------------------dump_nodes-------------------------------------
1736 static void dump_nodes(const Node* start, int d, bool only_ctrl) {
1737   Node* s = (Node*)start; // remove const
1738   if (NotANode(s)) return;
1739 
1740   uint depth = (uint)ABS(d);
1741   int direction = d;
1742   Compile* C = Compile::current();
1743   GrowableArray <Node *> nstack(C->unique());
1744 
1745   nstack.append(s);
1746   int begin = 0;
1747   int end = 0;
1748   for(uint i = 0; i < depth; i++) {
1749     end = nstack.length();
1750     for(int j = begin; j < end; j++) {
1751       Node* tp  = nstack.at(j);
1752       uint limit = direction > 0 ? tp->len() : tp->outcnt();
1753       for(uint k = 0; k < limit; k++) {
1754         Node* n = direction > 0 ? tp->in(k) : tp->raw_out(k);
1755 
1756         if (NotANode(n))  continue;
1757         // do not recurse through top or the root (would reach unrelated stuff)
1758         if (n->is_Root() || n->is_top())  continue;
1759         if (only_ctrl && !n->is_CFG()) continue;
1760 
1761         bool on_stack = nstack.contains(n);
1762         if (!on_stack) {
1763           nstack.append(n);
1764         }
1765       }
1766     }
1767     begin = end;
1768   }
1769   end = nstack.length();
1770   if (direction > 0) {
1771     for(int j = end-1; j >= 0; j--) {
1772       nstack.at(j)->dump();
1773     }
1774   } else {
1775     for(int j = 0; j < end; j++) {
1776       nstack.at(j)->dump();
1777     }
1778   }
1779 }
1780 
1781 //------------------------------dump-------------------------------------------
1782 void Node::dump(int d) const {
1783   dump_nodes(this, d, false);
1784 }
1785 
1786 //------------------------------dump_ctrl--------------------------------------
1787 // Dump a Node's control history to depth
1788 void Node::dump_ctrl(int d) const {
1789   dump_nodes(this, d, true);
1790 }
1791 
1792 // VERIFICATION CODE
1793 // For each input edge to a node (ie - for each Use-Def edge), verify that
1794 // there is a corresponding Def-Use edge.
1795 //------------------------------verify_edges-----------------------------------
1796 void Node::verify_edges(Unique_Node_List &visited) {
1797   uint i, j, idx;
1798   int  cnt;
1799   Node *n;
1800 
1801   // Recursive termination test
1802   if (visited.member(this))  return;
1803   visited.push(this);
1804 
1805   // Walk over all input edges, checking for correspondence
1806   for( i = 0; i < len(); i++ ) {
1807     n = in(i);
1808     if (n != NULL && !n->is_top()) {
1809       // Count instances of (Node *)this
1810       cnt = 0;
1811       for (idx = 0; idx < n->_outcnt; idx++ ) {
1812         if (n->_out[idx] == (Node *)this)  cnt++;
1813       }
1814       assert( cnt > 0,"Failed to find Def-Use edge." );
1815       // Check for duplicate edges
1816       // walk the input array downcounting the input edges to n
1817       for( j = 0; j < len(); j++ ) {
1818         if( in(j) == n ) cnt--;
1819       }
1820       assert( cnt == 0,"Mismatched edge count.");
1821     } else if (n == NULL) {
1822       assert(i >= req() || i == 0 || is_Region() || is_Phi(), "only regions or phis have null data edges");
1823     } else {
1824       assert(n->is_top(), "sanity");
1825       // Nothing to check.
1826     }
1827   }
1828   // Recursive walk over all input edges
1829   for( i = 0; i < len(); i++ ) {
1830     n = in(i);
1831     if( n != NULL )
1832       in(i)->verify_edges(visited);
1833   }
1834 }
1835 
1836 //------------------------------verify_recur-----------------------------------
1837 static const Node *unique_top = NULL;
1838 
1839 void Node::verify_recur(const Node *n, int verify_depth,
1840                         VectorSet &old_space, VectorSet &new_space) {
1841   if ( verify_depth == 0 )  return;
1842   if (verify_depth > 0)  --verify_depth;
1843 
1844   Compile* C = Compile::current();
1845 
1846   // Contained in new_space or old_space?
1847   VectorSet *v = C->node_arena()->contains(n) ? &new_space : &old_space;
1848   // Check for visited in the proper space.  Numberings are not unique
1849   // across spaces so we need a separate VectorSet for each space.
1850   if( v->test_set(n->_idx) ) return;
1851 
1852   if (n->is_Con() && n->bottom_type() == Type::TOP) {
1853     if (C->cached_top_node() == NULL)
1854       C->set_cached_top_node((Node*)n);
1855     assert(C->cached_top_node() == n, "TOP node must be unique");
1856   }
1857 
1858   for( uint i = 0; i < n->len(); i++ ) {
1859     Node *x = n->in(i);
1860     if (!x || x->is_top()) continue;
1861 
1862     // Verify my input has a def-use edge to me
1863     if (true /*VerifyDefUse*/) {
1864       // Count use-def edges from n to x
1865       int cnt = 0;
1866       for( uint j = 0; j < n->len(); j++ )
1867         if( n->in(j) == x )
1868           cnt++;
1869       // Count def-use edges from x to n
1870       uint max = x->_outcnt;
1871       for( uint k = 0; k < max; k++ )
1872         if (x->_out[k] == n)
1873           cnt--;
1874       assert( cnt == 0, "mismatched def-use edge counts" );
1875     }
1876 
1877     verify_recur(x, verify_depth, old_space, new_space);
1878   }
1879 
1880 }
1881 
1882 //------------------------------verify-----------------------------------------
1883 // Check Def-Use info for my subgraph
1884 void Node::verify() const {
1885   Compile* C = Compile::current();
1886   Node* old_top = C->cached_top_node();
1887   ResourceMark rm;
1888   ResourceArea *area = Thread::current()->resource_area();
1889   VectorSet old_space(area), new_space(area);
1890   verify_recur(this, -1, old_space, new_space);
1891   C->set_cached_top_node(old_top);
1892 }
1893 #endif
1894 
1895 
1896 //------------------------------walk-------------------------------------------
1897 // Graph walk, with both pre-order and post-order functions
1898 void Node::walk(NFunc pre, NFunc post, void *env) {
1899   VectorSet visited(Thread::current()->resource_area()); // Setup for local walk
1900   walk_(pre, post, env, visited);
1901 }
1902 
1903 void Node::walk_(NFunc pre, NFunc post, void *env, VectorSet &visited) {
1904   if( visited.test_set(_idx) ) return;
1905   pre(*this,env);               // Call the pre-order walk function
1906   for( uint i=0; i<_max; i++ )
1907     if( in(i) )                 // Input exists and is not walked?
1908       in(i)->walk_(pre,post,env,visited); // Walk it with pre & post functions
1909   post(*this,env);              // Call the post-order walk function
1910 }
1911 
1912 void Node::nop(Node &, void*) {}
1913 
1914 //------------------------------Registers--------------------------------------
1915 // Do we Match on this edge index or not?  Generally false for Control
1916 // and true for everything else.  Weird for calls & returns.
1917 uint Node::match_edge(uint idx) const {
1918   return idx;                   // True for other than index 0 (control)
1919 }
1920 
1921 static RegMask _not_used_at_all;
1922 // Register classes are defined for specific machines
1923 const RegMask &Node::out_RegMask() const {
1924   ShouldNotCallThis();
1925   return _not_used_at_all;
1926 }
1927 
1928 const RegMask &Node::in_RegMask(uint) const {
1929   ShouldNotCallThis();
1930   return _not_used_at_all;
1931 }
1932 
1933 //=============================================================================
1934 //-----------------------------------------------------------------------------
1935 void Node_Array::reset( Arena *new_arena ) {
1936   _a->Afree(_nodes,_max*sizeof(Node*));
1937   _max   = 0;
1938   _nodes = NULL;
1939   _a     = new_arena;
1940 }
1941 
1942 //------------------------------clear------------------------------------------
1943 // Clear all entries in _nodes to NULL but keep storage
1944 void Node_Array::clear() {
1945   Copy::zero_to_bytes( _nodes, _max*sizeof(Node*) );
1946 }
1947 
1948 //-----------------------------------------------------------------------------
1949 void Node_Array::grow( uint i ) {
1950   if( !_max ) {
1951     _max = 1;
1952     _nodes = (Node**)_a->Amalloc( _max * sizeof(Node*) );
1953     _nodes[0] = NULL;
1954   }
1955   uint old = _max;
1956   while( i >= _max ) _max <<= 1;        // Double to fit
1957   _nodes = (Node**)_a->Arealloc( _nodes, old*sizeof(Node*),_max*sizeof(Node*));
1958   Copy::zero_to_bytes( &_nodes[old], (_max-old)*sizeof(Node*) );
1959 }
1960 
1961 //-----------------------------------------------------------------------------
1962 void Node_Array::insert( uint i, Node *n ) {
1963   if( _nodes[_max-1] ) grow(_max);      // Get more space if full
1964   Copy::conjoint_words_to_higher((HeapWord*)&_nodes[i], (HeapWord*)&_nodes[i+1], ((_max-i-1)*sizeof(Node*)));
1965   _nodes[i] = n;
1966 }
1967 
1968 //-----------------------------------------------------------------------------
1969 void Node_Array::remove( uint i ) {
1970   Copy::conjoint_words_to_lower((HeapWord*)&_nodes[i+1], (HeapWord*)&_nodes[i], ((_max-i-1)*sizeof(Node*)));
1971   _nodes[_max-1] = NULL;
1972 }
1973 
1974 //-----------------------------------------------------------------------------
1975 void Node_Array::sort( C_sort_func_t func) {
1976   qsort( _nodes, _max, sizeof( Node* ), func );
1977 }
1978 
1979 //-----------------------------------------------------------------------------
1980 void Node_Array::dump() const {
1981 #ifndef PRODUCT
1982   for( uint i = 0; i < _max; i++ ) {
1983     Node *nn = _nodes[i];
1984     if( nn != NULL ) {
1985       tty->print("%5d--> ",i); nn->dump();
1986     }
1987   }
1988 #endif
1989 }
1990 
1991 //--------------------------is_iteratively_computed------------------------------
1992 // Operation appears to be iteratively computed (such as an induction variable)
1993 // It is possible for this operation to return false for a loop-varying
1994 // value, if it appears (by local graph inspection) to be computed by a simple conditional.
1995 bool Node::is_iteratively_computed() {
1996   if (ideal_reg()) { // does operation have a result register?
1997     for (uint i = 1; i < req(); i++) {
1998       Node* n = in(i);
1999       if (n != NULL && n->is_Phi()) {
2000         for (uint j = 1; j < n->req(); j++) {
2001           if (n->in(j) == this) {
2002             return true;
2003           }
2004         }
2005       }
2006     }
2007   }
2008   return false;
2009 }
2010 
2011 //--------------------------find_similar------------------------------
2012 // Return a node with opcode "opc" and same inputs as "this" if one can
2013 // be found; Otherwise return NULL;
2014 Node* Node::find_similar(int opc) {
2015   if (req() >= 2) {
2016     Node* def = in(1);
2017     if (def && def->outcnt() >= 2) {
2018       for (DUIterator_Fast dmax, i = def->fast_outs(dmax); i < dmax; i++) {
2019         Node* use = def->fast_out(i);
2020         if (use->Opcode() == opc &&
2021             use->req() == req()) {
2022           uint j;
2023           for (j = 0; j < use->req(); j++) {
2024             if (use->in(j) != in(j)) {
2025               break;
2026             }
2027           }
2028           if (j == use->req()) {
2029             return use;
2030           }
2031         }
2032       }
2033     }
2034   }
2035   return NULL;
2036 }
2037 
2038 
2039 //--------------------------unique_ctrl_out------------------------------
2040 // Return the unique control out if only one. Null if none or more than one.
2041 Node* Node::unique_ctrl_out() {
2042   Node* found = NULL;
2043   for (uint i = 0; i < outcnt(); i++) {
2044     Node* use = raw_out(i);
2045     if (use->is_CFG() && use != this) {
2046       if (found != NULL) return NULL;
2047       found = use;
2048     }
2049   }
2050   return found;
2051 }
2052 
2053 //=============================================================================
2054 //------------------------------yank-------------------------------------------
2055 // Find and remove
2056 void Node_List::yank( Node *n ) {
2057   uint i;
2058   for( i = 0; i < _cnt; i++ )
2059     if( _nodes[i] == n )
2060       break;
2061 
2062   if( i < _cnt )
2063     _nodes[i] = _nodes[--_cnt];
2064 }
2065 
2066 //------------------------------dump-------------------------------------------
2067 void Node_List::dump() const {
2068 #ifndef PRODUCT
2069   for( uint i = 0; i < _cnt; i++ )
2070     if( _nodes[i] ) {
2071       tty->print("%5d--> ",i);
2072       _nodes[i]->dump();
2073     }
2074 #endif
2075 }
2076 
2077 //=============================================================================
2078 //------------------------------remove-----------------------------------------
2079 void Unique_Node_List::remove( Node *n ) {
2080   if( _in_worklist[n->_idx] ) {
2081     for( uint i = 0; i < size(); i++ )
2082       if( _nodes[i] == n ) {
2083         map(i,Node_List::pop());
2084         _in_worklist >>= n->_idx;
2085         return;
2086       }
2087     ShouldNotReachHere();
2088   }
2089 }
2090 
2091 //-----------------------remove_useless_nodes----------------------------------
2092 // Remove useless nodes from worklist
2093 void Unique_Node_List::remove_useless_nodes(VectorSet &useful) {
2094 
2095   for( uint i = 0; i < size(); ++i ) {
2096     Node *n = at(i);
2097     assert( n != NULL, "Did not expect null entries in worklist");
2098     if( ! useful.test(n->_idx) ) {
2099       _in_worklist >>= n->_idx;
2100       map(i,Node_List::pop());
2101       // Node *replacement = Node_List::pop();
2102       // if( i != size() ) { // Check if removing last entry
2103       //   _nodes[i] = replacement;
2104       // }
2105       --i;  // Visit popped node
2106       // If it was last entry, loop terminates since size() was also reduced
2107     }
2108   }
2109 }
2110 
2111 //=============================================================================
2112 void Node_Stack::grow() {
2113   size_t old_top = pointer_delta(_inode_top,_inodes,sizeof(INode)); // save _top
2114   size_t old_max = pointer_delta(_inode_max,_inodes,sizeof(INode));
2115   size_t max = old_max << 1;             // max * 2
2116   _inodes = REALLOC_ARENA_ARRAY(_a, INode, _inodes, old_max, max);
2117   _inode_max = _inodes + max;
2118   _inode_top = _inodes + old_top;        // restore _top
2119 }
2120 
2121 // Node_Stack is used to map nodes.
2122 Node* Node_Stack::find(uint idx) const {
2123   uint sz = size();
2124   for (uint i=0; i < sz; i++) {
2125     if (idx == index_at(i) )
2126       return node_at(i);
2127   }
2128   return NULL;
2129 }
2130 
2131 //=============================================================================
2132 uint TypeNode::size_of() const { return sizeof(*this); }
2133 #ifndef PRODUCT
2134 void TypeNode::dump_spec(outputStream *st) const {
2135   if( !Verbose && !WizardMode ) {
2136     // standard dump does this in Verbose and WizardMode
2137     st->print(" #"); _type->dump_on(st);
2138   }
2139 }
2140 #endif
2141 uint TypeNode::hash() const {
2142   return Node::hash() + _type->hash();
2143 }
2144 uint TypeNode::cmp( const Node &n ) const
2145 { return !Type::cmp( _type, ((TypeNode&)n)._type ); }
2146 const Type *TypeNode::bottom_type() const { return _type; }
2147 const Type *TypeNode::Value( PhaseTransform * ) const { return _type; }
2148 
2149 //------------------------------ideal_reg--------------------------------------
2150 uint TypeNode::ideal_reg() const {
2151   return _type->ideal_reg();
2152 }