1 /*
2 * Copyright (c) 1998, 2018, 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 "asm/macroAssembler.inline.hpp"
27 #include "memory/allocation.inline.hpp"
28 #include "opto/ad.hpp"
29 #include "opto/block.hpp"
30 #include "opto/c2compiler.hpp"
31 #include "opto/callnode.hpp"
32 #include "opto/cfgnode.hpp"
33 #include "opto/machnode.hpp"
34 #include "opto/runtime.hpp"
35 #include "opto/chaitin.hpp"
36 #include "runtime/sharedRuntime.hpp"
37
38 // Optimization - Graph Style
39
40 // Check whether val is not-null-decoded compressed oop,
41 // i.e. will grab into the base of the heap if it represents NULL.
accesses_heap_base_zone(Node * val)42 static bool accesses_heap_base_zone(Node *val) {
43 if (Universe::narrow_oop_base() != NULL) { // Implies UseCompressedOops.
44 if (val && val->is_Mach()) {
45 if (val->as_Mach()->ideal_Opcode() == Op_DecodeN) {
46 // This assumes all Decodes with TypePtr::NotNull are matched to nodes that
47 // decode NULL to point to the heap base (Decode_NN).
48 if (val->bottom_type()->is_oopptr()->ptr() == TypePtr::NotNull) {
49 return true;
50 }
51 }
52 // Must recognize load operation with Decode matched in memory operand.
53 // We should not reach here exept for PPC/AIX, as os::zero_page_read_protected()
54 // returns true everywhere else. On PPC, no such memory operands
55 // exist, therefore we did not yet implement a check for such operands.
56 NOT_AIX(Unimplemented());
57 }
58 }
59 return false;
60 }
61
needs_explicit_null_check_for_read(Node * val)62 static bool needs_explicit_null_check_for_read(Node *val) {
63 // On some OSes (AIX) the page at address 0 is only write protected.
64 // If so, only Store operations will trap.
65 if (os::zero_page_read_protected()) {
66 return false; // Implicit null check will work.
67 }
68 // Also a read accessing the base of a heap-based compressed heap will trap.
69 if (accesses_heap_base_zone(val) && // Hits the base zone page.
70 Universe::narrow_oop_use_implicit_null_checks()) { // Base zone page is protected.
71 return false;
72 }
73
74 return true;
75 }
76
77 //------------------------------implicit_null_check----------------------------
78 // Detect implicit-null-check opportunities. Basically, find NULL checks
79 // with suitable memory ops nearby. Use the memory op to do the NULL check.
80 // I can generate a memory op if there is not one nearby.
81 // The proj is the control projection for the not-null case.
82 // The val is the pointer being checked for nullness or
83 // decodeHeapOop_not_null node if it did not fold into address.
implicit_null_check(Block * block,Node * proj,Node * val,int allowed_reasons)84 void PhaseCFG::implicit_null_check(Block* block, Node *proj, Node *val, int allowed_reasons) {
85 // Assume if null check need for 0 offset then always needed
86 // Intel solaris doesn't support any null checks yet and no
87 // mechanism exists (yet) to set the switches at an os_cpu level
88 if( !ImplicitNullChecks || MacroAssembler::needs_explicit_null_check(0)) return;
89
90 // Make sure the ptr-is-null path appears to be uncommon!
91 float f = block->end()->as_MachIf()->_prob;
92 if( proj->Opcode() == Op_IfTrue ) f = 1.0f - f;
93 if( f > PROB_UNLIKELY_MAG(4) ) return;
94
95 uint bidx = 0; // Capture index of value into memop
96 bool was_store; // Memory op is a store op
97
98 // Get the successor block for if the test ptr is non-null
99 Block* not_null_block; // this one goes with the proj
100 Block* null_block;
101 if (block->get_node(block->number_of_nodes()-1) == proj) {
102 null_block = block->_succs[0];
103 not_null_block = block->_succs[1];
104 } else {
105 assert(block->get_node(block->number_of_nodes()-2) == proj, "proj is one or the other");
106 not_null_block = block->_succs[0];
107 null_block = block->_succs[1];
108 }
109 while (null_block->is_Empty() == Block::empty_with_goto) {
110 null_block = null_block->_succs[0];
111 }
112
113 // Search the exception block for an uncommon trap.
114 // (See Parse::do_if and Parse::do_ifnull for the reason
115 // we need an uncommon trap. Briefly, we need a way to
116 // detect failure of this optimization, as in 6366351.)
117 {
118 bool found_trap = false;
119 for (uint i1 = 0; i1 < null_block->number_of_nodes(); i1++) {
120 Node* nn = null_block->get_node(i1);
121 if (nn->is_MachCall() &&
122 nn->as_MachCall()->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point()) {
123 const Type* trtype = nn->in(TypeFunc::Parms)->bottom_type();
124 if (trtype->isa_int() && trtype->is_int()->is_con()) {
125 jint tr_con = trtype->is_int()->get_con();
126 Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(tr_con);
127 Deoptimization::DeoptAction action = Deoptimization::trap_request_action(tr_con);
128 assert((int)reason < (int)BitsPerInt, "recode bit map");
129 if (is_set_nth_bit(allowed_reasons, (int) reason)
130 && action != Deoptimization::Action_none) {
131 // This uncommon trap is sure to recompile, eventually.
132 // When that happens, C->too_many_traps will prevent
133 // this transformation from happening again.
134 found_trap = true;
135 }
136 }
137 break;
138 }
139 }
140 if (!found_trap) {
141 // We did not find an uncommon trap.
142 return;
143 }
144 }
145
146 // Check for decodeHeapOop_not_null node which did not fold into address
147 bool is_decoden = ((intptr_t)val) & 1;
148 val = (Node*)(((intptr_t)val) & ~1);
149
150 assert(!is_decoden || (val->in(0) == NULL) && val->is_Mach() &&
151 (val->as_Mach()->ideal_Opcode() == Op_DecodeN), "sanity");
152
153 // Search the successor block for a load or store who's base value is also
154 // the tested value. There may be several.
155 Node_List *out = new Node_List(Thread::current()->resource_area());
156 MachNode *best = NULL; // Best found so far
157 for (DUIterator i = val->outs(); val->has_out(i); i++) {
158 Node *m = val->out(i);
159 if( !m->is_Mach() ) continue;
160 MachNode *mach = m->as_Mach();
161 was_store = false;
162 int iop = mach->ideal_Opcode();
163 switch( iop ) {
164 case Op_LoadB:
165 case Op_LoadUB:
166 case Op_LoadUS:
167 case Op_LoadD:
168 case Op_LoadF:
169 case Op_LoadI:
170 case Op_LoadL:
171 case Op_LoadP:
172 case Op_LoadBarrierSlowReg:
173 case Op_LoadBarrierWeakSlowReg:
174 case Op_LoadN:
175 case Op_LoadS:
176 case Op_LoadKlass:
177 case Op_LoadNKlass:
178 case Op_LoadRange:
179 case Op_LoadD_unaligned:
180 case Op_LoadL_unaligned:
181 assert(mach->in(2) == val, "should be address");
182 break;
183 case Op_StoreB:
184 case Op_StoreC:
185 case Op_StoreCM:
186 case Op_StoreD:
187 case Op_StoreF:
188 case Op_StoreI:
189 case Op_StoreL:
190 case Op_StoreP:
191 case Op_StoreN:
192 case Op_StoreNKlass:
193 was_store = true; // Memory op is a store op
194 // Stores will have their address in slot 2 (memory in slot 1).
195 // If the value being nul-checked is in another slot, it means we
196 // are storing the checked value, which does NOT check the value!
197 if( mach->in(2) != val ) continue;
198 break; // Found a memory op?
199 case Op_StrComp:
200 case Op_StrEquals:
201 case Op_StrIndexOf:
202 case Op_StrIndexOfChar:
203 case Op_AryEq:
204 case Op_StrInflatedCopy:
205 case Op_StrCompressedCopy:
206 case Op_EncodeISOArray:
207 case Op_HasNegatives:
208 // Not a legit memory op for implicit null check regardless of
209 // embedded loads
210 continue;
211 default: // Also check for embedded loads
212 if( !mach->needs_anti_dependence_check() )
213 continue; // Not an memory op; skip it
214 if( must_clone[iop] ) {
215 // Do not move nodes which produce flags because
216 // RA will try to clone it to place near branch and
217 // it will cause recompilation, see clone_node().
218 continue;
219 }
220 {
221 // Check that value is used in memory address in
222 // instructions with embedded load (CmpP val1,(val2+off)).
223 Node* base;
224 Node* index;
225 const MachOper* oper = mach->memory_inputs(base, index);
226 if (oper == NULL || oper == (MachOper*)-1) {
227 continue; // Not an memory op; skip it
228 }
229 if (val == base ||
230 (val == index && val->bottom_type()->isa_narrowoop())) {
231 break; // Found it
232 } else {
233 continue; // Skip it
234 }
235 }
236 break;
237 }
238
239 // On some OSes (AIX) the page at address 0 is only write protected.
240 // If so, only Store operations will trap.
241 // But a read accessing the base of a heap-based compressed heap will trap.
242 if (!was_store && needs_explicit_null_check_for_read(val)) {
243 continue;
244 }
245
246 // Check that node's control edge is not-null block's head or dominates it,
247 // otherwise we can't hoist it because there are other control dependencies.
248 Node* ctrl = mach->in(0);
249 if (ctrl != NULL && !(ctrl == not_null_block->head() ||
250 get_block_for_node(ctrl)->dominates(not_null_block))) {
251 continue;
252 }
253
254 // check if the offset is not too high for implicit exception
255 {
256 intptr_t offset = 0;
257 const TypePtr *adr_type = NULL; // Do not need this return value here
258 const Node* base = mach->get_base_and_disp(offset, adr_type);
259 if (base == NULL || base == NodeSentinel) {
260 // Narrow oop address doesn't have base, only index.
261 // Give up if offset is beyond page size or if heap base is not protected.
262 if (val->bottom_type()->isa_narrowoop() &&
263 (MacroAssembler::needs_explicit_null_check(offset) ||
264 !Universe::narrow_oop_use_implicit_null_checks()))
265 continue;
266 // cannot reason about it; is probably not implicit null exception
267 } else {
268 const TypePtr* tptr;
269 if (UseCompressedOops && (Universe::narrow_oop_shift() == 0 ||
270 Universe::narrow_klass_shift() == 0)) {
271 // 32-bits narrow oop can be the base of address expressions
272 tptr = base->get_ptr_type();
273 } else {
274 // only regular oops are expected here
275 tptr = base->bottom_type()->is_ptr();
276 }
277 // Give up if offset is not a compile-time constant.
278 if (offset == Type::OffsetBot || tptr->_offset == Type::OffsetBot)
279 continue;
280 offset += tptr->_offset; // correct if base is offseted
281 // Give up if reference is beyond page size.
282 if (MacroAssembler::needs_explicit_null_check(offset))
283 continue;
284 // Give up if base is a decode node and the heap base is not protected.
285 if (base->is_Mach() && base->as_Mach()->ideal_Opcode() == Op_DecodeN &&
286 !Universe::narrow_oop_use_implicit_null_checks())
287 continue;
288 }
289 }
290
291 // Check ctrl input to see if the null-check dominates the memory op
292 Block *cb = get_block_for_node(mach);
293 cb = cb->_idom; // Always hoist at least 1 block
294 if( !was_store ) { // Stores can be hoisted only one block
295 while( cb->_dom_depth > (block->_dom_depth + 1))
296 cb = cb->_idom; // Hoist loads as far as we want
297 // The non-null-block should dominate the memory op, too. Live
298 // range spilling will insert a spill in the non-null-block if it is
299 // needs to spill the memory op for an implicit null check.
300 if (cb->_dom_depth == (block->_dom_depth + 1)) {
301 if (cb != not_null_block) continue;
302 cb = cb->_idom;
303 }
304 }
305 if( cb != block ) continue;
306
307 // Found a memory user; see if it can be hoisted to check-block
308 uint vidx = 0; // Capture index of value into memop
309 uint j;
310 for( j = mach->req()-1; j > 0; j-- ) {
311 if( mach->in(j) == val ) {
312 vidx = j;
313 // Ignore DecodeN val which could be hoisted to where needed.
314 if( is_decoden ) continue;
315 }
316 // Block of memory-op input
317 Block *inb = get_block_for_node(mach->in(j));
318 Block *b = block; // Start from nul check
319 while( b != inb && b->_dom_depth > inb->_dom_depth )
320 b = b->_idom; // search upwards for input
321 // See if input dominates null check
322 if( b != inb )
323 break;
324 }
325 if( j > 0 )
326 continue;
327 Block *mb = get_block_for_node(mach);
328 // Hoisting stores requires more checks for the anti-dependence case.
329 // Give up hoisting if we have to move the store past any load.
330 if( was_store ) {
331 Block *b = mb; // Start searching here for a local load
332 // mach use (faulting) trying to hoist
333 // n might be blocker to hoisting
334 while( b != block ) {
335 uint k;
336 for( k = 1; k < b->number_of_nodes(); k++ ) {
337 Node *n = b->get_node(k);
338 if( n->needs_anti_dependence_check() &&
339 n->in(LoadNode::Memory) == mach->in(StoreNode::Memory) )
340 break; // Found anti-dependent load
341 }
342 if( k < b->number_of_nodes() )
343 break; // Found anti-dependent load
344 // Make sure control does not do a merge (would have to check allpaths)
345 if( b->num_preds() != 2 ) break;
346 b = get_block_for_node(b->pred(1)); // Move up to predecessor block
347 }
348 if( b != block ) continue;
349 }
350
351 // Make sure this memory op is not already being used for a NullCheck
352 Node *e = mb->end();
353 if( e->is_MachNullCheck() && e->in(1) == mach )
354 continue; // Already being used as a NULL check
355
356 // Found a candidate! Pick one with least dom depth - the highest
357 // in the dom tree should be closest to the null check.
358 if (best == NULL || get_block_for_node(mach)->_dom_depth < get_block_for_node(best)->_dom_depth) {
359 best = mach;
360 bidx = vidx;
361 }
362 }
363 // No candidate!
364 if (best == NULL) {
365 return;
366 }
367
368 // ---- Found an implicit null check
369 #ifndef PRODUCT
370 extern int implicit_null_checks;
371 implicit_null_checks++;
372 #endif
373
374 if( is_decoden ) {
375 // Check if we need to hoist decodeHeapOop_not_null first.
376 Block *valb = get_block_for_node(val);
377 if( block != valb && block->_dom_depth < valb->_dom_depth ) {
378 // Hoist it up to the end of the test block together with its inputs if they exist.
379 for (uint i = 2; i < val->req(); i++) {
380 // DecodeN has 2 regular inputs + optional MachTemp or load Base inputs.
381 Node *temp = val->in(i);
382 Block *tempb = get_block_for_node(temp);
383 if (!tempb->dominates(block)) {
384 assert(block->dominates(tempb), "sanity check: temp node placement");
385 // We only expect nodes without further inputs, like MachTemp or load Base.
386 assert(temp->req() == 0 || (temp->req() == 1 && temp->in(0) == (Node*)C->root()),
387 "need for recursive hoisting not expected");
388 tempb->find_remove(temp);
389 block->add_inst(temp);
390 map_node_to_block(temp, block);
391 }
392 }
393 valb->find_remove(val);
394 block->add_inst(val);
395 map_node_to_block(val, block);
396 // DecodeN on x86 may kill flags. Check for flag-killing projections
397 // that also need to be hoisted.
398 for (DUIterator_Fast jmax, j = val->fast_outs(jmax); j < jmax; j++) {
399 Node* n = val->fast_out(j);
400 if( n->is_MachProj() ) {
401 get_block_for_node(n)->find_remove(n);
402 block->add_inst(n);
403 map_node_to_block(n, block);
404 }
405 }
406 }
407 }
408 // Hoist the memory candidate up to the end of the test block.
409 Block *old_block = get_block_for_node(best);
410 old_block->find_remove(best);
411 block->add_inst(best);
412 map_node_to_block(best, block);
413
414 // Move the control dependence if it is pinned to not-null block.
415 // Don't change it in other cases: NULL or dominating control.
416 Node* ctrl = best->in(0);
417 if (ctrl != NULL && get_block_for_node(ctrl) == not_null_block) {
418 // Set it to control edge of null check.
419 best->set_req(0, proj->in(0)->in(0));
420 }
421
422 // Check for flag-killing projections that also need to be hoisted
423 // Should be DU safe because no edge updates.
424 for (DUIterator_Fast jmax, j = best->fast_outs(jmax); j < jmax; j++) {
425 Node* n = best->fast_out(j);
426 if( n->is_MachProj() ) {
427 get_block_for_node(n)->find_remove(n);
428 block->add_inst(n);
429 map_node_to_block(n, block);
430 }
431 }
432
433 // proj==Op_True --> ne test; proj==Op_False --> eq test.
434 // One of two graph shapes got matched:
435 // (IfTrue (If (Bool NE (CmpP ptr NULL))))
436 // (IfFalse (If (Bool EQ (CmpP ptr NULL))))
437 // NULL checks are always branch-if-eq. If we see a IfTrue projection
438 // then we are replacing a 'ne' test with a 'eq' NULL check test.
439 // We need to flip the projections to keep the same semantics.
440 if( proj->Opcode() == Op_IfTrue ) {
441 // Swap order of projections in basic block to swap branch targets
442 Node *tmp1 = block->get_node(block->end_idx()+1);
443 Node *tmp2 = block->get_node(block->end_idx()+2);
444 block->map_node(tmp2, block->end_idx()+1);
445 block->map_node(tmp1, block->end_idx()+2);
446 Node *tmp = new Node(C->top()); // Use not NULL input
447 tmp1->replace_by(tmp);
448 tmp2->replace_by(tmp1);
449 tmp->replace_by(tmp2);
450 tmp->destruct();
451 }
452
453 // Remove the existing null check; use a new implicit null check instead.
454 // Since schedule-local needs precise def-use info, we need to correct
455 // it as well.
456 Node *old_tst = proj->in(0);
457 MachNode *nul_chk = new MachNullCheckNode(old_tst->in(0),best,bidx);
458 block->map_node(nul_chk, block->end_idx());
459 map_node_to_block(nul_chk, block);
460 // Redirect users of old_test to nul_chk
461 for (DUIterator_Last i2min, i2 = old_tst->last_outs(i2min); i2 >= i2min; --i2)
462 old_tst->last_out(i2)->set_req(0, nul_chk);
463 // Clean-up any dead code
464 for (uint i3 = 0; i3 < old_tst->req(); i3++) {
465 Node* in = old_tst->in(i3);
466 old_tst->set_req(i3, NULL);
467 if (in->outcnt() == 0) {
468 // Remove dead input node
469 in->disconnect_inputs(NULL, C);
470 block->find_remove(in);
471 }
472 }
473
474 latency_from_uses(nul_chk);
475 latency_from_uses(best);
476
477 // insert anti-dependences to defs in this block
478 if (! best->needs_anti_dependence_check()) {
479 for (uint k = 1; k < block->number_of_nodes(); k++) {
480 Node *n = block->get_node(k);
481 if (n->needs_anti_dependence_check() &&
482 n->in(LoadNode::Memory) == best->in(StoreNode::Memory)) {
483 // Found anti-dependent load
484 insert_anti_dependences(block, n);
485 }
486 }
487 }
488 }
489
490
491 //------------------------------select-----------------------------------------
492 // Select a nice fellow from the worklist to schedule next. If there is only
493 // one choice, then use it. Projections take top priority for correctness
494 // reasons - if I see a projection, then it is next. There are a number of
495 // other special cases, for instructions that consume condition codes, et al.
496 // These are chosen immediately. Some instructions are required to immediately
497 // precede the last instruction in the block, and these are taken last. Of the
498 // remaining cases (most), choose the instruction with the greatest latency
499 // (that is, the most number of pseudo-cycles required to the end of the
500 // routine). If there is a tie, choose the instruction with the most inputs.
select(Block * block,Node_List & worklist,GrowableArray<int> & ready_cnt,VectorSet & next_call,uint sched_slot,intptr_t * recalc_pressure_nodes)501 Node* PhaseCFG::select(
502 Block* block,
503 Node_List &worklist,
504 GrowableArray<int> &ready_cnt,
505 VectorSet &next_call,
506 uint sched_slot,
507 intptr_t* recalc_pressure_nodes) {
508
509 // If only a single entry on the stack, use it
510 uint cnt = worklist.size();
511 if (cnt == 1) {
512 Node *n = worklist[0];
513 worklist.map(0,worklist.pop());
514 return n;
515 }
516
517 uint choice = 0; // Bigger is most important
518 uint latency = 0; // Bigger is scheduled first
519 uint score = 0; // Bigger is better
520 int idx = -1; // Index in worklist
521 int cand_cnt = 0; // Candidate count
522 bool block_size_threshold_ok = (block->number_of_nodes() > 10) ? true : false;
523
524 for( uint i=0; i<cnt; i++ ) { // Inspect entire worklist
525 // Order in worklist is used to break ties.
526 // See caller for how this is used to delay scheduling
527 // of induction variable increments to after the other
528 // uses of the phi are scheduled.
529 Node *n = worklist[i]; // Get Node on worklist
530
531 int iop = n->is_Mach() ? n->as_Mach()->ideal_Opcode() : 0;
532 if( n->is_Proj() || // Projections always win
533 n->Opcode()== Op_Con || // So does constant 'Top'
534 iop == Op_CreateEx || // Create-exception must start block
535 iop == Op_CheckCastPP
536 ) {
537 worklist.map(i,worklist.pop());
538 return n;
539 }
540
541 // Final call in a block must be adjacent to 'catch'
542 Node *e = block->end();
543 if( e->is_Catch() && e->in(0)->in(0) == n )
544 continue;
545
546 // Memory op for an implicit null check has to be at the end of the block
547 if( e->is_MachNullCheck() && e->in(1) == n )
548 continue;
549
550 // Schedule IV increment last.
551 if (e->is_Mach() && e->as_Mach()->ideal_Opcode() == Op_CountedLoopEnd) {
552 // Cmp might be matched into CountedLoopEnd node.
553 Node *cmp = (e->in(1)->ideal_reg() == Op_RegFlags) ? e->in(1) : e;
554 if (cmp->req() > 1 && cmp->in(1) == n && n->is_iteratively_computed()) {
555 continue;
556 }
557 }
558
559 uint n_choice = 2;
560
561 // See if this instruction is consumed by a branch. If so, then (as the
562 // branch is the last instruction in the basic block) force it to the
563 // end of the basic block
564 if ( must_clone[iop] ) {
565 // See if any use is a branch
566 bool found_machif = false;
567
568 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
569 Node* use = n->fast_out(j);
570
571 // The use is a conditional branch, make them adjacent
572 if (use->is_MachIf() && get_block_for_node(use) == block) {
573 found_machif = true;
574 break;
575 }
576
577 // More than this instruction pending for successor to be ready,
578 // don't choose this if other opportunities are ready
579 if (ready_cnt.at(use->_idx) > 1)
580 n_choice = 1;
581 }
582
583 // loop terminated, prefer not to use this instruction
584 if (found_machif)
585 continue;
586 }
587
588 // See if this has a predecessor that is "must_clone", i.e. sets the
589 // condition code. If so, choose this first
590 for (uint j = 0; j < n->req() ; j++) {
591 Node *inn = n->in(j);
592 if (inn) {
593 if (inn->is_Mach() && must_clone[inn->as_Mach()->ideal_Opcode()] ) {
594 n_choice = 3;
595 break;
596 }
597 }
598 }
599
600 // MachTemps should be scheduled last so they are near their uses
601 if (n->is_MachTemp()) {
602 n_choice = 1;
603 }
604
605 uint n_latency = get_latency_for_node(n);
606 uint n_score = n->req(); // Many inputs get high score to break ties
607
608 if (OptoRegScheduling && block_size_threshold_ok) {
609 if (recalc_pressure_nodes[n->_idx] == 0x7fff7fff) {
610 _regalloc->_scratch_int_pressure.init(_regalloc->_sched_int_pressure.high_pressure_limit());
611 _regalloc->_scratch_float_pressure.init(_regalloc->_sched_float_pressure.high_pressure_limit());
612 // simulate the notion that we just picked this node to schedule
613 n->add_flag(Node::Flag_is_scheduled);
614 // now caculate its effect upon the graph if we did
615 adjust_register_pressure(n, block, recalc_pressure_nodes, false);
616 // return its state for finalize in case somebody else wins
617 n->remove_flag(Node::Flag_is_scheduled);
618 // now save the two final pressure components of register pressure, limiting pressure calcs to short size
619 short int_pressure = (short)_regalloc->_scratch_int_pressure.current_pressure();
620 short float_pressure = (short)_regalloc->_scratch_float_pressure.current_pressure();
621 recalc_pressure_nodes[n->_idx] = int_pressure;
622 recalc_pressure_nodes[n->_idx] |= (float_pressure << 16);
623 }
624
625 if (_scheduling_for_pressure) {
626 latency = n_latency;
627 if (n_choice != 3) {
628 // Now evaluate each register pressure component based on threshold in the score.
629 // In general the defining register type will dominate the score, ergo we will not see register pressure grow on both banks
630 // on a single instruction, but we might see it shrink on both banks.
631 // For each use of register that has a register class that is over the high pressure limit, we build n_score up for
632 // live ranges that terminate on this instruction.
633 if (_regalloc->_sched_int_pressure.current_pressure() > _regalloc->_sched_int_pressure.high_pressure_limit()) {
634 short int_pressure = (short)recalc_pressure_nodes[n->_idx];
635 n_score = (int_pressure < 0) ? ((score + n_score) - int_pressure) : (int_pressure > 0) ? 1 : n_score;
636 }
637 if (_regalloc->_sched_float_pressure.current_pressure() > _regalloc->_sched_float_pressure.high_pressure_limit()) {
638 short float_pressure = (short)(recalc_pressure_nodes[n->_idx] >> 16);
639 n_score = (float_pressure < 0) ? ((score + n_score) - float_pressure) : (float_pressure > 0) ? 1 : n_score;
640 }
641 } else {
642 // make sure we choose these candidates
643 score = 0;
644 }
645 }
646 }
647
648 // Keep best latency found
649 cand_cnt++;
650 if (choice < n_choice ||
651 (choice == n_choice &&
652 ((StressLCM && Compile::randomized_select(cand_cnt)) ||
653 (!StressLCM &&
654 (latency < n_latency ||
655 (latency == n_latency &&
656 (score < n_score))))))) {
657 choice = n_choice;
658 latency = n_latency;
659 score = n_score;
660 idx = i; // Also keep index in worklist
661 }
662 } // End of for all ready nodes in worklist
663
664 guarantee(idx >= 0, "index should be set");
665 Node *n = worklist[(uint)idx]; // Get the winner
666
667 worklist.map((uint)idx, worklist.pop()); // Compress worklist
668 return n;
669 }
670
671 //-------------------------adjust_register_pressure----------------------------
adjust_register_pressure(Node * n,Block * block,intptr_t * recalc_pressure_nodes,bool finalize_mode)672 void PhaseCFG::adjust_register_pressure(Node* n, Block* block, intptr_t* recalc_pressure_nodes, bool finalize_mode) {
673 PhaseLive* liveinfo = _regalloc->get_live();
674 IndexSet* liveout = liveinfo->live(block);
675 // first adjust the register pressure for the sources
676 for (uint i = 1; i < n->req(); i++) {
677 bool lrg_ends = false;
678 Node *src_n = n->in(i);
679 if (src_n == NULL) continue;
680 if (!src_n->is_Mach()) continue;
681 uint src = _regalloc->_lrg_map.find(src_n);
682 if (src == 0) continue;
683 LRG& lrg_src = _regalloc->lrgs(src);
684 // detect if the live range ends or not
685 if (liveout->member(src) == false) {
686 lrg_ends = true;
687 for (DUIterator_Fast jmax, j = src_n->fast_outs(jmax); j < jmax; j++) {
688 Node* m = src_n->fast_out(j); // Get user
689 if (m == n) continue;
690 if (!m->is_Mach()) continue;
691 MachNode *mach = m->as_Mach();
692 bool src_matches = false;
693 int iop = mach->ideal_Opcode();
694
695 switch (iop) {
696 case Op_StoreB:
697 case Op_StoreC:
698 case Op_StoreCM:
699 case Op_StoreD:
700 case Op_StoreF:
701 case Op_StoreI:
702 case Op_StoreL:
703 case Op_StoreP:
704 case Op_StoreN:
705 case Op_StoreVector:
706 case Op_StoreNKlass:
707 for (uint k = 1; k < m->req(); k++) {
708 Node *in = m->in(k);
709 if (in == src_n) {
710 src_matches = true;
711 break;
712 }
713 }
714 break;
715
716 default:
717 src_matches = true;
718 break;
719 }
720
721 // If we have a store as our use, ignore the non source operands
722 if (src_matches == false) continue;
723
724 // Mark every unscheduled use which is not n with a recalculation
725 if ((get_block_for_node(m) == block) && (!m->is_scheduled())) {
726 if (finalize_mode && !m->is_Phi()) {
727 recalc_pressure_nodes[m->_idx] = 0x7fff7fff;
728 }
729 lrg_ends = false;
730 }
731 }
732 }
733 // if none, this live range ends and we can adjust register pressure
734 if (lrg_ends) {
735 if (finalize_mode) {
736 _regalloc->lower_pressure(block, 0, lrg_src, NULL, _regalloc->_sched_int_pressure, _regalloc->_sched_float_pressure);
737 } else {
738 _regalloc->lower_pressure(block, 0, lrg_src, NULL, _regalloc->_scratch_int_pressure, _regalloc->_scratch_float_pressure);
739 }
740 }
741 }
742
743 // now add the register pressure from the dest and evaluate which heuristic we should use:
744 // 1.) The default, latency scheduling
745 // 2.) Register pressure scheduling based on the high pressure limit threshold for int or float register stacks
746 uint dst = _regalloc->_lrg_map.find(n);
747 if (dst != 0) {
748 LRG& lrg_dst = _regalloc->lrgs(dst);
749 if (finalize_mode) {
750 _regalloc->raise_pressure(block, lrg_dst, _regalloc->_sched_int_pressure, _regalloc->_sched_float_pressure);
751 // check to see if we fall over the register pressure cliff here
752 if (_regalloc->_sched_int_pressure.current_pressure() > _regalloc->_sched_int_pressure.high_pressure_limit()) {
753 _scheduling_for_pressure = true;
754 } else if (_regalloc->_sched_float_pressure.current_pressure() > _regalloc->_sched_float_pressure.high_pressure_limit()) {
755 _scheduling_for_pressure = true;
756 } else {
757 // restore latency scheduling mode
758 _scheduling_for_pressure = false;
759 }
760 } else {
761 _regalloc->raise_pressure(block, lrg_dst, _regalloc->_scratch_int_pressure, _regalloc->_scratch_float_pressure);
762 }
763 }
764 }
765
766 //------------------------------set_next_call----------------------------------
set_next_call(Block * block,Node * n,VectorSet & next_call)767 void PhaseCFG::set_next_call(Block* block, Node* n, VectorSet& next_call) {
768 if( next_call.test_set(n->_idx) ) return;
769 for( uint i=0; i<n->len(); i++ ) {
770 Node *m = n->in(i);
771 if( !m ) continue; // must see all nodes in block that precede call
772 if (get_block_for_node(m) == block) {
773 set_next_call(block, m, next_call);
774 }
775 }
776 }
777
778 //------------------------------needed_for_next_call---------------------------
779 // Set the flag 'next_call' for each Node that is needed for the next call to
780 // be scheduled. This flag lets me bias scheduling so Nodes needed for the
781 // next subroutine call get priority - basically it moves things NOT needed
782 // for the next call till after the call. This prevents me from trying to
783 // carry lots of stuff live across a call.
needed_for_next_call(Block * block,Node * this_call,VectorSet & next_call)784 void PhaseCFG::needed_for_next_call(Block* block, Node* this_call, VectorSet& next_call) {
785 // Find the next control-defining Node in this block
786 Node* call = NULL;
787 for (DUIterator_Fast imax, i = this_call->fast_outs(imax); i < imax; i++) {
788 Node* m = this_call->fast_out(i);
789 if (get_block_for_node(m) == block && // Local-block user
790 m != this_call && // Not self-start node
791 m->is_MachCall()) {
792 call = m;
793 break;
794 }
795 }
796 if (call == NULL) return; // No next call (e.g., block end is near)
797 // Set next-call for all inputs to this call
798 set_next_call(block, call, next_call);
799 }
800
801 //------------------------------add_call_kills-------------------------------------
802 // helper function that adds caller save registers to MachProjNode
add_call_kills(MachProjNode * proj,RegMask & regs,const char * save_policy,bool exclude_soe)803 static void add_call_kills(MachProjNode *proj, RegMask& regs, const char* save_policy, bool exclude_soe) {
804 // Fill in the kill mask for the call
805 for( OptoReg::Name r = OptoReg::Name(0); r < _last_Mach_Reg; r=OptoReg::add(r,1) ) {
806 if( !regs.Member(r) ) { // Not already defined by the call
807 // Save-on-call register?
808 if ((save_policy[r] == 'C') ||
809 (save_policy[r] == 'A') ||
810 ((save_policy[r] == 'E') && exclude_soe)) {
811 proj->_rout.Insert(r);
812 }
813 }
814 }
815 }
816
817
818 //------------------------------sched_call-------------------------------------
sched_call(Block * block,uint node_cnt,Node_List & worklist,GrowableArray<int> & ready_cnt,MachCallNode * mcall,VectorSet & next_call)819 uint PhaseCFG::sched_call(Block* block, uint node_cnt, Node_List& worklist, GrowableArray<int>& ready_cnt, MachCallNode* mcall, VectorSet& next_call) {
820 RegMask regs;
821
822 // Schedule all the users of the call right now. All the users are
823 // projection Nodes, so they must be scheduled next to the call.
824 // Collect all the defined registers.
825 for (DUIterator_Fast imax, i = mcall->fast_outs(imax); i < imax; i++) {
826 Node* n = mcall->fast_out(i);
827 assert( n->is_MachProj(), "" );
828 int n_cnt = ready_cnt.at(n->_idx)-1;
829 ready_cnt.at_put(n->_idx, n_cnt);
830 assert( n_cnt == 0, "" );
831 // Schedule next to call
832 block->map_node(n, node_cnt++);
833 // Collect defined registers
834 regs.OR(n->out_RegMask());
835 // Check for scheduling the next control-definer
836 if( n->bottom_type() == Type::CONTROL )
837 // Warm up next pile of heuristic bits
838 needed_for_next_call(block, n, next_call);
839
840 // Children of projections are now all ready
841 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
842 Node* m = n->fast_out(j); // Get user
843 if(get_block_for_node(m) != block) {
844 continue;
845 }
846 if( m->is_Phi() ) continue;
847 int m_cnt = ready_cnt.at(m->_idx) - 1;
848 ready_cnt.at_put(m->_idx, m_cnt);
849 if( m_cnt == 0 )
850 worklist.push(m);
851 }
852
853 }
854
855 // Act as if the call defines the Frame Pointer.
856 // Certainly the FP is alive and well after the call.
857 regs.Insert(_matcher.c_frame_pointer());
858
859 // Set all registers killed and not already defined by the call.
860 uint r_cnt = mcall->tf()->range()->cnt();
861 int op = mcall->ideal_Opcode();
862 MachProjNode *proj = new MachProjNode( mcall, r_cnt+1, RegMask::Empty, MachProjNode::fat_proj );
863 map_node_to_block(proj, block);
864 block->insert_node(proj, node_cnt++);
865
866 // Select the right register save policy.
867 const char *save_policy = NULL;
868 switch (op) {
869 case Op_CallRuntime:
870 case Op_CallLeaf:
871 case Op_CallLeafNoFP:
872 // Calling C code so use C calling convention
873 save_policy = _matcher._c_reg_save_policy;
874 break;
875
876 case Op_CallStaticJava:
877 case Op_CallDynamicJava:
878 // Calling Java code so use Java calling convention
879 save_policy = _matcher._register_save_policy;
880 break;
881
882 default:
883 ShouldNotReachHere();
884 }
885
886 // When using CallRuntime mark SOE registers as killed by the call
887 // so values that could show up in the RegisterMap aren't live in a
888 // callee saved register since the register wouldn't know where to
889 // find them. CallLeaf and CallLeafNoFP are ok because they can't
890 // have debug info on them. Strictly speaking this only needs to be
891 // done for oops since idealreg2debugmask takes care of debug info
892 // references but there no way to handle oops differently than other
893 // pointers as far as the kill mask goes.
894 bool exclude_soe = op == Op_CallRuntime;
895
896 // If the call is a MethodHandle invoke, we need to exclude the
897 // register which is used to save the SP value over MH invokes from
898 // the mask. Otherwise this register could be used for
899 // deoptimization information.
900 if (op == Op_CallStaticJava) {
901 MachCallStaticJavaNode* mcallstaticjava = (MachCallStaticJavaNode*) mcall;
902 if (mcallstaticjava->_method_handle_invoke)
903 proj->_rout.OR(Matcher::method_handle_invoke_SP_save_mask());
904 }
905
906 add_call_kills(proj, regs, save_policy, exclude_soe);
907
908 return node_cnt;
909 }
910
911
912 //------------------------------schedule_local---------------------------------
913 // Topological sort within a block. Someday become a real scheduler.
schedule_local(Block * block,GrowableArray<int> & ready_cnt,VectorSet & next_call,intptr_t * recalc_pressure_nodes)914 bool PhaseCFG::schedule_local(Block* block, GrowableArray<int>& ready_cnt, VectorSet& next_call, intptr_t *recalc_pressure_nodes) {
915 // Already "sorted" are the block start Node (as the first entry), and
916 // the block-ending Node and any trailing control projections. We leave
917 // these alone. PhiNodes and ParmNodes are made to follow the block start
918 // Node. Everything else gets topo-sorted.
919
920 #ifndef PRODUCT
921 if (trace_opto_pipelining()) {
922 tty->print_cr("# --- schedule_local B%d, before: ---", block->_pre_order);
923 for (uint i = 0;i < block->number_of_nodes(); i++) {
924 tty->print("# ");
925 block->get_node(i)->fast_dump();
926 }
927 tty->print_cr("#");
928 }
929 #endif
930
931 // RootNode is already sorted
932 if (block->number_of_nodes() == 1) {
933 return true;
934 }
935
936 bool block_size_threshold_ok = (block->number_of_nodes() > 10) ? true : false;
937
938 // We track the uses of local definitions as input dependences so that
939 // we know when a given instruction is avialable to be scheduled.
940 uint i;
941 if (OptoRegScheduling && block_size_threshold_ok) {
942 for (i = 1; i < block->number_of_nodes(); i++) { // setup nodes for pressure calc
943 Node *n = block->get_node(i);
944 n->remove_flag(Node::Flag_is_scheduled);
945 if (!n->is_Phi()) {
946 recalc_pressure_nodes[n->_idx] = 0x7fff7fff;
947 }
948 }
949 }
950
951 // Move PhiNodes and ParmNodes from 1 to cnt up to the start
952 uint node_cnt = block->end_idx();
953 uint phi_cnt = 1;
954 for( i = 1; i<node_cnt; i++ ) { // Scan for Phi
955 Node *n = block->get_node(i);
956 if( n->is_Phi() || // Found a PhiNode or ParmNode
957 (n->is_Proj() && n->in(0) == block->head()) ) {
958 // Move guy at 'phi_cnt' to the end; makes a hole at phi_cnt
959 block->map_node(block->get_node(phi_cnt), i);
960 block->map_node(n, phi_cnt++); // swap Phi/Parm up front
961 if (OptoRegScheduling && block_size_threshold_ok) {
962 // mark n as scheduled
963 n->add_flag(Node::Flag_is_scheduled);
964 }
965 } else { // All others
966 // Count block-local inputs to 'n'
967 uint cnt = n->len(); // Input count
968 uint local = 0;
969 for( uint j=0; j<cnt; j++ ) {
970 Node *m = n->in(j);
971 if( m && get_block_for_node(m) == block && !m->is_top() )
972 local++; // One more block-local input
973 }
974 ready_cnt.at_put(n->_idx, local); // Count em up
975
976 #ifdef ASSERT
977 if( UseConcMarkSweepGC || UseG1GC ) {
978 if( n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_StoreCM ) {
979 // Check the precedence edges
980 for (uint prec = n->req(); prec < n->len(); prec++) {
981 Node* oop_store = n->in(prec);
982 if (oop_store != NULL) {
983 assert(get_block_for_node(oop_store)->_dom_depth <= block->_dom_depth, "oop_store must dominate card-mark");
984 }
985 }
986 }
987 }
988 #endif
989
990 // A few node types require changing a required edge to a precedence edge
991 // before allocation.
992 if( n->is_Mach() && n->req() > TypeFunc::Parms &&
993 (n->as_Mach()->ideal_Opcode() == Op_MemBarAcquire ||
994 n->as_Mach()->ideal_Opcode() == Op_MemBarVolatile) ) {
995 // MemBarAcquire could be created without Precedent edge.
996 // del_req() replaces the specified edge with the last input edge
997 // and then removes the last edge. If the specified edge > number of
998 // edges the last edge will be moved outside of the input edges array
999 // and the edge will be lost. This is why this code should be
1000 // executed only when Precedent (== TypeFunc::Parms) edge is present.
1001 Node *x = n->in(TypeFunc::Parms);
1002 if (x != NULL && get_block_for_node(x) == block && n->find_prec_edge(x) != -1) {
1003 // Old edge to node within same block will get removed, but no precedence
1004 // edge will get added because it already exists. Update ready count.
1005 int cnt = ready_cnt.at(n->_idx);
1006 assert(cnt > 1, "MemBar node %d must not get ready here", n->_idx);
1007 ready_cnt.at_put(n->_idx, cnt-1);
1008 }
1009 n->del_req(TypeFunc::Parms);
1010 n->add_prec(x);
1011 }
1012 }
1013 }
1014 for(uint i2=i; i2< block->number_of_nodes(); i2++ ) // Trailing guys get zapped count
1015 ready_cnt.at_put(block->get_node(i2)->_idx, 0);
1016
1017 // All the prescheduled guys do not hold back internal nodes
1018 uint i3;
1019 for (i3 = 0; i3 < phi_cnt; i3++) { // For all pre-scheduled
1020 Node *n = block->get_node(i3); // Get pre-scheduled
1021 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
1022 Node* m = n->fast_out(j);
1023 if (get_block_for_node(m) == block) { // Local-block user
1024 int m_cnt = ready_cnt.at(m->_idx)-1;
1025 if (OptoRegScheduling && block_size_threshold_ok) {
1026 // mark m as scheduled
1027 if (m_cnt < 0) {
1028 m->add_flag(Node::Flag_is_scheduled);
1029 }
1030 }
1031 ready_cnt.at_put(m->_idx, m_cnt); // Fix ready count
1032 }
1033 }
1034 }
1035
1036 Node_List delay;
1037 // Make a worklist
1038 Node_List worklist;
1039 for(uint i4=i3; i4<node_cnt; i4++ ) { // Put ready guys on worklist
1040 Node *m = block->get_node(i4);
1041 if( !ready_cnt.at(m->_idx) ) { // Zero ready count?
1042 if (m->is_iteratively_computed()) {
1043 // Push induction variable increments last to allow other uses
1044 // of the phi to be scheduled first. The select() method breaks
1045 // ties in scheduling by worklist order.
1046 delay.push(m);
1047 } else if (m->is_Mach() && m->as_Mach()->ideal_Opcode() == Op_CreateEx) {
1048 // Force the CreateEx to the top of the list so it's processed
1049 // first and ends up at the start of the block.
1050 worklist.insert(0, m);
1051 } else {
1052 worklist.push(m); // Then on to worklist!
1053 }
1054 }
1055 }
1056 while (delay.size()) {
1057 Node* d = delay.pop();
1058 worklist.push(d);
1059 }
1060
1061 if (OptoRegScheduling && block_size_threshold_ok) {
1062 // To stage register pressure calculations we need to examine the live set variables
1063 // breaking them up by register class to compartmentalize the calculations.
1064 uint float_pressure = Matcher::float_pressure(FLOATPRESSURE);
1065 _regalloc->_sched_int_pressure.init(INTPRESSURE);
1066 _regalloc->_sched_float_pressure.init(float_pressure);
1067 _regalloc->_scratch_int_pressure.init(INTPRESSURE);
1068 _regalloc->_scratch_float_pressure.init(float_pressure);
1069
1070 _regalloc->compute_entry_block_pressure(block);
1071 }
1072
1073 // Warm up the 'next_call' heuristic bits
1074 needed_for_next_call(block, block->head(), next_call);
1075
1076 #ifndef PRODUCT
1077 if (trace_opto_pipelining()) {
1078 for (uint j=0; j< block->number_of_nodes(); j++) {
1079 Node *n = block->get_node(j);
1080 int idx = n->_idx;
1081 tty->print("# ready cnt:%3d ", ready_cnt.at(idx));
1082 tty->print("latency:%3d ", get_latency_for_node(n));
1083 tty->print("%4d: %s\n", idx, n->Name());
1084 }
1085 }
1086 #endif
1087
1088 uint max_idx = (uint)ready_cnt.length();
1089 // Pull from worklist and schedule
1090 while( worklist.size() ) { // Worklist is not ready
1091
1092 #ifndef PRODUCT
1093 if (trace_opto_pipelining()) {
1094 tty->print("# ready list:");
1095 for( uint i=0; i<worklist.size(); i++ ) { // Inspect entire worklist
1096 Node *n = worklist[i]; // Get Node on worklist
1097 tty->print(" %d", n->_idx);
1098 }
1099 tty->cr();
1100 }
1101 #endif
1102
1103 // Select and pop a ready guy from worklist
1104 Node* n = select(block, worklist, ready_cnt, next_call, phi_cnt, recalc_pressure_nodes);
1105 block->map_node(n, phi_cnt++); // Schedule him next
1106
1107 if (OptoRegScheduling && block_size_threshold_ok) {
1108 n->add_flag(Node::Flag_is_scheduled);
1109
1110 // Now adjust the resister pressure with the node we selected
1111 if (!n->is_Phi()) {
1112 adjust_register_pressure(n, block, recalc_pressure_nodes, true);
1113 }
1114 }
1115
1116 #ifndef PRODUCT
1117 if (trace_opto_pipelining()) {
1118 tty->print("# select %d: %s", n->_idx, n->Name());
1119 tty->print(", latency:%d", get_latency_for_node(n));
1120 n->dump();
1121 if (Verbose) {
1122 tty->print("# ready list:");
1123 for( uint i=0; i<worklist.size(); i++ ) { // Inspect entire worklist
1124 Node *n = worklist[i]; // Get Node on worklist
1125 tty->print(" %d", n->_idx);
1126 }
1127 tty->cr();
1128 }
1129 }
1130
1131 #endif
1132 if( n->is_MachCall() ) {
1133 MachCallNode *mcall = n->as_MachCall();
1134 phi_cnt = sched_call(block, phi_cnt, worklist, ready_cnt, mcall, next_call);
1135 continue;
1136 }
1137
1138 if (n->is_Mach() && n->as_Mach()->has_call()) {
1139 RegMask regs;
1140 regs.Insert(_matcher.c_frame_pointer());
1141 regs.OR(n->out_RegMask());
1142
1143 MachProjNode *proj = new MachProjNode( n, 1, RegMask::Empty, MachProjNode::fat_proj );
1144 map_node_to_block(proj, block);
1145 block->insert_node(proj, phi_cnt++);
1146
1147 add_call_kills(proj, regs, _matcher._c_reg_save_policy, false);
1148 }
1149
1150 // Children are now all ready
1151 for (DUIterator_Fast i5max, i5 = n->fast_outs(i5max); i5 < i5max; i5++) {
1152 Node* m = n->fast_out(i5); // Get user
1153 if (get_block_for_node(m) != block) {
1154 continue;
1155 }
1156 if( m->is_Phi() ) continue;
1157 if (m->_idx >= max_idx) { // new node, skip it
1158 assert(m->is_MachProj() && n->is_Mach() && n->as_Mach()->has_call(), "unexpected node types");
1159 continue;
1160 }
1161 int m_cnt = ready_cnt.at(m->_idx) - 1;
1162 ready_cnt.at_put(m->_idx, m_cnt);
1163 if( m_cnt == 0 )
1164 worklist.push(m);
1165 }
1166 }
1167
1168 if( phi_cnt != block->end_idx() ) {
1169 // did not schedule all. Retry, Bailout, or Die
1170 if (C->subsume_loads() == true && !C->failing()) {
1171 // Retry with subsume_loads == false
1172 // If this is the first failure, the sentinel string will "stick"
1173 // to the Compile object, and the C2Compiler will see it and retry.
1174 C->record_failure(C2Compiler::retry_no_subsuming_loads());
1175 } else {
1176 assert(false, "graph should be schedulable");
1177 }
1178 // assert( phi_cnt == end_idx(), "did not schedule all" );
1179 return false;
1180 }
1181
1182 if (OptoRegScheduling && block_size_threshold_ok) {
1183 _regalloc->compute_exit_block_pressure(block);
1184 block->_reg_pressure = _regalloc->_sched_int_pressure.final_pressure();
1185 block->_freg_pressure = _regalloc->_sched_float_pressure.final_pressure();
1186 }
1187
1188 #ifndef PRODUCT
1189 if (trace_opto_pipelining()) {
1190 tty->print_cr("#");
1191 tty->print_cr("# after schedule_local");
1192 for (uint i = 0;i < block->number_of_nodes();i++) {
1193 tty->print("# ");
1194 block->get_node(i)->fast_dump();
1195 }
1196 tty->print_cr("# ");
1197
1198 if (OptoRegScheduling && block_size_threshold_ok) {
1199 tty->print_cr("# pressure info : %d", block->_pre_order);
1200 _regalloc->print_pressure_info(_regalloc->_sched_int_pressure, "int register info");
1201 _regalloc->print_pressure_info(_regalloc->_sched_float_pressure, "float register info");
1202 }
1203 tty->cr();
1204 }
1205 #endif
1206
1207 return true;
1208 }
1209
1210 //--------------------------catch_cleanup_fix_all_inputs-----------------------
catch_cleanup_fix_all_inputs(Node * use,Node * old_def,Node * new_def)1211 static void catch_cleanup_fix_all_inputs(Node *use, Node *old_def, Node *new_def) {
1212 for (uint l = 0; l < use->len(); l++) {
1213 if (use->in(l) == old_def) {
1214 if (l < use->req()) {
1215 use->set_req(l, new_def);
1216 } else {
1217 use->rm_prec(l);
1218 use->add_prec(new_def);
1219 l--;
1220 }
1221 }
1222 }
1223 }
1224
1225 //------------------------------catch_cleanup_find_cloned_def------------------
catch_cleanup_find_cloned_def(Block * use_blk,Node * def,Block * def_blk,int n_clone_idx)1226 Node* PhaseCFG::catch_cleanup_find_cloned_def(Block *use_blk, Node *def, Block *def_blk, int n_clone_idx) {
1227 assert( use_blk != def_blk, "Inter-block cleanup only");
1228
1229 // The use is some block below the Catch. Find and return the clone of the def
1230 // that dominates the use. If there is no clone in a dominating block, then
1231 // create a phi for the def in a dominating block.
1232
1233 // Find which successor block dominates this use. The successor
1234 // blocks must all be single-entry (from the Catch only; I will have
1235 // split blocks to make this so), hence they all dominate.
1236 while( use_blk->_dom_depth > def_blk->_dom_depth+1 )
1237 use_blk = use_blk->_idom;
1238
1239 // Find the successor
1240 Node *fixup = NULL;
1241
1242 uint j;
1243 for( j = 0; j < def_blk->_num_succs; j++ )
1244 if( use_blk == def_blk->_succs[j] )
1245 break;
1246
1247 if( j == def_blk->_num_succs ) {
1248 // Block at same level in dom-tree is not a successor. It needs a
1249 // PhiNode, the PhiNode uses from the def and IT's uses need fixup.
1250 Node_Array inputs = new Node_List(Thread::current()->resource_area());
1251 for(uint k = 1; k < use_blk->num_preds(); k++) {
1252 Block* block = get_block_for_node(use_blk->pred(k));
1253 inputs.map(k, catch_cleanup_find_cloned_def(block, def, def_blk, n_clone_idx));
1254 }
1255
1256 // Check to see if the use_blk already has an identical phi inserted.
1257 // If it exists, it will be at the first position since all uses of a
1258 // def are processed together.
1259 Node *phi = use_blk->get_node(1);
1260 if( phi->is_Phi() ) {
1261 fixup = phi;
1262 for (uint k = 1; k < use_blk->num_preds(); k++) {
1263 if (phi->in(k) != inputs[k]) {
1264 // Not a match
1265 fixup = NULL;
1266 break;
1267 }
1268 }
1269 }
1270
1271 // If an existing PhiNode was not found, make a new one.
1272 if (fixup == NULL) {
1273 Node *new_phi = PhiNode::make(use_blk->head(), def);
1274 use_blk->insert_node(new_phi, 1);
1275 map_node_to_block(new_phi, use_blk);
1276 for (uint k = 1; k < use_blk->num_preds(); k++) {
1277 new_phi->set_req(k, inputs[k]);
1278 }
1279 fixup = new_phi;
1280 }
1281
1282 } else {
1283 // Found the use just below the Catch. Make it use the clone.
1284 fixup = use_blk->get_node(n_clone_idx);
1285 }
1286
1287 return fixup;
1288 }
1289
1290 //--------------------------catch_cleanup_intra_block--------------------------
1291 // Fix all input edges in use that reference "def". The use is in the same
1292 // block as the def and both have been cloned in each successor block.
catch_cleanup_intra_block(Node * use,Node * def,Block * blk,int beg,int n_clone_idx)1293 static void catch_cleanup_intra_block(Node *use, Node *def, Block *blk, int beg, int n_clone_idx) {
1294
1295 // Both the use and def have been cloned. For each successor block,
1296 // get the clone of the use, and make its input the clone of the def
1297 // found in that block.
1298
1299 uint use_idx = blk->find_node(use);
1300 uint offset_idx = use_idx - beg;
1301 for( uint k = 0; k < blk->_num_succs; k++ ) {
1302 // Get clone in each successor block
1303 Block *sb = blk->_succs[k];
1304 Node *clone = sb->get_node(offset_idx+1);
1305 assert( clone->Opcode() == use->Opcode(), "" );
1306
1307 // Make use-clone reference the def-clone
1308 catch_cleanup_fix_all_inputs(clone, def, sb->get_node(n_clone_idx));
1309 }
1310 }
1311
1312 //------------------------------catch_cleanup_inter_block---------------------
1313 // Fix all input edges in use that reference "def". The use is in a different
1314 // block than the def.
catch_cleanup_inter_block(Node * use,Block * use_blk,Node * def,Block * def_blk,int n_clone_idx)1315 void PhaseCFG::catch_cleanup_inter_block(Node *use, Block *use_blk, Node *def, Block *def_blk, int n_clone_idx) {
1316 if( !use_blk ) return; // Can happen if the use is a precedence edge
1317
1318 Node *new_def = catch_cleanup_find_cloned_def(use_blk, def, def_blk, n_clone_idx);
1319 catch_cleanup_fix_all_inputs(use, def, new_def);
1320 }
1321
1322 //------------------------------call_catch_cleanup-----------------------------
1323 // If we inserted any instructions between a Call and his CatchNode,
1324 // clone the instructions on all paths below the Catch.
call_catch_cleanup(Block * block)1325 void PhaseCFG::call_catch_cleanup(Block* block) {
1326
1327 // End of region to clone
1328 uint end = block->end_idx();
1329 if( !block->get_node(end)->is_Catch() ) return;
1330 // Start of region to clone
1331 uint beg = end;
1332 while(!block->get_node(beg-1)->is_MachProj() ||
1333 !block->get_node(beg-1)->in(0)->is_MachCall() ) {
1334 beg--;
1335 assert(beg > 0,"Catch cleanup walking beyond block boundary");
1336 }
1337 // Range of inserted instructions is [beg, end)
1338 if( beg == end ) return;
1339
1340 // Clone along all Catch output paths. Clone area between the 'beg' and
1341 // 'end' indices.
1342 for( uint i = 0; i < block->_num_succs; i++ ) {
1343 Block *sb = block->_succs[i];
1344 // Clone the entire area; ignoring the edge fixup for now.
1345 for( uint j = end; j > beg; j-- ) {
1346 Node *clone = block->get_node(j-1)->clone();
1347 sb->insert_node(clone, 1);
1348 map_node_to_block(clone, sb);
1349 if (clone->needs_anti_dependence_check()) {
1350 insert_anti_dependences(sb, clone);
1351 }
1352 }
1353 }
1354
1355
1356 // Fixup edges. Check the def-use info per cloned Node
1357 for(uint i2 = beg; i2 < end; i2++ ) {
1358 uint n_clone_idx = i2-beg+1; // Index of clone of n in each successor block
1359 Node *n = block->get_node(i2); // Node that got cloned
1360 // Need DU safe iterator because of edge manipulation in calls.
1361 Unique_Node_List *out = new Unique_Node_List(Thread::current()->resource_area());
1362 for (DUIterator_Fast j1max, j1 = n->fast_outs(j1max); j1 < j1max; j1++) {
1363 out->push(n->fast_out(j1));
1364 }
1365 uint max = out->size();
1366 for (uint j = 0; j < max; j++) {// For all users
1367 Node *use = out->pop();
1368 Block *buse = get_block_for_node(use);
1369 if( use->is_Phi() ) {
1370 for( uint k = 1; k < use->req(); k++ )
1371 if( use->in(k) == n ) {
1372 Block* b = get_block_for_node(buse->pred(k));
1373 Node *fixup = catch_cleanup_find_cloned_def(b, n, block, n_clone_idx);
1374 use->set_req(k, fixup);
1375 }
1376 } else {
1377 if (block == buse) {
1378 catch_cleanup_intra_block(use, n, block, beg, n_clone_idx);
1379 } else {
1380 catch_cleanup_inter_block(use, buse, n, block, n_clone_idx);
1381 }
1382 }
1383 } // End for all users
1384
1385 } // End of for all Nodes in cloned area
1386
1387 // Remove the now-dead cloned ops
1388 for(uint i3 = beg; i3 < end; i3++ ) {
1389 block->get_node(beg)->disconnect_inputs(NULL, C);
1390 block->remove_node(beg);
1391 }
1392
1393 // If the successor blocks have a CreateEx node, move it back to the top
1394 for (uint i4 = 0; i4 < block->_num_succs; i4++) {
1395 Block *sb = block->_succs[i4];
1396 uint new_cnt = end - beg;
1397 // Remove any newly created, but dead, nodes by traversing their schedule
1398 // backwards. Here, a dead node is a node whose only outputs (if any) are
1399 // unused projections.
1400 for (uint j = new_cnt; j > 0; j--) {
1401 Node *n = sb->get_node(j);
1402 // Individual projections are examined together with all siblings when
1403 // their parent is visited.
1404 if (n->is_Proj()) {
1405 continue;
1406 }
1407 bool dead = true;
1408 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1409 Node* out = n->fast_out(i);
1410 // n is live if it has a non-projection output or a used projection.
1411 if (!out->is_Proj() || out->outcnt() > 0) {
1412 dead = false;
1413 break;
1414 }
1415 }
1416 if (dead) {
1417 // n's only outputs (if any) are unused projections scheduled next to n
1418 // (see PhaseCFG::select()). Remove these projections backwards.
1419 for (uint k = j + n->outcnt(); k > j; k--) {
1420 Node* proj = sb->get_node(k);
1421 assert(proj->is_Proj() && proj->in(0) == n,
1422 "projection should correspond to dead node");
1423 proj->disconnect_inputs(NULL, C);
1424 sb->remove_node(k);
1425 new_cnt--;
1426 }
1427 // Now remove the node itself.
1428 n->disconnect_inputs(NULL, C);
1429 sb->remove_node(j);
1430 new_cnt--;
1431 }
1432 }
1433 // If any newly created nodes remain, move the CreateEx node to the top
1434 if (new_cnt > 0) {
1435 Node *cex = sb->get_node(1+new_cnt);
1436 if( cex->is_Mach() && cex->as_Mach()->ideal_Opcode() == Op_CreateEx ) {
1437 sb->remove_node(1+new_cnt);
1438 sb->insert_node(cex, 1);
1439 }
1440 }
1441 }
1442 }
1443