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