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