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/assembler.inline.hpp" 26 #include "code/compiledIC.hpp" 27 #include "code/debugInfo.hpp" 28 #include "code/debugInfoRec.hpp" 29 #include "compiler/compileBroker.hpp" 30 #include "compiler/compilerDirectives.hpp" 31 #include "compiler/disassembler.hpp" 32 #include "compiler/oopMap.hpp" 33 #include "gc/shared/barrierSet.hpp" 34 #include "gc/shared/gc_globals.hpp" 35 #include "gc/shared/c2/barrierSetC2.hpp" 36 #include "memory/allocation.hpp" 37 #include "opto/ad.hpp" 38 #include "opto/block.hpp" 39 #include "opto/c2compiler.hpp" 40 #include "opto/c2_MacroAssembler.hpp" 41 #include "opto/callnode.hpp" 42 #include "opto/cfgnode.hpp" 43 #include "opto/locknode.hpp" 44 #include "opto/machnode.hpp" 45 #include "opto/node.hpp" 46 #include "opto/optoreg.hpp" 47 #include "opto/output.hpp" 48 #include "opto/regalloc.hpp" 49 #include "opto/type.hpp" 50 #include "runtime/sharedRuntime.hpp" 51 #include "utilities/macros.hpp" 52 #include "utilities/powerOfTwo.hpp" 53 #include "utilities/xmlstream.hpp" 54 55 #ifndef PRODUCT 56 #define DEBUG_ARG(x) , x 57 #else 58 #define DEBUG_ARG(x) 59 #endif 60 61 //------------------------------Scheduling---------------------------------- 62 // This class contains all the information necessary to implement instruction 63 // scheduling and bundling. 64 class Scheduling { 65 66 private: 67 // Arena to use 68 Arena *_arena; 69 70 // Control-Flow Graph info 71 PhaseCFG *_cfg; 72 73 // Register Allocation info 74 PhaseRegAlloc *_regalloc; 75 76 // Number of nodes in the method 77 uint _node_bundling_limit; 78 79 // List of scheduled nodes. Generated in reverse order 80 Node_List _scheduled; 81 82 // List of nodes currently available for choosing for scheduling 83 Node_List _available; 84 85 // For each instruction beginning a bundle, the number of following 86 // nodes to be bundled with it. 87 Bundle *_node_bundling_base; 88 89 // Mapping from register to Node 90 Node_List _reg_node; 91 92 // Free list for pinch nodes. 93 Node_List _pinch_free_list; 94 95 // Number of uses of this node within the containing basic block. 96 short *_uses; 97 98 // Schedulable portion of current block. Skips Region/Phi/CreateEx up 99 // front, branch+proj at end. Also skips Catch/CProj (same as 100 // branch-at-end), plus just-prior exception-throwing call. 101 uint _bb_start, _bb_end; 102 103 // Latency from the end of the basic block as scheduled 104 unsigned short *_current_latency; 105 106 // Remember the next node 107 Node *_next_node; 108 109 // Use this for an unconditional branch delay slot 110 Node *_unconditional_delay_slot; 111 112 // Pointer to a Nop 113 MachNopNode *_nop; 114 115 // Length of the current bundle, in instructions 116 uint _bundle_instr_count; 117 118 // Current Cycle number, for computing latencies and bundling 119 uint _bundle_cycle_number; 120 121 // Bundle information 122 Pipeline_Use_Element _bundle_use_elements[resource_count]; 123 Pipeline_Use _bundle_use; 124 125 // Dump the available list 126 void dump_available() const; 127 128 public: 129 Scheduling(Arena *arena, Compile &compile); 130 131 // Destructor 132 NOT_PRODUCT( ~Scheduling(); ) 133 134 // Step ahead "i" cycles 135 void step(uint i); 136 137 // Step ahead 1 cycle, and clear the bundle state (for example, 138 // at a branch target) 139 void step_and_clear(); 140 141 Bundle* node_bundling(const Node *n) { 142 assert(valid_bundle_info(n), "oob"); 143 return (&_node_bundling_base[n->_idx]); 144 } 145 146 bool valid_bundle_info(const Node *n) const { 147 return (_node_bundling_limit > n->_idx); 148 } 149 150 bool starts_bundle(const Node *n) const { 151 return (_node_bundling_limit > n->_idx && _node_bundling_base[n->_idx].starts_bundle()); 152 } 153 154 // Do the scheduling 155 void DoScheduling(); 156 157 // Compute the register antidependencies within a basic block 158 void ComputeRegisterAntidependencies(Block *bb); 159 void verify_do_def( Node *n, OptoReg::Name def, const char *msg ); 160 void verify_good_schedule( Block *b, const char *msg ); 161 void anti_do_def( Block *b, Node *def, OptoReg::Name def_reg, int is_def ); 162 void anti_do_use( Block *b, Node *use, OptoReg::Name use_reg ); 163 164 // Add a node to the current bundle 165 void AddNodeToBundle(Node *n, const Block *bb); 166 167 // Return an integer less than, equal to, or greater than zero 168 // if the stack offset of the first argument is respectively 169 // less than, equal to, or greater than the second. 170 int compare_two_spill_nodes(Node* first, Node* second); 171 172 // Add a node to the list of available nodes 173 void AddNodeToAvailableList(Node *n); 174 175 // Compute the local use count for the nodes in a block, and compute 176 // the list of instructions with no uses in the block as available 177 void ComputeUseCount(const Block *bb); 178 179 // Choose an instruction from the available list to add to the bundle 180 Node * ChooseNodeToBundle(); 181 182 // See if this Node fits into the currently accumulating bundle 183 bool NodeFitsInBundle(Node *n); 184 185 // Decrement the use count for a node 186 void DecrementUseCounts(Node *n, const Block *bb); 187 188 // Garbage collect pinch nodes for reuse by other blocks. 189 void garbage_collect_pinch_nodes(); 190 // Clean up a pinch node for reuse (helper for above). 191 void cleanup_pinch( Node *pinch ); 192 193 // Information for statistics gathering 194 #ifndef PRODUCT 195 private: 196 // Gather information on size of nops relative to total 197 uint _branches, _unconditional_delays; 198 199 static uint _total_nop_size, _total_method_size; 200 static uint _total_branches, _total_unconditional_delays; 201 static uint _total_instructions_per_bundle[Pipeline::_max_instrs_per_cycle+1]; 202 203 public: 204 static void print_statistics(); 205 206 static void increment_instructions_per_bundle(uint i) { 207 _total_instructions_per_bundle[i]++; 208 } 209 210 static void increment_nop_size(uint s) { 211 _total_nop_size += s; 212 } 213 214 static void increment_method_size(uint s) { 215 _total_method_size += s; 216 } 217 #endif 218 219 }; 220 221 PhaseOutput::PhaseOutput() 222 : Phase(Phase::Output), 223 _code_buffer("Compile::Fill_buffer"), 224 _first_block_size(0), 225 _handler_table(), 226 _inc_table(), 227 _stub_list(), 228 _oop_map_set(nullptr), 229 _scratch_buffer_blob(nullptr), 230 _scratch_locs_memory(nullptr), 231 _scratch_const_size(-1), 232 _in_scratch_emit_size(false), 233 _frame_slots(0), 234 _code_offsets(), 235 _node_bundling_limit(0), 236 _node_bundling_base(nullptr), 237 _orig_pc_slot(0), 238 _orig_pc_slot_offset_in_bytes(0), 239 _buf_sizes(), 240 _block(nullptr), 241 _index(0) { 242 C->set_output(this); 243 if (C->stub_name() == nullptr) { 244 int fixed_slots = C->fixed_slots(); 245 if (C->needs_stack_repair()) { 246 fixed_slots -= 2; 247 } 248 // TODO 8284443 Only reserve extra slot if needed 249 if (InlineTypeReturnedAsFields) { 250 fixed_slots -= 2; 251 } 252 _orig_pc_slot = fixed_slots - (sizeof(address) / VMRegImpl::stack_slot_size); 253 } 254 } 255 256 PhaseOutput::~PhaseOutput() { 257 C->set_output(nullptr); 258 if (_scratch_buffer_blob != nullptr) { 259 BufferBlob::free(_scratch_buffer_blob); 260 } 261 } 262 263 void PhaseOutput::perform_mach_node_analysis() { 264 // Late barrier analysis must be done after schedule and bundle 265 // Otherwise liveness based spilling will fail 266 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 267 bs->late_barrier_analysis(); 268 269 pd_perform_mach_node_analysis(); 270 271 C->print_method(CompilerPhaseType::PHASE_MACH_ANALYSIS, 3); 272 } 273 274 // Convert Nodes to instruction bits and pass off to the VM 275 void PhaseOutput::Output() { 276 // RootNode goes 277 assert( C->cfg()->get_root_block()->number_of_nodes() == 0, "" ); 278 279 // The number of new nodes (mostly MachNop) is proportional to 280 // the number of java calls and inner loops which are aligned. 281 if ( C->check_node_count((NodeLimitFudgeFactor + C->java_calls()*3 + 282 C->inner_loops()*(OptoLoopAlignment-1)), 283 "out of nodes before code generation" ) ) { 284 return; 285 } 286 // Make sure I can find the Start Node 287 Block *entry = C->cfg()->get_block(1); 288 Block *broot = C->cfg()->get_root_block(); 289 290 const StartNode *start = entry->head()->as_Start(); 291 292 // Replace StartNode with prolog 293 Label verified_entry; 294 MachPrologNode* prolog = new MachPrologNode(&verified_entry); 295 entry->map_node(prolog, 0); 296 C->cfg()->map_node_to_block(prolog, entry); 297 C->cfg()->unmap_node_from_block(start); // start is no longer in any block 298 299 // Virtual methods need an unverified entry point 300 if (C->is_osr_compilation()) { 301 if (PoisonOSREntry) { 302 // TODO: Should use a ShouldNotReachHereNode... 303 C->cfg()->insert( broot, 0, new MachBreakpointNode() ); 304 } 305 } else { 306 if (C->method()) { 307 if (C->method()->has_scalarized_args()) { 308 // Add entry point to unpack all inline type arguments 309 C->cfg()->insert(broot, 0, new MachVEPNode(&verified_entry, /* verified */ true, /* receiver_only */ false)); 310 if (!C->method()->is_static()) { 311 // Add verified/unverified entry points to only unpack inline type receiver at interface calls 312 C->cfg()->insert(broot, 0, new MachVEPNode(&verified_entry, /* verified */ false, /* receiver_only */ false)); 313 C->cfg()->insert(broot, 0, new MachVEPNode(&verified_entry, /* verified */ true, /* receiver_only */ true)); 314 C->cfg()->insert(broot, 0, new MachVEPNode(&verified_entry, /* verified */ false, /* receiver_only */ true)); 315 } 316 } else if (!C->method()->is_static()) { 317 // Insert unvalidated entry point 318 C->cfg()->insert(broot, 0, new MachUEPNode()); 319 } 320 } 321 } 322 323 // Break before main entry point 324 if ((C->method() && C->directive()->BreakAtExecuteOption) || 325 (OptoBreakpoint && C->is_method_compilation()) || 326 (OptoBreakpointOSR && C->is_osr_compilation()) || 327 (OptoBreakpointC2R && !C->method()) ) { 328 // checking for C->method() means that OptoBreakpoint does not apply to 329 // runtime stubs or frame converters 330 C->cfg()->insert( entry, 1, new MachBreakpointNode() ); 331 } 332 333 // Insert epilogs before every return 334 for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) { 335 Block* block = C->cfg()->get_block(i); 336 if (!block->is_connector() && block->non_connector_successor(0) == C->cfg()->get_root_block()) { // Found a program exit point? 337 Node* m = block->end(); 338 if (m->is_Mach() && m->as_Mach()->ideal_Opcode() != Op_Halt) { 339 MachEpilogNode* epilog = new MachEpilogNode(m->as_Mach()->ideal_Opcode() == Op_Return); 340 block->add_inst(epilog); 341 C->cfg()->map_node_to_block(epilog, block); 342 } 343 } 344 } 345 346 // Keeper of sizing aspects 347 _buf_sizes = BufferSizingData(); 348 349 // Initialize code buffer 350 estimate_buffer_size(_buf_sizes._const); 351 if (C->failing()) return; 352 353 // Pre-compute the length of blocks and replace 354 // long branches with short if machine supports it. 355 // Must be done before ScheduleAndBundle due to SPARC delay slots 356 uint* blk_starts = NEW_RESOURCE_ARRAY(uint, C->cfg()->number_of_blocks() + 1); 357 blk_starts[0] = 0; 358 shorten_branches(blk_starts); 359 360 if (!C->is_osr_compilation() && C->has_scalarized_args()) { 361 // Compute the offsets of the entry points required by the inline type calling convention 362 if (!C->method()->is_static()) { 363 // We have entries at the beginning of the method, implemented by the first 4 nodes. 364 // Entry (unverified) @ offset 0 365 // Verified_Inline_Entry_RO 366 // Inline_Entry (unverified) 367 // Verified_Inline_Entry 368 uint offset = 0; 369 _code_offsets.set_value(CodeOffsets::Entry, offset); 370 371 offset += ((MachVEPNode*)broot->get_node(0))->size(C->regalloc()); 372 _code_offsets.set_value(CodeOffsets::Verified_Inline_Entry_RO, offset); 373 374 offset += ((MachVEPNode*)broot->get_node(1))->size(C->regalloc()); 375 _code_offsets.set_value(CodeOffsets::Inline_Entry, offset); 376 377 offset += ((MachVEPNode*)broot->get_node(2))->size(C->regalloc()); 378 _code_offsets.set_value(CodeOffsets::Verified_Inline_Entry, offset); 379 } else { 380 _code_offsets.set_value(CodeOffsets::Entry, -1); // will be patched later 381 _code_offsets.set_value(CodeOffsets::Verified_Inline_Entry, 0); 382 } 383 } 384 385 ScheduleAndBundle(); 386 if (C->failing()) { 387 return; 388 } 389 390 perform_mach_node_analysis(); 391 392 // Complete sizing of codebuffer 393 CodeBuffer* cb = init_buffer(); 394 if (cb == nullptr || C->failing()) { 395 return; 396 } 397 398 BuildOopMaps(); 399 400 if (C->failing()) { 401 return; 402 } 403 404 C2_MacroAssembler masm(cb); 405 fill_buffer(&masm, blk_starts); 406 } 407 408 bool PhaseOutput::need_stack_bang(int frame_size_in_bytes) const { 409 // Determine if we need to generate a stack overflow check. 410 // Do it if the method is not a stub function and 411 // has java calls or has frame size > vm_page_size/8. 412 // The debug VM checks that deoptimization doesn't trigger an 413 // unexpected stack overflow (compiled method stack banging should 414 // guarantee it doesn't happen) so we always need the stack bang in 415 // a debug VM. 416 return (C->stub_function() == nullptr && 417 (C->has_java_calls() || frame_size_in_bytes > (int)(os::vm_page_size())>>3 418 DEBUG_ONLY(|| true))); 419 } 420 421 bool PhaseOutput::need_register_stack_bang() const { 422 // Determine if we need to generate a register stack overflow check. 423 // This is only used on architectures which have split register 424 // and memory stacks. 425 // Bang if the method is not a stub function and has java calls 426 return (C->stub_function() == nullptr && C->has_java_calls()); 427 } 428 429 430 // Compute the size of first NumberOfLoopInstrToAlign instructions at the top 431 // of a loop. When aligning a loop we need to provide enough instructions 432 // in cpu's fetch buffer to feed decoders. The loop alignment could be 433 // avoided if we have enough instructions in fetch buffer at the head of a loop. 434 // By default, the size is set to 999999 by Block's constructor so that 435 // a loop will be aligned if the size is not reset here. 436 // 437 // Note: Mach instructions could contain several HW instructions 438 // so the size is estimated only. 439 // 440 void PhaseOutput::compute_loop_first_inst_sizes() { 441 // The next condition is used to gate the loop alignment optimization. 442 // Don't aligned a loop if there are enough instructions at the head of a loop 443 // or alignment padding is larger then MaxLoopPad. By default, MaxLoopPad 444 // is equal to OptoLoopAlignment-1 except on new Intel cpus, where it is 445 // equal to 11 bytes which is the largest address NOP instruction. 446 if (MaxLoopPad < OptoLoopAlignment - 1) { 447 uint last_block = C->cfg()->number_of_blocks() - 1; 448 for (uint i = 1; i <= last_block; i++) { 449 Block* block = C->cfg()->get_block(i); 450 // Check the first loop's block which requires an alignment. 451 if (block->loop_alignment() > (uint)relocInfo::addr_unit()) { 452 uint sum_size = 0; 453 uint inst_cnt = NumberOfLoopInstrToAlign; 454 inst_cnt = block->compute_first_inst_size(sum_size, inst_cnt, C->regalloc()); 455 456 // Check subsequent fallthrough blocks if the loop's first 457 // block(s) does not have enough instructions. 458 Block *nb = block; 459 while(inst_cnt > 0 && 460 i < last_block && 461 !C->cfg()->get_block(i + 1)->has_loop_alignment() && 462 !nb->has_successor(block)) { 463 i++; 464 nb = C->cfg()->get_block(i); 465 inst_cnt = nb->compute_first_inst_size(sum_size, inst_cnt, C->regalloc()); 466 } // while( inst_cnt > 0 && i < last_block ) 467 468 block->set_first_inst_size(sum_size); 469 } // f( b->head()->is_Loop() ) 470 } // for( i <= last_block ) 471 } // if( MaxLoopPad < OptoLoopAlignment-1 ) 472 } 473 474 // The architecture description provides short branch variants for some long 475 // branch instructions. Replace eligible long branches with short branches. 476 void PhaseOutput::shorten_branches(uint* blk_starts) { 477 478 Compile::TracePhase tp(_t_shortenBranches); 479 480 // Compute size of each block, method size, and relocation information size 481 uint nblocks = C->cfg()->number_of_blocks(); 482 483 uint* jmp_offset = NEW_RESOURCE_ARRAY(uint,nblocks); 484 uint* jmp_size = NEW_RESOURCE_ARRAY(uint,nblocks); 485 int* jmp_nidx = NEW_RESOURCE_ARRAY(int ,nblocks); 486 487 // Collect worst case block paddings 488 int* block_worst_case_pad = NEW_RESOURCE_ARRAY(int, nblocks); 489 memset(block_worst_case_pad, 0, nblocks * sizeof(int)); 490 491 DEBUG_ONLY( uint *jmp_target = NEW_RESOURCE_ARRAY(uint,nblocks); ) 492 DEBUG_ONLY( uint *jmp_rule = NEW_RESOURCE_ARRAY(uint,nblocks); ) 493 494 bool has_short_branch_candidate = false; 495 496 // Initialize the sizes to 0 497 int code_size = 0; // Size in bytes of generated code 498 int stub_size = 0; // Size in bytes of all stub entries 499 // Size in bytes of all relocation entries, including those in local stubs. 500 // Start with 2-bytes of reloc info for the unvalidated entry point 501 int reloc_size = 1; // Number of relocation entries 502 503 // Make three passes. The first computes pessimistic blk_starts, 504 // relative jmp_offset and reloc_size information. The second performs 505 // short branch substitution using the pessimistic sizing. The 506 // third inserts nops where needed. 507 508 // Step one, perform a pessimistic sizing pass. 509 uint last_call_adr = max_juint; 510 uint last_avoid_back_to_back_adr = max_juint; 511 uint nop_size = (new MachNopNode())->size(C->regalloc()); 512 for (uint i = 0; i < nblocks; i++) { // For all blocks 513 Block* block = C->cfg()->get_block(i); 514 _block = block; 515 516 // During short branch replacement, we store the relative (to blk_starts) 517 // offset of jump in jmp_offset, rather than the absolute offset of jump. 518 // This is so that we do not need to recompute sizes of all nodes when 519 // we compute correct blk_starts in our next sizing pass. 520 jmp_offset[i] = 0; 521 jmp_size[i] = 0; 522 jmp_nidx[i] = -1; 523 DEBUG_ONLY( jmp_target[i] = 0; ) 524 DEBUG_ONLY( jmp_rule[i] = 0; ) 525 526 // Sum all instruction sizes to compute block size 527 uint last_inst = block->number_of_nodes(); 528 uint blk_size = 0; 529 for (uint j = 0; j < last_inst; j++) { 530 _index = j; 531 Node* nj = block->get_node(_index); 532 // Handle machine instruction nodes 533 if (nj->is_Mach()) { 534 MachNode* mach = nj->as_Mach(); 535 blk_size += (mach->alignment_required() - 1) * relocInfo::addr_unit(); // assume worst case padding 536 reloc_size += mach->reloc(); 537 if (mach->is_MachCall()) { 538 // add size information for trampoline stub 539 // class CallStubImpl is platform-specific and defined in the *.ad files. 540 stub_size += CallStubImpl::size_call_trampoline(); 541 reloc_size += CallStubImpl::reloc_call_trampoline(); 542 543 MachCallNode *mcall = mach->as_MachCall(); 544 // This destination address is NOT PC-relative 545 546 if (mcall->entry_point() != nullptr) { 547 mcall->method_set((intptr_t)mcall->entry_point()); 548 } 549 550 if (mcall->is_MachCallJava() && mcall->as_MachCallJava()->_method) { 551 stub_size += CompiledDirectCall::to_interp_stub_size(); 552 reloc_size += CompiledDirectCall::reloc_to_interp_stub(); 553 } 554 } else if (mach->is_MachSafePoint()) { 555 // If call/safepoint are adjacent, account for possible 556 // nop to disambiguate the two safepoints. 557 // ScheduleAndBundle() can rearrange nodes in a block, 558 // check for all offsets inside this block. 559 if (last_call_adr >= blk_starts[i]) { 560 blk_size += nop_size; 561 } 562 } 563 if (mach->avoid_back_to_back(MachNode::AVOID_BEFORE)) { 564 // Nop is inserted between "avoid back to back" instructions. 565 // ScheduleAndBundle() can rearrange nodes in a block, 566 // check for all offsets inside this block. 567 if (last_avoid_back_to_back_adr >= blk_starts[i]) { 568 blk_size += nop_size; 569 } 570 } 571 if (mach->may_be_short_branch()) { 572 if (!nj->is_MachBranch()) { 573 #ifndef PRODUCT 574 nj->dump(3); 575 #endif 576 Unimplemented(); 577 } 578 assert(jmp_nidx[i] == -1, "block should have only one branch"); 579 jmp_offset[i] = blk_size; 580 jmp_size[i] = nj->size(C->regalloc()); 581 jmp_nidx[i] = j; 582 has_short_branch_candidate = true; 583 } 584 } 585 blk_size += nj->size(C->regalloc()); 586 // Remember end of call offset 587 if (nj->is_MachCall() && !nj->is_MachCallLeaf()) { 588 last_call_adr = blk_starts[i]+blk_size; 589 } 590 // Remember end of avoid_back_to_back offset 591 if (nj->is_Mach() && nj->as_Mach()->avoid_back_to_back(MachNode::AVOID_AFTER)) { 592 last_avoid_back_to_back_adr = blk_starts[i]+blk_size; 593 } 594 } 595 596 // When the next block starts a loop, we may insert pad NOP 597 // instructions. Since we cannot know our future alignment, 598 // assume the worst. 599 if (i < nblocks - 1) { 600 Block* nb = C->cfg()->get_block(i + 1); 601 int max_loop_pad = nb->code_alignment()-relocInfo::addr_unit(); 602 if (max_loop_pad > 0) { 603 assert(is_power_of_2(max_loop_pad+relocInfo::addr_unit()), ""); 604 // Adjust last_call_adr and/or last_avoid_back_to_back_adr. 605 // If either is the last instruction in this block, bump by 606 // max_loop_pad in lock-step with blk_size, so sizing 607 // calculations in subsequent blocks still can conservatively 608 // detect that it may the last instruction in this block. 609 if (last_call_adr == blk_starts[i]+blk_size) { 610 last_call_adr += max_loop_pad; 611 } 612 if (last_avoid_back_to_back_adr == blk_starts[i]+blk_size) { 613 last_avoid_back_to_back_adr += max_loop_pad; 614 } 615 blk_size += max_loop_pad; 616 block_worst_case_pad[i + 1] = max_loop_pad; 617 } 618 } 619 620 // Save block size; update total method size 621 blk_starts[i+1] = blk_starts[i]+blk_size; 622 } 623 624 // Step two, replace eligible long jumps. 625 bool progress = true; 626 uint last_may_be_short_branch_adr = max_juint; 627 while (has_short_branch_candidate && progress) { 628 progress = false; 629 has_short_branch_candidate = false; 630 int adjust_block_start = 0; 631 for (uint i = 0; i < nblocks; i++) { 632 Block* block = C->cfg()->get_block(i); 633 int idx = jmp_nidx[i]; 634 MachNode* mach = (idx == -1) ? nullptr: block->get_node(idx)->as_Mach(); 635 if (mach != nullptr && mach->may_be_short_branch()) { 636 #ifdef ASSERT 637 assert(jmp_size[i] > 0 && mach->is_MachBranch(), "sanity"); 638 int j; 639 // Find the branch; ignore trailing NOPs. 640 for (j = block->number_of_nodes()-1; j>=0; j--) { 641 Node* n = block->get_node(j); 642 if (!n->is_Mach() || n->as_Mach()->ideal_Opcode() != Op_Con) 643 break; 644 } 645 assert(j >= 0 && j == idx && block->get_node(j) == (Node*)mach, "sanity"); 646 #endif 647 int br_size = jmp_size[i]; 648 int br_offs = blk_starts[i] + jmp_offset[i]; 649 650 // This requires the TRUE branch target be in succs[0] 651 uint bnum = block->non_connector_successor(0)->_pre_order; 652 int offset = blk_starts[bnum] - br_offs; 653 if (bnum > i) { // adjust following block's offset 654 offset -= adjust_block_start; 655 } 656 657 // This block can be a loop header, account for the padding 658 // in the previous block. 659 int block_padding = block_worst_case_pad[i]; 660 assert(i == 0 || block_padding == 0 || br_offs >= block_padding, "Should have at least a padding on top"); 661 // In the following code a nop could be inserted before 662 // the branch which will increase the backward distance. 663 bool needs_padding = ((uint)(br_offs - block_padding) == last_may_be_short_branch_adr); 664 assert(!needs_padding || jmp_offset[i] == 0, "padding only branches at the beginning of block"); 665 666 if (needs_padding && offset <= 0) 667 offset -= nop_size; 668 669 if (C->matcher()->is_short_branch_offset(mach->rule(), br_size, offset)) { 670 // We've got a winner. Replace this branch. 671 MachNode* replacement = mach->as_MachBranch()->short_branch_version(); 672 673 // Update the jmp_size. 674 int new_size = replacement->size(C->regalloc()); 675 int diff = br_size - new_size; 676 assert(diff >= (int)nop_size, "short_branch size should be smaller"); 677 // Conservatively take into account padding between 678 // avoid_back_to_back branches. Previous branch could be 679 // converted into avoid_back_to_back branch during next 680 // rounds. 681 if (needs_padding && replacement->avoid_back_to_back(MachNode::AVOID_BEFORE)) { 682 jmp_offset[i] += nop_size; 683 diff -= nop_size; 684 } 685 adjust_block_start += diff; 686 block->map_node(replacement, idx); 687 mach->subsume_by(replacement, C); 688 mach = replacement; 689 progress = true; 690 691 jmp_size[i] = new_size; 692 DEBUG_ONLY( jmp_target[i] = bnum; ); 693 DEBUG_ONLY( jmp_rule[i] = mach->rule(); ); 694 } else { 695 // The jump distance is not short, try again during next iteration. 696 has_short_branch_candidate = true; 697 } 698 } // (mach->may_be_short_branch()) 699 if (mach != nullptr && (mach->may_be_short_branch() || 700 mach->avoid_back_to_back(MachNode::AVOID_AFTER))) { 701 last_may_be_short_branch_adr = blk_starts[i] + jmp_offset[i] + jmp_size[i]; 702 } 703 blk_starts[i+1] -= adjust_block_start; 704 } 705 } 706 707 #ifdef ASSERT 708 for (uint i = 0; i < nblocks; i++) { // For all blocks 709 if (jmp_target[i] != 0) { 710 int br_size = jmp_size[i]; 711 int offset = blk_starts[jmp_target[i]]-(blk_starts[i] + jmp_offset[i]); 712 if (!C->matcher()->is_short_branch_offset(jmp_rule[i], br_size, offset)) { 713 tty->print_cr("target (%d) - jmp_offset(%d) = offset (%d), jump_size(%d), jmp_block B%d, target_block B%d", blk_starts[jmp_target[i]], blk_starts[i] + jmp_offset[i], offset, br_size, i, jmp_target[i]); 714 } 715 assert(C->matcher()->is_short_branch_offset(jmp_rule[i], br_size, offset), "Displacement too large for short jmp"); 716 } 717 } 718 #endif 719 720 // Step 3, compute the offsets of all blocks, will be done in fill_buffer() 721 // after ScheduleAndBundle(). 722 723 // ------------------ 724 // Compute size for code buffer 725 code_size = blk_starts[nblocks]; 726 727 // Relocation records 728 reloc_size += 1; // Relo entry for exception handler 729 730 // Adjust reloc_size to number of record of relocation info 731 // Min is 2 bytes, max is probably 6 or 8, with a tax up to 25% for 732 // a relocation index. 733 // The CodeBuffer will expand the locs array if this estimate is too low. 734 reloc_size *= 10 / sizeof(relocInfo); 735 736 _buf_sizes._reloc = reloc_size; 737 _buf_sizes._code = code_size; 738 _buf_sizes._stub = stub_size; 739 } 740 741 //------------------------------FillLocArray----------------------------------- 742 // Create a bit of debug info and append it to the array. The mapping is from 743 // Java local or expression stack to constant, register or stack-slot. For 744 // doubles, insert 2 mappings and return 1 (to tell the caller that the next 745 // entry has been taken care of and caller should skip it). 746 static LocationValue *new_loc_value( PhaseRegAlloc *ra, OptoReg::Name regnum, Location::Type l_type ) { 747 // This should never have accepted Bad before 748 assert(OptoReg::is_valid(regnum), "location must be valid"); 749 return (OptoReg::is_reg(regnum)) 750 ? new LocationValue(Location::new_reg_loc(l_type, OptoReg::as_VMReg(regnum)) ) 751 : new LocationValue(Location::new_stk_loc(l_type, ra->reg2offset(regnum))); 752 } 753 754 755 ObjectValue* 756 PhaseOutput::sv_for_node_id(GrowableArray<ScopeValue*> *objs, int id) { 757 for (int i = 0; i < objs->length(); i++) { 758 assert(objs->at(i)->is_object(), "corrupt object cache"); 759 ObjectValue* sv = objs->at(i)->as_ObjectValue(); 760 if (sv->id() == id) { 761 return sv; 762 } 763 } 764 // Otherwise.. 765 return nullptr; 766 } 767 768 void PhaseOutput::set_sv_for_object_node(GrowableArray<ScopeValue*> *objs, 769 ObjectValue* sv ) { 770 assert(sv_for_node_id(objs, sv->id()) == nullptr, "Precondition"); 771 objs->append(sv); 772 } 773 774 775 void PhaseOutput::FillLocArray( int idx, MachSafePointNode* sfpt, Node *local, 776 GrowableArray<ScopeValue*> *array, 777 GrowableArray<ScopeValue*> *objs ) { 778 assert( local, "use _top instead of null" ); 779 if (array->length() != idx) { 780 assert(array->length() == idx + 1, "Unexpected array count"); 781 // Old functionality: 782 // return 783 // New functionality: 784 // Assert if the local is not top. In product mode let the new node 785 // override the old entry. 786 assert(local == C->top(), "LocArray collision"); 787 if (local == C->top()) { 788 return; 789 } 790 array->pop(); 791 } 792 const Type *t = local->bottom_type(); 793 794 // Is it a safepoint scalar object node? 795 if (local->is_SafePointScalarObject()) { 796 SafePointScalarObjectNode* spobj = local->as_SafePointScalarObject(); 797 798 ObjectValue* sv = sv_for_node_id(objs, spobj->_idx); 799 if (sv == nullptr) { 800 ciKlass* cik = t->is_oopptr()->exact_klass(); 801 assert(cik->is_instance_klass() || 802 cik->is_array_klass(), "Not supported allocation."); 803 uint first_ind = spobj->first_index(sfpt->jvms()); 804 // Nullable, scalarized inline types have an is_init input 805 // that needs to be checked before using the field values. 806 ScopeValue* is_init = nullptr; 807 if (cik->is_inlinetype()) { 808 Node* init_node = sfpt->in(first_ind++); 809 assert(init_node != nullptr, "is_init node not found"); 810 if (!init_node->is_top()) { 811 const TypeInt* init_type = init_node->bottom_type()->is_int(); 812 if (init_node->is_Con()) { 813 is_init = new ConstantIntValue(init_type->get_con()); 814 } else { 815 OptoReg::Name init_reg = C->regalloc()->get_reg_first(init_node); 816 is_init = new_loc_value(C->regalloc(), init_reg, Location::normal); 817 } 818 } 819 } 820 sv = new ObjectValue(spobj->_idx, 821 new ConstantOopWriteValue(cik->java_mirror()->constant_encoding()), true, is_init); 822 set_sv_for_object_node(objs, sv); 823 824 for (uint i = 0; i < spobj->n_fields(); i++) { 825 Node* fld_node = sfpt->in(first_ind+i); 826 (void)FillLocArray(sv->field_values()->length(), sfpt, fld_node, sv->field_values(), objs); 827 } 828 } 829 array->append(sv); 830 return; 831 } else if (local->is_SafePointScalarMerge()) { 832 SafePointScalarMergeNode* smerge = local->as_SafePointScalarMerge(); 833 ObjectMergeValue* mv = (ObjectMergeValue*) sv_for_node_id(objs, smerge->_idx); 834 835 if (mv == nullptr) { 836 GrowableArray<ScopeValue*> deps; 837 838 int merge_pointer_idx = smerge->merge_pointer_idx(sfpt->jvms()); 839 (void)FillLocArray(0, sfpt, sfpt->in(merge_pointer_idx), &deps, objs); 840 assert(deps.length() == 1, "missing value"); 841 842 int selector_idx = smerge->selector_idx(sfpt->jvms()); 843 (void)FillLocArray(1, nullptr, sfpt->in(selector_idx), &deps, nullptr); 844 assert(deps.length() == 2, "missing value"); 845 846 mv = new ObjectMergeValue(smerge->_idx, deps.at(0), deps.at(1)); 847 set_sv_for_object_node(objs, mv); 848 849 for (uint i = 1; i < smerge->req(); i++) { 850 Node* obj_node = smerge->in(i); 851 int idx = mv->possible_objects()->length(); 852 (void)FillLocArray(idx, sfpt, obj_node, mv->possible_objects(), objs); 853 854 // By default ObjectValues that are in 'possible_objects' are not root objects. 855 // They will be marked as root later if they are directly referenced in a JVMS. 856 assert(mv->possible_objects()->length() > idx, "Didn't add entry to possible_objects?!"); 857 assert(mv->possible_objects()->at(idx)->is_object(), "Entries in possible_objects should be ObjectValue."); 858 mv->possible_objects()->at(idx)->as_ObjectValue()->set_root(false); 859 } 860 } 861 array->append(mv); 862 return; 863 } 864 865 // Grab the register number for the local 866 OptoReg::Name regnum = C->regalloc()->get_reg_first(local); 867 if( OptoReg::is_valid(regnum) ) {// Got a register/stack? 868 // Record the double as two float registers. 869 // The register mask for such a value always specifies two adjacent 870 // float registers, with the lower register number even. 871 // Normally, the allocation of high and low words to these registers 872 // is irrelevant, because nearly all operations on register pairs 873 // (e.g., StoreD) treat them as a single unit. 874 // Here, we assume in addition that the words in these two registers 875 // stored "naturally" (by operations like StoreD and double stores 876 // within the interpreter) such that the lower-numbered register 877 // is written to the lower memory address. This may seem like 878 // a machine dependency, but it is not--it is a requirement on 879 // the author of the <arch>.ad file to ensure that, for every 880 // even/odd double-register pair to which a double may be allocated, 881 // the word in the even single-register is stored to the first 882 // memory word. (Note that register numbers are completely 883 // arbitrary, and are not tied to any machine-level encodings.) 884 #ifdef _LP64 885 if( t->base() == Type::DoubleBot || t->base() == Type::DoubleCon ) { 886 array->append(new ConstantIntValue((jint)0)); 887 array->append(new_loc_value( C->regalloc(), regnum, Location::dbl )); 888 } else if ( t->base() == Type::Long ) { 889 array->append(new ConstantIntValue((jint)0)); 890 array->append(new_loc_value( C->regalloc(), regnum, Location::lng )); 891 } else if ( t->base() == Type::RawPtr ) { 892 // jsr/ret return address which must be restored into the full 893 // width 64-bit stack slot. 894 array->append(new_loc_value( C->regalloc(), regnum, Location::lng )); 895 } 896 #else //_LP64 897 if( t->base() == Type::DoubleBot || t->base() == Type::DoubleCon || t->base() == Type::Long ) { 898 // Repack the double/long as two jints. 899 // The convention the interpreter uses is that the second local 900 // holds the first raw word of the native double representation. 901 // This is actually reasonable, since locals and stack arrays 902 // grow downwards in all implementations. 903 // (If, on some machine, the interpreter's Java locals or stack 904 // were to grow upwards, the embedded doubles would be word-swapped.) 905 array->append(new_loc_value( C->regalloc(), OptoReg::add(regnum,1), Location::normal )); 906 array->append(new_loc_value( C->regalloc(), regnum , Location::normal )); 907 } 908 #endif //_LP64 909 else if( (t->base() == Type::FloatBot || t->base() == Type::FloatCon) && 910 OptoReg::is_reg(regnum) ) { 911 array->append(new_loc_value( C->regalloc(), regnum, Matcher::float_in_double() 912 ? Location::float_in_dbl : Location::normal )); 913 } else if( t->base() == Type::Int && OptoReg::is_reg(regnum) ) { 914 array->append(new_loc_value( C->regalloc(), regnum, Matcher::int_in_long 915 ? Location::int_in_long : Location::normal )); 916 } else if( t->base() == Type::NarrowOop ) { 917 array->append(new_loc_value( C->regalloc(), regnum, Location::narrowoop )); 918 } else if (t->base() == Type::VectorA || t->base() == Type::VectorS || 919 t->base() == Type::VectorD || t->base() == Type::VectorX || 920 t->base() == Type::VectorY || t->base() == Type::VectorZ) { 921 array->append(new_loc_value( C->regalloc(), regnum, Location::vector )); 922 } else if (C->regalloc()->is_oop(local)) { 923 assert(t->base() == Type::OopPtr || t->base() == Type::InstPtr || 924 t->base() == Type::AryPtr, 925 "Unexpected type: %s", t->msg()); 926 array->append(new_loc_value( C->regalloc(), regnum, Location::oop )); 927 } else { 928 assert(t->base() == Type::Int || t->base() == Type::Half || 929 t->base() == Type::FloatCon || t->base() == Type::FloatBot, 930 "Unexpected type: %s", t->msg()); 931 array->append(new_loc_value( C->regalloc(), regnum, Location::normal )); 932 } 933 return; 934 } 935 936 // No register. It must be constant data. 937 switch (t->base()) { 938 case Type::Half: // Second half of a double 939 ShouldNotReachHere(); // Caller should skip 2nd halves 940 break; 941 case Type::AnyPtr: 942 array->append(new ConstantOopWriteValue(nullptr)); 943 break; 944 case Type::AryPtr: 945 case Type::InstPtr: // fall through 946 array->append(new ConstantOopWriteValue(t->isa_oopptr()->const_oop()->constant_encoding())); 947 break; 948 case Type::NarrowOop: 949 if (t == TypeNarrowOop::NULL_PTR) { 950 array->append(new ConstantOopWriteValue(nullptr)); 951 } else { 952 array->append(new ConstantOopWriteValue(t->make_ptr()->isa_oopptr()->const_oop()->constant_encoding())); 953 } 954 break; 955 case Type::Int: 956 array->append(new ConstantIntValue(t->is_int()->get_con())); 957 break; 958 case Type::RawPtr: 959 // A return address (T_ADDRESS). 960 assert((intptr_t)t->is_ptr()->get_con() < (intptr_t)0x10000, "must be a valid BCI"); 961 #ifdef _LP64 962 // Must be restored to the full-width 64-bit stack slot. 963 array->append(new ConstantLongValue(t->is_ptr()->get_con())); 964 #else 965 array->append(new ConstantIntValue(t->is_ptr()->get_con())); 966 #endif 967 break; 968 case Type::FloatCon: { 969 float f = t->is_float_constant()->getf(); 970 array->append(new ConstantIntValue(jint_cast(f))); 971 break; 972 } 973 case Type::DoubleCon: { 974 jdouble d = t->is_double_constant()->getd(); 975 #ifdef _LP64 976 array->append(new ConstantIntValue((jint)0)); 977 array->append(new ConstantDoubleValue(d)); 978 #else 979 // Repack the double as two jints. 980 // The convention the interpreter uses is that the second local 981 // holds the first raw word of the native double representation. 982 // This is actually reasonable, since locals and stack arrays 983 // grow downwards in all implementations. 984 // (If, on some machine, the interpreter's Java locals or stack 985 // were to grow upwards, the embedded doubles would be word-swapped.) 986 jlong_accessor acc; 987 acc.long_value = jlong_cast(d); 988 array->append(new ConstantIntValue(acc.words[1])); 989 array->append(new ConstantIntValue(acc.words[0])); 990 #endif 991 break; 992 } 993 case Type::Long: { 994 jlong d = t->is_long()->get_con(); 995 #ifdef _LP64 996 array->append(new ConstantIntValue((jint)0)); 997 array->append(new ConstantLongValue(d)); 998 #else 999 // Repack the long as two jints. 1000 // The convention the interpreter uses is that the second local 1001 // holds the first raw word of the native double representation. 1002 // This is actually reasonable, since locals and stack arrays 1003 // grow downwards in all implementations. 1004 // (If, on some machine, the interpreter's Java locals or stack 1005 // were to grow upwards, the embedded doubles would be word-swapped.) 1006 jlong_accessor acc; 1007 acc.long_value = d; 1008 array->append(new ConstantIntValue(acc.words[1])); 1009 array->append(new ConstantIntValue(acc.words[0])); 1010 #endif 1011 break; 1012 } 1013 case Type::Top: // Add an illegal value here 1014 array->append(new LocationValue(Location())); 1015 break; 1016 default: 1017 ShouldNotReachHere(); 1018 break; 1019 } 1020 } 1021 1022 // Determine if this node starts a bundle 1023 bool PhaseOutput::starts_bundle(const Node *n) const { 1024 return (_node_bundling_limit > n->_idx && 1025 _node_bundling_base[n->_idx].starts_bundle()); 1026 } 1027 1028 // Determine if there is a monitor that has 'ov' as its owner. 1029 bool PhaseOutput::contains_as_owner(GrowableArray<MonitorValue*> *monarray, ObjectValue *ov) const { 1030 for (int k = 0; k < monarray->length(); k++) { 1031 MonitorValue* mv = monarray->at(k); 1032 if (mv->owner() == ov) { 1033 return true; 1034 } 1035 } 1036 1037 return false; 1038 } 1039 1040 // Determine if there is a scalar replaced object description represented by 'ov'. 1041 bool PhaseOutput::contains_as_scalarized_obj(JVMState* jvms, MachSafePointNode* sfn, 1042 GrowableArray<ScopeValue*>* objs, 1043 ObjectValue* ov) const { 1044 for (int i = 0; i < jvms->scl_size(); i++) { 1045 Node* n = sfn->scalarized_obj(jvms, i); 1046 // Other kinds of nodes that we may encounter here, for instance constants 1047 // representing values of fields of objects scalarized, aren't relevant for 1048 // us, since they don't map to ObjectValue. 1049 if (!n->is_SafePointScalarObject()) { 1050 continue; 1051 } 1052 1053 ObjectValue* other = sv_for_node_id(objs, n->_idx); 1054 if (ov == other) { 1055 return true; 1056 } 1057 } 1058 return false; 1059 } 1060 1061 //--------------------------Process_OopMap_Node-------------------------------- 1062 void PhaseOutput::Process_OopMap_Node(MachNode *mach, int current_offset) { 1063 // Handle special safepoint nodes for synchronization 1064 MachSafePointNode *sfn = mach->as_MachSafePoint(); 1065 MachCallNode *mcall; 1066 1067 int safepoint_pc_offset = current_offset; 1068 bool is_method_handle_invoke = false; 1069 bool return_oop = false; 1070 bool return_scalarized = false; 1071 bool has_ea_local_in_scope = sfn->_has_ea_local_in_scope; 1072 bool arg_escape = false; 1073 1074 // Add the safepoint in the DebugInfoRecorder 1075 if( !mach->is_MachCall() ) { 1076 mcall = nullptr; 1077 C->debug_info()->add_safepoint(safepoint_pc_offset, sfn->_oop_map); 1078 } else { 1079 mcall = mach->as_MachCall(); 1080 1081 // Is the call a MethodHandle call? 1082 if (mcall->is_MachCallJava()) { 1083 if (mcall->as_MachCallJava()->_method_handle_invoke) { 1084 assert(C->has_method_handle_invokes(), "must have been set during call generation"); 1085 is_method_handle_invoke = true; 1086 } 1087 arg_escape = mcall->as_MachCallJava()->_arg_escape; 1088 } 1089 1090 // Check if a call returns an object. 1091 if (mcall->returns_pointer() || mcall->returns_scalarized()) { 1092 return_oop = true; 1093 } 1094 if (mcall->returns_scalarized()) { 1095 return_scalarized = true; 1096 } 1097 safepoint_pc_offset += mcall->ret_addr_offset(); 1098 C->debug_info()->add_safepoint(safepoint_pc_offset, mcall->_oop_map); 1099 } 1100 1101 // Loop over the JVMState list to add scope information 1102 // Do not skip safepoints with a null method, they need monitor info 1103 JVMState* youngest_jvms = sfn->jvms(); 1104 int max_depth = youngest_jvms->depth(); 1105 1106 // Allocate the object pool for scalar-replaced objects -- the map from 1107 // small-integer keys (which can be recorded in the local and ostack 1108 // arrays) to descriptions of the object state. 1109 GrowableArray<ScopeValue*> *objs = new GrowableArray<ScopeValue*>(); 1110 1111 // Visit scopes from oldest to youngest. 1112 for (int depth = 1; depth <= max_depth; depth++) { 1113 JVMState* jvms = youngest_jvms->of_depth(depth); 1114 int idx; 1115 ciMethod* method = jvms->has_method() ? jvms->method() : nullptr; 1116 // Safepoints that do not have method() set only provide oop-map and monitor info 1117 // to support GC; these do not support deoptimization. 1118 int num_locs = (method == nullptr) ? 0 : jvms->loc_size(); 1119 int num_exps = (method == nullptr) ? 0 : jvms->stk_size(); 1120 int num_mon = jvms->nof_monitors(); 1121 assert(method == nullptr || jvms->bci() < 0 || num_locs == method->max_locals(), 1122 "JVMS local count must match that of the method"); 1123 1124 // Add Local and Expression Stack Information 1125 1126 // Insert locals into the locarray 1127 GrowableArray<ScopeValue*> *locarray = new GrowableArray<ScopeValue*>(num_locs); 1128 for( idx = 0; idx < num_locs; idx++ ) { 1129 FillLocArray( idx, sfn, sfn->local(jvms, idx), locarray, objs ); 1130 } 1131 1132 // Insert expression stack entries into the exparray 1133 GrowableArray<ScopeValue*> *exparray = new GrowableArray<ScopeValue*>(num_exps); 1134 for( idx = 0; idx < num_exps; idx++ ) { 1135 FillLocArray( idx, sfn, sfn->stack(jvms, idx), exparray, objs ); 1136 } 1137 1138 // Add in mappings of the monitors 1139 assert( !method || 1140 !method->is_synchronized() || 1141 method->is_native() || 1142 num_mon > 0 || 1143 !GenerateSynchronizationCode, 1144 "monitors must always exist for synchronized methods"); 1145 1146 // Build the growable array of ScopeValues for exp stack 1147 GrowableArray<MonitorValue*> *monarray = new GrowableArray<MonitorValue*>(num_mon); 1148 1149 // Loop over monitors and insert into array 1150 for (idx = 0; idx < num_mon; idx++) { 1151 // Grab the node that defines this monitor 1152 Node* box_node = sfn->monitor_box(jvms, idx); 1153 Node* obj_node = sfn->monitor_obj(jvms, idx); 1154 1155 // Create ScopeValue for object 1156 ScopeValue *scval = nullptr; 1157 1158 if (obj_node->is_SafePointScalarObject()) { 1159 SafePointScalarObjectNode* spobj = obj_node->as_SafePointScalarObject(); 1160 scval = PhaseOutput::sv_for_node_id(objs, spobj->_idx); 1161 if (scval == nullptr) { 1162 const Type *t = spobj->bottom_type(); 1163 ciKlass* cik = t->is_oopptr()->exact_klass(); 1164 assert(cik->is_instance_klass() || 1165 cik->is_array_klass(), "Not supported allocation."); 1166 ObjectValue* sv = new ObjectValue(spobj->_idx, 1167 new ConstantOopWriteValue(cik->java_mirror()->constant_encoding())); 1168 PhaseOutput::set_sv_for_object_node(objs, sv); 1169 1170 uint first_ind = spobj->first_index(youngest_jvms); 1171 for (uint i = 0; i < spobj->n_fields(); i++) { 1172 Node* fld_node = sfn->in(first_ind+i); 1173 (void)FillLocArray(sv->field_values()->length(), sfn, fld_node, sv->field_values(), objs); 1174 } 1175 scval = sv; 1176 } 1177 } else if (obj_node->is_SafePointScalarMerge()) { 1178 SafePointScalarMergeNode* smerge = obj_node->as_SafePointScalarMerge(); 1179 ObjectMergeValue* mv = (ObjectMergeValue*) sv_for_node_id(objs, smerge->_idx); 1180 1181 if (mv == nullptr) { 1182 GrowableArray<ScopeValue*> deps; 1183 1184 int merge_pointer_idx = smerge->merge_pointer_idx(youngest_jvms); 1185 FillLocArray(0, sfn, sfn->in(merge_pointer_idx), &deps, objs); 1186 assert(deps.length() == 1, "missing value"); 1187 1188 int selector_idx = smerge->selector_idx(youngest_jvms); 1189 FillLocArray(1, nullptr, sfn->in(selector_idx), &deps, nullptr); 1190 assert(deps.length() == 2, "missing value"); 1191 1192 mv = new ObjectMergeValue(smerge->_idx, deps.at(0), deps.at(1)); 1193 set_sv_for_object_node(objs, mv); 1194 1195 for (uint i = 1; i < smerge->req(); i++) { 1196 Node* obj_node = smerge->in(i); 1197 int idx = mv->possible_objects()->length(); 1198 (void)FillLocArray(idx, sfn, obj_node, mv->possible_objects(), objs); 1199 1200 // By default ObjectValues that are in 'possible_objects' are not root objects. 1201 // They will be marked as root later if they are directly referenced in a JVMS. 1202 assert(mv->possible_objects()->length() > idx, "Didn't add entry to possible_objects?!"); 1203 assert(mv->possible_objects()->at(idx)->is_object(), "Entries in possible_objects should be ObjectValue."); 1204 mv->possible_objects()->at(idx)->as_ObjectValue()->set_root(false); 1205 } 1206 } 1207 scval = mv; 1208 } else if (!obj_node->is_Con()) { 1209 OptoReg::Name obj_reg = C->regalloc()->get_reg_first(obj_node); 1210 if( obj_node->bottom_type()->base() == Type::NarrowOop ) { 1211 scval = new_loc_value( C->regalloc(), obj_reg, Location::narrowoop ); 1212 } else { 1213 scval = new_loc_value( C->regalloc(), obj_reg, Location::oop ); 1214 } 1215 } else { 1216 const TypePtr *tp = obj_node->get_ptr_type(); 1217 scval = new ConstantOopWriteValue(tp->is_oopptr()->const_oop()->constant_encoding()); 1218 } 1219 1220 OptoReg::Name box_reg = BoxLockNode::reg(box_node); 1221 Location basic_lock = Location::new_stk_loc(Location::normal,C->regalloc()->reg2offset(box_reg)); 1222 bool eliminated = (box_node->is_BoxLock() && box_node->as_BoxLock()->is_eliminated()); 1223 monarray->append(new MonitorValue(scval, basic_lock, eliminated)); 1224 } 1225 1226 // Mark ObjectValue nodes as root nodes if they are directly 1227 // referenced in the JVMS. 1228 for (int i = 0; i < objs->length(); i++) { 1229 ScopeValue* sv = objs->at(i); 1230 if (sv->is_object_merge()) { 1231 ObjectMergeValue* merge = sv->as_ObjectMergeValue(); 1232 1233 for (int j = 0; j< merge->possible_objects()->length(); j++) { 1234 ObjectValue* ov = merge->possible_objects()->at(j)->as_ObjectValue(); 1235 if (ov->is_root()) { 1236 // Already flagged as 'root' by something else. We shouldn't change it 1237 // to non-root in a younger JVMS because it may need to be alive in 1238 // a younger JVMS. 1239 } else { 1240 bool is_root = locarray->contains(ov) || 1241 exparray->contains(ov) || 1242 contains_as_owner(monarray, ov) || 1243 contains_as_scalarized_obj(jvms, sfn, objs, ov); 1244 ov->set_root(is_root); 1245 } 1246 } 1247 } 1248 } 1249 1250 // We dump the object pool first, since deoptimization reads it in first. 1251 C->debug_info()->dump_object_pool(objs); 1252 1253 // Build first class objects to pass to scope 1254 DebugToken *locvals = C->debug_info()->create_scope_values(locarray); 1255 DebugToken *expvals = C->debug_info()->create_scope_values(exparray); 1256 DebugToken *monvals = C->debug_info()->create_monitor_values(monarray); 1257 1258 // Make method available for all Safepoints 1259 ciMethod* scope_method = method ? method : C->method(); 1260 // Describe the scope here 1261 assert(jvms->bci() >= InvocationEntryBci && jvms->bci() <= 0x10000, "must be a valid or entry BCI"); 1262 assert(!jvms->should_reexecute() || depth == max_depth, "reexecute allowed only for the youngest"); 1263 // Now we can describe the scope. 1264 methodHandle null_mh; 1265 bool rethrow_exception = false; 1266 C->debug_info()->describe_scope( 1267 safepoint_pc_offset, 1268 null_mh, 1269 scope_method, 1270 jvms->bci(), 1271 jvms->should_reexecute(), 1272 rethrow_exception, 1273 is_method_handle_invoke, 1274 return_oop, 1275 return_scalarized, 1276 has_ea_local_in_scope, 1277 arg_escape, 1278 locvals, 1279 expvals, 1280 monvals 1281 ); 1282 } // End jvms loop 1283 1284 // Mark the end of the scope set. 1285 C->debug_info()->end_safepoint(safepoint_pc_offset); 1286 } 1287 1288 1289 1290 // A simplified version of Process_OopMap_Node, to handle non-safepoints. 1291 class NonSafepointEmitter { 1292 Compile* C; 1293 JVMState* _pending_jvms; 1294 int _pending_offset; 1295 1296 void emit_non_safepoint(); 1297 1298 public: 1299 NonSafepointEmitter(Compile* compile) { 1300 this->C = compile; 1301 _pending_jvms = nullptr; 1302 _pending_offset = 0; 1303 } 1304 1305 void observe_instruction(Node* n, int pc_offset) { 1306 if (!C->debug_info()->recording_non_safepoints()) return; 1307 1308 Node_Notes* nn = C->node_notes_at(n->_idx); 1309 if (nn == nullptr || nn->jvms() == nullptr) return; 1310 if (_pending_jvms != nullptr && 1311 _pending_jvms->same_calls_as(nn->jvms())) { 1312 // Repeated JVMS? Stretch it up here. 1313 _pending_offset = pc_offset; 1314 } else { 1315 if (_pending_jvms != nullptr && 1316 _pending_offset < pc_offset) { 1317 emit_non_safepoint(); 1318 } 1319 _pending_jvms = nullptr; 1320 if (pc_offset > C->debug_info()->last_pc_offset()) { 1321 // This is the only way _pending_jvms can become non-null: 1322 _pending_jvms = nn->jvms(); 1323 _pending_offset = pc_offset; 1324 } 1325 } 1326 } 1327 1328 // Stay out of the way of real safepoints: 1329 void observe_safepoint(JVMState* jvms, int pc_offset) { 1330 if (_pending_jvms != nullptr && 1331 !_pending_jvms->same_calls_as(jvms) && 1332 _pending_offset < pc_offset) { 1333 emit_non_safepoint(); 1334 } 1335 _pending_jvms = nullptr; 1336 } 1337 1338 void flush_at_end() { 1339 if (_pending_jvms != nullptr) { 1340 emit_non_safepoint(); 1341 } 1342 _pending_jvms = nullptr; 1343 } 1344 }; 1345 1346 void NonSafepointEmitter::emit_non_safepoint() { 1347 JVMState* youngest_jvms = _pending_jvms; 1348 int pc_offset = _pending_offset; 1349 1350 // Clear it now: 1351 _pending_jvms = nullptr; 1352 1353 DebugInformationRecorder* debug_info = C->debug_info(); 1354 assert(debug_info->recording_non_safepoints(), "sanity"); 1355 1356 debug_info->add_non_safepoint(pc_offset); 1357 int max_depth = youngest_jvms->depth(); 1358 1359 // Visit scopes from oldest to youngest. 1360 for (int depth = 1; depth <= max_depth; depth++) { 1361 JVMState* jvms = youngest_jvms->of_depth(depth); 1362 ciMethod* method = jvms->has_method() ? jvms->method() : nullptr; 1363 assert(!jvms->should_reexecute() || depth==max_depth, "reexecute allowed only for the youngest"); 1364 methodHandle null_mh; 1365 debug_info->describe_scope(pc_offset, null_mh, method, jvms->bci(), jvms->should_reexecute()); 1366 } 1367 1368 // Mark the end of the scope set. 1369 debug_info->end_non_safepoint(pc_offset); 1370 } 1371 1372 //------------------------------init_buffer------------------------------------ 1373 void PhaseOutput::estimate_buffer_size(int& const_req) { 1374 1375 // Set the initially allocated size 1376 const_req = initial_const_capacity; 1377 1378 // The extra spacing after the code is necessary on some platforms. 1379 // Sometimes we need to patch in a jump after the last instruction, 1380 // if the nmethod has been deoptimized. (See 4932387, 4894843.) 1381 1382 // Compute the byte offset where we can store the deopt pc. 1383 if (C->fixed_slots() != 0) { 1384 _orig_pc_slot_offset_in_bytes = C->regalloc()->reg2offset(OptoReg::stack2reg(_orig_pc_slot)); 1385 } 1386 1387 // Compute prolog code size 1388 _frame_slots = OptoReg::reg2stack(C->matcher()->_old_SP) + C->regalloc()->_framesize; 1389 assert(_frame_slots >= 0 && _frame_slots < 1000000, "sanity check"); 1390 1391 if (C->has_mach_constant_base_node()) { 1392 uint add_size = 0; 1393 // Fill the constant table. 1394 // Note: This must happen before shorten_branches. 1395 for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) { 1396 Block* b = C->cfg()->get_block(i); 1397 1398 for (uint j = 0; j < b->number_of_nodes(); j++) { 1399 Node* n = b->get_node(j); 1400 1401 // If the node is a MachConstantNode evaluate the constant 1402 // value section. 1403 if (n->is_MachConstant()) { 1404 MachConstantNode* machcon = n->as_MachConstant(); 1405 machcon->eval_constant(C); 1406 } else if (n->is_Mach()) { 1407 // On Power there are more nodes that issue constants. 1408 add_size += (n->as_Mach()->ins_num_consts() * 8); 1409 } 1410 } 1411 } 1412 1413 // Calculate the offsets of the constants and the size of the 1414 // constant table (including the padding to the next section). 1415 constant_table().calculate_offsets_and_size(); 1416 const_req = constant_table().alignment() + constant_table().size() + add_size; 1417 } 1418 1419 // Initialize the space for the BufferBlob used to find and verify 1420 // instruction size in MachNode::emit_size() 1421 init_scratch_buffer_blob(const_req); 1422 } 1423 1424 CodeBuffer* PhaseOutput::init_buffer() { 1425 int stub_req = _buf_sizes._stub; 1426 int code_req = _buf_sizes._code; 1427 int const_req = _buf_sizes._const; 1428 1429 int pad_req = NativeCall::byte_size(); 1430 1431 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 1432 stub_req += bs->estimate_stub_size(); 1433 1434 // nmethod and CodeBuffer count stubs & constants as part of method's code. 1435 // class HandlerImpl is platform-specific and defined in the *.ad files. 1436 int exception_handler_req = HandlerImpl::size_exception_handler() + MAX_stubs_size; // add marginal slop for handler 1437 int deopt_handler_req = HandlerImpl::size_deopt_handler() + MAX_stubs_size; // add marginal slop for handler 1438 stub_req += MAX_stubs_size; // ensure per-stub margin 1439 code_req += MAX_inst_size; // ensure per-instruction margin 1440 1441 if (StressCodeBuffers) 1442 code_req = const_req = stub_req = exception_handler_req = deopt_handler_req = 0x10; // force expansion 1443 1444 int total_req = 1445 const_req + 1446 code_req + 1447 pad_req + 1448 stub_req + 1449 exception_handler_req + 1450 deopt_handler_req; // deopt handler 1451 1452 if (C->has_method_handle_invokes()) 1453 total_req += deopt_handler_req; // deopt MH handler 1454 1455 CodeBuffer* cb = code_buffer(); 1456 cb->set_const_section_alignment(constant_table().alignment()); 1457 cb->initialize(total_req, _buf_sizes._reloc); 1458 1459 // Have we run out of code space? 1460 if ((cb->blob() == nullptr) || (!CompileBroker::should_compile_new_jobs())) { 1461 C->record_failure("CodeCache is full"); 1462 return nullptr; 1463 } 1464 // Configure the code buffer. 1465 cb->initialize_consts_size(const_req); 1466 cb->initialize_stubs_size(stub_req); 1467 cb->initialize_oop_recorder(C->env()->oop_recorder()); 1468 1469 // fill in the nop array for bundling computations 1470 MachNode *_nop_list[Bundle::_nop_count]; 1471 Bundle::initialize_nops(_nop_list); 1472 1473 return cb; 1474 } 1475 1476 //------------------------------fill_buffer------------------------------------ 1477 void PhaseOutput::fill_buffer(C2_MacroAssembler* masm, uint* blk_starts) { 1478 // blk_starts[] contains offsets calculated during short branches processing, 1479 // offsets should not be increased during following steps. 1480 1481 // Compute the size of first NumberOfLoopInstrToAlign instructions at head 1482 // of a loop. It is used to determine the padding for loop alignment. 1483 Compile::TracePhase tp(_t_fillBuffer); 1484 1485 compute_loop_first_inst_sizes(); 1486 1487 // Create oopmap set. 1488 _oop_map_set = new OopMapSet(); 1489 1490 // !!!!! This preserves old handling of oopmaps for now 1491 C->debug_info()->set_oopmaps(_oop_map_set); 1492 1493 uint nblocks = C->cfg()->number_of_blocks(); 1494 // Count and start of implicit null check instructions 1495 uint inct_cnt = 0; 1496 uint* inct_starts = NEW_RESOURCE_ARRAY(uint, nblocks+1); 1497 1498 // Count and start of calls 1499 uint* call_returns = NEW_RESOURCE_ARRAY(uint, nblocks+1); 1500 1501 uint return_offset = 0; 1502 int nop_size = (new MachNopNode())->size(C->regalloc()); 1503 1504 int previous_offset = 0; 1505 int current_offset = 0; 1506 int last_call_offset = -1; 1507 int last_avoid_back_to_back_offset = -1; 1508 #ifdef ASSERT 1509 uint* jmp_target = NEW_RESOURCE_ARRAY(uint,nblocks); 1510 uint* jmp_offset = NEW_RESOURCE_ARRAY(uint,nblocks); 1511 uint* jmp_size = NEW_RESOURCE_ARRAY(uint,nblocks); 1512 uint* jmp_rule = NEW_RESOURCE_ARRAY(uint,nblocks); 1513 #endif 1514 1515 // Create an array of unused labels, one for each basic block, if printing is enabled 1516 #if defined(SUPPORT_OPTO_ASSEMBLY) 1517 int* node_offsets = nullptr; 1518 uint node_offset_limit = C->unique(); 1519 1520 if (C->print_assembly()) { 1521 node_offsets = NEW_RESOURCE_ARRAY(int, node_offset_limit); 1522 } 1523 if (node_offsets != nullptr) { 1524 // We need to initialize. Unused array elements may contain garbage and mess up PrintOptoAssembly. 1525 memset(node_offsets, 0, node_offset_limit*sizeof(int)); 1526 } 1527 #endif 1528 1529 NonSafepointEmitter non_safepoints(C); // emit non-safepoints lazily 1530 1531 // Emit the constant table. 1532 if (C->has_mach_constant_base_node()) { 1533 if (!constant_table().emit(masm)) { 1534 C->record_failure("consts section overflow"); 1535 return; 1536 } 1537 } 1538 1539 // Create an array of labels, one for each basic block 1540 Label* blk_labels = NEW_RESOURCE_ARRAY(Label, nblocks+1); 1541 for (uint i = 0; i <= nblocks; i++) { 1542 blk_labels[i].init(); 1543 } 1544 1545 // Now fill in the code buffer 1546 Node* delay_slot = nullptr; 1547 for (uint i = 0; i < nblocks; i++) { 1548 Block* block = C->cfg()->get_block(i); 1549 _block = block; 1550 Node* head = block->head(); 1551 1552 // If this block needs to start aligned (i.e, can be reached other 1553 // than by falling-thru from the previous block), then force the 1554 // start of a new bundle. 1555 if (Pipeline::requires_bundling() && starts_bundle(head)) { 1556 masm->code()->flush_bundle(true); 1557 } 1558 1559 #ifdef ASSERT 1560 if (!block->is_connector()) { 1561 stringStream st; 1562 block->dump_head(C->cfg(), &st); 1563 masm->block_comment(st.freeze()); 1564 } 1565 jmp_target[i] = 0; 1566 jmp_offset[i] = 0; 1567 jmp_size[i] = 0; 1568 jmp_rule[i] = 0; 1569 #endif 1570 int blk_offset = current_offset; 1571 1572 // Define the label at the beginning of the basic block 1573 masm->bind(blk_labels[block->_pre_order]); 1574 1575 uint last_inst = block->number_of_nodes(); 1576 1577 // Emit block normally, except for last instruction. 1578 // Emit means "dump code bits into code buffer". 1579 for (uint j = 0; j<last_inst; j++) { 1580 _index = j; 1581 1582 // Get the node 1583 Node* n = block->get_node(j); 1584 1585 // See if delay slots are supported 1586 if (valid_bundle_info(n) && node_bundling(n)->used_in_unconditional_delay()) { 1587 assert(delay_slot == nullptr, "no use of delay slot node"); 1588 assert(n->size(C->regalloc()) == Pipeline::instr_unit_size(), "delay slot instruction wrong size"); 1589 1590 delay_slot = n; 1591 continue; 1592 } 1593 1594 // If this starts a new instruction group, then flush the current one 1595 // (but allow split bundles) 1596 if (Pipeline::requires_bundling() && starts_bundle(n)) 1597 masm->code()->flush_bundle(false); 1598 1599 // Special handling for SafePoint/Call Nodes 1600 bool is_mcall = false; 1601 if (n->is_Mach()) { 1602 MachNode *mach = n->as_Mach(); 1603 is_mcall = n->is_MachCall(); 1604 bool is_sfn = n->is_MachSafePoint(); 1605 1606 // If this requires all previous instructions be flushed, then do so 1607 if (is_sfn || is_mcall || mach->alignment_required() != 1) { 1608 masm->code()->flush_bundle(true); 1609 current_offset = masm->offset(); 1610 } 1611 1612 // A padding may be needed again since a previous instruction 1613 // could be moved to delay slot. 1614 1615 // align the instruction if necessary 1616 int padding = mach->compute_padding(current_offset); 1617 // Make sure safepoint node for polling is distinct from a call's 1618 // return by adding a nop if needed. 1619 if (is_sfn && !is_mcall && padding == 0 && current_offset == last_call_offset) { 1620 padding = nop_size; 1621 } 1622 if (padding == 0 && mach->avoid_back_to_back(MachNode::AVOID_BEFORE) && 1623 current_offset == last_avoid_back_to_back_offset) { 1624 // Avoid back to back some instructions. 1625 padding = nop_size; 1626 } 1627 1628 if (padding > 0) { 1629 assert((padding % nop_size) == 0, "padding is not a multiple of NOP size"); 1630 int nops_cnt = padding / nop_size; 1631 MachNode *nop = new MachNopNode(nops_cnt); 1632 block->insert_node(nop, j++); 1633 last_inst++; 1634 C->cfg()->map_node_to_block(nop, block); 1635 // Ensure enough space. 1636 masm->code()->insts()->maybe_expand_to_ensure_remaining(MAX_inst_size); 1637 if ((masm->code()->blob() == nullptr) || (!CompileBroker::should_compile_new_jobs())) { 1638 C->record_failure("CodeCache is full"); 1639 return; 1640 } 1641 nop->emit(masm, C->regalloc()); 1642 masm->code()->flush_bundle(true); 1643 current_offset = masm->offset(); 1644 } 1645 1646 bool observe_safepoint = is_sfn; 1647 // Remember the start of the last call in a basic block 1648 if (is_mcall) { 1649 MachCallNode *mcall = mach->as_MachCall(); 1650 1651 if (mcall->entry_point() != nullptr) { 1652 // This destination address is NOT PC-relative 1653 mcall->method_set((intptr_t)mcall->entry_point()); 1654 } 1655 1656 // Save the return address 1657 call_returns[block->_pre_order] = current_offset + mcall->ret_addr_offset(); 1658 1659 observe_safepoint = mcall->guaranteed_safepoint(); 1660 } 1661 1662 // sfn will be valid whenever mcall is valid now because of inheritance 1663 if (observe_safepoint) { 1664 // Handle special safepoint nodes for synchronization 1665 if (!is_mcall) { 1666 MachSafePointNode *sfn = mach->as_MachSafePoint(); 1667 // !!!!! Stubs only need an oopmap right now, so bail out 1668 if (sfn->jvms()->method() == nullptr) { 1669 // Write the oopmap directly to the code blob??!! 1670 continue; 1671 } 1672 } // End synchronization 1673 1674 non_safepoints.observe_safepoint(mach->as_MachSafePoint()->jvms(), 1675 current_offset); 1676 Process_OopMap_Node(mach, current_offset); 1677 } // End if safepoint 1678 1679 // If this is a null check, then add the start of the previous instruction to the list 1680 else if( mach->is_MachNullCheck() ) { 1681 inct_starts[inct_cnt++] = previous_offset; 1682 } 1683 1684 // If this is a branch, then fill in the label with the target BB's label 1685 else if (mach->is_MachBranch()) { 1686 // This requires the TRUE branch target be in succs[0] 1687 uint block_num = block->non_connector_successor(0)->_pre_order; 1688 1689 // Try to replace long branch if delay slot is not used, 1690 // it is mostly for back branches since forward branch's 1691 // distance is not updated yet. 1692 bool delay_slot_is_used = valid_bundle_info(n) && 1693 C->output()->node_bundling(n)->use_unconditional_delay(); 1694 if (!delay_slot_is_used && mach->may_be_short_branch()) { 1695 assert(delay_slot == nullptr, "not expecting delay slot node"); 1696 int br_size = n->size(C->regalloc()); 1697 int offset = blk_starts[block_num] - current_offset; 1698 if (block_num >= i) { 1699 // Current and following block's offset are not 1700 // finalized yet, adjust distance by the difference 1701 // between calculated and final offsets of current block. 1702 offset -= (blk_starts[i] - blk_offset); 1703 } 1704 // In the following code a nop could be inserted before 1705 // the branch which will increase the backward distance. 1706 bool needs_padding = (current_offset == last_avoid_back_to_back_offset); 1707 if (needs_padding && offset <= 0) 1708 offset -= nop_size; 1709 1710 if (C->matcher()->is_short_branch_offset(mach->rule(), br_size, offset)) { 1711 // We've got a winner. Replace this branch. 1712 MachNode* replacement = mach->as_MachBranch()->short_branch_version(); 1713 1714 // Update the jmp_size. 1715 int new_size = replacement->size(C->regalloc()); 1716 assert((br_size - new_size) >= (int)nop_size, "short_branch size should be smaller"); 1717 // Insert padding between avoid_back_to_back branches. 1718 if (needs_padding && replacement->avoid_back_to_back(MachNode::AVOID_BEFORE)) { 1719 MachNode *nop = new MachNopNode(); 1720 block->insert_node(nop, j++); 1721 C->cfg()->map_node_to_block(nop, block); 1722 last_inst++; 1723 nop->emit(masm, C->regalloc()); 1724 masm->code()->flush_bundle(true); 1725 current_offset = masm->offset(); 1726 } 1727 #ifdef ASSERT 1728 jmp_target[i] = block_num; 1729 jmp_offset[i] = current_offset - blk_offset; 1730 jmp_size[i] = new_size; 1731 jmp_rule[i] = mach->rule(); 1732 #endif 1733 block->map_node(replacement, j); 1734 mach->subsume_by(replacement, C); 1735 n = replacement; 1736 mach = replacement; 1737 } 1738 } 1739 mach->as_MachBranch()->label_set( &blk_labels[block_num], block_num ); 1740 } else if (mach->ideal_Opcode() == Op_Jump) { 1741 for (uint h = 0; h < block->_num_succs; h++) { 1742 Block* succs_block = block->_succs[h]; 1743 for (uint j = 1; j < succs_block->num_preds(); j++) { 1744 Node* jpn = succs_block->pred(j); 1745 if (jpn->is_JumpProj() && jpn->in(0) == mach) { 1746 uint block_num = succs_block->non_connector()->_pre_order; 1747 Label *blkLabel = &blk_labels[block_num]; 1748 mach->add_case_label(jpn->as_JumpProj()->proj_no(), blkLabel); 1749 } 1750 } 1751 } 1752 } else if (!n->is_Proj()) { 1753 // Remember the beginning of the previous instruction, in case 1754 // it's followed by a flag-kill and a null-check. Happens on 1755 // Intel all the time, with add-to-memory kind of opcodes. 1756 previous_offset = current_offset; 1757 } 1758 1759 // Not an else-if! 1760 // If this is a trap based cmp then add its offset to the list. 1761 if (mach->is_TrapBasedCheckNode()) { 1762 inct_starts[inct_cnt++] = current_offset; 1763 } 1764 } 1765 1766 // Verify that there is sufficient space remaining 1767 masm->code()->insts()->maybe_expand_to_ensure_remaining(MAX_inst_size); 1768 if ((masm->code()->blob() == nullptr) || (!CompileBroker::should_compile_new_jobs())) { 1769 C->record_failure("CodeCache is full"); 1770 return; 1771 } 1772 1773 // Save the offset for the listing 1774 #if defined(SUPPORT_OPTO_ASSEMBLY) 1775 if ((node_offsets != nullptr) && (n->_idx < node_offset_limit)) { 1776 node_offsets[n->_idx] = masm->offset(); 1777 } 1778 #endif 1779 assert(!C->failing_internal() || C->failure_is_artificial(), "Should not reach here if failing."); 1780 1781 // "Normal" instruction case 1782 DEBUG_ONLY(uint instr_offset = masm->offset()); 1783 n->emit(masm, C->regalloc()); 1784 current_offset = masm->offset(); 1785 1786 // Above we only verified that there is enough space in the instruction section. 1787 // However, the instruction may emit stubs that cause code buffer expansion. 1788 // Bail out here if expansion failed due to a lack of code cache space. 1789 if (C->failing()) { 1790 return; 1791 } 1792 1793 assert(!is_mcall || (call_returns[block->_pre_order] <= (uint)current_offset), 1794 "ret_addr_offset() not within emitted code"); 1795 #ifdef ASSERT 1796 uint n_size = n->size(C->regalloc()); 1797 if (n_size < (current_offset-instr_offset)) { 1798 MachNode* mach = n->as_Mach(); 1799 n->dump(); 1800 mach->dump_format(C->regalloc(), tty); 1801 tty->print_cr(" n_size (%d), current_offset (%d), instr_offset (%d)", n_size, current_offset, instr_offset); 1802 Disassembler::decode(masm->code()->insts_begin() + instr_offset, masm->code()->insts_begin() + current_offset + 1, tty); 1803 tty->print_cr(" ------------------- "); 1804 BufferBlob* blob = this->scratch_buffer_blob(); 1805 address blob_begin = blob->content_begin(); 1806 Disassembler::decode(blob_begin, blob_begin + n_size + 1, tty); 1807 assert(false, "wrong size of mach node"); 1808 } 1809 #endif 1810 non_safepoints.observe_instruction(n, current_offset); 1811 1812 // mcall is last "call" that can be a safepoint 1813 // record it so we can see if a poll will directly follow it 1814 // in which case we'll need a pad to make the PcDesc sites unique 1815 // see 5010568. This can be slightly inaccurate but conservative 1816 // in the case that return address is not actually at current_offset. 1817 // This is a small price to pay. 1818 1819 if (is_mcall) { 1820 last_call_offset = current_offset; 1821 } 1822 1823 if (n->is_Mach() && n->as_Mach()->avoid_back_to_back(MachNode::AVOID_AFTER)) { 1824 // Avoid back to back some instructions. 1825 last_avoid_back_to_back_offset = current_offset; 1826 } 1827 1828 // See if this instruction has a delay slot 1829 if (valid_bundle_info(n) && node_bundling(n)->use_unconditional_delay()) { 1830 guarantee(delay_slot != nullptr, "expecting delay slot node"); 1831 1832 // Back up 1 instruction 1833 masm->code()->set_insts_end(masm->code()->insts_end() - Pipeline::instr_unit_size()); 1834 1835 // Save the offset for the listing 1836 #if defined(SUPPORT_OPTO_ASSEMBLY) 1837 if ((node_offsets != nullptr) && (delay_slot->_idx < node_offset_limit)) { 1838 node_offsets[delay_slot->_idx] = masm->offset(); 1839 } 1840 #endif 1841 1842 // Support a SafePoint in the delay slot 1843 if (delay_slot->is_MachSafePoint()) { 1844 MachNode *mach = delay_slot->as_Mach(); 1845 // !!!!! Stubs only need an oopmap right now, so bail out 1846 if (!mach->is_MachCall() && mach->as_MachSafePoint()->jvms()->method() == nullptr) { 1847 // Write the oopmap directly to the code blob??!! 1848 delay_slot = nullptr; 1849 continue; 1850 } 1851 1852 int adjusted_offset = current_offset - Pipeline::instr_unit_size(); 1853 non_safepoints.observe_safepoint(mach->as_MachSafePoint()->jvms(), 1854 adjusted_offset); 1855 // Generate an OopMap entry 1856 Process_OopMap_Node(mach, adjusted_offset); 1857 } 1858 1859 // Insert the delay slot instruction 1860 delay_slot->emit(masm, C->regalloc()); 1861 1862 // Don't reuse it 1863 delay_slot = nullptr; 1864 } 1865 1866 } // End for all instructions in block 1867 1868 // If the next block is the top of a loop, pad this block out to align 1869 // the loop top a little. Helps prevent pipe stalls at loop back branches. 1870 if (i < nblocks-1) { 1871 Block *nb = C->cfg()->get_block(i + 1); 1872 int padding = nb->alignment_padding(current_offset); 1873 if( padding > 0 ) { 1874 MachNode *nop = new MachNopNode(padding / nop_size); 1875 block->insert_node(nop, block->number_of_nodes()); 1876 C->cfg()->map_node_to_block(nop, block); 1877 nop->emit(masm, C->regalloc()); 1878 current_offset = masm->offset(); 1879 } 1880 } 1881 // Verify that the distance for generated before forward 1882 // short branches is still valid. 1883 guarantee((int)(blk_starts[i+1] - blk_starts[i]) >= (current_offset - blk_offset), "shouldn't increase block size"); 1884 1885 // Save new block start offset 1886 blk_starts[i] = blk_offset; 1887 } // End of for all blocks 1888 blk_starts[nblocks] = current_offset; 1889 1890 non_safepoints.flush_at_end(); 1891 1892 // Offset too large? 1893 if (C->failing()) return; 1894 1895 // Define a pseudo-label at the end of the code 1896 masm->bind( blk_labels[nblocks] ); 1897 1898 // Compute the size of the first block 1899 _first_block_size = blk_labels[1].loc_pos() - blk_labels[0].loc_pos(); 1900 1901 #ifdef ASSERT 1902 for (uint i = 0; i < nblocks; i++) { // For all blocks 1903 if (jmp_target[i] != 0) { 1904 int br_size = jmp_size[i]; 1905 int offset = blk_starts[jmp_target[i]]-(blk_starts[i] + jmp_offset[i]); 1906 if (!C->matcher()->is_short_branch_offset(jmp_rule[i], br_size, offset)) { 1907 tty->print_cr("target (%d) - jmp_offset(%d) = offset (%d), jump_size(%d), jmp_block B%d, target_block B%d", blk_starts[jmp_target[i]], blk_starts[i] + jmp_offset[i], offset, br_size, i, jmp_target[i]); 1908 assert(false, "Displacement too large for short jmp"); 1909 } 1910 } 1911 } 1912 #endif 1913 1914 if (!masm->code()->finalize_stubs()) { 1915 C->record_failure("CodeCache is full"); 1916 return; 1917 } 1918 1919 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 1920 bs->emit_stubs(*masm->code()); 1921 if (C->failing()) return; 1922 1923 // Fill in stubs. 1924 assert(masm->inst_mark() == nullptr, "should be."); 1925 _stub_list.emit(*masm); 1926 if (C->failing()) return; 1927 1928 #ifndef PRODUCT 1929 // Information on the size of the method, without the extraneous code 1930 Scheduling::increment_method_size(masm->offset()); 1931 #endif 1932 1933 // ------------------ 1934 // Fill in exception table entries. 1935 FillExceptionTables(inct_cnt, call_returns, inct_starts, blk_labels); 1936 1937 // Only java methods have exception handlers and deopt handlers 1938 // class HandlerImpl is platform-specific and defined in the *.ad files. 1939 if (C->method()) { 1940 // Emit the exception handler code. 1941 _code_offsets.set_value(CodeOffsets::Exceptions, HandlerImpl::emit_exception_handler(masm)); 1942 if (C->failing()) { 1943 return; // CodeBuffer::expand failed 1944 } 1945 // Emit the deopt handler code. 1946 _code_offsets.set_value(CodeOffsets::Deopt, HandlerImpl::emit_deopt_handler(masm)); 1947 1948 // Emit the MethodHandle deopt handler code (if required). 1949 if (C->has_method_handle_invokes() && !C->failing()) { 1950 // We can use the same code as for the normal deopt handler, we 1951 // just need a different entry point address. 1952 _code_offsets.set_value(CodeOffsets::DeoptMH, HandlerImpl::emit_deopt_handler(masm)); 1953 } 1954 } 1955 1956 // One last check for failed CodeBuffer::expand: 1957 if ((masm->code()->blob() == nullptr) || (!CompileBroker::should_compile_new_jobs())) { 1958 C->record_failure("CodeCache is full"); 1959 return; 1960 } 1961 1962 #if defined(SUPPORT_ABSTRACT_ASSEMBLY) || defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_OPTO_ASSEMBLY) 1963 if (C->print_assembly()) { 1964 tty->cr(); 1965 tty->print_cr("============================= C2-compiled nmethod =============================="); 1966 } 1967 #endif 1968 1969 #if defined(SUPPORT_OPTO_ASSEMBLY) 1970 // Dump the assembly code, including basic-block numbers 1971 if (C->print_assembly()) { 1972 ttyLocker ttyl; // keep the following output all in one block 1973 if (!VMThread::should_terminate()) { // test this under the tty lock 1974 // print_metadata and dump_asm may safepoint which makes us loose the ttylock. 1975 // We call them first and write to a stringStream, then we retake the lock to 1976 // make sure the end tag is coherent, and that xmlStream->pop_tag is done thread safe. 1977 ResourceMark rm; 1978 stringStream method_metadata_str; 1979 if (C->method() != nullptr) { 1980 C->method()->print_metadata(&method_metadata_str); 1981 } 1982 stringStream dump_asm_str; 1983 dump_asm_on(&dump_asm_str, node_offsets, node_offset_limit); 1984 1985 NoSafepointVerifier nsv; 1986 ttyLocker ttyl2; 1987 // This output goes directly to the tty, not the compiler log. 1988 // To enable tools to match it up with the compilation activity, 1989 // be sure to tag this tty output with the compile ID. 1990 if (xtty != nullptr) { 1991 xtty->head("opto_assembly compile_id='%d'%s", C->compile_id(), 1992 C->is_osr_compilation() ? " compile_kind='osr'" : ""); 1993 } 1994 if (C->method() != nullptr) { 1995 tty->print_cr("----------------------- MetaData before Compile_id = %d ------------------------", C->compile_id()); 1996 tty->print_raw(method_metadata_str.freeze()); 1997 } else if (C->stub_name() != nullptr) { 1998 tty->print_cr("----------------------------- RuntimeStub %s -------------------------------", C->stub_name()); 1999 } 2000 tty->cr(); 2001 tty->print_cr("------------------------ OptoAssembly for Compile_id = %d -----------------------", C->compile_id()); 2002 tty->print_raw(dump_asm_str.freeze()); 2003 tty->print_cr("--------------------------------------------------------------------------------"); 2004 if (xtty != nullptr) { 2005 xtty->tail("opto_assembly"); 2006 } 2007 } 2008 } 2009 #endif 2010 } 2011 2012 void PhaseOutput::FillExceptionTables(uint cnt, uint *call_returns, uint *inct_starts, Label *blk_labels) { 2013 _inc_table.set_size(cnt); 2014 2015 uint inct_cnt = 0; 2016 for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) { 2017 Block* block = C->cfg()->get_block(i); 2018 Node *n = nullptr; 2019 int j; 2020 2021 // Find the branch; ignore trailing NOPs. 2022 for (j = block->number_of_nodes() - 1; j >= 0; j--) { 2023 n = block->get_node(j); 2024 if (!n->is_Mach() || n->as_Mach()->ideal_Opcode() != Op_Con) { 2025 break; 2026 } 2027 } 2028 2029 // If we didn't find anything, continue 2030 if (j < 0) { 2031 continue; 2032 } 2033 2034 // Compute ExceptionHandlerTable subtable entry and add it 2035 // (skip empty blocks) 2036 if (n->is_Catch()) { 2037 2038 // Get the offset of the return from the call 2039 uint call_return = call_returns[block->_pre_order]; 2040 #ifdef ASSERT 2041 assert( call_return > 0, "no call seen for this basic block" ); 2042 while (block->get_node(--j)->is_MachProj()) ; 2043 assert(block->get_node(j)->is_MachCall(), "CatchProj must follow call"); 2044 #endif 2045 // last instruction is a CatchNode, find it's CatchProjNodes 2046 int nof_succs = block->_num_succs; 2047 // allocate space 2048 GrowableArray<intptr_t> handler_bcis(nof_succs); 2049 GrowableArray<intptr_t> handler_pcos(nof_succs); 2050 // iterate through all successors 2051 for (int j = 0; j < nof_succs; j++) { 2052 Block* s = block->_succs[j]; 2053 bool found_p = false; 2054 for (uint k = 1; k < s->num_preds(); k++) { 2055 Node* pk = s->pred(k); 2056 if (pk->is_CatchProj() && pk->in(0) == n) { 2057 const CatchProjNode* p = pk->as_CatchProj(); 2058 found_p = true; 2059 // add the corresponding handler bci & pco information 2060 if (p->_con != CatchProjNode::fall_through_index) { 2061 // p leads to an exception handler (and is not fall through) 2062 assert(s == C->cfg()->get_block(s->_pre_order), "bad numbering"); 2063 // no duplicates, please 2064 if (!handler_bcis.contains(p->handler_bci())) { 2065 uint block_num = s->non_connector()->_pre_order; 2066 handler_bcis.append(p->handler_bci()); 2067 handler_pcos.append(blk_labels[block_num].loc_pos()); 2068 } 2069 } 2070 } 2071 } 2072 assert(found_p, "no matching predecessor found"); 2073 // Note: Due to empty block removal, one block may have 2074 // several CatchProj inputs, from the same Catch. 2075 } 2076 2077 // Set the offset of the return from the call 2078 assert(handler_bcis.find(-1) != -1, "must have default handler"); 2079 _handler_table.add_subtable(call_return, &handler_bcis, nullptr, &handler_pcos); 2080 continue; 2081 } 2082 2083 // Handle implicit null exception table updates 2084 if (n->is_MachNullCheck()) { 2085 assert(n->in(1)->as_Mach()->barrier_data() == 0, 2086 "Implicit null checks on memory accesses with barriers are not yet supported"); 2087 uint block_num = block->non_connector_successor(0)->_pre_order; 2088 _inc_table.append(inct_starts[inct_cnt++], blk_labels[block_num].loc_pos()); 2089 continue; 2090 } 2091 // Handle implicit exception table updates: trap instructions. 2092 if (n->is_Mach() && n->as_Mach()->is_TrapBasedCheckNode()) { 2093 uint block_num = block->non_connector_successor(0)->_pre_order; 2094 _inc_table.append(inct_starts[inct_cnt++], blk_labels[block_num].loc_pos()); 2095 continue; 2096 } 2097 } // End of for all blocks fill in exception table entries 2098 } 2099 2100 // Static Variables 2101 #ifndef PRODUCT 2102 uint Scheduling::_total_nop_size = 0; 2103 uint Scheduling::_total_method_size = 0; 2104 uint Scheduling::_total_branches = 0; 2105 uint Scheduling::_total_unconditional_delays = 0; 2106 uint Scheduling::_total_instructions_per_bundle[Pipeline::_max_instrs_per_cycle+1]; 2107 #endif 2108 2109 // Initializer for class Scheduling 2110 2111 Scheduling::Scheduling(Arena *arena, Compile &compile) 2112 : _arena(arena), 2113 _cfg(compile.cfg()), 2114 _regalloc(compile.regalloc()), 2115 _scheduled(arena), 2116 _available(arena), 2117 _reg_node(arena), 2118 _pinch_free_list(arena), 2119 _next_node(nullptr), 2120 _bundle_instr_count(0), 2121 _bundle_cycle_number(0), 2122 _bundle_use(0, 0, resource_count, &_bundle_use_elements[0]) 2123 #ifndef PRODUCT 2124 , _branches(0) 2125 , _unconditional_delays(0) 2126 #endif 2127 { 2128 // Create a MachNopNode 2129 _nop = new MachNopNode(); 2130 2131 // Now that the nops are in the array, save the count 2132 // (but allow entries for the nops) 2133 _node_bundling_limit = compile.unique(); 2134 uint node_max = _regalloc->node_regs_max_index(); 2135 2136 compile.output()->set_node_bundling_limit(_node_bundling_limit); 2137 2138 // This one is persistent within the Compile class 2139 _node_bundling_base = NEW_ARENA_ARRAY(compile.comp_arena(), Bundle, node_max); 2140 2141 // Allocate space for fixed-size arrays 2142 _uses = NEW_ARENA_ARRAY(arena, short, node_max); 2143 _current_latency = NEW_ARENA_ARRAY(arena, unsigned short, node_max); 2144 2145 // Clear the arrays 2146 for (uint i = 0; i < node_max; i++) { 2147 ::new (&_node_bundling_base[i]) Bundle(); 2148 } 2149 memset(_uses, 0, node_max * sizeof(short)); 2150 memset(_current_latency, 0, node_max * sizeof(unsigned short)); 2151 2152 // Clear the bundling information 2153 memcpy(_bundle_use_elements, Pipeline_Use::elaborated_elements, sizeof(Pipeline_Use::elaborated_elements)); 2154 2155 // Get the last node 2156 Block* block = _cfg->get_block(_cfg->number_of_blocks() - 1); 2157 2158 _next_node = block->get_node(block->number_of_nodes() - 1); 2159 } 2160 2161 #ifndef PRODUCT 2162 // Scheduling destructor 2163 Scheduling::~Scheduling() { 2164 _total_branches += _branches; 2165 _total_unconditional_delays += _unconditional_delays; 2166 } 2167 #endif 2168 2169 // Step ahead "i" cycles 2170 void Scheduling::step(uint i) { 2171 2172 Bundle *bundle = node_bundling(_next_node); 2173 bundle->set_starts_bundle(); 2174 2175 // Update the bundle record, but leave the flags information alone 2176 if (_bundle_instr_count > 0) { 2177 bundle->set_instr_count(_bundle_instr_count); 2178 bundle->set_resources_used(_bundle_use.resourcesUsed()); 2179 } 2180 2181 // Update the state information 2182 _bundle_instr_count = 0; 2183 _bundle_cycle_number += i; 2184 _bundle_use.step(i); 2185 } 2186 2187 void Scheduling::step_and_clear() { 2188 Bundle *bundle = node_bundling(_next_node); 2189 bundle->set_starts_bundle(); 2190 2191 // Update the bundle record 2192 if (_bundle_instr_count > 0) { 2193 bundle->set_instr_count(_bundle_instr_count); 2194 bundle->set_resources_used(_bundle_use.resourcesUsed()); 2195 2196 _bundle_cycle_number += 1; 2197 } 2198 2199 // Clear the bundling information 2200 _bundle_instr_count = 0; 2201 _bundle_use.reset(); 2202 2203 memcpy(_bundle_use_elements, 2204 Pipeline_Use::elaborated_elements, 2205 sizeof(Pipeline_Use::elaborated_elements)); 2206 } 2207 2208 // Perform instruction scheduling and bundling over the sequence of 2209 // instructions in backwards order. 2210 void PhaseOutput::ScheduleAndBundle() { 2211 2212 // Don't optimize this if it isn't a method 2213 if (!C->method()) 2214 return; 2215 2216 // Don't optimize this if scheduling is disabled 2217 if (!C->do_scheduling()) 2218 return; 2219 2220 // Scheduling code works only with pairs (8 bytes) maximum. 2221 // And when the scalable vector register is used, we may spill/unspill 2222 // the whole reg regardless of the max vector size. 2223 if (C->max_vector_size() > 8 || 2224 (C->max_vector_size() > 0 && Matcher::supports_scalable_vector())) { 2225 return; 2226 } 2227 2228 Compile::TracePhase tp(_t_instrSched); 2229 2230 // Create a data structure for all the scheduling information 2231 Scheduling scheduling(Thread::current()->resource_area(), *C); 2232 2233 // Walk backwards over each basic block, computing the needed alignment 2234 // Walk over all the basic blocks 2235 scheduling.DoScheduling(); 2236 2237 #ifndef PRODUCT 2238 if (C->trace_opto_output()) { 2239 // Buffer and print all at once 2240 ResourceMark rm; 2241 stringStream ss; 2242 ss.print("\n---- After ScheduleAndBundle ----\n"); 2243 print_scheduling(&ss); 2244 tty->print("%s", ss.as_string()); 2245 } 2246 #endif 2247 } 2248 2249 #ifndef PRODUCT 2250 // Separated out so that it can be called directly from debugger 2251 void PhaseOutput::print_scheduling() { 2252 print_scheduling(tty); 2253 } 2254 2255 void PhaseOutput::print_scheduling(outputStream* output_stream) { 2256 for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) { 2257 output_stream->print("\nBB#%03d:\n", i); 2258 Block* block = C->cfg()->get_block(i); 2259 for (uint j = 0; j < block->number_of_nodes(); j++) { 2260 Node* n = block->get_node(j); 2261 OptoReg::Name reg = C->regalloc()->get_reg_first(n); 2262 output_stream->print(" %-6s ", reg >= 0 && reg < REG_COUNT ? Matcher::regName[reg] : ""); 2263 n->dump("\n", false, output_stream); 2264 } 2265 } 2266 } 2267 #endif 2268 2269 // See if this node fits into the present instruction bundle 2270 bool Scheduling::NodeFitsInBundle(Node *n) { 2271 uint n_idx = n->_idx; 2272 2273 // If this is the unconditional delay instruction, then it fits 2274 if (n == _unconditional_delay_slot) { 2275 #ifndef PRODUCT 2276 if (_cfg->C->trace_opto_output()) 2277 tty->print("# NodeFitsInBundle [%4d]: TRUE; is in unconditional delay slot\n", n->_idx); 2278 #endif 2279 return (true); 2280 } 2281 2282 // If the node cannot be scheduled this cycle, skip it 2283 if (_current_latency[n_idx] > _bundle_cycle_number) { 2284 #ifndef PRODUCT 2285 if (_cfg->C->trace_opto_output()) 2286 tty->print("# NodeFitsInBundle [%4d]: FALSE; latency %4d > %d\n", 2287 n->_idx, _current_latency[n_idx], _bundle_cycle_number); 2288 #endif 2289 return (false); 2290 } 2291 2292 const Pipeline *node_pipeline = n->pipeline(); 2293 2294 uint instruction_count = node_pipeline->instructionCount(); 2295 if (node_pipeline->mayHaveNoCode() && n->size(_regalloc) == 0) 2296 instruction_count = 0; 2297 else if (node_pipeline->hasBranchDelay() && !_unconditional_delay_slot) 2298 instruction_count++; 2299 2300 if (_bundle_instr_count + instruction_count > Pipeline::_max_instrs_per_cycle) { 2301 #ifndef PRODUCT 2302 if (_cfg->C->trace_opto_output()) 2303 tty->print("# NodeFitsInBundle [%4d]: FALSE; too many instructions: %d > %d\n", 2304 n->_idx, _bundle_instr_count + instruction_count, Pipeline::_max_instrs_per_cycle); 2305 #endif 2306 return (false); 2307 } 2308 2309 // Don't allow non-machine nodes to be handled this way 2310 if (!n->is_Mach() && instruction_count == 0) 2311 return (false); 2312 2313 // See if there is any overlap 2314 uint delay = _bundle_use.full_latency(0, node_pipeline->resourceUse()); 2315 2316 if (delay > 0) { 2317 #ifndef PRODUCT 2318 if (_cfg->C->trace_opto_output()) 2319 tty->print("# NodeFitsInBundle [%4d]: FALSE; functional units overlap\n", n_idx); 2320 #endif 2321 return false; 2322 } 2323 2324 #ifndef PRODUCT 2325 if (_cfg->C->trace_opto_output()) 2326 tty->print("# NodeFitsInBundle [%4d]: TRUE\n", n_idx); 2327 #endif 2328 2329 return true; 2330 } 2331 2332 Node * Scheduling::ChooseNodeToBundle() { 2333 uint siz = _available.size(); 2334 2335 if (siz == 0) { 2336 2337 #ifndef PRODUCT 2338 if (_cfg->C->trace_opto_output()) 2339 tty->print("# ChooseNodeToBundle: null\n"); 2340 #endif 2341 return (nullptr); 2342 } 2343 2344 // Fast path, if only 1 instruction in the bundle 2345 if (siz == 1) { 2346 #ifndef PRODUCT 2347 if (_cfg->C->trace_opto_output()) { 2348 tty->print("# ChooseNodeToBundle (only 1): "); 2349 _available[0]->dump(); 2350 } 2351 #endif 2352 return (_available[0]); 2353 } 2354 2355 // Don't bother, if the bundle is already full 2356 if (_bundle_instr_count < Pipeline::_max_instrs_per_cycle) { 2357 for ( uint i = 0; i < siz; i++ ) { 2358 Node *n = _available[i]; 2359 2360 // Skip projections, we'll handle them another way 2361 if (n->is_Proj()) 2362 continue; 2363 2364 // This presupposed that instructions are inserted into the 2365 // available list in a legality order; i.e. instructions that 2366 // must be inserted first are at the head of the list 2367 if (NodeFitsInBundle(n)) { 2368 #ifndef PRODUCT 2369 if (_cfg->C->trace_opto_output()) { 2370 tty->print("# ChooseNodeToBundle: "); 2371 n->dump(); 2372 } 2373 #endif 2374 return (n); 2375 } 2376 } 2377 } 2378 2379 // Nothing fits in this bundle, choose the highest priority 2380 #ifndef PRODUCT 2381 if (_cfg->C->trace_opto_output()) { 2382 tty->print("# ChooseNodeToBundle: "); 2383 _available[0]->dump(); 2384 } 2385 #endif 2386 2387 return _available[0]; 2388 } 2389 2390 int Scheduling::compare_two_spill_nodes(Node* first, Node* second) { 2391 assert(first->is_MachSpillCopy() && second->is_MachSpillCopy(), ""); 2392 2393 OptoReg::Name first_src_lo = _regalloc->get_reg_first(first->in(1)); 2394 OptoReg::Name first_dst_lo = _regalloc->get_reg_first(first); 2395 OptoReg::Name second_src_lo = _regalloc->get_reg_first(second->in(1)); 2396 OptoReg::Name second_dst_lo = _regalloc->get_reg_first(second); 2397 2398 // Comparison between stack -> reg and stack -> reg 2399 if (OptoReg::is_stack(first_src_lo) && OptoReg::is_stack(second_src_lo) && 2400 OptoReg::is_reg(first_dst_lo) && OptoReg::is_reg(second_dst_lo)) { 2401 return _regalloc->reg2offset(first_src_lo) - _regalloc->reg2offset(second_src_lo); 2402 } 2403 2404 // Comparison between reg -> stack and reg -> stack 2405 if (OptoReg::is_stack(first_dst_lo) && OptoReg::is_stack(second_dst_lo) && 2406 OptoReg::is_reg(first_src_lo) && OptoReg::is_reg(second_src_lo)) { 2407 return _regalloc->reg2offset(first_dst_lo) - _regalloc->reg2offset(second_dst_lo); 2408 } 2409 2410 return 0; // Not comparable 2411 } 2412 2413 void Scheduling::AddNodeToAvailableList(Node *n) { 2414 assert( !n->is_Proj(), "projections never directly made available" ); 2415 #ifndef PRODUCT 2416 if (_cfg->C->trace_opto_output()) { 2417 tty->print("# AddNodeToAvailableList: "); 2418 n->dump(); 2419 } 2420 #endif 2421 2422 int latency = _current_latency[n->_idx]; 2423 2424 // Insert in latency order (insertion sort). If two MachSpillCopyNodes 2425 // for stack spilling or unspilling have the same latency, we sort 2426 // them in the order of stack offset. Some ports (e.g. aarch64) may also 2427 // have more opportunities to do ld/st merging 2428 uint i; 2429 for (i = 0; i < _available.size(); i++) { 2430 if (_current_latency[_available[i]->_idx] > latency) { 2431 break; 2432 } else if (_current_latency[_available[i]->_idx] == latency && 2433 n->is_MachSpillCopy() && _available[i]->is_MachSpillCopy() && 2434 compare_two_spill_nodes(n, _available[i]) > 0) { 2435 break; 2436 } 2437 } 2438 2439 // Special Check for compares following branches 2440 if( n->is_Mach() && _scheduled.size() > 0 ) { 2441 int op = n->as_Mach()->ideal_Opcode(); 2442 Node *last = _scheduled[0]; 2443 if( last->is_MachIf() && last->in(1) == n && 2444 ( op == Op_CmpI || 2445 op == Op_CmpU || 2446 op == Op_CmpUL || 2447 op == Op_CmpP || 2448 op == Op_CmpF || 2449 op == Op_CmpD || 2450 op == Op_CmpL ) ) { 2451 2452 // Recalculate position, moving to front of same latency 2453 for ( i=0 ; i < _available.size(); i++ ) 2454 if (_current_latency[_available[i]->_idx] >= latency) 2455 break; 2456 } 2457 } 2458 2459 // Insert the node in the available list 2460 _available.insert(i, n); 2461 2462 #ifndef PRODUCT 2463 if (_cfg->C->trace_opto_output()) 2464 dump_available(); 2465 #endif 2466 } 2467 2468 void Scheduling::DecrementUseCounts(Node *n, const Block *bb) { 2469 for ( uint i=0; i < n->len(); i++ ) { 2470 Node *def = n->in(i); 2471 if (!def) continue; 2472 if( def->is_Proj() ) // If this is a machine projection, then 2473 def = def->in(0); // propagate usage thru to the base instruction 2474 2475 if(_cfg->get_block_for_node(def) != bb) { // Ignore if not block-local 2476 continue; 2477 } 2478 2479 // Compute the latency 2480 uint l = _bundle_cycle_number + n->latency(i); 2481 if (_current_latency[def->_idx] < l) 2482 _current_latency[def->_idx] = l; 2483 2484 // If this does not have uses then schedule it 2485 if ((--_uses[def->_idx]) == 0) 2486 AddNodeToAvailableList(def); 2487 } 2488 } 2489 2490 void Scheduling::AddNodeToBundle(Node *n, const Block *bb) { 2491 #ifndef PRODUCT 2492 if (_cfg->C->trace_opto_output()) { 2493 tty->print("# AddNodeToBundle: "); 2494 n->dump(); 2495 } 2496 #endif 2497 2498 // Remove this from the available list 2499 uint i; 2500 for (i = 0; i < _available.size(); i++) 2501 if (_available[i] == n) 2502 break; 2503 assert(i < _available.size(), "entry in _available list not found"); 2504 _available.remove(i); 2505 2506 // See if this fits in the current bundle 2507 const Pipeline *node_pipeline = n->pipeline(); 2508 const Pipeline_Use& node_usage = node_pipeline->resourceUse(); 2509 2510 // Check for instructions to be placed in the delay slot. We 2511 // do this before we actually schedule the current instruction, 2512 // because the delay slot follows the current instruction. 2513 if (Pipeline::_branch_has_delay_slot && 2514 node_pipeline->hasBranchDelay() && 2515 !_unconditional_delay_slot) { 2516 2517 uint siz = _available.size(); 2518 2519 // Conditional branches can support an instruction that 2520 // is unconditionally executed and not dependent by the 2521 // branch, OR a conditionally executed instruction if 2522 // the branch is taken. In practice, this means that 2523 // the first instruction at the branch target is 2524 // copied to the delay slot, and the branch goes to 2525 // the instruction after that at the branch target 2526 if ( n->is_MachBranch() ) { 2527 2528 assert( !n->is_MachNullCheck(), "should not look for delay slot for Null Check" ); 2529 assert( !n->is_Catch(), "should not look for delay slot for Catch" ); 2530 2531 #ifndef PRODUCT 2532 _branches++; 2533 #endif 2534 2535 // At least 1 instruction is on the available list 2536 // that is not dependent on the branch 2537 for (uint i = 0; i < siz; i++) { 2538 Node *d = _available[i]; 2539 const Pipeline *avail_pipeline = d->pipeline(); 2540 2541 // Don't allow safepoints in the branch shadow, that will 2542 // cause a number of difficulties 2543 if ( avail_pipeline->instructionCount() == 1 && 2544 !avail_pipeline->hasMultipleBundles() && 2545 !avail_pipeline->hasBranchDelay() && 2546 Pipeline::instr_has_unit_size() && 2547 d->size(_regalloc) == Pipeline::instr_unit_size() && 2548 NodeFitsInBundle(d) && 2549 !node_bundling(d)->used_in_delay()) { 2550 2551 if (d->is_Mach() && !d->is_MachSafePoint()) { 2552 // A node that fits in the delay slot was found, so we need to 2553 // set the appropriate bits in the bundle pipeline information so 2554 // that it correctly indicates resource usage. Later, when we 2555 // attempt to add this instruction to the bundle, we will skip 2556 // setting the resource usage. 2557 _unconditional_delay_slot = d; 2558 node_bundling(n)->set_use_unconditional_delay(); 2559 node_bundling(d)->set_used_in_unconditional_delay(); 2560 _bundle_use.add_usage(avail_pipeline->resourceUse()); 2561 _current_latency[d->_idx] = _bundle_cycle_number; 2562 _next_node = d; 2563 ++_bundle_instr_count; 2564 #ifndef PRODUCT 2565 _unconditional_delays++; 2566 #endif 2567 break; 2568 } 2569 } 2570 } 2571 } 2572 2573 // No delay slot, add a nop to the usage 2574 if (!_unconditional_delay_slot) { 2575 // See if adding an instruction in the delay slot will overflow 2576 // the bundle. 2577 if (!NodeFitsInBundle(_nop)) { 2578 #ifndef PRODUCT 2579 if (_cfg->C->trace_opto_output()) 2580 tty->print("# *** STEP(1 instruction for delay slot) ***\n"); 2581 #endif 2582 step(1); 2583 } 2584 2585 _bundle_use.add_usage(_nop->pipeline()->resourceUse()); 2586 _next_node = _nop; 2587 ++_bundle_instr_count; 2588 } 2589 2590 // See if the instruction in the delay slot requires a 2591 // step of the bundles 2592 if (!NodeFitsInBundle(n)) { 2593 #ifndef PRODUCT 2594 if (_cfg->C->trace_opto_output()) 2595 tty->print("# *** STEP(branch won't fit) ***\n"); 2596 #endif 2597 // Update the state information 2598 _bundle_instr_count = 0; 2599 _bundle_cycle_number += 1; 2600 _bundle_use.step(1); 2601 } 2602 } 2603 2604 // Get the number of instructions 2605 uint instruction_count = node_pipeline->instructionCount(); 2606 if (node_pipeline->mayHaveNoCode() && n->size(_regalloc) == 0) 2607 instruction_count = 0; 2608 2609 // Compute the latency information 2610 uint delay = 0; 2611 2612 if (instruction_count > 0 || !node_pipeline->mayHaveNoCode()) { 2613 int relative_latency = _current_latency[n->_idx] - _bundle_cycle_number; 2614 if (relative_latency < 0) 2615 relative_latency = 0; 2616 2617 delay = _bundle_use.full_latency(relative_latency, node_usage); 2618 2619 // Does not fit in this bundle, start a new one 2620 if (delay > 0) { 2621 step(delay); 2622 2623 #ifndef PRODUCT 2624 if (_cfg->C->trace_opto_output()) 2625 tty->print("# *** STEP(%d) ***\n", delay); 2626 #endif 2627 } 2628 } 2629 2630 // If this was placed in the delay slot, ignore it 2631 if (n != _unconditional_delay_slot) { 2632 2633 if (delay == 0) { 2634 if (node_pipeline->hasMultipleBundles()) { 2635 #ifndef PRODUCT 2636 if (_cfg->C->trace_opto_output()) 2637 tty->print("# *** STEP(multiple instructions) ***\n"); 2638 #endif 2639 step(1); 2640 } 2641 2642 else if (instruction_count + _bundle_instr_count > Pipeline::_max_instrs_per_cycle) { 2643 #ifndef PRODUCT 2644 if (_cfg->C->trace_opto_output()) 2645 tty->print("# *** STEP(%d >= %d instructions) ***\n", 2646 instruction_count + _bundle_instr_count, 2647 Pipeline::_max_instrs_per_cycle); 2648 #endif 2649 step(1); 2650 } 2651 } 2652 2653 if (node_pipeline->hasBranchDelay() && !_unconditional_delay_slot) 2654 _bundle_instr_count++; 2655 2656 // Set the node's latency 2657 _current_latency[n->_idx] = _bundle_cycle_number; 2658 2659 // Now merge the functional unit information 2660 if (instruction_count > 0 || !node_pipeline->mayHaveNoCode()) 2661 _bundle_use.add_usage(node_usage); 2662 2663 // Increment the number of instructions in this bundle 2664 _bundle_instr_count += instruction_count; 2665 2666 // Remember this node for later 2667 if (n->is_Mach()) 2668 _next_node = n; 2669 } 2670 2671 // It's possible to have a BoxLock in the graph and in the _bbs mapping but 2672 // not in the bb->_nodes array. This happens for debug-info-only BoxLocks. 2673 // 'Schedule' them (basically ignore in the schedule) but do not insert them 2674 // into the block. All other scheduled nodes get put in the schedule here. 2675 int op = n->Opcode(); 2676 if( (op == Op_Node && n->req() == 0) || // anti-dependence node OR 2677 (op != Op_Node && // Not an unused antidepedence node and 2678 // not an unallocated boxlock 2679 (OptoReg::is_valid(_regalloc->get_reg_first(n)) || op != Op_BoxLock)) ) { 2680 2681 // Push any trailing projections 2682 if( bb->get_node(bb->number_of_nodes()-1) != n ) { 2683 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 2684 Node *foi = n->fast_out(i); 2685 if( foi->is_Proj() ) 2686 _scheduled.push(foi); 2687 } 2688 } 2689 2690 // Put the instruction in the schedule list 2691 _scheduled.push(n); 2692 } 2693 2694 #ifndef PRODUCT 2695 if (_cfg->C->trace_opto_output()) 2696 dump_available(); 2697 #endif 2698 2699 // Walk all the definitions, decrementing use counts, and 2700 // if a definition has a 0 use count, place it in the available list. 2701 DecrementUseCounts(n,bb); 2702 } 2703 2704 // This method sets the use count within a basic block. We will ignore all 2705 // uses outside the current basic block. As we are doing a backwards walk, 2706 // any node we reach that has a use count of 0 may be scheduled. This also 2707 // avoids the problem of cyclic references from phi nodes, as long as phi 2708 // nodes are at the front of the basic block. This method also initializes 2709 // the available list to the set of instructions that have no uses within this 2710 // basic block. 2711 void Scheduling::ComputeUseCount(const Block *bb) { 2712 #ifndef PRODUCT 2713 if (_cfg->C->trace_opto_output()) 2714 tty->print("# -> ComputeUseCount\n"); 2715 #endif 2716 2717 // Clear the list of available and scheduled instructions, just in case 2718 _available.clear(); 2719 _scheduled.clear(); 2720 2721 // No delay slot specified 2722 _unconditional_delay_slot = nullptr; 2723 2724 #ifdef ASSERT 2725 for( uint i=0; i < bb->number_of_nodes(); i++ ) 2726 assert( _uses[bb->get_node(i)->_idx] == 0, "_use array not clean" ); 2727 #endif 2728 2729 // Force the _uses count to never go to zero for unscheduable pieces 2730 // of the block 2731 for( uint k = 0; k < _bb_start; k++ ) 2732 _uses[bb->get_node(k)->_idx] = 1; 2733 for( uint l = _bb_end; l < bb->number_of_nodes(); l++ ) 2734 _uses[bb->get_node(l)->_idx] = 1; 2735 2736 // Iterate backwards over the instructions in the block. Don't count the 2737 // branch projections at end or the block header instructions. 2738 for( uint j = _bb_end-1; j >= _bb_start; j-- ) { 2739 Node *n = bb->get_node(j); 2740 if( n->is_Proj() ) continue; // Projections handled another way 2741 2742 // Account for all uses 2743 for ( uint k = 0; k < n->len(); k++ ) { 2744 Node *inp = n->in(k); 2745 if (!inp) continue; 2746 assert(inp != n, "no cycles allowed" ); 2747 if (_cfg->get_block_for_node(inp) == bb) { // Block-local use? 2748 if (inp->is_Proj()) { // Skip through Proj's 2749 inp = inp->in(0); 2750 } 2751 ++_uses[inp->_idx]; // Count 1 block-local use 2752 } 2753 } 2754 2755 // If this instruction has a 0 use count, then it is available 2756 if (!_uses[n->_idx]) { 2757 _current_latency[n->_idx] = _bundle_cycle_number; 2758 AddNodeToAvailableList(n); 2759 } 2760 2761 #ifndef PRODUCT 2762 if (_cfg->C->trace_opto_output()) { 2763 tty->print("# uses: %3d: ", _uses[n->_idx]); 2764 n->dump(); 2765 } 2766 #endif 2767 } 2768 2769 #ifndef PRODUCT 2770 if (_cfg->C->trace_opto_output()) 2771 tty->print("# <- ComputeUseCount\n"); 2772 #endif 2773 } 2774 2775 // This routine performs scheduling on each basic block in reverse order, 2776 // using instruction latencies and taking into account function unit 2777 // availability. 2778 void Scheduling::DoScheduling() { 2779 #ifndef PRODUCT 2780 if (_cfg->C->trace_opto_output()) 2781 tty->print("# -> DoScheduling\n"); 2782 #endif 2783 2784 Block *succ_bb = nullptr; 2785 Block *bb; 2786 Compile* C = Compile::current(); 2787 2788 // Walk over all the basic blocks in reverse order 2789 for (int i = _cfg->number_of_blocks() - 1; i >= 0; succ_bb = bb, i--) { 2790 bb = _cfg->get_block(i); 2791 2792 #ifndef PRODUCT 2793 if (_cfg->C->trace_opto_output()) { 2794 tty->print("# Schedule BB#%03d (initial)\n", i); 2795 for (uint j = 0; j < bb->number_of_nodes(); j++) { 2796 bb->get_node(j)->dump(); 2797 } 2798 } 2799 #endif 2800 2801 // On the head node, skip processing 2802 if (bb == _cfg->get_root_block()) { 2803 continue; 2804 } 2805 2806 // Skip empty, connector blocks 2807 if (bb->is_connector()) 2808 continue; 2809 2810 // If the following block is not the sole successor of 2811 // this one, then reset the pipeline information 2812 if (bb->_num_succs != 1 || bb->non_connector_successor(0) != succ_bb) { 2813 #ifndef PRODUCT 2814 if (_cfg->C->trace_opto_output()) { 2815 tty->print("*** bundle start of next BB, node %d, for %d instructions\n", 2816 _next_node->_idx, _bundle_instr_count); 2817 } 2818 #endif 2819 step_and_clear(); 2820 } 2821 2822 // Leave untouched the starting instruction, any Phis, a CreateEx node 2823 // or Top. bb->get_node(_bb_start) is the first schedulable instruction. 2824 _bb_end = bb->number_of_nodes()-1; 2825 for( _bb_start=1; _bb_start <= _bb_end; _bb_start++ ) { 2826 Node *n = bb->get_node(_bb_start); 2827 // Things not matched, like Phinodes and ProjNodes don't get scheduled. 2828 // Also, MachIdealNodes do not get scheduled 2829 if( !n->is_Mach() ) continue; // Skip non-machine nodes 2830 MachNode *mach = n->as_Mach(); 2831 int iop = mach->ideal_Opcode(); 2832 if( iop == Op_CreateEx ) continue; // CreateEx is pinned 2833 if( iop == Op_Con ) continue; // Do not schedule Top 2834 if( iop == Op_Node && // Do not schedule PhiNodes, ProjNodes 2835 mach->pipeline() == MachNode::pipeline_class() && 2836 !n->is_SpillCopy() && !n->is_MachMerge() ) // Breakpoints, Prolog, etc 2837 continue; 2838 break; // Funny loop structure to be sure... 2839 } 2840 // Compute last "interesting" instruction in block - last instruction we 2841 // might schedule. _bb_end points just after last schedulable inst. We 2842 // normally schedule conditional branches (despite them being forced last 2843 // in the block), because they have delay slots we can fill. Calls all 2844 // have their delay slots filled in the template expansions, so we don't 2845 // bother scheduling them. 2846 Node *last = bb->get_node(_bb_end); 2847 // Ignore trailing NOPs. 2848 while (_bb_end > 0 && last->is_Mach() && 2849 last->as_Mach()->ideal_Opcode() == Op_Con) { 2850 last = bb->get_node(--_bb_end); 2851 } 2852 assert(!last->is_Mach() || last->as_Mach()->ideal_Opcode() != Op_Con, ""); 2853 if( last->is_Catch() || 2854 (last->is_Mach() && last->as_Mach()->ideal_Opcode() == Op_Halt) ) { 2855 // There might be a prior call. Skip it. 2856 while (_bb_start < _bb_end && bb->get_node(--_bb_end)->is_MachProj()); 2857 } else if( last->is_MachNullCheck() ) { 2858 // Backup so the last null-checked memory instruction is 2859 // outside the schedulable range. Skip over the nullcheck, 2860 // projection, and the memory nodes. 2861 Node *mem = last->in(1); 2862 do { 2863 _bb_end--; 2864 } while (mem != bb->get_node(_bb_end)); 2865 } else { 2866 // Set _bb_end to point after last schedulable inst. 2867 _bb_end++; 2868 } 2869 2870 assert( _bb_start <= _bb_end, "inverted block ends" ); 2871 2872 // Compute the register antidependencies for the basic block 2873 ComputeRegisterAntidependencies(bb); 2874 if (C->failing()) return; // too many D-U pinch points 2875 2876 // Compute the usage within the block, and set the list of all nodes 2877 // in the block that have no uses within the block. 2878 ComputeUseCount(bb); 2879 2880 // Schedule the remaining instructions in the block 2881 while ( _available.size() > 0 ) { 2882 Node *n = ChooseNodeToBundle(); 2883 guarantee(n != nullptr, "no nodes available"); 2884 AddNodeToBundle(n,bb); 2885 } 2886 2887 assert( _scheduled.size() == _bb_end - _bb_start, "wrong number of instructions" ); 2888 #ifdef ASSERT 2889 for( uint l = _bb_start; l < _bb_end; l++ ) { 2890 Node *n = bb->get_node(l); 2891 uint m; 2892 for( m = 0; m < _bb_end-_bb_start; m++ ) 2893 if( _scheduled[m] == n ) 2894 break; 2895 assert( m < _bb_end-_bb_start, "instruction missing in schedule" ); 2896 } 2897 #endif 2898 2899 // Now copy the instructions (in reverse order) back to the block 2900 for ( uint k = _bb_start; k < _bb_end; k++ ) 2901 bb->map_node(_scheduled[_bb_end-k-1], k); 2902 2903 #ifndef PRODUCT 2904 if (_cfg->C->trace_opto_output()) { 2905 tty->print("# Schedule BB#%03d (final)\n", i); 2906 uint current = 0; 2907 for (uint j = 0; j < bb->number_of_nodes(); j++) { 2908 Node *n = bb->get_node(j); 2909 if( valid_bundle_info(n) ) { 2910 Bundle *bundle = node_bundling(n); 2911 if (bundle->instr_count() > 0 || bundle->flags() > 0) { 2912 tty->print("*** Bundle: "); 2913 bundle->dump(); 2914 } 2915 n->dump(); 2916 } 2917 } 2918 } 2919 #endif 2920 #ifdef ASSERT 2921 verify_good_schedule(bb,"after block local scheduling"); 2922 #endif 2923 } 2924 2925 #ifndef PRODUCT 2926 if (_cfg->C->trace_opto_output()) 2927 tty->print("# <- DoScheduling\n"); 2928 #endif 2929 2930 // Record final node-bundling array location 2931 _regalloc->C->output()->set_node_bundling_base(_node_bundling_base); 2932 2933 } // end DoScheduling 2934 2935 // Verify that no live-range used in the block is killed in the block by a 2936 // wrong DEF. This doesn't verify live-ranges that span blocks. 2937 2938 // Check for edge existence. Used to avoid adding redundant precedence edges. 2939 static bool edge_from_to( Node *from, Node *to ) { 2940 for( uint i=0; i<from->len(); i++ ) 2941 if( from->in(i) == to ) 2942 return true; 2943 return false; 2944 } 2945 2946 #ifdef ASSERT 2947 void Scheduling::verify_do_def( Node *n, OptoReg::Name def, const char *msg ) { 2948 // Check for bad kills 2949 if( OptoReg::is_valid(def) ) { // Ignore stores & control flow 2950 Node *prior_use = _reg_node[def]; 2951 if( prior_use && !edge_from_to(prior_use,n) ) { 2952 tty->print("%s = ",OptoReg::as_VMReg(def)->name()); 2953 n->dump(); 2954 tty->print_cr("..."); 2955 prior_use->dump(); 2956 assert(edge_from_to(prior_use,n), "%s", msg); 2957 } 2958 _reg_node.map(def,nullptr); // Kill live USEs 2959 } 2960 } 2961 2962 void Scheduling::verify_good_schedule( Block *b, const char *msg ) { 2963 2964 // Zap to something reasonable for the verify code 2965 _reg_node.clear(); 2966 2967 // Walk over the block backwards. Check to make sure each DEF doesn't 2968 // kill a live value (other than the one it's supposed to). Add each 2969 // USE to the live set. 2970 for( uint i = b->number_of_nodes()-1; i >= _bb_start; i-- ) { 2971 Node *n = b->get_node(i); 2972 int n_op = n->Opcode(); 2973 if( n_op == Op_MachProj && n->ideal_reg() == MachProjNode::fat_proj ) { 2974 // Fat-proj kills a slew of registers 2975 RegMaskIterator rmi(n->out_RegMask()); 2976 while (rmi.has_next()) { 2977 OptoReg::Name kill = rmi.next(); 2978 verify_do_def(n, kill, msg); 2979 } 2980 } else if( n_op != Op_Node ) { // Avoid brand new antidependence nodes 2981 // Get DEF'd registers the normal way 2982 verify_do_def( n, _regalloc->get_reg_first(n), msg ); 2983 verify_do_def( n, _regalloc->get_reg_second(n), msg ); 2984 } 2985 2986 // Now make all USEs live 2987 for( uint i=1; i<n->req(); i++ ) { 2988 Node *def = n->in(i); 2989 assert(def != nullptr, "input edge required"); 2990 OptoReg::Name reg_lo = _regalloc->get_reg_first(def); 2991 OptoReg::Name reg_hi = _regalloc->get_reg_second(def); 2992 if( OptoReg::is_valid(reg_lo) ) { 2993 assert(!_reg_node[reg_lo] || edge_from_to(_reg_node[reg_lo],def), "%s", msg); 2994 _reg_node.map(reg_lo,n); 2995 } 2996 if( OptoReg::is_valid(reg_hi) ) { 2997 assert(!_reg_node[reg_hi] || edge_from_to(_reg_node[reg_hi],def), "%s", msg); 2998 _reg_node.map(reg_hi,n); 2999 } 3000 } 3001 3002 } 3003 3004 // Zap to something reasonable for the Antidependence code 3005 _reg_node.clear(); 3006 } 3007 #endif 3008 3009 // Conditionally add precedence edges. Avoid putting edges on Projs. 3010 static void add_prec_edge_from_to( Node *from, Node *to ) { 3011 if( from->is_Proj() ) { // Put precedence edge on Proj's input 3012 assert( from->req() == 1 && (from->len() == 1 || from->in(1) == nullptr), "no precedence edges on projections" ); 3013 from = from->in(0); 3014 } 3015 if( from != to && // No cycles (for things like LD L0,[L0+4] ) 3016 !edge_from_to( from, to ) ) // Avoid duplicate edge 3017 from->add_prec(to); 3018 } 3019 3020 void Scheduling::anti_do_def( Block *b, Node *def, OptoReg::Name def_reg, int is_def ) { 3021 if( !OptoReg::is_valid(def_reg) ) // Ignore stores & control flow 3022 return; 3023 3024 if (OptoReg::is_reg(def_reg)) { 3025 VMReg vmreg = OptoReg::as_VMReg(def_reg); 3026 if (vmreg->is_reg() && !vmreg->is_concrete() && !vmreg->prev()->is_concrete()) { 3027 // This is one of the high slots of a vector register. 3028 // ScheduleAndBundle already checked there are no live wide 3029 // vectors in this method so it can be safely ignored. 3030 return; 3031 } 3032 } 3033 3034 Node *pinch = _reg_node[def_reg]; // Get pinch point 3035 if ((pinch == nullptr) || _cfg->get_block_for_node(pinch) != b || // No pinch-point yet? 3036 is_def ) { // Check for a true def (not a kill) 3037 _reg_node.map(def_reg,def); // Record def/kill as the optimistic pinch-point 3038 return; 3039 } 3040 3041 Node *kill = def; // Rename 'def' to more descriptive 'kill' 3042 debug_only( def = (Node*)((intptr_t)0xdeadbeef); ) 3043 3044 // After some number of kills there _may_ be a later def 3045 Node *later_def = nullptr; 3046 3047 Compile* C = Compile::current(); 3048 3049 // Finding a kill requires a real pinch-point. 3050 // Check for not already having a pinch-point. 3051 // Pinch points are Op_Node's. 3052 if( pinch->Opcode() != Op_Node ) { // Or later-def/kill as pinch-point? 3053 later_def = pinch; // Must be def/kill as optimistic pinch-point 3054 if ( _pinch_free_list.size() > 0) { 3055 pinch = _pinch_free_list.pop(); 3056 } else { 3057 pinch = new Node(1); // Pinch point to-be 3058 } 3059 if (pinch->_idx >= _regalloc->node_regs_max_index()) { 3060 DEBUG_ONLY( pinch->dump(); ); 3061 assert(false, "too many D-U pinch points: %d >= %d", pinch->_idx, _regalloc->node_regs_max_index()); 3062 _cfg->C->record_method_not_compilable("too many D-U pinch points"); 3063 return; 3064 } 3065 _cfg->map_node_to_block(pinch, b); // Pretend it's valid in this block (lazy init) 3066 _reg_node.map(def_reg,pinch); // Record pinch-point 3067 //regalloc()->set_bad(pinch->_idx); // Already initialized this way. 3068 if( later_def->outcnt() == 0 || later_def->ideal_reg() == MachProjNode::fat_proj ) { // Distinguish def from kill 3069 pinch->init_req(0, C->top()); // set not null for the next call 3070 add_prec_edge_from_to(later_def,pinch); // Add edge from kill to pinch 3071 later_def = nullptr; // and no later def 3072 } 3073 pinch->set_req(0,later_def); // Hook later def so we can find it 3074 } else { // Else have valid pinch point 3075 if( pinch->in(0) ) // If there is a later-def 3076 later_def = pinch->in(0); // Get it 3077 } 3078 3079 // Add output-dependence edge from later def to kill 3080 if( later_def ) // If there is some original def 3081 add_prec_edge_from_to(later_def,kill); // Add edge from def to kill 3082 3083 // See if current kill is also a use, and so is forced to be the pinch-point. 3084 if( pinch->Opcode() == Op_Node ) { 3085 Node *uses = kill->is_Proj() ? kill->in(0) : kill; 3086 for( uint i=1; i<uses->req(); i++ ) { 3087 if( _regalloc->get_reg_first(uses->in(i)) == def_reg || 3088 _regalloc->get_reg_second(uses->in(i)) == def_reg ) { 3089 // Yes, found a use/kill pinch-point 3090 pinch->set_req(0,nullptr); // 3091 pinch->replace_by(kill); // Move anti-dep edges up 3092 pinch = kill; 3093 _reg_node.map(def_reg,pinch); 3094 return; 3095 } 3096 } 3097 } 3098 3099 // Add edge from kill to pinch-point 3100 add_prec_edge_from_to(kill,pinch); 3101 } 3102 3103 void Scheduling::anti_do_use( Block *b, Node *use, OptoReg::Name use_reg ) { 3104 if( !OptoReg::is_valid(use_reg) ) // Ignore stores & control flow 3105 return; 3106 Node *pinch = _reg_node[use_reg]; // Get pinch point 3107 // Check for no later def_reg/kill in block 3108 if ((pinch != nullptr) && _cfg->get_block_for_node(pinch) == b && 3109 // Use has to be block-local as well 3110 _cfg->get_block_for_node(use) == b) { 3111 if( pinch->Opcode() == Op_Node && // Real pinch-point (not optimistic?) 3112 pinch->req() == 1 ) { // pinch not yet in block? 3113 pinch->del_req(0); // yank pointer to later-def, also set flag 3114 // Insert the pinch-point in the block just after the last use 3115 b->insert_node(pinch, b->find_node(use) + 1); 3116 _bb_end++; // Increase size scheduled region in block 3117 } 3118 3119 add_prec_edge_from_to(pinch,use); 3120 } 3121 } 3122 3123 // We insert antidependences between the reads and following write of 3124 // allocated registers to prevent illegal code motion. Hopefully, the 3125 // number of added references should be fairly small, especially as we 3126 // are only adding references within the current basic block. 3127 void Scheduling::ComputeRegisterAntidependencies(Block *b) { 3128 3129 #ifdef ASSERT 3130 verify_good_schedule(b,"before block local scheduling"); 3131 #endif 3132 3133 // A valid schedule, for each register independently, is an endless cycle 3134 // of: a def, then some uses (connected to the def by true dependencies), 3135 // then some kills (defs with no uses), finally the cycle repeats with a new 3136 // def. The uses are allowed to float relative to each other, as are the 3137 // kills. No use is allowed to slide past a kill (or def). This requires 3138 // antidependencies between all uses of a single def and all kills that 3139 // follow, up to the next def. More edges are redundant, because later defs 3140 // & kills are already serialized with true or antidependencies. To keep 3141 // the edge count down, we add a 'pinch point' node if there's more than 3142 // one use or more than one kill/def. 3143 3144 // We add dependencies in one bottom-up pass. 3145 3146 // For each instruction we handle it's DEFs/KILLs, then it's USEs. 3147 3148 // For each DEF/KILL, we check to see if there's a prior DEF/KILL for this 3149 // register. If not, we record the DEF/KILL in _reg_node, the 3150 // register-to-def mapping. If there is a prior DEF/KILL, we insert a 3151 // "pinch point", a new Node that's in the graph but not in the block. 3152 // We put edges from the prior and current DEF/KILLs to the pinch point. 3153 // We put the pinch point in _reg_node. If there's already a pinch point 3154 // we merely add an edge from the current DEF/KILL to the pinch point. 3155 3156 // After doing the DEF/KILLs, we handle USEs. For each used register, we 3157 // put an edge from the pinch point to the USE. 3158 3159 // To be expedient, the _reg_node array is pre-allocated for the whole 3160 // compilation. _reg_node is lazily initialized; it either contains a null, 3161 // or a valid def/kill/pinch-point, or a leftover node from some prior 3162 // block. Leftover node from some prior block is treated like a null (no 3163 // prior def, so no anti-dependence needed). Valid def is distinguished by 3164 // it being in the current block. 3165 bool fat_proj_seen = false; 3166 uint last_safept = _bb_end-1; 3167 Node* end_node = (_bb_end-1 >= _bb_start) ? b->get_node(last_safept) : nullptr; 3168 Node* last_safept_node = end_node; 3169 for( uint i = _bb_end-1; i >= _bb_start; i-- ) { 3170 Node *n = b->get_node(i); 3171 int is_def = n->outcnt(); // def if some uses prior to adding precedence edges 3172 if( n->is_MachProj() && n->ideal_reg() == MachProjNode::fat_proj ) { 3173 // Fat-proj kills a slew of registers 3174 // This can add edges to 'n' and obscure whether or not it was a def, 3175 // hence the is_def flag. 3176 fat_proj_seen = true; 3177 RegMaskIterator rmi(n->out_RegMask()); 3178 while (rmi.has_next()) { 3179 OptoReg::Name kill = rmi.next(); 3180 anti_do_def(b, n, kill, is_def); 3181 } 3182 } else { 3183 // Get DEF'd registers the normal way 3184 anti_do_def( b, n, _regalloc->get_reg_first(n), is_def ); 3185 anti_do_def( b, n, _regalloc->get_reg_second(n), is_def ); 3186 } 3187 3188 // Kill projections on a branch should appear to occur on the 3189 // branch, not afterwards, so grab the masks from the projections 3190 // and process them. 3191 if (n->is_MachBranch() || (n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_Jump)) { 3192 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 3193 Node* use = n->fast_out(i); 3194 if (use->is_Proj()) { 3195 RegMaskIterator rmi(use->out_RegMask()); 3196 while (rmi.has_next()) { 3197 OptoReg::Name kill = rmi.next(); 3198 anti_do_def(b, n, kill, false); 3199 } 3200 } 3201 } 3202 } 3203 3204 // Check each register used by this instruction for a following DEF/KILL 3205 // that must occur afterward and requires an anti-dependence edge. 3206 for( uint j=0; j<n->req(); j++ ) { 3207 Node *def = n->in(j); 3208 if( def ) { 3209 assert( !def->is_MachProj() || def->ideal_reg() != MachProjNode::fat_proj, "" ); 3210 anti_do_use( b, n, _regalloc->get_reg_first(def) ); 3211 anti_do_use( b, n, _regalloc->get_reg_second(def) ); 3212 } 3213 } 3214 // Do not allow defs of new derived values to float above GC 3215 // points unless the base is definitely available at the GC point. 3216 3217 Node *m = b->get_node(i); 3218 3219 // Add precedence edge from following safepoint to use of derived pointer 3220 if( last_safept_node != end_node && 3221 m != last_safept_node) { 3222 for (uint k = 1; k < m->req(); k++) { 3223 const Type *t = m->in(k)->bottom_type(); 3224 if( t->isa_oop_ptr() && 3225 t->is_ptr()->offset() != 0 ) { 3226 last_safept_node->add_prec( m ); 3227 break; 3228 } 3229 } 3230 3231 // Do not allow a CheckCastPP node whose input is a raw pointer to 3232 // float past a safepoint. This can occur when a buffered inline 3233 // type is allocated in a loop and the CheckCastPP from that 3234 // allocation is reused outside the loop. If the use inside the 3235 // loop is scalarized the CheckCastPP will no longer be connected 3236 // to the loop safepoint. See JDK-8264340. 3237 if (m->is_Mach() && m->as_Mach()->ideal_Opcode() == Op_CheckCastPP) { 3238 Node *def = m->in(1); 3239 if (def != nullptr && def->bottom_type()->base() == Type::RawPtr) { 3240 last_safept_node->add_prec(m); 3241 } 3242 } 3243 } 3244 3245 if( n->jvms() ) { // Precedence edge from derived to safept 3246 // Check if last_safept_node was moved by pinch-point insertion in anti_do_use() 3247 if( b->get_node(last_safept) != last_safept_node ) { 3248 last_safept = b->find_node(last_safept_node); 3249 } 3250 for( uint j=last_safept; j > i; j-- ) { 3251 Node *mach = b->get_node(j); 3252 if( mach->is_Mach() && mach->as_Mach()->ideal_Opcode() == Op_AddP ) 3253 mach->add_prec( n ); 3254 } 3255 last_safept = i; 3256 last_safept_node = m; 3257 } 3258 } 3259 3260 if (fat_proj_seen) { 3261 // Garbage collect pinch nodes that were not consumed. 3262 // They are usually created by a fat kill MachProj for a call. 3263 garbage_collect_pinch_nodes(); 3264 } 3265 } 3266 3267 // Garbage collect pinch nodes for reuse by other blocks. 3268 // 3269 // The block scheduler's insertion of anti-dependence 3270 // edges creates many pinch nodes when the block contains 3271 // 2 or more Calls. A pinch node is used to prevent a 3272 // combinatorial explosion of edges. If a set of kills for a 3273 // register is anti-dependent on a set of uses (or defs), rather 3274 // than adding an edge in the graph between each pair of kill 3275 // and use (or def), a pinch is inserted between them: 3276 // 3277 // use1 use2 use3 3278 // \ | / 3279 // \ | / 3280 // pinch 3281 // / | \ 3282 // / | \ 3283 // kill1 kill2 kill3 3284 // 3285 // One pinch node is created per register killed when 3286 // the second call is encountered during a backwards pass 3287 // over the block. Most of these pinch nodes are never 3288 // wired into the graph because the register is never 3289 // used or def'ed in the block. 3290 // 3291 void Scheduling::garbage_collect_pinch_nodes() { 3292 #ifndef PRODUCT 3293 if (_cfg->C->trace_opto_output()) tty->print("Reclaimed pinch nodes:"); 3294 #endif 3295 int trace_cnt = 0; 3296 for (uint k = 0; k < _reg_node.max(); k++) { 3297 Node* pinch = _reg_node[k]; 3298 if ((pinch != nullptr) && pinch->Opcode() == Op_Node && 3299 // no predecence input edges 3300 (pinch->req() == pinch->len() || pinch->in(pinch->req()) == nullptr) ) { 3301 cleanup_pinch(pinch); 3302 _pinch_free_list.push(pinch); 3303 _reg_node.map(k, nullptr); 3304 #ifndef PRODUCT 3305 if (_cfg->C->trace_opto_output()) { 3306 trace_cnt++; 3307 if (trace_cnt > 40) { 3308 tty->print("\n"); 3309 trace_cnt = 0; 3310 } 3311 tty->print(" %d", pinch->_idx); 3312 } 3313 #endif 3314 } 3315 } 3316 #ifndef PRODUCT 3317 if (_cfg->C->trace_opto_output()) tty->print("\n"); 3318 #endif 3319 } 3320 3321 // Clean up a pinch node for reuse. 3322 void Scheduling::cleanup_pinch( Node *pinch ) { 3323 assert (pinch && pinch->Opcode() == Op_Node && pinch->req() == 1, "just checking"); 3324 3325 for (DUIterator_Last imin, i = pinch->last_outs(imin); i >= imin; ) { 3326 Node* use = pinch->last_out(i); 3327 uint uses_found = 0; 3328 for (uint j = use->req(); j < use->len(); j++) { 3329 if (use->in(j) == pinch) { 3330 use->rm_prec(j); 3331 uses_found++; 3332 } 3333 } 3334 assert(uses_found > 0, "must be a precedence edge"); 3335 i -= uses_found; // we deleted 1 or more copies of this edge 3336 } 3337 // May have a later_def entry 3338 pinch->set_req(0, nullptr); 3339 } 3340 3341 #ifndef PRODUCT 3342 3343 void Scheduling::dump_available() const { 3344 tty->print("#Availist "); 3345 for (uint i = 0; i < _available.size(); i++) 3346 tty->print(" N%d/l%d", _available[i]->_idx,_current_latency[_available[i]->_idx]); 3347 tty->cr(); 3348 } 3349 3350 // Print Scheduling Statistics 3351 void Scheduling::print_statistics() { 3352 // Print the size added by nops for bundling 3353 tty->print("Nops added %d bytes to total of %d bytes", 3354 _total_nop_size, _total_method_size); 3355 if (_total_method_size > 0) 3356 tty->print(", for %.2f%%", 3357 ((double)_total_nop_size) / ((double) _total_method_size) * 100.0); 3358 tty->print("\n"); 3359 3360 // Print the number of branch shadows filled 3361 if (Pipeline::_branch_has_delay_slot) { 3362 tty->print("Of %d branches, %d had unconditional delay slots filled", 3363 _total_branches, _total_unconditional_delays); 3364 if (_total_branches > 0) 3365 tty->print(", for %.2f%%", 3366 ((double)_total_unconditional_delays) / ((double)_total_branches) * 100.0); 3367 tty->print("\n"); 3368 } 3369 3370 uint total_instructions = 0, total_bundles = 0; 3371 3372 for (uint i = 1; i <= Pipeline::_max_instrs_per_cycle; i++) { 3373 uint bundle_count = _total_instructions_per_bundle[i]; 3374 total_instructions += bundle_count * i; 3375 total_bundles += bundle_count; 3376 } 3377 3378 if (total_bundles > 0) 3379 tty->print("Average ILP (excluding nops) is %.2f\n", 3380 ((double)total_instructions) / ((double)total_bundles)); 3381 } 3382 #endif 3383 3384 //-----------------------init_scratch_buffer_blob------------------------------ 3385 // Construct a temporary BufferBlob and cache it for this compile. 3386 void PhaseOutput::init_scratch_buffer_blob(int const_size) { 3387 // If there is already a scratch buffer blob allocated and the 3388 // constant section is big enough, use it. Otherwise free the 3389 // current and allocate a new one. 3390 BufferBlob* blob = scratch_buffer_blob(); 3391 if ((blob != nullptr) && (const_size <= _scratch_const_size)) { 3392 // Use the current blob. 3393 } else { 3394 if (blob != nullptr) { 3395 BufferBlob::free(blob); 3396 } 3397 3398 ResourceMark rm; 3399 _scratch_const_size = const_size; 3400 int size = C2Compiler::initial_code_buffer_size(const_size); 3401 if (C->has_scalarized_args()) { 3402 // Inline type entry points (MachVEPNodes) require lots of space for GC barriers and oop verification 3403 // when loading object fields from the buffered argument. Increase scratch buffer size accordingly. 3404 ciMethod* method = C->method(); 3405 int barrier_size = UseZGC ? 200 : (7 DEBUG_ONLY(+ 37)); 3406 int arg_num = 0; 3407 if (!method->is_static()) { 3408 if (method->is_scalarized_arg(arg_num)) { 3409 size += method->holder()->as_inline_klass()->oop_count() * barrier_size; 3410 } 3411 arg_num++; 3412 } 3413 for (ciSignatureStream str(method->signature()); !str.at_return_type(); str.next()) { 3414 if (method->is_scalarized_arg(arg_num)) { 3415 size += str.type()->as_inline_klass()->oop_count() * barrier_size; 3416 } 3417 arg_num++; 3418 } 3419 } 3420 blob = BufferBlob::create("Compile::scratch_buffer", size); 3421 // Record the buffer blob for next time. 3422 set_scratch_buffer_blob(blob); 3423 // Have we run out of code space? 3424 if (scratch_buffer_blob() == nullptr) { 3425 // Let CompilerBroker disable further compilations. 3426 C->record_failure("Not enough space for scratch buffer in CodeCache"); 3427 return; 3428 } 3429 } 3430 3431 // Initialize the relocation buffers 3432 relocInfo* locs_buf = (relocInfo*) blob->content_end() - MAX_locs_size; 3433 set_scratch_locs_memory(locs_buf); 3434 } 3435 3436 3437 //-----------------------scratch_emit_size------------------------------------- 3438 // Helper function that computes size by emitting code 3439 uint PhaseOutput::scratch_emit_size(const Node* n) { 3440 // Start scratch_emit_size section. 3441 set_in_scratch_emit_size(true); 3442 3443 // Emit into a trash buffer and count bytes emitted. 3444 // This is a pretty expensive way to compute a size, 3445 // but it works well enough if seldom used. 3446 // All common fixed-size instructions are given a size 3447 // method by the AD file. 3448 // Note that the scratch buffer blob and locs memory are 3449 // allocated at the beginning of the compile task, and 3450 // may be shared by several calls to scratch_emit_size. 3451 // The allocation of the scratch buffer blob is particularly 3452 // expensive, since it has to grab the code cache lock. 3453 BufferBlob* blob = this->scratch_buffer_blob(); 3454 assert(blob != nullptr, "Initialize BufferBlob at start"); 3455 assert(blob->size() > MAX_inst_size, "sanity"); 3456 relocInfo* locs_buf = scratch_locs_memory(); 3457 address blob_begin = blob->content_begin(); 3458 address blob_end = (address)locs_buf; 3459 assert(blob->contains(blob_end), "sanity"); 3460 CodeBuffer buf(blob_begin, blob_end - blob_begin); 3461 buf.initialize_consts_size(_scratch_const_size); 3462 buf.initialize_stubs_size(MAX_stubs_size); 3463 assert(locs_buf != nullptr, "sanity"); 3464 int lsize = MAX_locs_size / 3; 3465 buf.consts()->initialize_shared_locs(&locs_buf[lsize * 0], lsize); 3466 buf.insts()->initialize_shared_locs( &locs_buf[lsize * 1], lsize); 3467 buf.stubs()->initialize_shared_locs( &locs_buf[lsize * 2], lsize); 3468 // Mark as scratch buffer. 3469 buf.consts()->set_scratch_emit(); 3470 buf.insts()->set_scratch_emit(); 3471 buf.stubs()->set_scratch_emit(); 3472 3473 // Do the emission. 3474 3475 Label fakeL; // Fake label for branch instructions. 3476 Label* saveL = nullptr; 3477 uint save_bnum = 0; 3478 bool is_branch = n->is_MachBranch(); 3479 C2_MacroAssembler masm(&buf); 3480 masm.bind(fakeL); 3481 if (is_branch) { 3482 n->as_MachBranch()->save_label(&saveL, &save_bnum); 3483 n->as_MachBranch()->label_set(&fakeL, 0); 3484 } 3485 n->emit(&masm, C->regalloc()); 3486 3487 // Emitting into the scratch buffer should not fail 3488 assert(!C->failing_internal() || C->failure_is_artificial(), "Must not have pending failure. Reason is: %s", C->failure_reason()); 3489 3490 // Restore label. 3491 if (is_branch) { 3492 n->as_MachBranch()->label_set(saveL, save_bnum); 3493 } 3494 3495 // End scratch_emit_size section. 3496 set_in_scratch_emit_size(false); 3497 3498 return buf.insts_size(); 3499 } 3500 3501 void PhaseOutput::install() { 3502 if (!C->should_install_code()) { 3503 return; 3504 } else if (C->stub_function() != nullptr) { 3505 install_stub(C->stub_name()); 3506 } else { 3507 install_code(C->method(), 3508 C->entry_bci(), 3509 CompileBroker::compiler2(), 3510 C->has_unsafe_access(), 3511 SharedRuntime::is_wide_vector(C->max_vector_size())); 3512 } 3513 } 3514 3515 void PhaseOutput::install_code(ciMethod* target, 3516 int entry_bci, 3517 AbstractCompiler* compiler, 3518 bool has_unsafe_access, 3519 bool has_wide_vectors) { 3520 // Check if we want to skip execution of all compiled code. 3521 { 3522 #ifndef PRODUCT 3523 if (OptoNoExecute) { 3524 C->record_method_not_compilable("+OptoNoExecute"); // Flag as failed 3525 return; 3526 } 3527 #endif 3528 Compile::TracePhase tp(_t_registerMethod); 3529 3530 if (C->is_osr_compilation()) { 3531 _code_offsets.set_value(CodeOffsets::Verified_Entry, 0); 3532 _code_offsets.set_value(CodeOffsets::OSR_Entry, _first_block_size); 3533 } else { 3534 _code_offsets.set_value(CodeOffsets::Verified_Entry, _first_block_size); 3535 if (_code_offsets.value(CodeOffsets::Verified_Inline_Entry) == -1) { 3536 _code_offsets.set_value(CodeOffsets::Verified_Inline_Entry, _first_block_size); 3537 } 3538 if (_code_offsets.value(CodeOffsets::Verified_Inline_Entry_RO) == -1) { 3539 _code_offsets.set_value(CodeOffsets::Verified_Inline_Entry_RO, _first_block_size); 3540 } 3541 if (_code_offsets.value(CodeOffsets::Entry) == -1) { 3542 _code_offsets.set_value(CodeOffsets::Entry, _first_block_size); 3543 } 3544 _code_offsets.set_value(CodeOffsets::OSR_Entry, 0); 3545 } 3546 3547 C->env()->register_method(target, 3548 entry_bci, 3549 &_code_offsets, 3550 _orig_pc_slot_offset_in_bytes, 3551 code_buffer(), 3552 frame_size_in_words(), 3553 _oop_map_set, 3554 &_handler_table, 3555 inc_table(), 3556 compiler, 3557 has_unsafe_access, 3558 SharedRuntime::is_wide_vector(C->max_vector_size()), 3559 C->has_monitors(), 3560 C->has_scoped_access(), 3561 0); 3562 3563 if (C->log() != nullptr) { // Print code cache state into compiler log 3564 C->log()->code_cache_state(); 3565 } 3566 } 3567 } 3568 void PhaseOutput::install_stub(const char* stub_name) { 3569 // Entry point will be accessed using stub_entry_point(); 3570 if (code_buffer() == nullptr) { 3571 Matcher::soft_match_failure(); 3572 } else { 3573 if (PrintAssembly && (WizardMode || Verbose)) 3574 tty->print_cr("### Stub::%s", stub_name); 3575 3576 if (!C->failing()) { 3577 assert(C->fixed_slots() == 0, "no fixed slots used for runtime stubs"); 3578 3579 // Make the NMethod 3580 // For now we mark the frame as never safe for profile stackwalking 3581 RuntimeStub *rs = RuntimeStub::new_runtime_stub(stub_name, 3582 code_buffer(), 3583 CodeOffsets::frame_never_safe, 3584 // _code_offsets.value(CodeOffsets::Frame_Complete), 3585 frame_size_in_words(), 3586 oop_map_set(), 3587 false); 3588 assert(rs != nullptr && rs->is_runtime_stub(), "sanity check"); 3589 3590 C->set_stub_entry_point(rs->entry_point()); 3591 } 3592 } 3593 } 3594 3595 // Support for bundling info 3596 Bundle* PhaseOutput::node_bundling(const Node *n) { 3597 assert(valid_bundle_info(n), "oob"); 3598 return &_node_bundling_base[n->_idx]; 3599 } 3600 3601 bool PhaseOutput::valid_bundle_info(const Node *n) { 3602 return (_node_bundling_limit > n->_idx); 3603 } 3604 3605 //------------------------------frame_size_in_words----------------------------- 3606 // frame_slots in units of words 3607 int PhaseOutput::frame_size_in_words() const { 3608 // shift is 0 in LP32 and 1 in LP64 3609 const int shift = (LogBytesPerWord - LogBytesPerInt); 3610 int words = _frame_slots >> shift; 3611 assert( words << shift == _frame_slots, "frame size must be properly aligned in LP64" ); 3612 return words; 3613 } 3614 3615 // To bang the stack of this compiled method we use the stack size 3616 // that the interpreter would need in case of a deoptimization. This 3617 // removes the need to bang the stack in the deoptimization blob which 3618 // in turn simplifies stack overflow handling. 3619 int PhaseOutput::bang_size_in_bytes() const { 3620 return MAX2(frame_size_in_bytes() + os::extra_bang_size_in_bytes(), C->interpreter_frame_size()); 3621 } 3622 3623 //------------------------------dump_asm--------------------------------------- 3624 // Dump formatted assembly 3625 #if defined(SUPPORT_OPTO_ASSEMBLY) 3626 void PhaseOutput::dump_asm_on(outputStream* st, int* pcs, uint pc_limit) { 3627 3628 int pc_digits = 3; // #chars required for pc 3629 int sb_chars = 3; // #chars for "start bundle" indicator 3630 int tab_size = 8; 3631 if (pcs != nullptr) { 3632 int max_pc = 0; 3633 for (uint i = 0; i < pc_limit; i++) { 3634 max_pc = (max_pc < pcs[i]) ? pcs[i] : max_pc; 3635 } 3636 pc_digits = ((max_pc < 4096) ? 3 : ((max_pc < 65536) ? 4 : ((max_pc < 65536*256) ? 6 : 8))); // #chars required for pc 3637 } 3638 int prefix_len = ((pc_digits + sb_chars + tab_size - 1)/tab_size)*tab_size; 3639 3640 bool cut_short = false; 3641 st->print_cr("#"); 3642 st->print("# "); C->tf()->dump_on(st); st->cr(); 3643 st->print_cr("#"); 3644 3645 // For all blocks 3646 int pc = 0x0; // Program counter 3647 char starts_bundle = ' '; 3648 C->regalloc()->dump_frame(); 3649 3650 Node *n = nullptr; 3651 for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) { 3652 if (VMThread::should_terminate()) { 3653 cut_short = true; 3654 break; 3655 } 3656 Block* block = C->cfg()->get_block(i); 3657 if (block->is_connector() && !Verbose) { 3658 continue; 3659 } 3660 n = block->head(); 3661 if ((pcs != nullptr) && (n->_idx < pc_limit)) { 3662 pc = pcs[n->_idx]; 3663 st->print("%*.*x", pc_digits, pc_digits, pc); 3664 } 3665 st->fill_to(prefix_len); 3666 block->dump_head(C->cfg(), st); 3667 if (block->is_connector()) { 3668 st->fill_to(prefix_len); 3669 st->print_cr("# Empty connector block"); 3670 } else if (block->num_preds() == 2 && block->pred(1)->is_CatchProj() && block->pred(1)->as_CatchProj()->_con == CatchProjNode::fall_through_index) { 3671 st->fill_to(prefix_len); 3672 st->print_cr("# Block is sole successor of call"); 3673 } 3674 3675 // For all instructions 3676 Node *delay = nullptr; 3677 for (uint j = 0; j < block->number_of_nodes(); j++) { 3678 if (VMThread::should_terminate()) { 3679 cut_short = true; 3680 break; 3681 } 3682 n = block->get_node(j); 3683 if (valid_bundle_info(n)) { 3684 Bundle* bundle = node_bundling(n); 3685 if (bundle->used_in_unconditional_delay()) { 3686 delay = n; 3687 continue; 3688 } 3689 if (bundle->starts_bundle()) { 3690 starts_bundle = '+'; 3691 } 3692 } 3693 3694 if (WizardMode) { 3695 n->dump(); 3696 } 3697 3698 if( !n->is_Region() && // Dont print in the Assembly 3699 !n->is_Phi() && // a few noisely useless nodes 3700 !n->is_Proj() && 3701 !n->is_MachTemp() && 3702 !n->is_SafePointScalarObject() && 3703 !n->is_Catch() && // Would be nice to print exception table targets 3704 !n->is_MergeMem() && // Not very interesting 3705 !n->is_top() && // Debug info table constants 3706 !(n->is_Con() && !n->is_Mach())// Debug info table constants 3707 ) { 3708 if ((pcs != nullptr) && (n->_idx < pc_limit)) { 3709 pc = pcs[n->_idx]; 3710 st->print("%*.*x", pc_digits, pc_digits, pc); 3711 } else { 3712 st->fill_to(pc_digits); 3713 } 3714 st->print(" %c ", starts_bundle); 3715 starts_bundle = ' '; 3716 st->fill_to(prefix_len); 3717 n->format(C->regalloc(), st); 3718 st->cr(); 3719 } 3720 3721 // If we have an instruction with a delay slot, and have seen a delay, 3722 // then back up and print it 3723 if (valid_bundle_info(n) && node_bundling(n)->use_unconditional_delay()) { 3724 // Coverity finding - Explicit null dereferenced. 3725 guarantee(delay != nullptr, "no unconditional delay instruction"); 3726 if (WizardMode) delay->dump(); 3727 3728 if (node_bundling(delay)->starts_bundle()) 3729 starts_bundle = '+'; 3730 if ((pcs != nullptr) && (n->_idx < pc_limit)) { 3731 pc = pcs[n->_idx]; 3732 st->print("%*.*x", pc_digits, pc_digits, pc); 3733 } else { 3734 st->fill_to(pc_digits); 3735 } 3736 st->print(" %c ", starts_bundle); 3737 starts_bundle = ' '; 3738 st->fill_to(prefix_len); 3739 delay->format(C->regalloc(), st); 3740 st->cr(); 3741 delay = nullptr; 3742 } 3743 3744 // Dump the exception table as well 3745 if( n->is_Catch() && (Verbose || WizardMode) ) { 3746 // Print the exception table for this offset 3747 _handler_table.print_subtable_for(pc); 3748 } 3749 st->bol(); // Make sure we start on a new line 3750 } 3751 st->cr(); // one empty line between blocks 3752 assert(cut_short || delay == nullptr, "no unconditional delay branch"); 3753 } // End of per-block dump 3754 3755 if (cut_short) st->print_cr("*** disassembly is cut short ***"); 3756 } 3757 #endif 3758 3759 #ifndef PRODUCT 3760 void PhaseOutput::print_statistics() { 3761 Scheduling::print_statistics(); 3762 } 3763 #endif