1 /*
   2  * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2024, 2025, Alibaba Group Holding Limited. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "gc/shared/barrierSet.hpp"
  27 #include "gc/shared/c2/barrierSetC2.hpp"
  28 #include "libadt/vectset.hpp"
  29 #include "memory/allocation.inline.hpp"
  30 #include "memory/resourceArea.hpp"
  31 #include "opto/ad.hpp"
  32 #include "opto/callGenerator.hpp"
  33 #include "opto/castnode.hpp"
  34 #include "opto/cfgnode.hpp"
  35 #include "opto/connode.hpp"

  36 #include "opto/loopnode.hpp"
  37 #include "opto/machnode.hpp"
  38 #include "opto/matcher.hpp"
  39 #include "opto/node.hpp"
  40 #include "opto/opcodes.hpp"
  41 #include "opto/regmask.hpp"
  42 #include "opto/rootnode.hpp"
  43 #include "opto/type.hpp"
  44 #include "utilities/copy.hpp"
  45 #include "utilities/macros.hpp"
  46 #include "utilities/powerOfTwo.hpp"
  47 #include "utilities/stringUtils.hpp"
  48 
  49 class RegMask;
  50 // #include "phase.hpp"
  51 class PhaseTransform;
  52 class PhaseGVN;
  53 
  54 // Arena we are currently building Nodes in
  55 const uint Node::NotAMachineReg = 0xffff0000;
  56 
  57 #ifndef PRODUCT
  58 extern uint nodes_created;
  59 #endif
  60 #ifdef __clang__
  61 #pragma clang diagnostic push
  62 #pragma GCC diagnostic ignored "-Wuninitialized"
  63 #endif
  64 
  65 #ifdef ASSERT
  66 
  67 //-------------------------- construct_node------------------------------------
  68 // Set a breakpoint here to identify where a particular node index is built.
  69 void Node::verify_construction() {
  70   _debug_orig = nullptr;
  71   // The decimal digits of _debug_idx are <compile_id> followed by 10 digits of <_idx>
  72   Compile* C = Compile::current();
  73   assert(C->unique() < (INT_MAX - 1), "Node limit exceeded INT_MAX");
  74   uint64_t new_debug_idx = (uint64_t)C->compile_id() * 10000000000 + _idx;
  75   set_debug_idx(new_debug_idx);
  76   if (!C->phase_optimize_finished()) {
  77     // Only check assert during parsing and optimization phase. Skip it while generating code.
  78     assert(C->live_nodes() <= C->max_node_limit(), "Live Node limit exceeded limit");
  79   }
  80   if (BreakAtNode != 0 && (_debug_idx == BreakAtNode || (uint64_t)_idx == BreakAtNode)) {
  81     tty->print_cr("BreakAtNode: _idx=%d _debug_idx=" UINT64_FORMAT, _idx, _debug_idx);
  82     BREAKPOINT;
  83   }
  84 #if OPTO_DU_ITERATOR_ASSERT
  85   _last_del = nullptr;
  86   _del_tick = 0;
  87 #endif
  88   _hash_lock = 0;
  89 }
  90 
  91 
  92 // #ifdef ASSERT ...
  93 
  94 #if OPTO_DU_ITERATOR_ASSERT
  95 void DUIterator_Common::sample(const Node* node) {
  96   _vdui     = VerifyDUIterators;
  97   _node     = node;
  98   _outcnt   = node->_outcnt;
  99   _del_tick = node->_del_tick;
 100   _last     = nullptr;
 101 }
 102 
 103 void DUIterator_Common::verify(const Node* node, bool at_end_ok) {
 104   assert(_node     == node, "consistent iterator source");
 105   assert(_del_tick == node->_del_tick, "no unexpected deletions allowed");
 106 }
 107 
 108 void DUIterator_Common::verify_resync() {
 109   // Ensure that the loop body has just deleted the last guy produced.
 110   const Node* node = _node;
 111   // Ensure that at least one copy of the last-seen edge was deleted.
 112   // Note:  It is OK to delete multiple copies of the last-seen edge.
 113   // Unfortunately, we have no way to verify that all the deletions delete
 114   // that same edge.  On this point we must use the Honor System.
 115   assert(node->_del_tick >= _del_tick+1, "must have deleted an edge");
 116   assert(node->_last_del == _last, "must have deleted the edge just produced");
 117   // We liked this deletion, so accept the resulting outcnt and tick.
 118   _outcnt   = node->_outcnt;
 119   _del_tick = node->_del_tick;
 120 }
 121 
 122 void DUIterator_Common::reset(const DUIterator_Common& that) {
 123   if (this == &that)  return;  // ignore assignment to self
 124   if (!_vdui) {
 125     // We need to initialize everything, overwriting garbage values.
 126     _last = that._last;
 127     _vdui = that._vdui;
 128   }
 129   // Note:  It is legal (though odd) for an iterator over some node x
 130   // to be reassigned to iterate over another node y.  Some doubly-nested
 131   // progress loops depend on being able to do this.
 132   const Node* node = that._node;
 133   // Re-initialize everything, except _last.
 134   _node     = node;
 135   _outcnt   = node->_outcnt;
 136   _del_tick = node->_del_tick;
 137 }
 138 
 139 void DUIterator::sample(const Node* node) {
 140   DUIterator_Common::sample(node);      // Initialize the assertion data.
 141   _refresh_tick = 0;                    // No refreshes have happened, as yet.
 142 }
 143 
 144 void DUIterator::verify(const Node* node, bool at_end_ok) {
 145   DUIterator_Common::verify(node, at_end_ok);
 146   assert(_idx      <  node->_outcnt + (uint)at_end_ok, "idx in range");
 147 }
 148 
 149 void DUIterator::verify_increment() {
 150   if (_refresh_tick & 1) {
 151     // We have refreshed the index during this loop.
 152     // Fix up _idx to meet asserts.
 153     if (_idx > _outcnt)  _idx = _outcnt;
 154   }
 155   verify(_node, true);
 156 }
 157 
 158 void DUIterator::verify_resync() {
 159   // Note:  We do not assert on _outcnt, because insertions are OK here.
 160   DUIterator_Common::verify_resync();
 161   // Make sure we are still in sync, possibly with no more out-edges:
 162   verify(_node, true);
 163 }
 164 
 165 void DUIterator::reset(const DUIterator& that) {
 166   if (this == &that)  return;  // self assignment is always a no-op
 167   assert(that._refresh_tick == 0, "assign only the result of Node::outs()");
 168   assert(that._idx          == 0, "assign only the result of Node::outs()");
 169   assert(_idx               == that._idx, "already assigned _idx");
 170   if (!_vdui) {
 171     // We need to initialize everything, overwriting garbage values.
 172     sample(that._node);
 173   } else {
 174     DUIterator_Common::reset(that);
 175     if (_refresh_tick & 1) {
 176       _refresh_tick++;                  // Clear the "was refreshed" flag.
 177     }
 178     assert(_refresh_tick < 2*100000, "DU iteration must converge quickly");
 179   }
 180 }
 181 
 182 void DUIterator::refresh() {
 183   DUIterator_Common::sample(_node);     // Re-fetch assertion data.
 184   _refresh_tick |= 1;                   // Set the "was refreshed" flag.
 185 }
 186 
 187 void DUIterator::verify_finish() {
 188   // If the loop has killed the node, do not require it to re-run.
 189   if (_node->_outcnt == 0)  _refresh_tick &= ~1;
 190   // If this assert triggers, it means that a loop used refresh_out_pos
 191   // to re-synch an iteration index, but the loop did not correctly
 192   // re-run itself, using a "while (progress)" construct.
 193   // This iterator enforces the rule that you must keep trying the loop
 194   // until it "runs clean" without any need for refreshing.
 195   assert(!(_refresh_tick & 1), "the loop must run once with no refreshing");
 196 }
 197 
 198 
 199 void DUIterator_Fast::verify(const Node* node, bool at_end_ok) {
 200   DUIterator_Common::verify(node, at_end_ok);
 201   Node** out    = node->_out;
 202   uint   cnt    = node->_outcnt;
 203   assert(cnt == _outcnt, "no insertions allowed");
 204   assert(_outp >= out && _outp <= out + cnt - !at_end_ok, "outp in range");
 205   // This last check is carefully designed to work for NO_OUT_ARRAY.
 206 }
 207 
 208 void DUIterator_Fast::verify_limit() {
 209   const Node* node = _node;
 210   verify(node, true);
 211   assert(_outp == node->_out + node->_outcnt, "limit still correct");
 212 }
 213 
 214 void DUIterator_Fast::verify_resync() {
 215   const Node* node = _node;
 216   if (_outp == node->_out + _outcnt) {
 217     // Note that the limit imax, not the pointer i, gets updated with the
 218     // exact count of deletions.  (For the pointer it's always "--i".)
 219     assert(node->_outcnt+node->_del_tick == _outcnt+_del_tick, "no insertions allowed with deletion(s)");
 220     // This is a limit pointer, with a name like "imax".
 221     // Fudge the _last field so that the common assert will be happy.
 222     _last = (Node*) node->_last_del;
 223     DUIterator_Common::verify_resync();
 224   } else {
 225     assert(node->_outcnt < _outcnt, "no insertions allowed with deletion(s)");
 226     // A normal internal pointer.
 227     DUIterator_Common::verify_resync();
 228     // Make sure we are still in sync, possibly with no more out-edges:
 229     verify(node, true);
 230   }
 231 }
 232 
 233 void DUIterator_Fast::verify_relimit(uint n) {
 234   const Node* node = _node;
 235   assert((int)n > 0, "use imax -= n only with a positive count");
 236   // This must be a limit pointer, with a name like "imax".
 237   assert(_outp == node->_out + node->_outcnt, "apply -= only to a limit (imax)");
 238   // The reported number of deletions must match what the node saw.
 239   assert(node->_del_tick == _del_tick + n, "must have deleted n edges");
 240   // Fudge the _last field so that the common assert will be happy.
 241   _last = (Node*) node->_last_del;
 242   DUIterator_Common::verify_resync();
 243 }
 244 
 245 void DUIterator_Fast::reset(const DUIterator_Fast& that) {
 246   assert(_outp              == that._outp, "already assigned _outp");
 247   DUIterator_Common::reset(that);
 248 }
 249 
 250 void DUIterator_Last::verify(const Node* node, bool at_end_ok) {
 251   // at_end_ok means the _outp is allowed to underflow by 1
 252   _outp += at_end_ok;
 253   DUIterator_Fast::verify(node, at_end_ok);  // check _del_tick, etc.
 254   _outp -= at_end_ok;
 255   assert(_outp == (node->_out + node->_outcnt) - 1, "pointer must point to end of nodes");
 256 }
 257 
 258 void DUIterator_Last::verify_limit() {
 259   // Do not require the limit address to be resynched.
 260   //verify(node, true);
 261   assert(_outp == _node->_out, "limit still correct");
 262 }
 263 
 264 void DUIterator_Last::verify_step(uint num_edges) {
 265   assert((int)num_edges > 0, "need non-zero edge count for loop progress");
 266   _outcnt   -= num_edges;
 267   _del_tick += num_edges;
 268   // Make sure we are still in sync, possibly with no more out-edges:
 269   const Node* node = _node;
 270   verify(node, true);
 271   assert(node->_last_del == _last, "must have deleted the edge just produced");
 272 }
 273 
 274 #endif //OPTO_DU_ITERATOR_ASSERT
 275 
 276 
 277 #endif //ASSERT
 278 
 279 
 280 // This constant used to initialize _out may be any non-null value.
 281 // The value null is reserved for the top node only.
 282 #define NO_OUT_ARRAY ((Node**)-1)
 283 
 284 // Out-of-line code from node constructors.
 285 // Executed only when extra debug info. is being passed around.
 286 static void init_node_notes(Compile* C, int idx, Node_Notes* nn) {
 287   C->set_node_notes_at(idx, nn);
 288 }
 289 
 290 // Shared initialization code.
 291 inline int Node::Init(int req) {
 292   Compile* C = Compile::current();
 293   int idx = C->next_unique();
 294   NOT_PRODUCT(_igv_idx = C->next_igv_idx());
 295 
 296   // Allocate memory for the necessary number of edges.
 297   if (req > 0) {
 298     // Allocate space for _in array to have double alignment.
 299     _in = (Node **) ((char *) (C->node_arena()->AmallocWords(req * sizeof(void*))));
 300   }
 301   // If there are default notes floating around, capture them:
 302   Node_Notes* nn = C->default_node_notes();
 303   if (nn != nullptr)  init_node_notes(C, idx, nn);
 304 
 305   // Note:  At this point, C is dead,
 306   // and we begin to initialize the new Node.
 307 
 308   _cnt = _max = req;
 309   _outcnt = _outmax = 0;
 310   _class_id = Class_Node;
 311   _flags = 0;
 312   _out = NO_OUT_ARRAY;
 313   return idx;
 314 }
 315 
 316 //------------------------------Node-------------------------------------------
 317 // Create a Node, with a given number of required edges.
 318 Node::Node(uint req)
 319   : _idx(Init(req))
 320 #ifdef ASSERT
 321   , _parse_idx(_idx)
 322 #endif
 323 {
 324   assert( req < Compile::current()->max_node_limit() - NodeLimitFudgeFactor, "Input limit exceeded" );
 325   DEBUG_ONLY( verify_construction() );
 326   NOT_PRODUCT(nodes_created++);
 327   if (req == 0) {
 328     _in = nullptr;
 329   } else {
 330     Node** to = _in;
 331     for(uint i = 0; i < req; i++) {
 332       to[i] = nullptr;
 333     }
 334   }
 335 }
 336 
 337 //------------------------------Node-------------------------------------------
 338 Node::Node(Node *n0)
 339   : _idx(Init(1))
 340 #ifdef ASSERT
 341   , _parse_idx(_idx)
 342 #endif
 343 {
 344   DEBUG_ONLY( verify_construction() );
 345   NOT_PRODUCT(nodes_created++);
 346   assert( is_not_dead(n0), "can not use dead node");
 347   _in[0] = n0; if (n0 != nullptr) n0->add_out((Node *)this);
 348 }
 349 
 350 //------------------------------Node-------------------------------------------
 351 Node::Node(Node *n0, Node *n1)
 352   : _idx(Init(2))
 353 #ifdef ASSERT
 354   , _parse_idx(_idx)
 355 #endif
 356 {
 357   DEBUG_ONLY( verify_construction() );
 358   NOT_PRODUCT(nodes_created++);
 359   assert( is_not_dead(n0), "can not use dead node");
 360   assert( is_not_dead(n1), "can not use dead node");
 361   _in[0] = n0; if (n0 != nullptr) n0->add_out((Node *)this);
 362   _in[1] = n1; if (n1 != nullptr) n1->add_out((Node *)this);
 363 }
 364 
 365 //------------------------------Node-------------------------------------------
 366 Node::Node(Node *n0, Node *n1, Node *n2)
 367   : _idx(Init(3))
 368 #ifdef ASSERT
 369   , _parse_idx(_idx)
 370 #endif
 371 {
 372   DEBUG_ONLY( verify_construction() );
 373   NOT_PRODUCT(nodes_created++);
 374   assert( is_not_dead(n0), "can not use dead node");
 375   assert( is_not_dead(n1), "can not use dead node");
 376   assert( is_not_dead(n2), "can not use dead node");
 377   _in[0] = n0; if (n0 != nullptr) n0->add_out((Node *)this);
 378   _in[1] = n1; if (n1 != nullptr) n1->add_out((Node *)this);
 379   _in[2] = n2; if (n2 != nullptr) n2->add_out((Node *)this);
 380 }
 381 
 382 //------------------------------Node-------------------------------------------
 383 Node::Node(Node *n0, Node *n1, Node *n2, Node *n3)
 384   : _idx(Init(4))
 385 #ifdef ASSERT
 386   , _parse_idx(_idx)
 387 #endif
 388 {
 389   DEBUG_ONLY( verify_construction() );
 390   NOT_PRODUCT(nodes_created++);
 391   assert( is_not_dead(n0), "can not use dead node");
 392   assert( is_not_dead(n1), "can not use dead node");
 393   assert( is_not_dead(n2), "can not use dead node");
 394   assert( is_not_dead(n3), "can not use dead node");
 395   _in[0] = n0; if (n0 != nullptr) n0->add_out((Node *)this);
 396   _in[1] = n1; if (n1 != nullptr) n1->add_out((Node *)this);
 397   _in[2] = n2; if (n2 != nullptr) n2->add_out((Node *)this);
 398   _in[3] = n3; if (n3 != nullptr) n3->add_out((Node *)this);
 399 }
 400 
 401 //------------------------------Node-------------------------------------------
 402 Node::Node(Node *n0, Node *n1, Node *n2, Node *n3, Node *n4)
 403   : _idx(Init(5))
 404 #ifdef ASSERT
 405   , _parse_idx(_idx)
 406 #endif
 407 {
 408   DEBUG_ONLY( verify_construction() );
 409   NOT_PRODUCT(nodes_created++);
 410   assert( is_not_dead(n0), "can not use dead node");
 411   assert( is_not_dead(n1), "can not use dead node");
 412   assert( is_not_dead(n2), "can not use dead node");
 413   assert( is_not_dead(n3), "can not use dead node");
 414   assert( is_not_dead(n4), "can not use dead node");
 415   _in[0] = n0; if (n0 != nullptr) n0->add_out((Node *)this);
 416   _in[1] = n1; if (n1 != nullptr) n1->add_out((Node *)this);
 417   _in[2] = n2; if (n2 != nullptr) n2->add_out((Node *)this);
 418   _in[3] = n3; if (n3 != nullptr) n3->add_out((Node *)this);
 419   _in[4] = n4; if (n4 != nullptr) n4->add_out((Node *)this);
 420 }
 421 
 422 //------------------------------Node-------------------------------------------
 423 Node::Node(Node *n0, Node *n1, Node *n2, Node *n3,
 424                      Node *n4, Node *n5)
 425   : _idx(Init(6))
 426 #ifdef ASSERT
 427   , _parse_idx(_idx)
 428 #endif
 429 {
 430   DEBUG_ONLY( verify_construction() );
 431   NOT_PRODUCT(nodes_created++);
 432   assert( is_not_dead(n0), "can not use dead node");
 433   assert( is_not_dead(n1), "can not use dead node");
 434   assert( is_not_dead(n2), "can not use dead node");
 435   assert( is_not_dead(n3), "can not use dead node");
 436   assert( is_not_dead(n4), "can not use dead node");
 437   assert( is_not_dead(n5), "can not use dead node");
 438   _in[0] = n0; if (n0 != nullptr) n0->add_out((Node *)this);
 439   _in[1] = n1; if (n1 != nullptr) n1->add_out((Node *)this);
 440   _in[2] = n2; if (n2 != nullptr) n2->add_out((Node *)this);
 441   _in[3] = n3; if (n3 != nullptr) n3->add_out((Node *)this);
 442   _in[4] = n4; if (n4 != nullptr) n4->add_out((Node *)this);
 443   _in[5] = n5; if (n5 != nullptr) n5->add_out((Node *)this);
 444 }
 445 
 446 //------------------------------Node-------------------------------------------
 447 Node::Node(Node *n0, Node *n1, Node *n2, Node *n3,
 448                      Node *n4, Node *n5, Node *n6)
 449   : _idx(Init(7))
 450 #ifdef ASSERT
 451   , _parse_idx(_idx)
 452 #endif
 453 {
 454   DEBUG_ONLY( verify_construction() );
 455   NOT_PRODUCT(nodes_created++);
 456   assert( is_not_dead(n0), "can not use dead node");
 457   assert( is_not_dead(n1), "can not use dead node");
 458   assert( is_not_dead(n2), "can not use dead node");
 459   assert( is_not_dead(n3), "can not use dead node");
 460   assert( is_not_dead(n4), "can not use dead node");
 461   assert( is_not_dead(n5), "can not use dead node");
 462   assert( is_not_dead(n6), "can not use dead node");
 463   _in[0] = n0; if (n0 != nullptr) n0->add_out((Node *)this);
 464   _in[1] = n1; if (n1 != nullptr) n1->add_out((Node *)this);
 465   _in[2] = n2; if (n2 != nullptr) n2->add_out((Node *)this);
 466   _in[3] = n3; if (n3 != nullptr) n3->add_out((Node *)this);
 467   _in[4] = n4; if (n4 != nullptr) n4->add_out((Node *)this);
 468   _in[5] = n5; if (n5 != nullptr) n5->add_out((Node *)this);
 469   _in[6] = n6; if (n6 != nullptr) n6->add_out((Node *)this);
 470 }
 471 
 472 #ifdef __clang__
 473 #pragma clang diagnostic pop
 474 #endif
 475 
 476 
 477 //------------------------------clone------------------------------------------
 478 // Clone a Node.
 479 Node *Node::clone() const {
 480   Compile* C = Compile::current();
 481   uint s = size_of();           // Size of inherited Node
 482   Node *n = (Node*)C->node_arena()->AmallocWords(size_of() + _max*sizeof(Node*));
 483   Copy::conjoint_words_to_lower((HeapWord*)this, (HeapWord*)n, s);
 484   // Set the new input pointer array
 485   n->_in = (Node**)(((char*)n)+s);
 486   // Cannot share the old output pointer array, so kill it
 487   n->_out = NO_OUT_ARRAY;
 488   // And reset the counters to 0
 489   n->_outcnt = 0;
 490   n->_outmax = 0;
 491   // Unlock this guy, since he is not in any hash table.
 492   DEBUG_ONLY(n->_hash_lock = 0);
 493   // Walk the old node's input list to duplicate its edges
 494   uint i;
 495   for( i = 0; i < len(); i++ ) {
 496     Node *x = in(i);
 497     n->_in[i] = x;
 498     if (x != nullptr) x->add_out(n);
 499   }
 500   if (is_macro()) {
 501     C->add_macro_node(n);
 502   }
 503   if (is_expensive()) {
 504     C->add_expensive_node(n);
 505   }
 506   if (for_post_loop_opts_igvn()) {
 507     // Don't add cloned node to Compile::_for_post_loop_opts_igvn list automatically.
 508     // If it is applicable, it will happen anyway when the cloned node is registered with IGVN.
 509     n->remove_flag(Node::NodeFlags::Flag_for_post_loop_opts_igvn);
 510   }
 511   if (for_merge_stores_igvn()) {
 512     // Don't add cloned node to Compile::_for_merge_stores_igvn list automatically.
 513     // If it is applicable, it will happen anyway when the cloned node is registered with IGVN.
 514     n->remove_flag(Node::NodeFlags::Flag_for_merge_stores_igvn);
 515   }
 516   if (n->is_ParsePredicate()) {
 517     C->add_parse_predicate(n->as_ParsePredicate());
 518   }
 519   if (n->is_OpaqueTemplateAssertionPredicate()) {
 520     C->add_template_assertion_predicate_opaque(n->as_OpaqueTemplateAssertionPredicate());
 521   }
 522 
 523   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 524   bs->register_potential_barrier_node(n);
 525 
 526   n->set_idx(C->next_unique()); // Get new unique index as well
 527   NOT_PRODUCT(n->_igv_idx = C->next_igv_idx());
 528   DEBUG_ONLY( n->verify_construction() );
 529   NOT_PRODUCT(nodes_created++);
 530   // Do not patch over the debug_idx of a clone, because it makes it
 531   // impossible to break on the clone's moment of creation.
 532   //DEBUG_ONLY( n->set_debug_idx( debug_idx() ) );
 533 
 534   C->copy_node_notes_to(n, (Node*) this);
 535 
 536   // MachNode clone
 537   uint nopnds;
 538   if (this->is_Mach() && (nopnds = this->as_Mach()->num_opnds()) > 0) {
 539     MachNode *mach  = n->as_Mach();
 540     MachNode *mthis = this->as_Mach();
 541     // Get address of _opnd_array.
 542     // It should be the same offset since it is the clone of this node.
 543     MachOper **from = mthis->_opnds;
 544     MachOper **to = (MachOper **)((size_t)(&mach->_opnds) +
 545                     pointer_delta((const void*)from,
 546                                   (const void*)(&mthis->_opnds), 1));
 547     mach->_opnds = to;
 548     for ( uint i = 0; i < nopnds; ++i ) {
 549       to[i] = from[i]->clone();
 550     }
 551   }
 552   if (this->is_MachProj()) {
 553     // MachProjNodes contain register masks that may contain pointers to
 554     // externally allocated memory. Make sure to use a proper constructor
 555     // instead of just shallowly copying.
 556     MachProjNode* mach = n->as_MachProj();
 557     MachProjNode* mthis = this->as_MachProj();
 558     new (&mach->_rout) RegMask(mthis->_rout);
 559   }
 560   if (n->is_Call()) {
 561     // CallGenerator is linked to the original node.
 562     CallGenerator* cg = n->as_Call()->generator();
 563     if (cg != nullptr) {
 564       CallGenerator* cloned_cg = cg->with_call_node(n->as_Call());
 565       n->as_Call()->set_generator(cloned_cg);
 566     }
 567   }
 568   if (n->is_SafePoint()) {
 569     // Scalar replacement and macro expansion might modify the JVMState.
 570     // Clone it to make sure it's not shared between SafePointNodes.
 571     n->as_SafePoint()->clone_jvms(C);
 572     n->as_SafePoint()->clone_replaced_nodes();
 573   }






 574   Compile::current()->record_modified_node(n);
 575   return n;                     // Return the clone
 576 }
 577 
 578 //---------------------------setup_is_top--------------------------------------
 579 // Call this when changing the top node, to reassert the invariants
 580 // required by Node::is_top.  See Compile::set_cached_top_node.
 581 void Node::setup_is_top() {
 582   if (this == (Node*)Compile::current()->top()) {
 583     // This node has just become top.  Kill its out array.
 584     _outcnt = _outmax = 0;
 585     _out = nullptr;                           // marker value for top
 586     assert(is_top(), "must be top");
 587   } else {
 588     if (_out == nullptr)  _out = NO_OUT_ARRAY;
 589     assert(!is_top(), "must not be top");
 590   }
 591 }
 592 
 593 //------------------------------~Node------------------------------------------
 594 // Fancy destructor; eagerly attempt to reclaim Node numberings and storage
 595 void Node::destruct(PhaseValues* phase) {
 596   Compile* compile = (phase != nullptr) ? phase->C : Compile::current();
 597   if (phase != nullptr && phase->is_IterGVN()) {
 598     phase->is_IterGVN()->_worklist.remove(this);
 599   }
 600   // If this is the most recently created node, reclaim its index. Otherwise,
 601   // record the node as dead to keep liveness information accurate.
 602   if ((uint)_idx+1 == compile->unique()) {
 603     compile->set_unique(compile->unique()-1);
 604   } else {
 605     compile->record_dead_node(_idx);
 606   }
 607   // Clear debug info:
 608   Node_Notes* nn = compile->node_notes_at(_idx);
 609   if (nn != nullptr)  nn->clear();
 610   // Walk the input array, freeing the corresponding output edges
 611   _cnt = _max;  // forget req/prec distinction
 612   uint i;
 613   for( i = 0; i < _max; i++ ) {
 614     set_req(i, nullptr);
 615     //assert(def->out(def->outcnt()-1) == (Node *)this,"bad def-use hacking in reclaim");
 616   }
 617   assert(outcnt() == 0, "deleting a node must not leave a dangling use");
 618 
 619   if (is_macro()) {
 620     compile->remove_macro_node(this);
 621   }
 622   if (is_expensive()) {
 623     compile->remove_expensive_node(this);
 624   }
 625   if (is_OpaqueTemplateAssertionPredicate()) {
 626     compile->remove_template_assertion_predicate_opaque(as_OpaqueTemplateAssertionPredicate());
 627   }
 628   if (is_ParsePredicate()) {
 629     compile->remove_parse_predicate(as_ParsePredicate());
 630   }
 631   if (for_post_loop_opts_igvn()) {
 632     compile->remove_from_post_loop_opts_igvn(this);
 633   }



 634   if (for_merge_stores_igvn()) {
 635     compile->remove_from_merge_stores_igvn(this);
 636   }
 637 
 638   if (is_SafePoint()) {
 639     as_SafePoint()->delete_replaced_nodes();
 640 
 641     if (is_CallStaticJava()) {
 642       compile->remove_unstable_if_trap(as_CallStaticJava(), false);
 643     }
 644   }
 645   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 646   bs->unregister_potential_barrier_node(this);
 647 
 648   // See if the input array was allocated just prior to the object
 649   int edge_size = _max*sizeof(void*);
 650   int out_edge_size = _outmax*sizeof(void*);
 651   char *in_array = ((char*)_in);
 652   char *edge_end = in_array + edge_size;
 653   char *out_array = (char*)(_out == NO_OUT_ARRAY? nullptr: _out);
 654   int node_size = size_of();
 655 
 656 #ifdef ASSERT
 657   // We will not actually delete the storage, but we'll make the node unusable.
 658   compile->remove_modified_node(this);
 659   *(address*)this = badAddress;  // smash the C++ vtbl, probably
 660   _in = _out = (Node**) badAddress;
 661   _max = _cnt = _outmax = _outcnt = 0;
 662 #endif
 663 
 664   // Free the output edge array
 665   if (out_edge_size > 0) {
 666     compile->node_arena()->Afree(out_array, out_edge_size);
 667   }
 668 
 669   // Free the input edge array and the node itself
 670   if( edge_end == (char*)this ) {
 671     // It was; free the input array and object all in one hit
 672 #ifndef ASSERT
 673     compile->node_arena()->Afree(in_array, edge_size+node_size);
 674 #endif
 675   } else {
 676     // Free just the input array
 677     compile->node_arena()->Afree(in_array, edge_size);
 678 
 679     // Free just the object
 680 #ifndef ASSERT
 681     compile->node_arena()->Afree(this, node_size);
 682 #endif
 683   }
 684 }
 685 
 686 // Resize input or output array to grow it to the next larger power-of-2 bigger
 687 // than len.
 688 void Node::resize_array(Node**& array, node_idx_t& max_size, uint len, bool needs_clearing) {
 689   Arena* arena = Compile::current()->node_arena();
 690   uint new_max = max_size;
 691   if (new_max == 0) {
 692     max_size = 4;
 693     array = (Node**)arena->Amalloc(4 * sizeof(Node*));
 694     if (needs_clearing) {
 695       array[0] = nullptr;
 696       array[1] = nullptr;
 697       array[2] = nullptr;
 698       array[3] = nullptr;
 699     }
 700     return;
 701   }
 702   new_max = next_power_of_2(len);
 703   assert(needs_clearing || (array != nullptr && array != NO_OUT_ARRAY), "out must have sensible value");
 704   array = (Node**)arena->Arealloc(array, max_size * sizeof(Node*), new_max * sizeof(Node*));
 705   if (needs_clearing) {
 706     Copy::zero_to_bytes(&array[max_size], (new_max - max_size) * sizeof(Node*)); // null all new space
 707   }
 708   max_size = new_max;               // Record new max length
 709   // This assertion makes sure that Node::_max is wide enough to
 710   // represent the numerical value of new_max.
 711   assert(max_size > len, "int width of _max or _outmax is too small");
 712 }
 713 
 714 //------------------------------grow-------------------------------------------
 715 // Grow the input array, making space for more edges
 716 void Node::grow(uint len) {
 717   resize_array(_in, _max, len, true);
 718 }
 719 
 720 //-----------------------------out_grow----------------------------------------
 721 // Grow the input array, making space for more edges
 722 void Node::out_grow(uint len) {
 723   assert(!is_top(), "cannot grow a top node's out array");
 724   resize_array(_out, _outmax, len, false);
 725 }
 726 
 727 #ifdef ASSERT
 728 //------------------------------is_dead----------------------------------------
 729 bool Node::is_dead() const {
 730   // Mach and pinch point nodes may look like dead.
 731   if( is_top() || is_Mach() || (Opcode() == Op_Node && _outcnt > 0) )
 732     return false;
 733   for( uint i = 0; i < _max; i++ )
 734     if( _in[i] != nullptr )
 735       return false;
 736   return true;
 737 }
 738 
 739 bool Node::is_not_dead(const Node* n) {
 740   return n == nullptr || !PhaseIterGVN::is_verify_def_use() || !(n->is_dead());
 741 }
 742 
 743 bool Node::is_reachable_from_root() const {
 744   ResourceMark rm;
 745   Unique_Node_List wq;
 746   wq.push((Node*)this);
 747   RootNode* root = Compile::current()->root();
 748   for (uint i = 0; i < wq.size(); i++) {
 749     Node* m = wq.at(i);
 750     if (m == root) {
 751       return true;
 752     }
 753     for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
 754       Node* u = m->fast_out(j);
 755       wq.push(u);
 756     }
 757   }
 758   return false;
 759 }
 760 #endif
 761 
 762 //------------------------------is_unreachable---------------------------------
 763 bool Node::is_unreachable(PhaseIterGVN &igvn) const {
 764   assert(!is_Mach(), "doesn't work with MachNodes");
 765   return outcnt() == 0 || igvn.type(this) == Type::TOP || (in(0) != nullptr && in(0)->is_top());
 766 }
 767 
 768 //------------------------------add_req----------------------------------------
 769 // Add a new required input at the end
 770 void Node::add_req( Node *n ) {
 771   assert( is_not_dead(n), "can not use dead node");
 772 
 773   // Look to see if I can move precedence down one without reallocating
 774   if( (_cnt >= _max) || (in(_max-1) != nullptr) )
 775     grow( _max+1 );
 776 
 777   // Find a precedence edge to move
 778   if( in(_cnt) != nullptr ) {   // Next precedence edge is busy?
 779     uint i;
 780     for( i=_cnt; i<_max; i++ )
 781       if( in(i) == nullptr )    // Find the null at end of prec edge list
 782         break;                  // There must be one, since we grew the array
 783     _in[i] = in(_cnt);          // Move prec over, making space for req edge
 784   }
 785   _in[_cnt++] = n;            // Stuff over old prec edge
 786   if (n != nullptr) n->add_out((Node *)this);
 787   Compile::current()->record_modified_node(this);
 788 }
 789 
 790 //---------------------------add_req_batch-------------------------------------
 791 // Add a new required input at the end
 792 void Node::add_req_batch( Node *n, uint m ) {
 793   assert( is_not_dead(n), "can not use dead node");
 794   // check various edge cases
 795   if ((int)m <= 1) {
 796     assert((int)m >= 0, "oob");
 797     if (m != 0)  add_req(n);
 798     return;
 799   }
 800 
 801   // Look to see if I can move precedence down one without reallocating
 802   if( (_cnt+m) > _max || _in[_max-m] )
 803     grow( _max+m );
 804 
 805   // Find a precedence edge to move
 806   if( _in[_cnt] != nullptr ) {  // Next precedence edge is busy?
 807     uint i;
 808     for( i=_cnt; i<_max; i++ )
 809       if( _in[i] == nullptr )   // Find the null at end of prec edge list
 810         break;                  // There must be one, since we grew the array
 811     // Slide all the precs over by m positions (assume #prec << m).
 812     Copy::conjoint_words_to_higher((HeapWord*)&_in[_cnt], (HeapWord*)&_in[_cnt+m], ((i-_cnt)*sizeof(Node*)));
 813   }
 814 
 815   // Stuff over the old prec edges
 816   for(uint i=0; i<m; i++ ) {
 817     _in[_cnt++] = n;
 818   }
 819 
 820   // Insert multiple out edges on the node.
 821   if (n != nullptr && !n->is_top()) {
 822     for(uint i=0; i<m; i++ ) {
 823       n->add_out((Node *)this);
 824     }
 825   }
 826   Compile::current()->record_modified_node(this);
 827 }
 828 
 829 //------------------------------del_req----------------------------------------
 830 // Delete the required edge and compact the edge array
 831 void Node::del_req( uint idx ) {
 832   assert( idx < _cnt, "oob");
 833   assert( !VerifyHashTableKeys || _hash_lock == 0,
 834           "remove node from hash table before modifying it");
 835   // First remove corresponding def-use edge
 836   Node *n = in(idx);
 837   if (n != nullptr) n->del_out((Node *)this);
 838   _in[idx] = in(--_cnt); // Compact the array
 839   // Avoid spec violation: Gap in prec edges.
 840   close_prec_gap_at(_cnt);
 841   Compile::current()->record_modified_node(this);
 842 }
 843 
 844 //------------------------------del_req_ordered--------------------------------
 845 // Delete the required edge and compact the edge array with preserved order
 846 void Node::del_req_ordered( uint idx ) {
 847   assert( idx < _cnt, "oob");
 848   assert( !VerifyHashTableKeys || _hash_lock == 0,
 849           "remove node from hash table before modifying it");
 850   // First remove corresponding def-use edge
 851   Node *n = in(idx);
 852   if (n != nullptr) n->del_out((Node *)this);
 853   if (idx < --_cnt) {    // Not last edge ?
 854     Copy::conjoint_words_to_lower((HeapWord*)&_in[idx+1], (HeapWord*)&_in[idx], ((_cnt-idx)*sizeof(Node*)));
 855   }
 856   // Avoid spec violation: Gap in prec edges.
 857   close_prec_gap_at(_cnt);
 858   Compile::current()->record_modified_node(this);
 859 }
 860 
 861 //------------------------------ins_req----------------------------------------
 862 // Insert a new required input at the end
 863 void Node::ins_req( uint idx, Node *n ) {
 864   assert( is_not_dead(n), "can not use dead node");
 865   add_req(nullptr);                // Make space
 866   assert( idx < _max, "Must have allocated enough space");
 867   // Slide over
 868   if(_cnt-idx-1 > 0) {
 869     Copy::conjoint_words_to_higher((HeapWord*)&_in[idx], (HeapWord*)&_in[idx+1], ((_cnt-idx-1)*sizeof(Node*)));
 870   }
 871   _in[idx] = n;                            // Stuff over old required edge
 872   if (n != nullptr) n->add_out((Node *)this); // Add reciprocal def-use edge
 873   Compile::current()->record_modified_node(this);
 874 }
 875 
 876 //-----------------------------find_edge---------------------------------------
 877 int Node::find_edge(Node* n) {
 878   for (uint i = 0; i < len(); i++) {
 879     if (_in[i] == n)  return i;
 880   }
 881   return -1;
 882 }
 883 
 884 //----------------------------replace_edge-------------------------------------
 885 int Node::replace_edge(Node* old, Node* neww, PhaseGVN* gvn) {
 886   if (old == neww)  return 0;  // nothing to do
 887   uint nrep = 0;
 888   for (uint i = 0; i < len(); i++) {
 889     if (in(i) == old) {
 890       if (i < req()) {
 891         if (gvn != nullptr) {
 892           set_req_X(i, neww, gvn);
 893         } else {
 894           set_req(i, neww);
 895         }
 896       } else {
 897         assert(gvn == nullptr || gvn->is_IterGVN() == nullptr, "no support for igvn here");
 898         assert(find_prec_edge(neww) == -1, "spec violation: duplicated prec edge (node %d -> %d)", _idx, neww->_idx);
 899         set_prec(i, neww);
 900       }
 901       nrep++;
 902     }
 903   }
 904   return nrep;
 905 }
 906 
 907 /**
 908  * Replace input edges in the range pointing to 'old' node.
 909  */
 910 int Node::replace_edges_in_range(Node* old, Node* neww, int start, int end, PhaseGVN* gvn) {
 911   if (old == neww)  return 0;  // nothing to do
 912   uint nrep = 0;
 913   for (int i = start; i < end; i++) {
 914     if (in(i) == old) {
 915       set_req_X(i, neww, gvn);
 916       nrep++;
 917     }
 918   }
 919   return nrep;
 920 }
 921 
 922 //-------------------------disconnect_inputs-----------------------------------
 923 // null out all inputs to eliminate incoming Def-Use edges.
 924 void Node::disconnect_inputs(Compile* C) {
 925   // the layout of Node::_in
 926   // r: a required input, null is allowed
 927   // p: a precedence, null values are all at the end
 928   // -----------------------------------
 929   // |r|...|r|p|...|p|null|...|null|
 930   //         |                     |
 931   //         req()                 len()
 932   // -----------------------------------
 933   for (uint i = 0; i < req(); ++i) {
 934     if (in(i) != nullptr) {
 935       set_req(i, nullptr);
 936     }
 937   }
 938 
 939   // Remove precedence edges if any exist
 940   // Note: Safepoints may have precedence edges, even during parsing
 941   for (uint i = len(); i > req(); ) {
 942     rm_prec(--i);  // no-op if _in[i] is null
 943   }
 944 
 945 #ifdef ASSERT
 946   // sanity check
 947   for (uint i = 0; i < len(); ++i) {
 948     assert(_in[i] == nullptr, "disconnect_inputs() failed!");
 949   }
 950 #endif
 951 
 952   // Node::destruct requires all out edges be deleted first
 953   // DEBUG_ONLY(destruct();)   // no reuse benefit expected
 954   C->record_dead_node(_idx);
 955 }
 956 
 957 //-----------------------------uncast---------------------------------------
 958 // %%% Temporary, until we sort out CheckCastPP vs. CastPP.
 959 // Strip away casting.  (It is depth-limited.)
 960 // Optionally, keep casts with dependencies.
 961 Node* Node::uncast(bool keep_deps) const {
 962   // Should be inline:
 963   //return is_ConstraintCast() ? uncast_helper(this) : (Node*) this;
 964   if (is_ConstraintCast()) {
 965     return uncast_helper(this, keep_deps);
 966   } else {
 967     return (Node*) this;
 968   }
 969 }
 970 
 971 // Find out of current node that matches opcode.
 972 Node* Node::find_out_with(int opcode) {
 973   for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
 974     Node* use = fast_out(i);
 975     if (use->Opcode() == opcode) {
 976       return use;
 977     }
 978   }
 979   return nullptr;
 980 }
 981 
 982 // Return true if the current node has an out that matches opcode.
 983 bool Node::has_out_with(int opcode) {
 984   return (find_out_with(opcode) != nullptr);
 985 }
 986 
 987 // Return true if the current node has an out that matches any of the opcodes.
 988 bool Node::has_out_with(int opcode1, int opcode2, int opcode3, int opcode4) {
 989   for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
 990       int opcode = fast_out(i)->Opcode();
 991       if (opcode == opcode1 || opcode == opcode2 || opcode == opcode3 || opcode == opcode4) {
 992         return true;
 993       }
 994   }
 995   return false;
 996 }
 997 
 998 
 999 //---------------------------uncast_helper-------------------------------------
1000 Node* Node::uncast_helper(const Node* p, bool keep_deps) {
1001 #ifdef ASSERT
1002   // If we end up traversing more nodes than we actually have,
1003   // it is definitely an infinite loop.
1004   uint max_depth = Compile::current()->unique();
1005   uint depth_count = 0;
1006   const Node* orig_p = p;
1007 #endif
1008 
1009   while (true) {
1010 #ifdef ASSERT
1011     if (depth_count++ >= max_depth) {
1012       orig_p->dump(4);
1013       if (p != orig_p) {
1014         p->dump(1);
1015       }
1016       fatal("infinite loop in Node::uncast_helper");
1017     }
1018 #endif
1019     if (p == nullptr || p->req() != 2) {
1020       break;
1021     } else if (p->is_ConstraintCast()) {
1022       if (keep_deps && p->as_ConstraintCast()->carry_dependency()) {
1023         break; // stop at casts with dependencies
1024       }
1025       p = p->in(1);
1026     } else {
1027       break;
1028     }
1029   }
1030   return (Node*) p;
1031 }
1032 
1033 //------------------------------add_prec---------------------------------------
1034 // Add a new precedence input.  Precedence inputs are unordered, with
1035 // duplicates removed and nulls packed down at the end.
1036 void Node::add_prec( Node *n ) {
1037   assert( is_not_dead(n), "can not use dead node");
1038 
1039   // Check for null at end
1040   if( _cnt >= _max || in(_max-1) )
1041     grow( _max+1 );
1042 
1043   // Find a precedence edge to move
1044   uint i = _cnt;
1045   while( in(i) != nullptr ) {
1046     if (in(i) == n) return; // Avoid spec violation: duplicated prec edge.
1047     i++;
1048   }
1049   _in[i] = n;                                   // Stuff prec edge over null
1050   if ( n != nullptr) n->add_out((Node *)this);  // Add mirror edge
1051 
1052 #ifdef ASSERT
1053   while ((++i)<_max) { assert(_in[i] == nullptr, "spec violation: Gap in prec edges (node %d)", _idx); }
1054 #endif
1055   Compile::current()->record_modified_node(this);
1056 }
1057 
1058 //------------------------------rm_prec----------------------------------------
1059 // Remove a precedence input.  Precedence inputs are unordered, with
1060 // duplicates removed and nulls packed down at the end.
1061 void Node::rm_prec( uint j ) {
1062   assert(j < _max, "oob: i=%d, _max=%d", j, _max);
1063   assert(j >= _cnt, "not a precedence edge");
1064   if (_in[j] == nullptr) return;   // Avoid spec violation: Gap in prec edges.
1065   _in[j]->del_out((Node *)this);
1066   close_prec_gap_at(j);
1067   Compile::current()->record_modified_node(this);
1068 }
1069 
1070 //------------------------------size_of----------------------------------------
1071 uint Node::size_of() const { return sizeof(*this); }
1072 
1073 //------------------------------ideal_reg--------------------------------------
1074 uint Node::ideal_reg() const { return 0; }
1075 
1076 //------------------------------jvms-------------------------------------------
1077 JVMState* Node::jvms() const { return nullptr; }
1078 
1079 #ifdef ASSERT
1080 //------------------------------jvms-------------------------------------------
1081 bool Node::verify_jvms(const JVMState* using_jvms) const {
1082   for (JVMState* jvms = this->jvms(); jvms != nullptr; jvms = jvms->caller()) {
1083     if (jvms == using_jvms)  return true;
1084   }
1085   return false;
1086 }
1087 
1088 //------------------------------init_NodeProperty------------------------------
1089 void Node::init_NodeProperty() {
1090   assert(_max_classes <= max_juint, "too many NodeProperty classes");
1091   assert(max_flags() <= max_juint, "too many NodeProperty flags");
1092 }
1093 
1094 //-----------------------------max_flags---------------------------------------
1095 juint Node::max_flags() {
1096   return (PD::_last_flag << 1) - 1; // allow flags combination
1097 }
1098 #endif
1099 
1100 //------------------------------format-----------------------------------------
1101 // Print as assembly
1102 void Node::format( PhaseRegAlloc *, outputStream *st ) const {}
1103 //------------------------------emit-------------------------------------------
1104 // Emit bytes using C2_MacroAssembler
1105 void Node::emit(C2_MacroAssembler *masm, PhaseRegAlloc *ra_) const {}
1106 //------------------------------size-------------------------------------------
1107 // Size of instruction in bytes
1108 uint Node::size(PhaseRegAlloc *ra_) const { return 0; }
1109 
1110 //------------------------------CFG Construction-------------------------------
1111 // Nodes that end basic blocks, e.g. IfTrue/IfFalse, JumpProjNode, Root,
1112 // Goto and Return.
1113 const Node *Node::is_block_proj() const { return nullptr; }
1114 
1115 // Minimum guaranteed type
1116 const Type *Node::bottom_type() const { return Type::BOTTOM; }
1117 
1118 
1119 //------------------------------raise_bottom_type------------------------------
1120 // Get the worst-case Type output for this Node.
1121 void Node::raise_bottom_type(const Type* new_type) {
1122   if (is_Type()) {
1123     TypeNode *n = this->as_Type();
1124     if (VerifyAliases) {
1125       assert(new_type->higher_equal_speculative(n->type()), "new type must refine old type");
1126     }
1127     n->set_type(new_type);
1128   } else if (is_Load()) {
1129     LoadNode *n = this->as_Load();
1130     if (VerifyAliases) {
1131       assert(new_type->higher_equal_speculative(n->type()), "new type must refine old type");
1132     }
1133     n->set_type(new_type);
1134   }
1135 }
1136 
1137 //------------------------------Identity---------------------------------------
1138 // Return a node that the given node is equivalent to.
1139 Node* Node::Identity(PhaseGVN* phase) {
1140   return this;                  // Default to no identities
1141 }
1142 
1143 //------------------------------Value------------------------------------------
1144 // Compute a new Type for a node using the Type of the inputs.
1145 const Type* Node::Value(PhaseGVN* phase) const {
1146   return bottom_type();         // Default to worst-case Type
1147 }
1148 
1149 //------------------------------Ideal------------------------------------------
1150 //
1151 // 'Idealize' the graph rooted at this Node.
1152 //
1153 // In order to be efficient and flexible there are some subtle invariants
1154 // these Ideal calls need to hold.  Running with '-XX:VerifyIterativeGVN=1' checks
1155 // these invariants, although its too slow to have on by default.  If you are
1156 // hacking an Ideal call, be sure to test with '-XX:VerifyIterativeGVN=1'
1157 //
1158 // The Ideal call almost arbitrarily reshape the graph rooted at the 'this'
1159 // pointer.  If ANY change is made, it must return the root of the reshaped
1160 // graph - even if the root is the same Node.  Example: swapping the inputs
1161 // to an AddINode gives the same answer and same root, but you still have to
1162 // return the 'this' pointer instead of null.
1163 //
1164 // You cannot return an OLD Node, except for the 'this' pointer.  Use the
1165 // Identity call to return an old Node; basically if Identity can find
1166 // another Node have the Ideal call make no change and return null.
1167 // Example: AddINode::Ideal must check for add of zero; in this case it
1168 // returns null instead of doing any graph reshaping.
1169 //
1170 // You cannot modify any old Nodes except for the 'this' pointer.  Due to
1171 // sharing there may be other users of the old Nodes relying on their current
1172 // semantics.  Modifying them will break the other users.
1173 // Example: when reshape "(X+3)+4" into "X+7" you must leave the Node for
1174 // "X+3" unchanged in case it is shared.
1175 //
1176 // If you modify the 'this' pointer's inputs, you should use
1177 // 'set_req'.  If you are making a new Node (either as the new root or
1178 // some new internal piece) you may use 'init_req' to set the initial
1179 // value.  You can make a new Node with either 'new' or 'clone'.  In
1180 // either case, def-use info is correctly maintained.
1181 //
1182 // Example: reshape "(X+3)+4" into "X+7":
1183 //    set_req(1, in(1)->in(1));
1184 //    set_req(2, phase->intcon(7));
1185 //    return this;
1186 // Example: reshape "X*4" into "X<<2"
1187 //    return new LShiftINode(in(1), phase->intcon(2));
1188 //
1189 // You must call 'phase->transform(X)' on any new Nodes X you make, except
1190 // for the returned root node.  Example: reshape "X*31" with "(X<<5)-X".
1191 //    Node *shift=phase->transform(new LShiftINode(in(1),phase->intcon(5)));
1192 //    return new AddINode(shift, in(1));
1193 //
1194 // When making a Node for a constant use 'phase->makecon' or 'phase->intcon'.
1195 // These forms are faster than 'phase->transform(new ConNode())' and Do
1196 // The Right Thing with def-use info.
1197 //
1198 // You cannot bury the 'this' Node inside of a graph reshape.  If the reshaped
1199 // graph uses the 'this' Node it must be the root.  If you want a Node with
1200 // the same Opcode as the 'this' pointer use 'clone'.
1201 //
1202 Node *Node::Ideal(PhaseGVN *phase, bool can_reshape) {
1203   return nullptr;                  // Default to being Ideal already
1204 }
1205 
1206 // Some nodes have specific Ideal subgraph transformations only if they are
1207 // unique users of specific nodes. Such nodes should be put on IGVN worklist
1208 // for the transformations to happen.
1209 bool Node::has_special_unique_user() const {
1210   assert(outcnt() == 1, "match only for unique out");
1211   Node* n = unique_out();
1212   int op  = Opcode();
1213   if (this->is_Store()) {
1214     // Condition for back-to-back stores folding.
1215     return n->Opcode() == op && n->in(MemNode::Memory) == this;
1216   } else if ((this->is_Load() || this->is_DecodeN() || this->is_Phi()) && n->Opcode() == Op_MemBarAcquire) {
1217     // Condition for removing an unused LoadNode or DecodeNNode from the MemBarAcquire precedence input
1218     return true;
1219   } else if (this->is_Load() && n->is_Move()) {
1220     // Condition for MoveX2Y (LoadX mem) => LoadY mem
1221     return true;
1222   } else if (op == Op_AddL) {
1223     // Condition for convL2I(addL(x,y)) ==> addI(convL2I(x),convL2I(y))
1224     return n->Opcode() == Op_ConvL2I && n->in(1) == this;
1225   } else if (op == Op_SubI || op == Op_SubL) {
1226     // Condition for subI(x,subI(y,z)) ==> subI(addI(x,z),y)
1227     return n->Opcode() == op && n->in(2) == this;
1228   } else if (is_If() && (n->is_IfFalse() || n->is_IfTrue())) {
1229     // See IfProjNode::Identity()
1230     return true;
1231   } else if ((is_IfFalse() || is_IfTrue()) && n->is_If()) {
1232     // See IfNode::fold_compares
1233     return true;
1234   } else if (n->Opcode() == Op_XorV || n->Opcode() == Op_XorVMask) {
1235     // Condition for XorVMask(VectorMaskCmp(x,y,cond), MaskAll(true)) ==> VectorMaskCmp(x,y,ncond)
1236     return true;
1237   } else {
1238     return false;
1239   }
1240 };
1241 
1242 //--------------------------find_exact_control---------------------------------
1243 // Skip Proj and CatchProj nodes chains. Check for Null and Top.
1244 Node* Node::find_exact_control(Node* ctrl) {
1245   if (ctrl == nullptr && this->is_Region())
1246     ctrl = this->as_Region()->is_copy();
1247 
1248   if (ctrl != nullptr && ctrl->is_CatchProj()) {
1249     if (ctrl->as_CatchProj()->_con == CatchProjNode::fall_through_index)
1250       ctrl = ctrl->in(0);
1251     if (ctrl != nullptr && !ctrl->is_top())
1252       ctrl = ctrl->in(0);
1253   }
1254 
1255   if (ctrl != nullptr && ctrl->is_Proj())
1256     ctrl = ctrl->in(0);
1257 
1258   return ctrl;
1259 }
1260 
1261 //--------------------------dominates------------------------------------------
1262 // Helper function for MemNode::all_controls_dominate().
1263 // Check if 'this' control node dominates or equal to 'sub' control node.
1264 // We already know that if any path back to Root or Start reaches 'this',
1265 // then all paths so, so this is a simple search for one example,
1266 // not an exhaustive search for a counterexample.
1267 Node::DomResult Node::dominates(Node* sub, Node_List &nlist) {
1268   assert(this->is_CFG(), "expecting control");
1269   assert(sub != nullptr && sub->is_CFG(), "expecting control");
1270 
1271   // detect dead cycle without regions
1272   int iterations_without_region_limit = DominatorSearchLimit;
1273 
1274   Node* orig_sub = sub;
1275   Node* dom      = this;
1276   bool  met_dom  = false;
1277   nlist.clear();
1278 
1279   // Walk 'sub' backward up the chain to 'dom', watching for regions.
1280   // After seeing 'dom', continue up to Root or Start.
1281   // If we hit a region (backward split point), it may be a loop head.
1282   // Keep going through one of the region's inputs.  If we reach the
1283   // same region again, go through a different input.  Eventually we
1284   // will either exit through the loop head, or give up.
1285   // (If we get confused, break out and return a conservative 'false'.)
1286   while (sub != nullptr) {
1287     if (sub->is_top()) {
1288       // Conservative answer for dead code.
1289       return DomResult::EncounteredDeadCode;
1290     }
1291     if (sub == dom) {
1292       if (nlist.size() == 0) {
1293         // No Region nodes except loops were visited before and the EntryControl
1294         // path was taken for loops: it did not walk in a cycle.
1295         return DomResult::Dominate;
1296       } else if (met_dom) {
1297         break;          // already met before: walk in a cycle
1298       } else {
1299         // Region nodes were visited. Continue walk up to Start or Root
1300         // to make sure that it did not walk in a cycle.
1301         met_dom = true; // first time meet
1302         iterations_without_region_limit = DominatorSearchLimit; // Reset
1303      }
1304     }
1305     if (sub->is_Start() || sub->is_Root()) {
1306       // Success if we met 'dom' along a path to Start or Root.
1307       // We assume there are no alternative paths that avoid 'dom'.
1308       // (This assumption is up to the caller to ensure!)
1309       return met_dom ? DomResult::Dominate : DomResult::NotDominate;
1310     }
1311     Node* up = sub->in(0);
1312     // Normalize simple pass-through regions and projections:
1313     up = sub->find_exact_control(up);
1314     // If sub == up, we found a self-loop.  Try to push past it.
1315     if (sub == up && sub->is_Loop()) {
1316       // Take loop entry path on the way up to 'dom'.
1317       up = sub->in(1); // in(LoopNode::EntryControl);
1318     } else if (sub == up && sub->is_Region() && sub->req() == 2) {
1319       // Take in(1) path on the way up to 'dom' for regions with only one input
1320       up = sub->in(1);
1321     } else if (sub == up && sub->is_Region()) {
1322       // Try both paths for Regions with 2 input paths (it may be a loop head).
1323       // It could give conservative 'false' answer without information
1324       // which region's input is the entry path.
1325       iterations_without_region_limit = DominatorSearchLimit; // Reset
1326 
1327       bool region_was_visited_before = false;
1328       // Was this Region node visited before?
1329       // If so, we have reached it because we accidentally took a
1330       // loop-back edge from 'sub' back into the body of the loop,
1331       // and worked our way up again to the loop header 'sub'.
1332       // So, take the first unexplored path on the way up to 'dom'.
1333       for (int j = nlist.size() - 1; j >= 0; j--) {
1334         intptr_t ni = (intptr_t)nlist.at(j);
1335         Node* visited = (Node*)(ni & ~1);
1336         bool  visited_twice_already = ((ni & 1) != 0);
1337         if (visited == sub) {
1338           if (visited_twice_already) {
1339             // Visited 2 paths, but still stuck in loop body.  Give up.
1340             return DomResult::NotDominate;
1341           }
1342           // The Region node was visited before only once.
1343           // (We will repush with the low bit set, below.)
1344           nlist.remove(j);
1345           // We will find a new edge and re-insert.
1346           region_was_visited_before = true;
1347           break;
1348         }
1349       }
1350 
1351       // Find an incoming edge which has not been seen yet; walk through it.
1352       assert(up == sub, "");
1353       uint skip = region_was_visited_before ? 1 : 0;
1354       for (uint i = 1; i < sub->req(); i++) {
1355         Node* in = sub->in(i);
1356         if (in != nullptr && !in->is_top() && in != sub) {
1357           if (skip == 0) {
1358             up = in;
1359             break;
1360           }
1361           --skip;               // skip this nontrivial input
1362         }
1363       }
1364 
1365       // Set 0 bit to indicate that both paths were taken.
1366       nlist.push((Node*)((intptr_t)sub + (region_was_visited_before ? 1 : 0)));
1367     }
1368 
1369     if (up == sub) {
1370       break;    // some kind of tight cycle
1371     }
1372     if (up == orig_sub && met_dom) {
1373       // returned back after visiting 'dom'
1374       break;    // some kind of cycle
1375     }
1376     if (--iterations_without_region_limit < 0) {
1377       break;    // dead cycle
1378     }
1379     sub = up;
1380   }
1381 
1382   // Did not meet Root or Start node in pred. chain.
1383   return DomResult::NotDominate;
1384 }
1385 
1386 //------------------------------remove_dead_region-----------------------------
1387 // This control node is dead.  Follow the subgraph below it making everything
1388 // using it dead as well.  This will happen normally via the usual IterGVN
1389 // worklist but this call is more efficient.  Do not update use-def info
1390 // inside the dead region, just at the borders.
1391 static void kill_dead_code( Node *dead, PhaseIterGVN *igvn ) {
1392   // Con's are a popular node to re-hit in the hash table again.
1393   if( dead->is_Con() ) return;
1394 
1395   ResourceMark rm;
1396   Node_List nstack;
1397   VectorSet dead_set; // notify uses only once
1398 
1399   Node *top = igvn->C->top();
1400   nstack.push(dead);
1401   bool has_irreducible_loop = igvn->C->has_irreducible_loop();
1402 
1403   while (nstack.size() > 0) {
1404     dead = nstack.pop();
1405     if (!dead_set.test_set(dead->_idx)) {
1406       // If dead has any live uses, those are now still attached. Notify them before we lose them.
1407       igvn->add_users_to_worklist(dead);
1408     }
1409     if (dead->Opcode() == Op_SafePoint) {
1410       dead->as_SafePoint()->disconnect_from_root(igvn);
1411     }
1412     if (dead->outcnt() > 0) {
1413       // Keep dead node on stack until all uses are processed.
1414       nstack.push(dead);
1415       // For all Users of the Dead...    ;-)
1416       for (DUIterator_Last kmin, k = dead->last_outs(kmin); k >= kmin; ) {
1417         Node* use = dead->last_out(k);
1418         igvn->hash_delete(use);       // Yank from hash table prior to mod
1419         if (use->in(0) == dead) {     // Found another dead node
1420           assert (!use->is_Con(), "Control for Con node should be Root node.");
1421           use->set_req(0, top);       // Cut dead edge to prevent processing
1422           nstack.push(use);           // the dead node again.
1423         } else if (!has_irreducible_loop && // Backedge could be alive in irreducible loop
1424                    use->is_Loop() && !use->is_Root() &&       // Don't kill Root (RootNode extends LoopNode)
1425                    use->in(LoopNode::EntryControl) == dead) { // Dead loop if its entry is dead
1426           use->set_req(LoopNode::EntryControl, top);          // Cut dead edge to prevent processing
1427           use->set_req(0, top);       // Cut self edge
1428           nstack.push(use);
1429         } else {                      // Else found a not-dead user
1430           // Dead if all inputs are top or null
1431           bool dead_use = !use->is_Root(); // Keep empty graph alive
1432           for (uint j = 1; j < use->req(); j++) {
1433             Node* in = use->in(j);
1434             if (in == dead) {         // Turn all dead inputs into TOP
1435               use->set_req(j, top);
1436             } else if (in != nullptr && !in->is_top()) {
1437               dead_use = false;
1438             }
1439           }
1440           if (dead_use) {
1441             if (use->is_Region()) {
1442               use->set_req(0, top);   // Cut self edge
1443             }
1444             nstack.push(use);
1445           } else {
1446             igvn->_worklist.push(use);
1447           }
1448         }
1449         // Refresh the iterator, since any number of kills might have happened.
1450         k = dead->last_outs(kmin);
1451       }
1452     } else { // (dead->outcnt() == 0)
1453       // Done with outputs.
1454       igvn->hash_delete(dead);
1455       igvn->_worklist.remove(dead);
1456       igvn->set_type(dead, Type::TOP);
1457       // Kill all inputs to the dead guy
1458       for (uint i=0; i < dead->req(); i++) {
1459         Node *n = dead->in(i);      // Get input to dead guy
1460         if (n != nullptr && !n->is_top()) { // Input is valid?
1461           dead->set_req(i, top);    // Smash input away
1462           if (n->outcnt() == 0) {   // Input also goes dead?
1463             if (!n->is_Con())
1464               nstack.push(n);       // Clear it out as well
1465           } else if (n->outcnt() == 1 &&
1466                      n->has_special_unique_user()) {
1467             igvn->add_users_to_worklist( n );
1468           } else if (n->outcnt() <= 2 && n->is_Store()) {
1469             // Push store's uses on worklist to enable folding optimization for
1470             // store/store and store/load to the same address.
1471             // The restriction (outcnt() <= 2) is the same as in set_req_X()
1472             // and remove_globally_dead_node().
1473             igvn->add_users_to_worklist( n );
1474           } else if (dead->is_data_proj_of_pure_function(n)) {
1475             igvn->_worklist.push(n);
1476           } else {
1477             BarrierSet::barrier_set()->barrier_set_c2()->enqueue_useful_gc_barrier(igvn, n);
1478           }
1479         }
1480       }
1481       igvn->C->remove_useless_node(dead);
1482     } // (dead->outcnt() == 0)
1483   }   // while (nstack.size() > 0) for outputs
1484   return;
1485 }
1486 
1487 //------------------------------remove_dead_region-----------------------------
1488 bool Node::remove_dead_region(PhaseGVN *phase, bool can_reshape) {
1489   Node *n = in(0);
1490   if( !n ) return false;
1491   // Lost control into this guy?  I.e., it became unreachable?
1492   // Aggressively kill all unreachable code.
1493   if (can_reshape && n->is_top()) {
1494     kill_dead_code(this, phase->is_IterGVN());
1495     return false; // Node is dead.
1496   }
1497 
1498   if( n->is_Region() && n->as_Region()->is_copy() ) {
1499     Node *m = n->nonnull_req();
1500     set_req(0, m);
1501     return true;
1502   }
1503   return false;
1504 }
1505 
1506 //------------------------------hash-------------------------------------------
1507 // Hash function over Nodes.
1508 uint Node::hash() const {
1509   uint sum = 0;
1510   for( uint i=0; i<_cnt; i++ )  // Add in all inputs
1511     sum = (sum<<1)-(uintptr_t)in(i);        // Ignore embedded nulls
1512   return (sum>>2) + _cnt + Opcode();
1513 }
1514 
1515 //------------------------------cmp--------------------------------------------
1516 // Compare special parts of simple Nodes
1517 bool Node::cmp( const Node &n ) const {
1518   return true;                  // Must be same
1519 }
1520 
1521 //------------------------------rematerialize-----------------------------------
1522 // Should we clone rather than spill this instruction?
1523 bool Node::rematerialize() const {
1524   if ( is_Mach() )
1525     return this->as_Mach()->rematerialize();
1526   else
1527     return (_flags & Flag_rematerialize) != 0;
1528 }
1529 
1530 //------------------------------needs_anti_dependence_check---------------------
1531 // Nodes which use memory without consuming it, hence need antidependences.
1532 bool Node::needs_anti_dependence_check() const {
1533   if (req() < 2 || (_flags & Flag_needs_anti_dependence_check) == 0) {
1534     return false;
1535   }
1536   return in(1)->bottom_type()->has_memory();
1537 }
1538 
1539 // Get an integer constant from a ConNode (or CastIINode).
1540 // Return a default value if there is no apparent constant here.
1541 const TypeInt* Node::find_int_type() const {
1542   if (this->is_Type()) {
1543     return this->as_Type()->type()->isa_int();
1544   } else if (this->is_Con()) {
1545     assert(is_Mach(), "should be ConNode(TypeNode) or else a MachNode");
1546     return this->bottom_type()->isa_int();
1547   }
1548   return nullptr;
1549 }
1550 
1551 const TypeInteger* Node::find_integer_type(BasicType bt) const {
1552   if (this->is_Type()) {
1553     return this->as_Type()->type()->isa_integer(bt);
1554   } else if (this->is_Con()) {
1555     assert(is_Mach(), "should be ConNode(TypeNode) or else a MachNode");
1556     return this->bottom_type()->isa_integer(bt);
1557   }
1558   return nullptr;
1559 }
1560 
1561 // Get a pointer constant from a ConstNode.
1562 // Returns the constant if it is a pointer ConstNode
1563 intptr_t Node::get_ptr() const {
1564   assert( Opcode() == Op_ConP, "" );
1565   return ((ConPNode*)this)->type()->is_ptr()->get_con();
1566 }
1567 
1568 // Get a narrow oop constant from a ConNNode.
1569 intptr_t Node::get_narrowcon() const {
1570   assert( Opcode() == Op_ConN, "" );
1571   return ((ConNNode*)this)->type()->is_narrowoop()->get_con();
1572 }
1573 
1574 // Get a long constant from a ConNode.
1575 // Return a default value if there is no apparent constant here.
1576 const TypeLong* Node::find_long_type() const {
1577   if (this->is_Type()) {
1578     return this->as_Type()->type()->isa_long();
1579   } else if (this->is_Con()) {
1580     assert(is_Mach(), "should be ConNode(TypeNode) or else a MachNode");
1581     return this->bottom_type()->isa_long();
1582   }
1583   return nullptr;
1584 }
1585 
1586 
1587 /**
1588  * Return a ptr type for nodes which should have it.
1589  */
1590 const TypePtr* Node::get_ptr_type() const {
1591   const TypePtr* tp = this->bottom_type()->make_ptr();
1592 #ifdef ASSERT
1593   if (tp == nullptr) {
1594     this->dump(1);
1595     assert((tp != nullptr), "unexpected node type");
1596   }
1597 #endif
1598   return tp;
1599 }
1600 
1601 // Get a double constant from a ConstNode.
1602 // Returns the constant if it is a double ConstNode
1603 jdouble Node::getd() const {
1604   assert( Opcode() == Op_ConD, "" );
1605   return ((ConDNode*)this)->type()->is_double_constant()->getd();
1606 }
1607 
1608 // Get a float constant from a ConstNode.
1609 // Returns the constant if it is a float ConstNode
1610 jfloat Node::getf() const {
1611   assert( Opcode() == Op_ConF, "" );
1612   return ((ConFNode*)this)->type()->is_float_constant()->getf();
1613 }
1614 
1615 // Get a half float constant from a ConstNode.
1616 // Returns the constant if it is a float ConstNode
1617 jshort Node::geth() const {
1618   assert( Opcode() == Op_ConH, "" );
1619   return ((ConHNode*)this)->type()->is_half_float_constant()->geth();
1620 }
1621 
1622 #ifndef PRODUCT
1623 
1624 // Call this from debugger:
1625 Node* old_root() {
1626   Matcher* matcher = Compile::current()->matcher();
1627   if (matcher != nullptr) {
1628     Node* new_root = Compile::current()->root();
1629     Node* old_root = matcher->find_old_node(new_root);
1630     if (old_root != nullptr) {
1631       return old_root;
1632     }
1633   }
1634   tty->print("old_root: not found.\n");
1635   return nullptr;
1636 }
1637 
1638 // BFS traverse all reachable nodes from start, call callback on them
1639 template <typename Callback>
1640 void visit_nodes(Node* start, Callback callback, bool traverse_output, bool only_ctrl) {
1641   Unique_Mixed_Node_List worklist;
1642   worklist.add(start);
1643   for (uint i = 0; i < worklist.size(); i++) {
1644     Node* n = worklist[i];
1645     callback(n);
1646     for (uint i = 0; i < n->len(); i++) {
1647       if (!only_ctrl || n->is_Region() || (n->Opcode() == Op_Root) || (i == TypeFunc::Control)) {
1648         // If only_ctrl is set: Add regions, the root node, or control inputs only
1649         worklist.add(n->in(i));
1650       }
1651     }
1652     if (traverse_output && !only_ctrl) {
1653       for (uint i = 0; i < n->outcnt(); i++) {
1654         worklist.add(n->raw_out(i));
1655       }
1656     }
1657   }
1658 }
1659 
1660 // BFS traverse from start, return node with idx
1661 static Node* find_node_by_idx(Node* start, uint idx, bool traverse_output, bool only_ctrl) {
1662   ResourceMark rm;
1663   Node* result = nullptr;
1664   auto callback = [&] (Node* n) {
1665     if (n->_idx == idx) {
1666       if (result != nullptr) {
1667         tty->print("find_node_by_idx: " INTPTR_FORMAT " and " INTPTR_FORMAT " both have idx==%d\n",
1668           (uintptr_t)result, (uintptr_t)n, idx);
1669       }
1670       result = n;
1671     }
1672   };
1673   visit_nodes(start, callback, traverse_output, only_ctrl);
1674   return result;
1675 }
1676 
1677 static int node_idx_cmp(const Node** n1, const Node** n2) {
1678   return (*n1)->_idx - (*n2)->_idx;
1679 }
1680 
1681 static void find_nodes_by_name(Node* start, const char* name) {
1682   ResourceMark rm;
1683   GrowableArray<const Node*> ns;
1684   auto callback = [&] (const Node* n) {
1685     if (StringUtils::is_star_match(name, n->Name())) {
1686       ns.push(n);
1687     }
1688   };
1689   visit_nodes(start, callback, true, false);
1690   ns.sort(node_idx_cmp);
1691   for (int i = 0; i < ns.length(); i++) {
1692     ns.at(i)->dump();
1693   }
1694 }
1695 
1696 static void find_nodes_by_dump(Node* start, const char* pattern) {
1697   ResourceMark rm;
1698   GrowableArray<const Node*> ns;
1699   auto callback = [&] (const Node* n) {
1700     stringStream stream;
1701     n->dump("", false, &stream);
1702     if (StringUtils::is_star_match(pattern, stream.base())) {
1703       ns.push(n);
1704     }
1705   };
1706   visit_nodes(start, callback, true, false);
1707   ns.sort(node_idx_cmp);
1708   for (int i = 0; i < ns.length(); i++) {
1709     ns.at(i)->dump();
1710   }
1711 }
1712 
1713 // call from debugger: find node with name pattern in new/current graph
1714 // name can contain "*" in match pattern to match any characters
1715 // the matching is case insensitive
1716 void find_nodes_by_name(const char* name) {
1717   Node* root = Compile::current()->root();
1718   find_nodes_by_name(root, name);
1719 }
1720 
1721 // call from debugger: find node with name pattern in old graph
1722 // name can contain "*" in match pattern to match any characters
1723 // the matching is case insensitive
1724 void find_old_nodes_by_name(const char* name) {
1725   Node* root = old_root();
1726   find_nodes_by_name(root, name);
1727 }
1728 
1729 // call from debugger: find node with dump pattern in new/current graph
1730 // can contain "*" in match pattern to match any characters
1731 // the matching is case insensitive
1732 void find_nodes_by_dump(const char* pattern) {
1733   Node* root = Compile::current()->root();
1734   find_nodes_by_dump(root, pattern);
1735 }
1736 
1737 // call from debugger: find node with name pattern in old graph
1738 // can contain "*" in match pattern to match any characters
1739 // the matching is case insensitive
1740 void find_old_nodes_by_dump(const char* pattern) {
1741   Node* root = old_root();
1742   find_nodes_by_dump(root, pattern);
1743 }
1744 
1745 // Call this from debugger, search in same graph as n:
1746 Node* find_node(Node* n, const int idx) {
1747   return n->find(idx);
1748 }
1749 
1750 // Call this from debugger, search in new nodes:
1751 Node* find_node(const int idx) {
1752   return Compile::current()->root()->find(idx);
1753 }
1754 
1755 // Call this from debugger, search in old nodes:
1756 Node* find_old_node(const int idx) {
1757   Node* root = old_root();
1758   return (root == nullptr) ? nullptr : root->find(idx);
1759 }
1760 
1761 // Call this from debugger, search in same graph as n:
1762 Node* find_ctrl(Node* n, const int idx) {
1763   return n->find_ctrl(idx);
1764 }
1765 
1766 // Call this from debugger, search in new nodes:
1767 Node* find_ctrl(const int idx) {
1768   return Compile::current()->root()->find_ctrl(idx);
1769 }
1770 
1771 // Call this from debugger, search in old nodes:
1772 Node* find_old_ctrl(const int idx) {
1773   Node* root = old_root();
1774   return (root == nullptr) ? nullptr : root->find_ctrl(idx);
1775 }
1776 
1777 //------------------------------find_ctrl--------------------------------------
1778 // Find an ancestor to this node in the control history with given _idx
1779 Node* Node::find_ctrl(int idx) {
1780   return find(idx, true);
1781 }
1782 
1783 //------------------------------find-------------------------------------------
1784 // Tries to find the node with the index |idx| starting from this node. If idx is negative,
1785 // the search also includes forward (out) edges. Returns null if not found.
1786 // If only_ctrl is set, the search will only be done on control nodes. Returns null if
1787 // not found or if the node to be found is not a control node (search will not find it).
1788 Node* Node::find(const int idx, bool only_ctrl) {
1789   ResourceMark rm;
1790   return find_node_by_idx(this, abs(idx), (idx < 0), only_ctrl);
1791 }
1792 
1793 class PrintBFS {
1794 public:
1795   PrintBFS(const Node* start, const int max_distance, const Node* target, const char* options, outputStream* st, const frame* fr)
1796     : _start(start), _max_distance(max_distance), _target(target), _options(options), _output(st), _frame(fr),
1797     _dcc(this), _info_uid(cmpkey, hashkey) {}
1798 
1799   void run();
1800 private:
1801   // pipeline steps
1802   bool configure();
1803   void collect();
1804   void select();
1805   void select_all();
1806   void select_all_paths();
1807   void select_shortest_path();
1808   void sort();
1809   void print();
1810 
1811   // inputs
1812   const Node* _start;
1813   const int _max_distance;
1814   const Node* _target;
1815   const char* _options;
1816   outputStream* _output;
1817   const frame* _frame;
1818 
1819   // options
1820   bool _traverse_inputs = false;
1821   bool _traverse_outputs = false;
1822   struct Filter {
1823     bool _control = false;
1824     bool _memory = false;
1825     bool _data = false;
1826     bool _mixed = false;
1827     bool _other = false;
1828     bool is_empty() const {
1829       return !(_control || _memory || _data || _mixed || _other);
1830     }
1831     void set_all() {
1832       _control = true;
1833       _memory = true;
1834       _data = true;
1835       _mixed = true;
1836       _other = true;
1837     }
1838     // Check if the filter accepts the node. Go by the type categories, but also all CFG nodes
1839     // are considered to have control.
1840     bool accepts(const Node* n) {
1841       const Type* t = n->bottom_type();
1842       return ( _data    &&  t->has_category(Type::Category::Data)                    ) ||
1843              ( _memory  &&  t->has_category(Type::Category::Memory)                  ) ||
1844              ( _mixed   &&  t->has_category(Type::Category::Mixed)                   ) ||
1845              ( _control && (t->has_category(Type::Category::Control) || n->is_CFG()) ) ||
1846              ( _other   &&  t->has_category(Type::Category::Other)                   );
1847     }
1848   };
1849   Filter _filter_visit;
1850   Filter _filter_boundary;
1851   bool _sort_idx = false;
1852   bool _all_paths = false;
1853   bool _use_color = false;
1854   bool _print_blocks = false;
1855   bool _print_old = false;
1856   bool _dump_only = false;
1857   bool _print_igv = false;
1858 
1859   void print_options_help(bool print_examples);
1860   bool parse_options();
1861 
1862 public:
1863   class DumpConfigColored : public Node::DumpConfig {
1864   public:
1865     DumpConfigColored(PrintBFS* bfs) : _bfs(bfs) {};
1866     virtual void pre_dump(outputStream* st, const Node* n);
1867     virtual void post_dump(outputStream* st);
1868   private:
1869     PrintBFS* _bfs;
1870   };
1871 private:
1872   DumpConfigColored _dcc;
1873 
1874   // node info
1875   static Node* old_node(const Node* n); // mach node -> prior IR node
1876   void print_node_idx(const Node* n);
1877   void print_block_id(const Block* b);
1878   void print_node_block(const Node* n); // _pre_order, head idx, _idom, _dom_depth
1879 
1880   // traversal data structures
1881   GrowableArray<const Node*> _worklist; // BFS queue
1882   void maybe_traverse(const Node* src, const Node* dst);
1883 
1884   // node info annotation
1885   class Info {
1886   public:
1887     Info() : Info(nullptr, 0) {};
1888     Info(const Node* node, int distance)
1889       : _node(node), _distance_from_start(distance) {};
1890     const Node* node() const { return _node; };
1891     int distance() const { return _distance_from_start; };
1892     int distance_from_target() const { return _distance_from_target; }
1893     void set_distance_from_target(int d) { _distance_from_target = d; }
1894     GrowableArray<const Node*> edge_bwd; // pointing toward _start
1895     bool is_marked() const { return _mark; } // marked to keep during select
1896     void set_mark() { _mark = true; }
1897   private:
1898     const Node* _node;
1899     int _distance_from_start; // distance from _start
1900     int _distance_from_target = 0; // distance from _target if _all_paths
1901     bool _mark = false;
1902   };
1903   Dict _info_uid;            // Node -> uid
1904   GrowableArray<Info> _info; // uid  -> info
1905 
1906   Info* find_info(const Node* n) {
1907     size_t uid = (size_t)_info_uid[n];
1908     if (uid == 0) {
1909       return nullptr;
1910     }
1911     return &_info.at((int)uid);
1912   }
1913 
1914   void make_info(const Node* node, const int distance) {
1915     assert(find_info(node) == nullptr, "node does not yet have info");
1916     size_t uid = _info.length() + 1;
1917     _info_uid.Insert((void*)node, (void*)uid);
1918     _info.at_put_grow((int)uid, Info(node, distance));
1919     assert(find_info(node)->node() == node, "stored correct node");
1920   };
1921 
1922   // filled by sort, printed by print
1923   GrowableArray<const Node*> _print_list;
1924 
1925   // print header + node table
1926   void print_header() const;
1927   void print_node(const Node* n);
1928 };
1929 
1930 void PrintBFS::run() {
1931   if (!configure()) {
1932     return;
1933   }
1934   collect();
1935   select();
1936   sort();
1937   print();
1938 }
1939 
1940 // set up configuration for BFS and print
1941 bool PrintBFS::configure() {
1942   if (_max_distance < 0) {
1943     _output->print_cr("dump_bfs: max_distance must be non-negative!");
1944     return false;
1945   }
1946   return parse_options();
1947 }
1948 
1949 // BFS traverse according to configuration, fill worklist and info
1950 void PrintBFS::collect() {
1951   maybe_traverse(_start, _start);
1952   int pos = 0;
1953   while (pos < _worklist.length()) {
1954     const Node* n = _worklist.at(pos++); // next node to traverse
1955     Info* info = find_info(n);
1956     if (!_filter_visit.accepts(n) && n != _start) {
1957       continue; // we hit boundary, do not traverse further
1958     }
1959     if (n != _start && n->is_Root()) {
1960       continue; // traversing through root node would lead to unrelated nodes
1961     }
1962     if (_traverse_inputs && _max_distance > info->distance()) {
1963       for (uint i = 0; i < n->req(); i++) {
1964         maybe_traverse(n, n->in(i));
1965       }
1966     }
1967     if (_traverse_outputs && _max_distance > info->distance()) {
1968       for (uint i = 0; i < n->outcnt(); i++) {
1969         maybe_traverse(n, n->raw_out(i));
1970       }
1971     }
1972   }
1973 }
1974 
1975 // go through work list, mark those that we want to print
1976 void PrintBFS::select() {
1977   if (_target == nullptr ) {
1978     select_all();
1979   } else {
1980     if (find_info(_target) == nullptr) {
1981       _output->print_cr("Could not find target in BFS.");
1982       return;
1983     }
1984     if (_all_paths) {
1985       select_all_paths();
1986     } else {
1987       select_shortest_path();
1988     }
1989   }
1990 }
1991 
1992 // take all nodes from BFS
1993 void PrintBFS::select_all() {
1994   for (int i = 0; i < _worklist.length(); i++) {
1995     const Node* n = _worklist.at(i);
1996     Info* info = find_info(n);
1997     info->set_mark();
1998   }
1999 }
2000 
2001 // traverse backward from target, along edges found in BFS
2002 void PrintBFS::select_all_paths() {
2003   int pos = 0;
2004   GrowableArray<const Node*> backtrace;
2005   // start from target
2006   backtrace.push(_target);
2007   find_info(_target)->set_mark();
2008   // traverse backward
2009   while (pos < backtrace.length()) {
2010     const Node* n = backtrace.at(pos++);
2011     Info* info = find_info(n);
2012     for (int i = 0; i < info->edge_bwd.length(); i++) {
2013       // all backward edges
2014       const Node* back = info->edge_bwd.at(i);
2015       Info* back_info = find_info(back);
2016       if (!back_info->is_marked()) {
2017         // not yet found this on way back.
2018         back_info->set_distance_from_target(info->distance_from_target() + 1);
2019         if (back_info->distance_from_target() + back_info->distance() <= _max_distance) {
2020           // total distance is small enough
2021           back_info->set_mark();
2022           backtrace.push(back);
2023         }
2024       }
2025     }
2026   }
2027 }
2028 
2029 void PrintBFS::select_shortest_path() {
2030   const Node* current = _target;
2031   while (true) {
2032     Info* info = find_info(current);
2033     info->set_mark();
2034     if (current == _start) {
2035       break;
2036     }
2037     // first edge -> leads us one step closer to _start
2038     current = info->edge_bwd.at(0);
2039   }
2040 }
2041 
2042 // go through worklist in desired order, put the marked ones in print list
2043 void PrintBFS::sort() {
2044   if (_traverse_inputs && !_traverse_outputs) {
2045     // reverse order
2046     for (int i = _worklist.length() - 1; i >= 0; i--) {
2047       const Node* n = _worklist.at(i);
2048       Info* info = find_info(n);
2049       if (info->is_marked()) {
2050         _print_list.push(n);
2051       }
2052     }
2053   } else {
2054     // same order as worklist
2055     for (int i = 0; i < _worklist.length(); i++) {
2056       const Node* n = _worklist.at(i);
2057       Info* info = find_info(n);
2058       if (info->is_marked()) {
2059         _print_list.push(n);
2060       }
2061     }
2062   }
2063   if (_sort_idx) {
2064     _print_list.sort(node_idx_cmp);
2065   }
2066 }
2067 
2068 // go through printlist and print
2069 void PrintBFS::print() {
2070   if (_print_list.length() > 0 ) {
2071     print_header();
2072     for (int i = 0; i < _print_list.length(); i++) {
2073       const Node* n = _print_list.at(i);
2074       print_node(n);
2075     }
2076     if (_print_igv) {
2077       Compile* C = Compile::current();
2078       C->init_igv();
2079       C->igv_print_graph_to_network(nullptr, _print_list, _frame);
2080     }
2081   } else {
2082     _output->print_cr("No nodes to print.");
2083   }
2084 }
2085 
2086 void PrintBFS::print_options_help(bool print_examples) {
2087   _output->print_cr("Usage: node->dump_bfs(int max_distance, Node* target, char* options)");
2088   _output->print_cr("");
2089   _output->print_cr("Use cases:");
2090   _output->print_cr("  BFS traversal: no target required");
2091   _output->print_cr("  shortest path: set target");
2092   _output->print_cr("  all paths: set target and put 'A' in options");
2093   _output->print_cr("  detect loop: subcase of all paths, have start==target");
2094   _output->print_cr("");
2095   _output->print_cr("Arguments:");
2096   _output->print_cr("  this/start: staring point of BFS");
2097   _output->print_cr("  target:");
2098   _output->print_cr("    if null: simple BFS");
2099   _output->print_cr("    else: shortest path or all paths between this/start and target");
2100   _output->print_cr("  options:");
2101   _output->print_cr("    if null: same as \"cdmox@B\"");
2102   _output->print_cr("    else: use combination of following characters");
2103   _output->print_cr("      h: display this help info");
2104   _output->print_cr("      H: display this help info, with examples");
2105   _output->print_cr("      +: traverse in-edges (on if neither + nor -)");
2106   _output->print_cr("      -: traverse out-edges");
2107   _output->print_cr("      c: visit control nodes");
2108   _output->print_cr("      d: visit data nodes");
2109   _output->print_cr("      m: visit memory nodes");
2110   _output->print_cr("      o: visit other nodes");
2111   _output->print_cr("      x: visit mixed nodes");
2112   _output->print_cr("      C: boundary control nodes");
2113   _output->print_cr("      D: boundary data nodes");
2114   _output->print_cr("      M: boundary memory nodes");
2115   _output->print_cr("      O: boundary other nodes");
2116   _output->print_cr("      X: boundary mixed nodes");
2117   _output->print_cr("      #: display node category in color (not supported in all terminals)");
2118   _output->print_cr("      S: sort displayed nodes by node idx");
2119   _output->print_cr("      A: all paths (not just shortest path to target)");
2120   _output->print_cr("      @: print old nodes - before matching (if available)");
2121   _output->print_cr("      B: print scheduling blocks (if available)");
2122   _output->print_cr("      $: dump only, no header, no other columns");
2123   _output->print_cr("      !: show nodes on IGV (sent over network stream)");
2124   _output->print_cr("        (use preferably with dump_bfs(int, Node*, char*, void*, void*, void*)");
2125   _output->print_cr("         to produce a C2 stack trace along with the graph dump, see examples below)");
2126   _output->print_cr("");
2127   _output->print_cr("recursively follow edges to nodes with permitted visit types,");
2128   _output->print_cr("on the boundary additionally display nodes allowed in boundary types");
2129   _output->print_cr("Note: the categories can be overlapping. For example a mixed node");
2130   _output->print_cr("      can contain control and memory output. Some from the other");
2131   _output->print_cr("      category are also control (Halt, Return, etc).");
2132   _output->print_cr("");
2133   _output->print_cr("output columns:");
2134   _output->print_cr("  dist:  BFS distance to this/start");
2135   _output->print_cr("  apd:   all paths distance (d_outputart + d_target)");
2136   _output->print_cr("  block: block identifier, based on _pre_order");
2137   _output->print_cr("  head:  first node in block");
2138   _output->print_cr("  idom:  head node of idom block");
2139   _output->print_cr("  depth: depth of block (_dom_depth)");
2140   _output->print_cr("  old:   old IR node - before matching");
2141   _output->print_cr("  dump:  node->dump()");
2142   _output->print_cr("");
2143   _output->print_cr("Note: if none of the \"cmdxo\" characters are in the options string");
2144   _output->print_cr("      then we set all of them.");
2145   _output->print_cr("      This allows for short strings like \"#\" for colored input traversal");
2146   _output->print_cr("      or \"-#\" for colored output traversal.");
2147   if (print_examples) {
2148     _output->print_cr("");
2149     _output->print_cr("Examples:");
2150     _output->print_cr("  if->dump_bfs(10, 0, \"+cxo\")");
2151     _output->print_cr("    starting at some if node, traverse inputs recursively");
2152     _output->print_cr("    only along control (mixed and other can also be control)");
2153     _output->print_cr("  phi->dump_bfs(5, 0, \"-dxo\")");
2154     _output->print_cr("    starting at phi node, traverse outputs recursively");
2155     _output->print_cr("    only along data (mixed and other can also have data flow)");
2156     _output->print_cr("  find_node(385)->dump_bfs(3, 0, \"cdmox+#@B\")");
2157     _output->print_cr("    find inputs of node 385, up to 3 nodes up (+)");
2158     _output->print_cr("    traverse all nodes (cdmox), use colors (#)");
2159     _output->print_cr("    display old nodes and blocks, if they exist");
2160     _output->print_cr("    useful call to start with");
2161     _output->print_cr("  find_node(102)->dump_bfs(10, 0, \"dCDMOX-\")");
2162     _output->print_cr("    find non-data dependencies of a data node");
2163     _output->print_cr("    follow data node outputs until we find another category");
2164     _output->print_cr("    node as the boundary");
2165     _output->print_cr("  x->dump_bfs(10, y, 0)");
2166     _output->print_cr("    find shortest path from x to y, along any edge or node");
2167     _output->print_cr("    will not find a path if it is longer than 10");
2168     _output->print_cr("    useful to find how x and y are related");
2169     _output->print_cr("  find_node(741)->dump_bfs(20, find_node(746), \"c+\")");
2170     _output->print_cr("    find shortest control path between two nodes");
2171     _output->print_cr("  find_node(741)->dump_bfs(8, find_node(746), \"cdmox+A\")");
2172     _output->print_cr("    find all paths (A) between two nodes of length at most 8");
2173     _output->print_cr("  find_node(741)->dump_bfs(7, find_node(741), \"c+A\")");
2174     _output->print_cr("    find all control loops for this node");
2175     _output->print_cr("  find_node(741)->dump_bfs(7, find_node(741), \"c+A!\", $sp, $fp, $pc)");
2176     _output->print_cr("    same as above, but printing the resulting subgraph");
2177     _output->print_cr("    along with a C2 stack trace on IGV");
2178   }
2179 }
2180 
2181 bool PrintBFS::parse_options() {
2182   if (_options == nullptr) {
2183     _options = "cdmox@B"; // default options
2184   }
2185   size_t len = strlen(_options);
2186   for (size_t i = 0; i < len; i++) {
2187     switch (_options[i]) {
2188       case '+':
2189         _traverse_inputs = true;
2190         break;
2191       case '-':
2192         _traverse_outputs = true;
2193         break;
2194       case 'c':
2195         _filter_visit._control = true;
2196         break;
2197       case 'm':
2198         _filter_visit._memory = true;
2199         break;
2200       case 'd':
2201         _filter_visit._data = true;
2202         break;
2203       case 'x':
2204         _filter_visit._mixed = true;
2205         break;
2206       case 'o':
2207         _filter_visit._other = true;
2208         break;
2209       case 'C':
2210         _filter_boundary._control = true;
2211         break;
2212       case 'M':
2213         _filter_boundary._memory = true;
2214         break;
2215       case 'D':
2216         _filter_boundary._data = true;
2217         break;
2218       case 'X':
2219         _filter_boundary._mixed = true;
2220         break;
2221       case 'O':
2222         _filter_boundary._other = true;
2223         break;
2224       case 'S':
2225         _sort_idx = true;
2226         break;
2227       case 'A':
2228         _all_paths = true;
2229         break;
2230       case '#':
2231         _use_color = true;
2232         break;
2233       case 'B':
2234         _print_blocks = true;
2235         break;
2236       case '@':
2237         _print_old = true;
2238         break;
2239       case '$':
2240         _dump_only = true;
2241         break;
2242       case '!':
2243         _print_igv = true;
2244         break;
2245       case 'h':
2246         print_options_help(false);
2247         return false;
2248        case 'H':
2249         print_options_help(true);
2250         return false;
2251       default:
2252         _output->print_cr("dump_bfs: Unrecognized option \'%c\'", _options[i]);
2253         _output->print_cr("for help, run: find_node(0)->dump_bfs(0,0,\"H\")");
2254         return false;
2255     }
2256   }
2257   if (!_traverse_inputs && !_traverse_outputs) {
2258     _traverse_inputs = true;
2259   }
2260   if (_filter_visit.is_empty()) {
2261     _filter_visit.set_all();
2262   }
2263   Compile* C = Compile::current();
2264   _print_old &= (C->matcher() != nullptr); // only show old if there are new
2265   _print_blocks &= (C->cfg() != nullptr); // only show blocks if available
2266   return true;
2267 }
2268 
2269 void PrintBFS::DumpConfigColored::pre_dump(outputStream* st, const Node* n) {
2270   if (!_bfs->_use_color) {
2271     return;
2272   }
2273   Info* info = _bfs->find_info(n);
2274   if (info == nullptr || !info->is_marked()) {
2275     return;
2276   }
2277 
2278   const Type* t = n->bottom_type();
2279   switch (t->category()) {
2280     case Type::Category::Data:
2281       st->print("\u001b[34m");
2282       break;
2283     case Type::Category::Memory:
2284       st->print("\u001b[32m");
2285       break;
2286     case Type::Category::Mixed:
2287       st->print("\u001b[35m");
2288       break;
2289     case Type::Category::Control:
2290       st->print("\u001b[31m");
2291       break;
2292     case Type::Category::Other:
2293       st->print("\u001b[33m");
2294       break;
2295     case Type::Category::Undef:
2296       n->dump();
2297       assert(false, "category undef ??");
2298       break;
2299     default:
2300       n->dump();
2301       assert(false, "not covered");
2302       break;
2303   }
2304 }
2305 
2306 void PrintBFS::DumpConfigColored::post_dump(outputStream* st) {
2307   if (!_bfs->_use_color) {
2308     return;
2309   }
2310   st->print("\u001b[0m"); // white
2311 }
2312 
2313 Node* PrintBFS::old_node(const Node* n) {
2314   Compile* C = Compile::current();
2315   if (C->matcher() == nullptr || !C->node_arena()->contains(n)) {
2316     return (Node*)nullptr;
2317   } else {
2318     return C->matcher()->find_old_node(n);
2319   }
2320 }
2321 
2322 void PrintBFS::print_node_idx(const Node* n) {
2323   Compile* C = Compile::current();
2324   char buf[30];
2325   if (n == nullptr) {
2326     os::snprintf_checked(buf, sizeof(buf), "_");           // null
2327   } else if (C->node_arena()->contains(n)) {
2328     os::snprintf_checked(buf, sizeof(buf), "%d", n->_idx);  // new node
2329   } else {
2330     os::snprintf_checked(buf, sizeof(buf), "o%d", n->_idx); // old node
2331   }
2332   _output->print("%6s", buf);
2333 }
2334 
2335 void PrintBFS::print_block_id(const Block* b) {
2336   Compile* C = Compile::current();
2337   char buf[30];
2338   os::snprintf_checked(buf, sizeof(buf), "B%d", b->_pre_order);
2339   _output->print("%7s", buf);
2340 }
2341 
2342 void PrintBFS::print_node_block(const Node* n) {
2343   Compile* C = Compile::current();
2344   Block* b = C->node_arena()->contains(n)
2345              ? C->cfg()->get_block_for_node(n)
2346              : nullptr; // guard against old nodes
2347   if (b == nullptr) {
2348     _output->print("      _"); // Block
2349     _output->print("     _");  // head
2350     _output->print("     _");  // idom
2351     _output->print("      _"); // depth
2352   } else {
2353     print_block_id(b);
2354     print_node_idx(b->head());
2355     if (b->_idom) {
2356       print_node_idx(b->_idom->head());
2357     } else {
2358       _output->print("     _"); // idom
2359     }
2360     _output->print("%6d ", b->_dom_depth);
2361   }
2362 }
2363 
2364 // filter, and add to worklist, add info, note traversal edges
2365 void PrintBFS::maybe_traverse(const Node* src, const Node* dst) {
2366   if (dst != nullptr &&
2367      (_filter_visit.accepts(dst) ||
2368       _filter_boundary.accepts(dst) ||
2369       dst == _start)) { // correct category or start?
2370     if (find_info(dst) == nullptr) {
2371       // never visited - set up info
2372       _worklist.push(dst);
2373       int d = 0;
2374       if (dst != _start) {
2375         d = find_info(src)->distance() + 1;
2376       }
2377       make_info(dst, d);
2378     }
2379     if (src != dst) {
2380       // traversal edges useful during select
2381       find_info(dst)->edge_bwd.push(src);
2382     }
2383   }
2384 }
2385 
2386 void PrintBFS::print_header() const {
2387   if (_dump_only) {
2388     return; // no header in dump only mode
2389   }
2390   _output->print("dist");                         // distance
2391   if (_all_paths) {
2392     _output->print(" apd");                       // all paths distance
2393   }
2394   if (_print_blocks) {
2395     _output->print(" [block  head  idom depth]"); // block
2396   }
2397   if (_print_old) {
2398     _output->print("   old");                     // old node
2399   }
2400   _output->print(" dump\n");                      // node dump
2401   _output->print_cr("---------------------------------------------");
2402 }
2403 
2404 void PrintBFS::print_node(const Node* n) {
2405   if (_dump_only) {
2406     n->dump("\n", false, _output, &_dcc);
2407     return;
2408   }
2409   _output->print("%4d", find_info(n)->distance());// distance
2410   if (_all_paths) {
2411     Info* info = find_info(n);
2412     int apd = info->distance() + info->distance_from_target();
2413     _output->print("%4d", apd);                   // all paths distance
2414   }
2415   if (_print_blocks) {
2416     print_node_block(n);                          // block
2417   }
2418   if (_print_old) {
2419     print_node_idx(old_node(n));                  // old node
2420   }
2421   _output->print(" ");
2422   n->dump("\n", false, _output, &_dcc);           // node dump
2423 }
2424 
2425 //------------------------------dump_bfs--------------------------------------
2426 // Call this from debugger
2427 // Useful for BFS traversal, shortest path, all path, loop detection, etc
2428 // Designed to be more readable, and provide additional info
2429 // To find all options, run:
2430 //   find_node(0)->dump_bfs(0,0,"H")
2431 void Node::dump_bfs(const int max_distance, Node* target, const char* options) const {
2432   dump_bfs(max_distance, target, options, tty);
2433 }
2434 
2435 // Used to dump to stream.
2436 void Node::dump_bfs(const int max_distance, Node* target, const char* options, outputStream* st, const frame* fr) const {
2437   PrintBFS bfs(this, max_distance, target, options, st, fr);
2438   bfs.run();
2439 }
2440 
2441 // Call this from debugger, with default arguments
2442 void Node::dump_bfs(const int max_distance) const {
2443   dump_bfs(max_distance, nullptr, nullptr);
2444 }
2445 
2446 // Call this from debugger, with stack handling register arguments for IGV dumps.
2447 // Example: p find_node(741)->dump_bfs(7, find_node(741), "c+A!", $sp, $fp, $pc).
2448 void Node::dump_bfs(const int max_distance, Node* target, const char* options, void* sp, void* fp, void* pc) const {
2449   frame fr(sp, fp, pc);
2450   dump_bfs(max_distance, target, options, tty, &fr);
2451 }
2452 
2453 // -----------------------------dump_idx---------------------------------------
2454 void Node::dump_idx(bool align, outputStream* st, DumpConfig* dc) const {
2455   if (dc != nullptr) {
2456     dc->pre_dump(st, this);
2457   }
2458   Compile* C = Compile::current();
2459   bool is_new = C->node_arena()->contains(this);
2460   if (align) { // print prefix empty spaces$
2461     // +1 for leading digit, +1 for "o"
2462     uint max_width = (C->unique() == 0 ? 0 : static_cast<uint>(log10(static_cast<double>(C->unique())))) + 2;
2463     // +1 for leading digit, maybe +1 for "o"
2464     uint width = (_idx == 0 ? 0 : static_cast<uint>(log10(static_cast<double>(_idx)))) + 1 + (is_new ? 0 : 1);
2465     while (max_width > width) {
2466       st->print(" ");
2467       width++;
2468     }
2469   }
2470   if (!is_new) {
2471     st->print("o");
2472   }
2473   st->print("%d", _idx);
2474   if (dc != nullptr) {
2475     dc->post_dump(st);
2476   }
2477 }
2478 
2479 // -----------------------------dump_name--------------------------------------
2480 void Node::dump_name(outputStream* st, DumpConfig* dc) const {
2481   if (dc != nullptr) {
2482     dc->pre_dump(st, this);
2483   }
2484   st->print("%s", Name());
2485   if (dc != nullptr) {
2486     dc->post_dump(st);
2487   }
2488 }
2489 
2490 // -----------------------------Name-------------------------------------------
2491 extern const char *NodeClassNames[];
2492 const char *Node::Name() const { return NodeClassNames[Opcode()]; }
2493 
2494 static bool is_disconnected(const Node* n) {
2495   for (uint i = 0; i < n->req(); i++) {
2496     if (n->in(i) != nullptr)  return false;
2497   }
2498   return true;
2499 }
2500 
2501 #ifdef ASSERT
2502 void Node::dump_orig(outputStream *st, bool print_key) const {
2503   Compile* C = Compile::current();
2504   Node* orig = _debug_orig;
2505   if (not_a_node(orig)) orig = nullptr;
2506   if (orig != nullptr && !C->node_arena()->contains(orig)) orig = nullptr;
2507   if (orig == nullptr) return;
2508   if (print_key) {
2509     st->print(" !orig=");
2510   }
2511   Node* fast = orig->debug_orig(); // tortoise & hare algorithm to detect loops
2512   if (not_a_node(fast)) fast = nullptr;
2513   while (orig != nullptr) {
2514     bool discon = is_disconnected(orig);  // if discon, print [123] else 123
2515     if (discon) st->print("[");
2516     if (!Compile::current()->node_arena()->contains(orig))
2517       st->print("o");
2518     st->print("%d", orig->_idx);
2519     if (discon) st->print("]");
2520     orig = orig->debug_orig();
2521     if (not_a_node(orig)) orig = nullptr;
2522     if (orig != nullptr && !C->node_arena()->contains(orig)) orig = nullptr;
2523     if (orig != nullptr) st->print(",");
2524     if (fast != nullptr) {
2525       // Step fast twice for each single step of orig:
2526       fast = fast->debug_orig();
2527       if (not_a_node(fast)) fast = nullptr;
2528       if (fast != nullptr && fast != orig) {
2529         fast = fast->debug_orig();
2530         if (not_a_node(fast)) fast = nullptr;
2531       }
2532       if (fast == orig) {
2533         st->print("...");
2534         break;
2535       }
2536     }
2537   }
2538 }
2539 
2540 void Node::set_debug_orig(Node* orig) {
2541   _debug_orig = orig;
2542   if (BreakAtNode == 0)  return;
2543   if (not_a_node(orig))  orig = nullptr;
2544   int trip = 10;
2545   while (orig != nullptr) {
2546     if (orig->debug_idx() == BreakAtNode || (uintx)orig->_idx == BreakAtNode) {
2547       tty->print_cr("BreakAtNode: _idx=%d _debug_idx=" UINT64_FORMAT " orig._idx=%d orig._debug_idx=" UINT64_FORMAT,
2548                     this->_idx, this->debug_idx(), orig->_idx, orig->debug_idx());
2549       BREAKPOINT;
2550     }
2551     orig = orig->debug_orig();
2552     if (not_a_node(orig))  orig = nullptr;
2553     if (trip-- <= 0)  break;
2554   }
2555 }
2556 #endif //ASSERT
2557 
2558 //------------------------------dump------------------------------------------
2559 // Dump a Node
2560 void Node::dump(const char* suffix, bool mark, outputStream* st, DumpConfig* dc) const {
2561   Compile* C = Compile::current();
2562   bool is_new = C->node_arena()->contains(this);
2563   C->_in_dump_cnt++;
2564 
2565   // idx mark name ===
2566   dump_idx(true, st, dc);
2567   st->print(mark ? " >" : "  ");
2568   dump_name(st, dc);
2569   st->print("  === ");
2570 
2571   // Dump the required and precedence inputs
2572   dump_req(st, dc);
2573   dump_prec(st, dc);
2574   // Dump the outputs
2575   dump_out(st, dc);
2576 
2577   if (is_disconnected(this)) {
2578 #ifdef ASSERT
2579     st->print("  [" UINT64_FORMAT "]", debug_idx());
2580     dump_orig(st);
2581 #endif
2582     st->cr();
2583     C->_in_dump_cnt--;
2584     return;                     // don't process dead nodes
2585   }
2586 
2587   if (C->clone_map().value(_idx) != 0) {
2588     C->clone_map().dump(_idx, st);
2589   }
2590   // Dump node-specific info
2591   dump_spec(st);
2592 #ifdef ASSERT
2593   // Dump the non-reset _debug_idx
2594   if (Verbose && WizardMode) {
2595     st->print("  [" UINT64_FORMAT "]", debug_idx());
2596   }
2597 #endif
2598 
2599   const Type *t = bottom_type();
2600 
2601   if (t != nullptr && (t->isa_instptr() || t->isa_instklassptr())) {
2602     const TypeInstPtr  *toop = t->isa_instptr();
2603     const TypeInstKlassPtr *tkls = t->isa_instklassptr();
2604     if (toop) {
2605       st->print("  Oop:");
2606     } else if (tkls) {
2607       st->print("  Klass:");
2608     }
2609     t->dump_on(st);
2610   } else if (t == Type::MEMORY) {
2611     st->print("  Memory:");
2612     MemNode::dump_adr_type(adr_type(), st);
2613   } else if (Verbose || WizardMode) {
2614     st->print("  Type:");
2615     if (t) {
2616       t->dump_on(st);
2617     } else {
2618       st->print("no type");
2619     }
2620   } else if (t->isa_vect() && this->is_MachSpillCopy()) {
2621     // Dump MachSpillcopy vector type.
2622     t->dump_on(st);
2623   }
2624   if (is_new) {
2625     DEBUG_ONLY(dump_orig(st));
2626     Node_Notes* nn = C->node_notes_at(_idx);
2627     if (nn != nullptr && !nn->is_clear()) {
2628       if (nn->jvms() != nullptr) {
2629         st->print(" !jvms:");
2630         nn->jvms()->dump_spec(st);
2631       }
2632     }
2633   }
2634   if (suffix) st->print("%s", suffix);
2635   C->_in_dump_cnt--;
2636 }
2637 
2638 // call from debugger: dump node to tty with newline
2639 void Node::dump() const {
2640   dump("\n");
2641 }
2642 
2643 //------------------------------dump_req--------------------------------------
2644 void Node::dump_req(outputStream* st, DumpConfig* dc) const {
2645   // Dump the required input edges
2646   for (uint i = 0; i < req(); i++) {    // For all required inputs
2647     Node* d = in(i);
2648     if (d == nullptr) {
2649       st->print("_ ");
2650     } else if (not_a_node(d)) {
2651       st->print("not_a_node ");  // uninitialized, sentinel, garbage, etc.
2652     } else {
2653       d->dump_idx(false, st, dc);
2654       st->print(" ");
2655     }
2656   }
2657 }
2658 
2659 
2660 //------------------------------dump_prec-------------------------------------
2661 void Node::dump_prec(outputStream* st, DumpConfig* dc) const {
2662   // Dump the precedence edges
2663   int any_prec = 0;
2664   for (uint i = req(); i < len(); i++) {       // For all precedence inputs
2665     Node* p = in(i);
2666     if (p != nullptr) {
2667       if (!any_prec++) st->print(" |");
2668       if (not_a_node(p)) { st->print("not_a_node "); continue; }
2669       p->dump_idx(false, st, dc);
2670       st->print(" ");
2671     }
2672   }
2673 }
2674 
2675 //------------------------------dump_out--------------------------------------
2676 void Node::dump_out(outputStream* st, DumpConfig* dc) const {
2677   // Delimit the output edges
2678   st->print(" [[ ");
2679   // Dump the output edges
2680   for (uint i = 0; i < _outcnt; i++) {    // For all outputs
2681     Node* u = _out[i];
2682     if (u == nullptr) {
2683       st->print("_ ");
2684     } else if (not_a_node(u)) {
2685       st->print("not_a_node ");
2686     } else {
2687       u->dump_idx(false, st, dc);
2688       st->print(" ");
2689     }
2690   }
2691   st->print("]] ");
2692 }
2693 
2694 //------------------------------dump-------------------------------------------
2695 // call from debugger: dump Node's inputs (or outputs if d negative)
2696 void Node::dump(int d) const {
2697   dump_bfs(abs(d), nullptr, (d > 0) ? "+$" : "-$");
2698 }
2699 
2700 //------------------------------dump_ctrl--------------------------------------
2701 // call from debugger: dump Node's control inputs (or outputs if d negative)
2702 void Node::dump_ctrl(int d) const {
2703   dump_bfs(abs(d), nullptr, (d > 0) ? "+$c" : "-$c");
2704 }
2705 
2706 //-----------------------------dump_compact------------------------------------
2707 void Node::dump_comp() const {
2708   this->dump_comp("\n");
2709 }
2710 
2711 //-----------------------------dump_compact------------------------------------
2712 // Dump a Node in compact representation, i.e., just print its name and index.
2713 // Nodes can specify additional specifics to print in compact representation by
2714 // implementing dump_compact_spec.
2715 void Node::dump_comp(const char* suffix, outputStream *st) const {
2716   Compile* C = Compile::current();
2717   C->_in_dump_cnt++;
2718   st->print("%s(%d)", Name(), _idx);
2719   this->dump_compact_spec(st);
2720   if (suffix) {
2721     st->print("%s", suffix);
2722   }
2723   C->_in_dump_cnt--;
2724 }
2725 
2726 // VERIFICATION CODE
2727 // Verify all nodes if verify_depth is negative
2728 void Node::verify(int verify_depth, VectorSet& visited, Node_List& worklist) {
2729   assert(verify_depth != 0, "depth should not be 0");
2730   Compile* C = Compile::current();
2731   uint last_index_on_current_depth = worklist.size() - 1;
2732   verify_depth--; // Visiting the first node on depth 1
2733   // Only add nodes to worklist if verify_depth is negative (visit all nodes) or greater than 0
2734   bool add_to_worklist = verify_depth != 0;
2735 
2736   for (uint list_index = 0; list_index < worklist.size(); list_index++) {
2737     Node* n = worklist[list_index];
2738 
2739     if (n->is_Con() && n->bottom_type() == Type::TOP) {
2740       if (C->cached_top_node() == nullptr) {
2741         C->set_cached_top_node((Node*)n);
2742       }
2743       assert(C->cached_top_node() == n, "TOP node must be unique");
2744     }
2745 
2746     uint in_len = n->len();
2747     for (uint i = 0; i < in_len; i++) {
2748       Node* x = n->_in[i];
2749       if (!x || x->is_top()) {
2750         continue;
2751       }
2752 
2753       // Verify my input has a def-use edge to me
2754       // Count use-def edges from n to x
2755       int cnt = 1;
2756       for (uint j = 0; j < i; j++) {
2757         if (n->_in[j] == x) {
2758           cnt++;
2759           break;
2760         }
2761       }
2762       if (cnt == 2) {
2763         // x is already checked as n's previous input, skip its duplicated def-use count checking
2764         continue;
2765       }
2766       for (uint j = i + 1; j < in_len; j++) {
2767         if (n->_in[j] == x) {
2768           cnt++;
2769         }
2770       }
2771 
2772       // Count def-use edges from x to n
2773       uint max = x->_outcnt;
2774       for (uint k = 0; k < max; k++) {
2775         if (x->_out[k] == n) {
2776           cnt--;
2777         }
2778       }
2779       assert(cnt == 0, "mismatched def-use edge counts");
2780 
2781       if (add_to_worklist && !visited.test_set(x->_idx)) {
2782         worklist.push(x);
2783       }
2784     }
2785 
2786     if (verify_depth > 0 && list_index == last_index_on_current_depth) {
2787       // All nodes on this depth were processed and its inputs are on the worklist. Decrement verify_depth and
2788       // store the current last list index which is the last node in the list with the new depth. All nodes
2789       // added afterwards will have a new depth again. Stop adding new nodes if depth limit is reached (=0).
2790       verify_depth--;
2791       if (verify_depth == 0) {
2792         add_to_worklist = false;
2793       }
2794       last_index_on_current_depth = worklist.size() - 1;
2795     }
2796   }
2797 }
2798 #endif // not PRODUCT
2799 
2800 //------------------------------Registers--------------------------------------
2801 // Do we Match on this edge index or not?  Generally false for Control
2802 // and true for everything else.  Weird for calls & returns.
2803 uint Node::match_edge(uint idx) const {
2804   return idx;                   // True for other than index 0 (control)
2805 }
2806 
2807 // Register classes are defined for specific machines
2808 const RegMask &Node::out_RegMask() const {
2809   ShouldNotCallThis();
2810   return RegMask::EMPTY;
2811 }
2812 
2813 const RegMask &Node::in_RegMask(uint) const {
2814   ShouldNotCallThis();
2815   return RegMask::EMPTY;
2816 }
2817 
2818 void Node_Array::grow(uint i) {
2819   assert(i >= _max, "Should have been checked before, use maybe_grow?");
2820   assert(_max > 0, "invariant");
2821   uint old = _max;
2822   _max = next_power_of_2(i);
2823   _nodes = (Node**)_a->Arealloc( _nodes, old*sizeof(Node*),_max*sizeof(Node*));
2824   Copy::zero_to_bytes( &_nodes[old], (_max-old)*sizeof(Node*) );
2825 }
2826 
2827 void Node_Array::insert(uint i, Node* n) {
2828   if (_nodes[_max - 1]) {
2829     grow(_max);
2830   }
2831   Copy::conjoint_words_to_higher((HeapWord*)&_nodes[i], (HeapWord*)&_nodes[i + 1], ((_max - i - 1) * sizeof(Node*)));
2832   _nodes[i] = n;
2833 }
2834 
2835 void Node_Array::remove(uint i) {
2836   Copy::conjoint_words_to_lower((HeapWord*)&_nodes[i + 1], (HeapWord*)&_nodes[i], ((_max - i - 1) * sizeof(Node*)));
2837   _nodes[_max - 1] = nullptr;
2838 }
2839 
2840 void Node_Array::dump() const {
2841 #ifndef PRODUCT
2842   for (uint i = 0; i < _max; i++) {
2843     Node* nn = _nodes[i];
2844     if (nn != nullptr) {
2845       tty->print("%5d--> ",i); nn->dump();
2846     }
2847   }
2848 #endif
2849 }
2850 
2851 //--------------------------is_iteratively_computed------------------------------
2852 // Operation appears to be iteratively computed (such as an induction variable)
2853 // It is possible for this operation to return false for a loop-varying
2854 // value, if it appears (by local graph inspection) to be computed by a simple conditional.
2855 bool Node::is_iteratively_computed() {
2856   if (ideal_reg()) { // does operation have a result register?
2857     for (uint i = 1; i < req(); i++) {
2858       Node* n = in(i);
2859       if (n != nullptr && n->is_Phi()) {
2860         for (uint j = 1; j < n->req(); j++) {
2861           if (n->in(j) == this) {
2862             return true;
2863           }
2864         }
2865       }
2866     }
2867   }
2868   return false;
2869 }
2870 
2871 //--------------------------find_similar------------------------------
2872 // Return a node with opcode "opc" and same inputs as "this" if one can
2873 // be found; Otherwise return null;
2874 Node* Node::find_similar(int opc) {
2875   if (req() >= 2) {
2876     Node* def = in(1);
2877     if (def && def->outcnt() >= 2) {
2878       for (DUIterator_Fast dmax, i = def->fast_outs(dmax); i < dmax; i++) {
2879         Node* use = def->fast_out(i);
2880         if (use != this &&
2881             use->Opcode() == opc &&
2882             use->req() == req()) {
2883           uint j;
2884           for (j = 0; j < use->req(); j++) {
2885             if (use->in(j) != in(j)) {
2886               break;
2887             }
2888           }
2889           if (j == use->req()) {
2890             return use;
2891           }
2892         }
2893       }
2894     }
2895   }
2896   return nullptr;
2897 }
2898 
2899 Node* Node::unique_multiple_edges_out_or_null() const {
2900   Node* use = nullptr;
2901   for (DUIterator_Fast kmax, k = fast_outs(kmax); k < kmax; k++) {
2902     Node* u = fast_out(k);
2903     if (use == nullptr) {
2904       use = u; // first use
2905     } else if (u != use) {
2906       return nullptr; // not unique
2907     } else {
2908       // secondary use
2909     }
2910   }
2911   return use;
2912 }
2913 
2914 //--------------------------unique_ctrl_out_or_null-------------------------
2915 // Return the unique control out if only one. Null if none or more than one.
2916 Node* Node::unique_ctrl_out_or_null() const {
2917   Node* found = nullptr;
2918   for (uint i = 0; i < outcnt(); i++) {
2919     Node* use = raw_out(i);
2920     if (use->is_CFG() && use != this) {
2921       if (found != nullptr) {
2922         return nullptr;
2923       }
2924       found = use;
2925     }
2926   }
2927   return found;
2928 }
2929 
2930 //--------------------------unique_ctrl_out------------------------------
2931 // Return the unique control out. Asserts if none or more than one control out.
2932 Node* Node::unique_ctrl_out() const {
2933   Node* ctrl = unique_ctrl_out_or_null();
2934   assert(ctrl != nullptr, "control out is assumed to be unique");
2935   return ctrl;
2936 }
2937 
2938 void Node::ensure_control_or_add_prec(Node* c) {
2939   if (in(0) == nullptr) {
2940     set_req(0, c);
2941   } else if (in(0) != c) {
2942     add_prec(c);
2943   }
2944 }
2945 
2946 void Node::add_prec_from(Node* n) {
2947   for (uint i = n->req(); i < n->len(); i++) {
2948     Node* prec = n->in(i);
2949     if (prec != nullptr) {
2950       add_prec(prec);
2951     }
2952   }
2953 }
2954 
2955 bool Node::is_dead_loop_safe() const {
2956   if (is_Phi()) {
2957     return true;
2958   }
2959   if (is_Proj() && in(0) == nullptr)  {
2960     return true;
2961   }
2962   if ((_flags & (Flag_is_dead_loop_safe | Flag_is_Con)) != 0) {
2963     if (!is_Proj()) {
2964       return true;
2965     }
2966     if (in(0)->is_Allocate()) {
2967       return false;
2968     }
2969     // MemNode::can_see_stored_value() peeks through the boxing call
2970     if (in(0)->is_CallStaticJava() && in(0)->as_CallStaticJava()->is_boxing_method()) {
2971       return false;
2972     }
2973     return true;
2974   }
2975   return false;
2976 }
2977 
2978 bool Node::is_div_or_mod(BasicType bt) const { return Opcode() == Op_Div(bt) || Opcode() == Op_Mod(bt) ||
2979                                                       Opcode() == Op_UDiv(bt) || Opcode() == Op_UMod(bt); }
2980 
2981 // `maybe_pure_function` is assumed to be the input of `this`. This is a bit redundant,
2982 // but we already have and need maybe_pure_function in all the call sites, so
2983 // it makes it obvious that the `maybe_pure_function` is the same node as in the caller,
2984 // while it takes more thinking to realize that a locally computed in(0) must be equal to
2985 // the local in the caller.
2986 bool Node::is_data_proj_of_pure_function(const Node* maybe_pure_function) const {
2987   return Opcode() == Op_Proj && as_Proj()->_con == TypeFunc::Parms && maybe_pure_function->is_CallLeafPure();
2988 }
2989 
2990 //=============================================================================
2991 //------------------------------yank-------------------------------------------
2992 // Find and remove
2993 void Node_List::yank( Node *n ) {
2994   uint i;
2995   for (i = 0; i < _cnt; i++) {
2996     if (_nodes[i] == n) {
2997       break;
2998     }
2999   }
3000 
3001   if (i < _cnt) {
3002     _nodes[i] = _nodes[--_cnt];
3003   }
3004 }
3005 
3006 //------------------------------dump-------------------------------------------
3007 void Node_List::dump() const {
3008 #ifndef PRODUCT
3009   for (uint i = 0; i < _cnt; i++) {
3010     if (_nodes[i]) {
3011       tty->print("%5d--> ", i);
3012       _nodes[i]->dump();
3013     }
3014   }
3015 #endif
3016 }
3017 
3018 void Node_List::dump_simple() const {
3019 #ifndef PRODUCT
3020   for (uint i = 0; i < _cnt; i++) {
3021     if( _nodes[i] ) {
3022       tty->print(" %d", _nodes[i]->_idx);
3023     } else {
3024       tty->print(" null");
3025     }
3026   }
3027 #endif
3028 }
3029 
3030 //=============================================================================
3031 //------------------------------remove-----------------------------------------
3032 void Unique_Node_List::remove(Node* n) {
3033   if (_in_worklist.test(n->_idx)) {
3034     for (uint i = 0; i < size(); i++) {
3035       if (_nodes[i] == n) {
3036         map(i, Node_List::pop());
3037         _in_worklist.remove(n->_idx);
3038         return;
3039       }
3040     }
3041     ShouldNotReachHere();
3042   }
3043 }
3044 
3045 //-----------------------remove_useless_nodes----------------------------------
3046 // Remove useless nodes from worklist
3047 void Unique_Node_List::remove_useless_nodes(VectorSet &useful) {
3048   for (uint i = 0; i < size(); ++i) {
3049     Node *n = at(i);
3050     assert( n != nullptr, "Did not expect null entries in worklist");
3051     if (!useful.test(n->_idx)) {
3052       _in_worklist.remove(n->_idx);
3053       map(i, Node_List::pop());
3054       --i;  // Visit popped node
3055       // If it was last entry, loop terminates since size() was also reduced
3056     }
3057   }
3058 }
3059 
3060 //=============================================================================
3061 void Node_Stack::grow() {
3062   size_t old_top = pointer_delta(_inode_top,_inodes,sizeof(INode)); // save _top
3063   size_t old_max = pointer_delta(_inode_max,_inodes,sizeof(INode));
3064   size_t max = old_max << 1;             // max * 2
3065   _inodes = REALLOC_ARENA_ARRAY(_a, INode, _inodes, old_max, max);
3066   _inode_max = _inodes + max;
3067   _inode_top = _inodes + old_top;        // restore _top
3068 }
3069 
3070 // Node_Stack is used to map nodes.
3071 Node* Node_Stack::find(uint idx) const {
3072   uint sz = size();
3073   for (uint i = 0; i < sz; i++) {
3074     if (idx == index_at(i)) {
3075       return node_at(i);
3076     }
3077   }
3078   return nullptr;
3079 }
3080 
3081 //=============================================================================
3082 uint TypeNode::size_of() const { return sizeof(*this); }
3083 #ifndef PRODUCT
3084 void TypeNode::dump_spec(outputStream *st) const {
3085   if (!Verbose && !WizardMode) {
3086     // standard dump does this in Verbose and WizardMode
3087     st->print(" #"); _type->dump_on(st);
3088   }
3089 }
3090 
3091 void TypeNode::dump_compact_spec(outputStream *st) const {
3092   st->print("#");
3093   _type->dump_on(st);
3094 }
3095 #endif
3096 uint TypeNode::hash() const {
3097   return Node::hash() + _type->hash();
3098 }
3099 bool TypeNode::cmp(const Node& n) const {
3100   return Type::equals(_type, n.as_Type()->_type);
3101 }
3102 const Type* TypeNode::bottom_type() const { return _type; }
3103 const Type* TypeNode::Value(PhaseGVN* phase) const { return _type; }
3104 
3105 //------------------------------ideal_reg--------------------------------------
3106 uint TypeNode::ideal_reg() const {
3107   return _type->ideal_reg();
3108 }
3109 
3110 void TypeNode::make_path_dead(PhaseIterGVN* igvn, PhaseIdealLoop* loop, Node* ctrl_use, uint j, const char* phase_str) {
3111   Node* c = ctrl_use->in(j);
3112   if (igvn->type(c) != Type::TOP) {
3113     igvn->replace_input_of(ctrl_use, j, igvn->C->top());
3114     create_halt_path(igvn, c, loop, phase_str);
3115   }
3116 }
3117 
3118 // This Type node is dead. It could be because the type that it captures and the type of the node computed from its
3119 // inputs do not intersect anymore. That node has some uses along some control flow paths. Those control flow paths must
3120 // be unreachable as using a dead value makes no sense. For the Type node to capture a narrowed down type, some control
3121 // flow construct must guard the Type node (an If node usually). When the Type node becomes dead, the guard usually
3122 // constant folds and the control flow that leads to the Type node becomes unreachable. There are cases where that
3123 // doesn't happen, however. They are handled here by following uses of the Type node until a CFG or a Phi to find dead
3124 // paths. The dead paths are then replaced by a Halt node.
3125 void TypeNode::make_paths_from_here_dead(PhaseIterGVN* igvn, PhaseIdealLoop* loop, const char* phase_str) {
3126   Unique_Node_List wq;
3127   wq.push(this);
3128   for (uint i = 0; i < wq.size(); ++i) {
3129     Node* n = wq.at(i);
3130     for (DUIterator_Fast kmax, k = n->fast_outs(kmax); k < kmax; k++) {
3131       Node* u = n->fast_out(k);
3132       if (u->is_CFG()) {
3133         assert(!u->is_Region(), "Can't reach a Region without going through a Phi");
3134         make_path_dead(igvn, loop, u, 0, phase_str);
3135       } else if (u->is_Phi()) {
3136         Node* r = u->in(0);
3137         assert(r->is_Region() || r->is_top(), "unexpected Phi's control");
3138         if (r->is_Region()) {
3139           for (uint j = 1; j < u->req(); ++j) {
3140             if (u->in(j) == n && r->in(j) != nullptr) {
3141               make_path_dead(igvn, loop, r, j, phase_str);
3142             }
3143           }
3144         }
3145       } else {
3146         wq.push(u);
3147       }
3148     }
3149   }
3150 }
3151 
3152 void TypeNode::create_halt_path(PhaseIterGVN* igvn, Node* c, PhaseIdealLoop* loop, const char* phase_str) const {
3153   Node* frame = new ParmNode(igvn->C->start(), TypeFunc::FramePtr);
3154   if (loop == nullptr) {
3155     igvn->register_new_node_with_optimizer(frame);
3156   } else {
3157     loop->register_new_node(frame, igvn->C->start());
3158   }
3159 
3160   stringStream ss;
3161   ss.print("dead path discovered by TypeNode during %s", phase_str);
3162 
3163   Node* halt = new HaltNode(c, frame, ss.as_string(igvn->C->comp_arena()));
3164   if (loop == nullptr) {
3165     igvn->register_new_node_with_optimizer(halt);
3166   } else {
3167     loop->register_control(halt, loop->ltree_root(), c);
3168   }
3169   igvn->add_input_to(igvn->C->root(), halt);
3170 }
3171 
3172 Node* TypeNode::Ideal(PhaseGVN* phase, bool can_reshape) {
3173   if (KillPathsReachableByDeadTypeNode && can_reshape && Value(phase) == Type::TOP) {
3174     PhaseIterGVN* igvn = phase->is_IterGVN();
3175     Node* top = igvn->C->top();
3176     ResourceMark rm;
3177     make_paths_from_here_dead(igvn, nullptr, "igvn");
3178     return top;
3179   }
3180 
3181   return Node::Ideal(phase, can_reshape);
3182 }
3183 
--- EOF ---