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