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






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



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