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