Thu, 24 May 2018 19:26:50 +0800
#7046 C2 supports long branch
Contributed-by: fujie
1 /*
2 * Copyright (c) 1998, 2014, 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 */
25 /*
26 * This file has been modified by Loongson Technology in 2015. These
27 * modifications are Copyright (c) 2015 Loongson Technology, and are made
28 * available on the same license terms set forth above.
29 */
31 #include "precompiled.hpp"
32 #include "asm/assembler.inline.hpp"
33 #include "code/compiledIC.hpp"
34 #include "code/debugInfo.hpp"
35 #include "code/debugInfoRec.hpp"
36 #include "compiler/compileBroker.hpp"
37 #include "compiler/oopMap.hpp"
38 #include "memory/allocation.inline.hpp"
39 #include "opto/callnode.hpp"
40 #include "opto/cfgnode.hpp"
41 #include "opto/locknode.hpp"
42 #include "opto/machnode.hpp"
43 #include "opto/output.hpp"
44 #include "opto/regalloc.hpp"
45 #include "opto/runtime.hpp"
46 #include "opto/subnode.hpp"
47 #include "opto/type.hpp"
48 #include "runtime/handles.inline.hpp"
49 #include "utilities/xmlstream.hpp"
51 #ifndef PRODUCT
52 #define DEBUG_ARG(x) , x
53 #else
54 #define DEBUG_ARG(x)
55 #endif
57 // Convert Nodes to instruction bits and pass off to the VM
58 void Compile::Output() {
59 // RootNode goes
60 assert( _cfg->get_root_block()->number_of_nodes() == 0, "" );
62 // The number of new nodes (mostly MachNop) is proportional to
63 // the number of java calls and inner loops which are aligned.
64 if ( C->check_node_count((NodeLimitFudgeFactor + C->java_calls()*3 +
65 C->inner_loops()*(OptoLoopAlignment-1)),
66 "out of nodes before code generation" ) ) {
67 return;
68 }
69 // Make sure I can find the Start Node
70 Block *entry = _cfg->get_block(1);
71 Block *broot = _cfg->get_root_block();
73 const StartNode *start = entry->head()->as_Start();
75 // Replace StartNode with prolog
76 MachPrologNode *prolog = new (this) MachPrologNode();
77 entry->map_node(prolog, 0);
78 _cfg->map_node_to_block(prolog, entry);
79 _cfg->unmap_node_from_block(start); // start is no longer in any block
81 // Virtual methods need an unverified entry point
83 if( is_osr_compilation() ) {
84 if( PoisonOSREntry ) {
85 // TODO: Should use a ShouldNotReachHereNode...
86 _cfg->insert( broot, 0, new (this) MachBreakpointNode() );
87 }
88 } else {
89 if( _method && !_method->flags().is_static() ) {
90 // Insert unvalidated entry point
91 _cfg->insert( broot, 0, new (this) MachUEPNode() );
92 }
94 }
97 // Break before main entry point
98 if( (_method && _method->break_at_execute())
99 #ifndef PRODUCT
100 ||(OptoBreakpoint && is_method_compilation())
101 ||(OptoBreakpointOSR && is_osr_compilation())
102 ||(OptoBreakpointC2R && !_method)
103 #endif
104 ) {
105 // checking for _method means that OptoBreakpoint does not apply to
106 // runtime stubs or frame converters
107 _cfg->insert( entry, 1, new (this) MachBreakpointNode() );
108 }
110 // Insert epilogs before every return
111 for (uint i = 0; i < _cfg->number_of_blocks(); i++) {
112 Block* block = _cfg->get_block(i);
113 if (!block->is_connector() && block->non_connector_successor(0) == _cfg->get_root_block()) { // Found a program exit point?
114 Node* m = block->end();
115 if (m->is_Mach() && m->as_Mach()->ideal_Opcode() != Op_Halt) {
116 MachEpilogNode* epilog = new (this) MachEpilogNode(m->as_Mach()->ideal_Opcode() == Op_Return);
117 block->add_inst(epilog);
118 _cfg->map_node_to_block(epilog, block);
119 }
120 }
121 }
123 # ifdef ENABLE_ZAP_DEAD_LOCALS
124 if (ZapDeadCompiledLocals) {
125 Insert_zap_nodes();
126 }
127 # endif
129 uint* blk_starts = NEW_RESOURCE_ARRAY(uint, _cfg->number_of_blocks() + 1);
130 blk_starts[0] = 0;
132 // Initialize code buffer and process short branches.
133 CodeBuffer* cb = init_buffer(blk_starts);
135 if (cb == NULL || failing()) {
136 return;
137 }
139 ScheduleAndBundle();
141 #ifndef PRODUCT
142 if (trace_opto_output()) {
143 tty->print("\n---- After ScheduleAndBundle ----\n");
144 for (uint i = 0; i < _cfg->number_of_blocks(); i++) {
145 tty->print("\nBB#%03d:\n", i);
146 Block* block = _cfg->get_block(i);
147 for (uint j = 0; j < block->number_of_nodes(); j++) {
148 Node* n = block->get_node(j);
149 OptoReg::Name reg = _regalloc->get_reg_first(n);
150 tty->print(" %-6s ", reg >= 0 && reg < REG_COUNT ? Matcher::regName[reg] : "");
151 n->dump();
152 }
153 }
154 }
155 #endif
157 if (failing()) {
158 return;
159 }
161 BuildOopMaps();
163 if (failing()) {
164 return;
165 }
167 fill_buffer(cb, blk_starts);
168 }
170 bool Compile::need_stack_bang(int frame_size_in_bytes) const {
171 // Determine if we need to generate a stack overflow check.
172 // Do it if the method is not a stub function and
173 // has java calls or has frame size > vm_page_size/8.
174 // The debug VM checks that deoptimization doesn't trigger an
175 // unexpected stack overflow (compiled method stack banging should
176 // guarantee it doesn't happen) so we always need the stack bang in
177 // a debug VM.
178 return (UseStackBanging && stub_function() == NULL &&
179 (has_java_calls() || frame_size_in_bytes > os::vm_page_size()>>3
180 DEBUG_ONLY(|| true)));
181 }
183 bool Compile::need_register_stack_bang() const {
184 // Determine if we need to generate a register stack overflow check.
185 // This is only used on architectures which have split register
186 // and memory stacks (ie. IA64).
187 // Bang if the method is not a stub function and has java calls
188 return (stub_function() == NULL && has_java_calls());
189 }
191 # ifdef ENABLE_ZAP_DEAD_LOCALS
194 // In order to catch compiler oop-map bugs, we have implemented
195 // a debugging mode called ZapDeadCompilerLocals.
196 // This mode causes the compiler to insert a call to a runtime routine,
197 // "zap_dead_locals", right before each place in compiled code
198 // that could potentially be a gc-point (i.e., a safepoint or oop map point).
199 // The runtime routine checks that locations mapped as oops are really
200 // oops, that locations mapped as values do not look like oops,
201 // and that locations mapped as dead are not used later
202 // (by zapping them to an invalid address).
204 int Compile::_CompiledZap_count = 0;
206 void Compile::Insert_zap_nodes() {
207 bool skip = false;
210 // Dink with static counts because code code without the extra
211 // runtime calls is MUCH faster for debugging purposes
213 if ( CompileZapFirst == 0 ) ; // nothing special
214 else if ( CompileZapFirst > CompiledZap_count() ) skip = true;
215 else if ( CompileZapFirst == CompiledZap_count() )
216 warning("starting zap compilation after skipping");
218 if ( CompileZapLast == -1 ) ; // nothing special
219 else if ( CompileZapLast < CompiledZap_count() ) skip = true;
220 else if ( CompileZapLast == CompiledZap_count() )
221 warning("about to compile last zap");
223 ++_CompiledZap_count; // counts skipped zaps, too
225 if ( skip ) return;
228 if ( _method == NULL )
229 return; // no safepoints/oopmaps emitted for calls in stubs,so we don't care
231 // Insert call to zap runtime stub before every node with an oop map
232 for( uint i=0; i<_cfg->number_of_blocks(); i++ ) {
233 Block *b = _cfg->get_block(i);
234 for ( uint j = 0; j < b->number_of_nodes(); ++j ) {
235 Node *n = b->get_node(j);
237 // Determining if we should insert a zap-a-lot node in output.
238 // We do that for all nodes that has oopmap info, except for calls
239 // to allocation. Calls to allocation passes in the old top-of-eden pointer
240 // and expect the C code to reset it. Hence, there can be no safepoints between
241 // the inlined-allocation and the call to new_Java, etc.
242 // We also cannot zap monitor calls, as they must hold the microlock
243 // during the call to Zap, which also wants to grab the microlock.
244 bool insert = n->is_MachSafePoint() && (n->as_MachSafePoint()->oop_map() != NULL);
245 if ( insert ) { // it is MachSafePoint
246 if ( !n->is_MachCall() ) {
247 insert = false;
248 } else if ( n->is_MachCall() ) {
249 MachCallNode* call = n->as_MachCall();
250 if (call->entry_point() == OptoRuntime::new_instance_Java() ||
251 call->entry_point() == OptoRuntime::new_array_Java() ||
252 call->entry_point() == OptoRuntime::multianewarray2_Java() ||
253 call->entry_point() == OptoRuntime::multianewarray3_Java() ||
254 call->entry_point() == OptoRuntime::multianewarray4_Java() ||
255 call->entry_point() == OptoRuntime::multianewarray5_Java() ||
256 call->entry_point() == OptoRuntime::slow_arraycopy_Java() ||
257 call->entry_point() == OptoRuntime::complete_monitor_locking_Java()
258 ) {
259 insert = false;
260 }
261 }
262 if (insert) {
263 Node *zap = call_zap_node(n->as_MachSafePoint(), i);
264 b->insert_node(zap, j);
265 _cfg->map_node_to_block(zap, b);
266 ++j;
267 }
268 }
269 }
270 }
271 }
274 Node* Compile::call_zap_node(MachSafePointNode* node_to_check, int block_no) {
275 const TypeFunc *tf = OptoRuntime::zap_dead_locals_Type();
276 CallStaticJavaNode* ideal_node =
277 new (this) CallStaticJavaNode( tf,
278 OptoRuntime::zap_dead_locals_stub(_method->flags().is_native()),
279 "call zap dead locals stub", 0, TypePtr::BOTTOM);
280 // We need to copy the OopMap from the site we're zapping at.
281 // We have to make a copy, because the zap site might not be
282 // a call site, and zap_dead is a call site.
283 OopMap* clone = node_to_check->oop_map()->deep_copy();
285 // Add the cloned OopMap to the zap node
286 ideal_node->set_oop_map(clone);
287 return _matcher->match_sfpt(ideal_node);
288 }
290 bool Compile::is_node_getting_a_safepoint( Node* n) {
291 // This code duplicates the logic prior to the call of add_safepoint
292 // below in this file.
293 if( n->is_MachSafePoint() ) return true;
294 return false;
295 }
297 # endif // ENABLE_ZAP_DEAD_LOCALS
299 // Compute the size of first NumberOfLoopInstrToAlign instructions at the top
300 // of a loop. When aligning a loop we need to provide enough instructions
301 // in cpu's fetch buffer to feed decoders. The loop alignment could be
302 // avoided if we have enough instructions in fetch buffer at the head of a loop.
303 // By default, the size is set to 999999 by Block's constructor so that
304 // a loop will be aligned if the size is not reset here.
305 //
306 // Note: Mach instructions could contain several HW instructions
307 // so the size is estimated only.
308 //
309 void Compile::compute_loop_first_inst_sizes() {
310 // The next condition is used to gate the loop alignment optimization.
311 // Don't aligned a loop if there are enough instructions at the head of a loop
312 // or alignment padding is larger then MaxLoopPad. By default, MaxLoopPad
313 // is equal to OptoLoopAlignment-1 except on new Intel cpus, where it is
314 // equal to 11 bytes which is the largest address NOP instruction.
315 if (MaxLoopPad < OptoLoopAlignment - 1) {
316 uint last_block = _cfg->number_of_blocks() - 1;
317 for (uint i = 1; i <= last_block; i++) {
318 Block* block = _cfg->get_block(i);
319 // Check the first loop's block which requires an alignment.
320 if (block->loop_alignment() > (uint)relocInfo::addr_unit()) {
321 uint sum_size = 0;
322 uint inst_cnt = NumberOfLoopInstrToAlign;
323 inst_cnt = block->compute_first_inst_size(sum_size, inst_cnt, _regalloc);
325 // Check subsequent fallthrough blocks if the loop's first
326 // block(s) does not have enough instructions.
327 Block *nb = block;
328 while(inst_cnt > 0 &&
329 i < last_block &&
330 !_cfg->get_block(i + 1)->has_loop_alignment() &&
331 !nb->has_successor(block)) {
332 i++;
333 nb = _cfg->get_block(i);
334 inst_cnt = nb->compute_first_inst_size(sum_size, inst_cnt, _regalloc);
335 } // while( inst_cnt > 0 && i < last_block )
337 block->set_first_inst_size(sum_size);
338 } // f( b->head()->is_Loop() )
339 } // for( i <= last_block )
340 } // if( MaxLoopPad < OptoLoopAlignment-1 )
341 }
343 // The architecture description provides short branch variants for some long
344 // branch instructions. Replace eligible long branches with short branches.
345 void Compile::shorten_branches(uint* blk_starts, int& code_size, int& reloc_size, int& stub_size) {
346 // Compute size of each block, method size, and relocation information size
347 uint nblocks = _cfg->number_of_blocks();
349 uint* jmp_offset = NEW_RESOURCE_ARRAY(uint,nblocks);
350 uint* jmp_size = NEW_RESOURCE_ARRAY(uint,nblocks);
351 int* jmp_nidx = NEW_RESOURCE_ARRAY(int ,nblocks);
353 // Collect worst case block paddings
354 int* block_worst_case_pad = NEW_RESOURCE_ARRAY(int, nblocks);
355 memset(block_worst_case_pad, 0, nblocks * sizeof(int));
357 DEBUG_ONLY( uint *jmp_target = NEW_RESOURCE_ARRAY(uint,nblocks); )
358 DEBUG_ONLY( uint *jmp_rule = NEW_RESOURCE_ARRAY(uint,nblocks); )
360 bool has_short_branch_candidate = false;
362 // Initialize the sizes to 0
363 code_size = 0; // Size in bytes of generated code
364 stub_size = 0; // Size in bytes of all stub entries
365 // Size in bytes of all relocation entries, including those in local stubs.
366 // Start with 2-bytes of reloc info for the unvalidated entry point
367 reloc_size = 1; // Number of relocation entries
369 // Make three passes. The first computes pessimistic blk_starts,
370 // relative jmp_offset and reloc_size information. The second performs
371 // short branch substitution using the pessimistic sizing. The
372 // third inserts nops where needed.
374 // Step one, perform a pessimistic sizing pass.
375 uint last_call_adr = max_uint;
376 uint last_avoid_back_to_back_adr = max_uint;
377 uint nop_size = (new (this) MachNopNode())->size(_regalloc);
378 for (uint i = 0; i < nblocks; i++) { // For all blocks
379 Block* block = _cfg->get_block(i);
381 // During short branch replacement, we store the relative (to blk_starts)
382 // offset of jump in jmp_offset, rather than the absolute offset of jump.
383 // This is so that we do not need to recompute sizes of all nodes when
384 // we compute correct blk_starts in our next sizing pass.
385 jmp_offset[i] = 0;
386 jmp_size[i] = 0;
387 jmp_nidx[i] = -1;
388 DEBUG_ONLY( jmp_target[i] = 0; )
389 DEBUG_ONLY( jmp_rule[i] = 0; )
391 // Sum all instruction sizes to compute block size
392 uint last_inst = block->number_of_nodes();
393 uint blk_size = 0;
394 for (uint j = 0; j < last_inst; j++) {
395 Node* nj = block->get_node(j);
396 // Handle machine instruction nodes
397 if (nj->is_Mach()) {
398 MachNode *mach = nj->as_Mach();
399 blk_size += (mach->alignment_required() - 1) * relocInfo::addr_unit(); // assume worst case padding
400 reloc_size += mach->reloc();
401 if (mach->is_MachCall()) {
402 // add size information for trampoline stub
403 // class CallStubImpl is platform-specific and defined in the *.ad files.
404 stub_size += CallStubImpl::size_call_trampoline();
405 reloc_size += CallStubImpl::reloc_call_trampoline();
407 MachCallNode *mcall = mach->as_MachCall();
408 // This destination address is NOT PC-relative
410 mcall->method_set((intptr_t)mcall->entry_point());
412 if (mcall->is_MachCallJava() && mcall->as_MachCallJava()->_method) {
413 stub_size += CompiledStaticCall::to_interp_stub_size();
414 reloc_size += CompiledStaticCall::reloc_to_interp_stub();
415 }
416 } else if (mach->is_MachSafePoint()) {
417 // If call/safepoint are adjacent, account for possible
418 // nop to disambiguate the two safepoints.
419 // ScheduleAndBundle() can rearrange nodes in a block,
420 // check for all offsets inside this block.
421 if (last_call_adr >= blk_starts[i]) {
422 blk_size += nop_size;
423 }
424 }
425 if (mach->avoid_back_to_back(MachNode::AVOID_BEFORE)) {
426 // Nop is inserted between "avoid back to back" instructions.
427 // ScheduleAndBundle() can rearrange nodes in a block,
428 // check for all offsets inside this block.
429 if (last_avoid_back_to_back_adr >= blk_starts[i]) {
430 blk_size += nop_size;
431 }
432 }
433 if (mach->may_be_short_branch()) {
434 if (!nj->is_MachBranch()) {
435 #ifndef PRODUCT
436 nj->dump(3);
437 #endif
438 Unimplemented();
439 }
440 assert(jmp_nidx[i] == -1, "block should have only one branch");
441 jmp_offset[i] = blk_size;
442 jmp_size[i] = nj->size(_regalloc);
443 jmp_nidx[i] = j;
444 has_short_branch_candidate = true;
445 }
446 }
447 blk_size += nj->size(_regalloc);
448 // Remember end of call offset
449 if (nj->is_MachCall() && !nj->is_MachCallLeaf()) {
450 last_call_adr = blk_starts[i]+blk_size;
451 }
452 // Remember end of avoid_back_to_back offset
453 if (nj->is_Mach() && nj->as_Mach()->avoid_back_to_back(MachNode::AVOID_AFTER)) {
454 last_avoid_back_to_back_adr = blk_starts[i]+blk_size;
455 }
456 }
458 // When the next block starts a loop, we may insert pad NOP
459 // instructions. Since we cannot know our future alignment,
460 // assume the worst.
461 if (i < nblocks - 1) {
462 Block* nb = _cfg->get_block(i + 1);
463 int max_loop_pad = nb->code_alignment()-relocInfo::addr_unit();
464 if (max_loop_pad > 0) {
465 assert(is_power_of_2(max_loop_pad+relocInfo::addr_unit()), "");
466 // Adjust last_call_adr and/or last_avoid_back_to_back_adr.
467 // If either is the last instruction in this block, bump by
468 // max_loop_pad in lock-step with blk_size, so sizing
469 // calculations in subsequent blocks still can conservatively
470 // detect that it may the last instruction in this block.
471 if (last_call_adr == blk_starts[i]+blk_size) {
472 last_call_adr += max_loop_pad;
473 }
474 if (last_avoid_back_to_back_adr == blk_starts[i]+blk_size) {
475 last_avoid_back_to_back_adr += max_loop_pad;
476 }
477 blk_size += max_loop_pad;
478 block_worst_case_pad[i + 1] = max_loop_pad;
479 }
480 }
482 // Save block size; update total method size
483 blk_starts[i+1] = blk_starts[i]+blk_size;
484 }
486 // Step two, replace eligible long jumps.
487 bool progress = true;
488 uint last_may_be_short_branch_adr = max_uint;
489 while (has_short_branch_candidate && progress) {
490 progress = false;
491 has_short_branch_candidate = false;
492 int adjust_block_start = 0;
493 for (uint i = 0; i < nblocks; i++) {
494 Block* block = _cfg->get_block(i);
495 int idx = jmp_nidx[i];
496 MachNode* mach = (idx == -1) ? NULL: block->get_node(idx)->as_Mach();
497 if (mach != NULL && mach->may_be_short_branch()) {
498 #ifdef ASSERT
499 assert(jmp_size[i] > 0 && mach->is_MachBranch(), "sanity");
500 int j;
501 // Find the branch; ignore trailing NOPs.
502 for (j = block->number_of_nodes()-1; j>=0; j--) {
503 Node* n = block->get_node(j);
504 if (!n->is_Mach() || n->as_Mach()->ideal_Opcode() != Op_Con)
505 break;
506 }
507 assert(j >= 0 && j == idx && block->get_node(j) == (Node*)mach, "sanity");
508 #endif
509 int br_size = jmp_size[i];
510 int br_offs = blk_starts[i] + jmp_offset[i];
512 // This requires the TRUE branch target be in succs[0]
513 uint bnum = block->non_connector_successor(0)->_pre_order;
514 int offset = blk_starts[bnum] - br_offs;
515 if (bnum > i) { // adjust following block's offset
516 offset -= adjust_block_start;
517 }
519 // This block can be a loop header, account for the padding
520 // in the previous block.
521 int block_padding = block_worst_case_pad[i];
522 assert(i == 0 || block_padding == 0 || br_offs >= block_padding, "Should have at least a padding on top");
523 // In the following code a nop could be inserted before
524 // the branch which will increase the backward distance.
525 bool needs_padding = ((uint)(br_offs - block_padding) == last_may_be_short_branch_adr);
526 assert(!needs_padding || jmp_offset[i] == 0, "padding only branches at the beginning of block");
528 if (needs_padding && offset <= 0)
529 offset -= nop_size;
531 if (_matcher->is_short_branch_offset(mach->rule(), br_size, offset)) {
532 // We've got a winner. Replace this branch.
533 MachNode* replacement = mach->as_MachBranch()->short_branch_version(this);
535 // Update the jmp_size.
536 int new_size = replacement->size(_regalloc);
537 int diff = br_size - new_size;
538 assert(diff >= (int)nop_size, "short_branch size should be smaller");
539 // Conservatively take into account padding between
540 // avoid_back_to_back branches. Previous branch could be
541 // converted into avoid_back_to_back branch during next
542 // rounds.
543 if (needs_padding && replacement->avoid_back_to_back(MachNode::AVOID_BEFORE)) {
544 jmp_offset[i] += nop_size;
545 diff -= nop_size;
546 }
547 adjust_block_start += diff;
548 block->map_node(replacement, idx);
549 mach->subsume_by(replacement, C);
550 mach = replacement;
551 progress = true;
553 jmp_size[i] = new_size;
554 DEBUG_ONLY( jmp_target[i] = bnum; );
555 DEBUG_ONLY( jmp_rule[i] = mach->rule(); );
556 } else {
557 // The jump distance is not short, try again during next iteration.
558 has_short_branch_candidate = true;
559 }
560 } // (mach->may_be_short_branch())
561 if (mach != NULL && (mach->may_be_short_branch() ||
562 mach->avoid_back_to_back(MachNode::AVOID_AFTER))) {
563 last_may_be_short_branch_adr = blk_starts[i] + jmp_offset[i] + jmp_size[i];
564 }
565 blk_starts[i+1] -= adjust_block_start;
566 }
567 }
569 #ifdef ASSERT
570 for (uint i = 0; i < nblocks; i++) { // For all blocks
571 if (jmp_target[i] != 0) {
572 int br_size = jmp_size[i];
573 int offset = blk_starts[jmp_target[i]]-(blk_starts[i] + jmp_offset[i]);
574 if (!_matcher->is_short_branch_offset(jmp_rule[i], br_size, offset)) {
575 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]);
576 }
577 assert(_matcher->is_short_branch_offset(jmp_rule[i], br_size, offset), "Displacement too large for short jmp");
578 }
579 }
580 #endif
582 // Step 3, compute the offsets of all blocks, will be done in fill_buffer()
583 // after ScheduleAndBundle().
585 // ------------------
586 // Compute size for code buffer
587 code_size = blk_starts[nblocks];
589 // Relocation records
590 reloc_size += 1; // Relo entry for exception handler
592 // Adjust reloc_size to number of record of relocation info
593 // Min is 2 bytes, max is probably 6 or 8, with a tax up to 25% for
594 // a relocation index.
595 // The CodeBuffer will expand the locs array if this estimate is too low.
596 reloc_size *= 10 / sizeof(relocInfo);
597 }
599 //------------------------------FillLocArray-----------------------------------
600 // Create a bit of debug info and append it to the array. The mapping is from
601 // Java local or expression stack to constant, register or stack-slot. For
602 // doubles, insert 2 mappings and return 1 (to tell the caller that the next
603 // entry has been taken care of and caller should skip it).
604 static LocationValue *new_loc_value( PhaseRegAlloc *ra, OptoReg::Name regnum, Location::Type l_type ) {
605 // This should never have accepted Bad before
606 assert(OptoReg::is_valid(regnum), "location must be valid");
607 return (OptoReg::is_reg(regnum))
608 ? new LocationValue(Location::new_reg_loc(l_type, OptoReg::as_VMReg(regnum)) )
609 : new LocationValue(Location::new_stk_loc(l_type, ra->reg2offset(regnum)));
610 }
613 ObjectValue*
614 Compile::sv_for_node_id(GrowableArray<ScopeValue*> *objs, int id) {
615 for (int i = 0; i < objs->length(); i++) {
616 assert(objs->at(i)->is_object(), "corrupt object cache");
617 ObjectValue* sv = (ObjectValue*) objs->at(i);
618 if (sv->id() == id) {
619 return sv;
620 }
621 }
622 // Otherwise..
623 return NULL;
624 }
626 void Compile::set_sv_for_object_node(GrowableArray<ScopeValue*> *objs,
627 ObjectValue* sv ) {
628 assert(sv_for_node_id(objs, sv->id()) == NULL, "Precondition");
629 objs->append(sv);
630 }
633 void Compile::FillLocArray( int idx, MachSafePointNode* sfpt, Node *local,
634 GrowableArray<ScopeValue*> *array,
635 GrowableArray<ScopeValue*> *objs ) {
636 assert( local, "use _top instead of null" );
637 if (array->length() != idx) {
638 assert(array->length() == idx + 1, "Unexpected array count");
639 // Old functionality:
640 // return
641 // New functionality:
642 // Assert if the local is not top. In product mode let the new node
643 // override the old entry.
644 assert(local == top(), "LocArray collision");
645 if (local == top()) {
646 return;
647 }
648 array->pop();
649 }
650 const Type *t = local->bottom_type();
652 // Is it a safepoint scalar object node?
653 if (local->is_SafePointScalarObject()) {
654 SafePointScalarObjectNode* spobj = local->as_SafePointScalarObject();
656 ObjectValue* sv = Compile::sv_for_node_id(objs, spobj->_idx);
657 if (sv == NULL) {
658 ciKlass* cik = t->is_oopptr()->klass();
659 assert(cik->is_instance_klass() ||
660 cik->is_array_klass(), "Not supported allocation.");
661 sv = new ObjectValue(spobj->_idx,
662 new ConstantOopWriteValue(cik->java_mirror()->constant_encoding()));
663 Compile::set_sv_for_object_node(objs, sv);
665 uint first_ind = spobj->first_index(sfpt->jvms());
666 for (uint i = 0; i < spobj->n_fields(); i++) {
667 Node* fld_node = sfpt->in(first_ind+i);
668 (void)FillLocArray(sv->field_values()->length(), sfpt, fld_node, sv->field_values(), objs);
669 }
670 }
671 array->append(sv);
672 return;
673 }
675 // Grab the register number for the local
676 OptoReg::Name regnum = _regalloc->get_reg_first(local);
677 if( OptoReg::is_valid(regnum) ) {// Got a register/stack?
678 // Record the double as two float registers.
679 // The register mask for such a value always specifies two adjacent
680 // float registers, with the lower register number even.
681 // Normally, the allocation of high and low words to these registers
682 // is irrelevant, because nearly all operations on register pairs
683 // (e.g., StoreD) treat them as a single unit.
684 // Here, we assume in addition that the words in these two registers
685 // stored "naturally" (by operations like StoreD and double stores
686 // within the interpreter) such that the lower-numbered register
687 // is written to the lower memory address. This may seem like
688 // a machine dependency, but it is not--it is a requirement on
689 // the author of the <arch>.ad file to ensure that, for every
690 // even/odd double-register pair to which a double may be allocated,
691 // the word in the even single-register is stored to the first
692 // memory word. (Note that register numbers are completely
693 // arbitrary, and are not tied to any machine-level encodings.)
694 #ifdef _LP64
695 if( t->base() == Type::DoubleBot || t->base() == Type::DoubleCon ) {
696 array->append(new ConstantIntValue(0));
697 array->append(new_loc_value( _regalloc, regnum, Location::dbl ));
698 } else if ( t->base() == Type::Long ) {
699 array->append(new ConstantIntValue(0));
700 array->append(new_loc_value( _regalloc, regnum, Location::lng ));
701 } else if ( t->base() == Type::RawPtr ) {
702 // jsr/ret return address which must be restored into a the full
703 // width 64-bit stack slot.
704 array->append(new_loc_value( _regalloc, regnum, Location::lng ));
705 }
706 #else //_LP64
707 #ifdef SPARC
708 if (t->base() == Type::Long && OptoReg::is_reg(regnum)) {
709 // For SPARC we have to swap high and low words for
710 // long values stored in a single-register (g0-g7).
711 array->append(new_loc_value( _regalloc, regnum , Location::normal ));
712 array->append(new_loc_value( _regalloc, OptoReg::add(regnum,1), Location::normal ));
713 } else
714 #endif //SPARC
715 if( t->base() == Type::DoubleBot || t->base() == Type::DoubleCon || t->base() == Type::Long ) {
716 // Repack the double/long as two jints.
717 // The convention the interpreter uses is that the second local
718 // holds the first raw word of the native double representation.
719 // This is actually reasonable, since locals and stack arrays
720 // grow downwards in all implementations.
721 // (If, on some machine, the interpreter's Java locals or stack
722 // were to grow upwards, the embedded doubles would be word-swapped.)
723 array->append(new_loc_value( _regalloc, OptoReg::add(regnum,1), Location::normal ));
724 array->append(new_loc_value( _regalloc, regnum , Location::normal ));
725 }
726 #endif //_LP64
727 else if( (t->base() == Type::FloatBot || t->base() == Type::FloatCon) &&
728 OptoReg::is_reg(regnum) ) {
729 array->append(new_loc_value( _regalloc, regnum, Matcher::float_in_double()
730 ? Location::float_in_dbl : Location::normal ));
731 } else if( t->base() == Type::Int && OptoReg::is_reg(regnum) ) {
732 array->append(new_loc_value( _regalloc, regnum, Matcher::int_in_long
733 ? Location::int_in_long : Location::normal ));
734 } else if( t->base() == Type::NarrowOop ) {
735 array->append(new_loc_value( _regalloc, regnum, Location::narrowoop ));
736 } else {
737 array->append(new_loc_value( _regalloc, regnum, _regalloc->is_oop(local) ? Location::oop : Location::normal ));
738 }
739 return;
740 }
742 // No register. It must be constant data.
743 switch (t->base()) {
744 case Type::Half: // Second half of a double
745 ShouldNotReachHere(); // Caller should skip 2nd halves
746 break;
747 case Type::AnyPtr:
748 array->append(new ConstantOopWriteValue(NULL));
749 break;
750 case Type::AryPtr:
751 case Type::InstPtr: // fall through
752 array->append(new ConstantOopWriteValue(t->isa_oopptr()->const_oop()->constant_encoding()));
753 break;
754 case Type::NarrowOop:
755 if (t == TypeNarrowOop::NULL_PTR) {
756 array->append(new ConstantOopWriteValue(NULL));
757 } else {
758 array->append(new ConstantOopWriteValue(t->make_ptr()->isa_oopptr()->const_oop()->constant_encoding()));
759 }
760 break;
761 case Type::Int:
762 array->append(new ConstantIntValue(t->is_int()->get_con()));
763 break;
764 case Type::RawPtr:
765 // A return address (T_ADDRESS).
766 assert((intptr_t)t->is_ptr()->get_con() < (intptr_t)0x10000, "must be a valid BCI");
767 #ifdef _LP64
768 // Must be restored to the full-width 64-bit stack slot.
769 array->append(new ConstantLongValue(t->is_ptr()->get_con()));
770 #else
771 array->append(new ConstantIntValue(t->is_ptr()->get_con()));
772 #endif
773 break;
774 case Type::FloatCon: {
775 float f = t->is_float_constant()->getf();
776 array->append(new ConstantIntValue(jint_cast(f)));
777 break;
778 }
779 case Type::DoubleCon: {
780 jdouble d = t->is_double_constant()->getd();
781 #ifdef _LP64
782 array->append(new ConstantIntValue(0));
783 array->append(new ConstantDoubleValue(d));
784 #else
785 // Repack the double as two jints.
786 // The convention the interpreter uses is that the second local
787 // holds the first raw word of the native double representation.
788 // This is actually reasonable, since locals and stack arrays
789 // grow downwards in all implementations.
790 // (If, on some machine, the interpreter's Java locals or stack
791 // were to grow upwards, the embedded doubles would be word-swapped.)
792 jlong_accessor acc;
793 acc.long_value = jlong_cast(d);
794 array->append(new ConstantIntValue(acc.words[1]));
795 array->append(new ConstantIntValue(acc.words[0]));
796 #endif
797 break;
798 }
799 case Type::Long: {
800 jlong d = t->is_long()->get_con();
801 #ifdef _LP64
802 array->append(new ConstantIntValue(0));
803 array->append(new ConstantLongValue(d));
804 #else
805 // Repack the long as two jints.
806 // The convention the interpreter uses is that the second local
807 // holds the first raw word of the native double representation.
808 // This is actually reasonable, since locals and stack arrays
809 // grow downwards in all implementations.
810 // (If, on some machine, the interpreter's Java locals or stack
811 // were to grow upwards, the embedded doubles would be word-swapped.)
812 jlong_accessor acc;
813 acc.long_value = d;
814 array->append(new ConstantIntValue(acc.words[1]));
815 array->append(new ConstantIntValue(acc.words[0]));
816 #endif
817 break;
818 }
819 case Type::Top: // Add an illegal value here
820 array->append(new LocationValue(Location()));
821 break;
822 default:
823 ShouldNotReachHere();
824 break;
825 }
826 }
828 // Determine if this node starts a bundle
829 bool Compile::starts_bundle(const Node *n) const {
830 return (_node_bundling_limit > n->_idx &&
831 _node_bundling_base[n->_idx].starts_bundle());
832 }
834 //--------------------------Process_OopMap_Node--------------------------------
835 void Compile::Process_OopMap_Node(MachNode *mach, int current_offset) {
837 // Handle special safepoint nodes for synchronization
838 MachSafePointNode *sfn = mach->as_MachSafePoint();
839 MachCallNode *mcall;
841 #ifdef ENABLE_ZAP_DEAD_LOCALS
842 assert( is_node_getting_a_safepoint(mach), "logic does not match; false negative");
843 #endif
845 int safepoint_pc_offset = current_offset;
846 bool is_method_handle_invoke = false;
847 bool return_oop = false;
849 // Add the safepoint in the DebugInfoRecorder
850 if( !mach->is_MachCall() ) {
851 mcall = NULL;
852 #ifdef MIPS64
853 /*
854 2013/10/30 Jin: safepoint_pc_offset should point to tha last instruction in safePoint.
855 In X86 and sparc, their safePoints only contain one instruction.
856 However, we should add current_offset with the size of safePoint in MIPS.
857 0x2d6ff22c: lw s2, 0x14(s2)
858 last_pd->pc_offset()=308, pc_offset=304, bci=64
859 last_pd->pc_offset()=312, pc_offset=312, bci=64
860 /mnt/openjdk6/hotspot/src/share/vm/code/debugInfoRec.cpp, 289 , assert(last_pd->pc_offset() == pc_offset,"must be last pc")
862 ;; Safepoint:
863 ---> pc_offset=304
864 0x2d6ff230: lui at, 0x2b7a ; OopMap{s2=Oop s5=Oop t4=Oop off=308}
865 ;*goto
866 ; - java.util.Hashtable::get@64 (line 353)
867 ---> last_pd(308)
868 0x2d6ff234: lw at, 0xffffc100(at) ;*goto
869 ; - java.util.Hashtable::get@64 (line 353)
870 ; {poll}
871 0x2d6ff238: addiu s0, zero, 0x0
872 */
873 safepoint_pc_offset += sfn->size(_regalloc) - 4;
874 #endif
875 debug_info()->add_safepoint(safepoint_pc_offset, sfn->_oop_map);
876 } else {
877 mcall = mach->as_MachCall();
879 // Is the call a MethodHandle call?
880 if (mcall->is_MachCallJava()) {
881 if (mcall->as_MachCallJava()->_method_handle_invoke) {
882 assert(has_method_handle_invokes(), "must have been set during call generation");
883 is_method_handle_invoke = true;
884 }
885 }
887 // Check if a call returns an object.
888 if (mcall->returns_pointer()) {
889 return_oop = true;
890 }
891 safepoint_pc_offset += mcall->ret_addr_offset();
892 debug_info()->add_safepoint(safepoint_pc_offset, mcall->_oop_map);
893 }
895 // Loop over the JVMState list to add scope information
896 // Do not skip safepoints with a NULL method, they need monitor info
897 JVMState* youngest_jvms = sfn->jvms();
898 int max_depth = youngest_jvms->depth();
900 // Allocate the object pool for scalar-replaced objects -- the map from
901 // small-integer keys (which can be recorded in the local and ostack
902 // arrays) to descriptions of the object state.
903 GrowableArray<ScopeValue*> *objs = new GrowableArray<ScopeValue*>();
905 // Visit scopes from oldest to youngest.
906 for (int depth = 1; depth <= max_depth; depth++) {
907 JVMState* jvms = youngest_jvms->of_depth(depth);
908 int idx;
909 ciMethod* method = jvms->has_method() ? jvms->method() : NULL;
910 // Safepoints that do not have method() set only provide oop-map and monitor info
911 // to support GC; these do not support deoptimization.
912 int num_locs = (method == NULL) ? 0 : jvms->loc_size();
913 int num_exps = (method == NULL) ? 0 : jvms->stk_size();
914 int num_mon = jvms->nof_monitors();
915 assert(method == NULL || jvms->bci() < 0 || num_locs == method->max_locals(),
916 "JVMS local count must match that of the method");
918 // Add Local and Expression Stack Information
920 // Insert locals into the locarray
921 GrowableArray<ScopeValue*> *locarray = new GrowableArray<ScopeValue*>(num_locs);
922 for( idx = 0; idx < num_locs; idx++ ) {
923 FillLocArray( idx, sfn, sfn->local(jvms, idx), locarray, objs );
924 }
926 // Insert expression stack entries into the exparray
927 GrowableArray<ScopeValue*> *exparray = new GrowableArray<ScopeValue*>(num_exps);
928 for( idx = 0; idx < num_exps; idx++ ) {
929 FillLocArray( idx, sfn, sfn->stack(jvms, idx), exparray, objs );
930 }
932 // Add in mappings of the monitors
933 assert( !method ||
934 !method->is_synchronized() ||
935 method->is_native() ||
936 num_mon > 0 ||
937 !GenerateSynchronizationCode,
938 "monitors must always exist for synchronized methods");
940 // Build the growable array of ScopeValues for exp stack
941 GrowableArray<MonitorValue*> *monarray = new GrowableArray<MonitorValue*>(num_mon);
943 // Loop over monitors and insert into array
944 for (idx = 0; idx < num_mon; idx++) {
945 // Grab the node that defines this monitor
946 Node* box_node = sfn->monitor_box(jvms, idx);
947 Node* obj_node = sfn->monitor_obj(jvms, idx);
949 // Create ScopeValue for object
950 ScopeValue *scval = NULL;
952 if (obj_node->is_SafePointScalarObject()) {
953 SafePointScalarObjectNode* spobj = obj_node->as_SafePointScalarObject();
954 scval = Compile::sv_for_node_id(objs, spobj->_idx);
955 if (scval == NULL) {
956 const Type *t = spobj->bottom_type();
957 ciKlass* cik = t->is_oopptr()->klass();
958 assert(cik->is_instance_klass() ||
959 cik->is_array_klass(), "Not supported allocation.");
960 ObjectValue* sv = new ObjectValue(spobj->_idx,
961 new ConstantOopWriteValue(cik->java_mirror()->constant_encoding()));
962 Compile::set_sv_for_object_node(objs, sv);
964 uint first_ind = spobj->first_index(youngest_jvms);
965 for (uint i = 0; i < spobj->n_fields(); i++) {
966 Node* fld_node = sfn->in(first_ind+i);
967 (void)FillLocArray(sv->field_values()->length(), sfn, fld_node, sv->field_values(), objs);
968 }
969 scval = sv;
970 }
971 } else if (!obj_node->is_Con()) {
972 OptoReg::Name obj_reg = _regalloc->get_reg_first(obj_node);
973 if( obj_node->bottom_type()->base() == Type::NarrowOop ) {
974 scval = new_loc_value( _regalloc, obj_reg, Location::narrowoop );
975 } else {
976 scval = new_loc_value( _regalloc, obj_reg, Location::oop );
977 }
978 } else {
979 const TypePtr *tp = obj_node->get_ptr_type();
980 scval = new ConstantOopWriteValue(tp->is_oopptr()->const_oop()->constant_encoding());
981 }
983 OptoReg::Name box_reg = BoxLockNode::reg(box_node);
984 Location basic_lock = Location::new_stk_loc(Location::normal,_regalloc->reg2offset(box_reg));
985 bool eliminated = (box_node->is_BoxLock() && box_node->as_BoxLock()->is_eliminated());
986 monarray->append(new MonitorValue(scval, basic_lock, eliminated));
987 }
989 // We dump the object pool first, since deoptimization reads it in first.
990 debug_info()->dump_object_pool(objs);
992 // Build first class objects to pass to scope
993 DebugToken *locvals = debug_info()->create_scope_values(locarray);
994 DebugToken *expvals = debug_info()->create_scope_values(exparray);
995 DebugToken *monvals = debug_info()->create_monitor_values(monarray);
997 // Make method available for all Safepoints
998 ciMethod* scope_method = method ? method : _method;
999 // Describe the scope here
1000 assert(jvms->bci() >= InvocationEntryBci && jvms->bci() <= 0x10000, "must be a valid or entry BCI");
1001 assert(!jvms->should_reexecute() || depth == max_depth, "reexecute allowed only for the youngest");
1002 // Now we can describe the scope.
1003 debug_info()->describe_scope(safepoint_pc_offset, scope_method, jvms->bci(), jvms->should_reexecute(), is_method_handle_invoke, return_oop, locvals, expvals, monvals);
1004 } // End jvms loop
1006 // Mark the end of the scope set.
1007 debug_info()->end_safepoint(safepoint_pc_offset);
1008 }
1012 // A simplified version of Process_OopMap_Node, to handle non-safepoints.
1013 class NonSafepointEmitter {
1014 Compile* C;
1015 JVMState* _pending_jvms;
1016 int _pending_offset;
1018 void emit_non_safepoint();
1020 public:
1021 NonSafepointEmitter(Compile* compile) {
1022 this->C = compile;
1023 _pending_jvms = NULL;
1024 _pending_offset = 0;
1025 }
1027 void observe_instruction(Node* n, int pc_offset) {
1028 if (!C->debug_info()->recording_non_safepoints()) return;
1030 Node_Notes* nn = C->node_notes_at(n->_idx);
1031 if (nn == NULL || nn->jvms() == NULL) return;
1032 if (_pending_jvms != NULL &&
1033 _pending_jvms->same_calls_as(nn->jvms())) {
1034 // Repeated JVMS? Stretch it up here.
1035 _pending_offset = pc_offset;
1036 } else {
1037 if (_pending_jvms != NULL &&
1038 _pending_offset < pc_offset) {
1039 emit_non_safepoint();
1040 }
1041 _pending_jvms = NULL;
1042 if (pc_offset > C->debug_info()->last_pc_offset()) {
1043 // This is the only way _pending_jvms can become non-NULL:
1044 _pending_jvms = nn->jvms();
1045 _pending_offset = pc_offset;
1046 }
1047 }
1048 }
1050 // Stay out of the way of real safepoints:
1051 void observe_safepoint(JVMState* jvms, int pc_offset) {
1052 if (_pending_jvms != NULL &&
1053 !_pending_jvms->same_calls_as(jvms) &&
1054 _pending_offset < pc_offset) {
1055 emit_non_safepoint();
1056 }
1057 _pending_jvms = NULL;
1058 }
1060 void flush_at_end() {
1061 if (_pending_jvms != NULL) {
1062 emit_non_safepoint();
1063 }
1064 _pending_jvms = NULL;
1065 }
1066 };
1068 void NonSafepointEmitter::emit_non_safepoint() {
1069 JVMState* youngest_jvms = _pending_jvms;
1070 int pc_offset = _pending_offset;
1072 // Clear it now:
1073 _pending_jvms = NULL;
1075 DebugInformationRecorder* debug_info = C->debug_info();
1076 assert(debug_info->recording_non_safepoints(), "sanity");
1078 debug_info->add_non_safepoint(pc_offset);
1079 int max_depth = youngest_jvms->depth();
1081 // Visit scopes from oldest to youngest.
1082 for (int depth = 1; depth <= max_depth; depth++) {
1083 JVMState* jvms = youngest_jvms->of_depth(depth);
1084 ciMethod* method = jvms->has_method() ? jvms->method() : NULL;
1085 assert(!jvms->should_reexecute() || depth==max_depth, "reexecute allowed only for the youngest");
1086 debug_info->describe_scope(pc_offset, method, jvms->bci(), jvms->should_reexecute());
1087 }
1089 // Mark the end of the scope set.
1090 debug_info->end_non_safepoint(pc_offset);
1091 }
1093 //------------------------------init_buffer------------------------------------
1094 CodeBuffer* Compile::init_buffer(uint* blk_starts) {
1096 // Set the initially allocated size
1097 int code_req = initial_code_capacity;
1098 int locs_req = initial_locs_capacity;
1099 int stub_req = TraceJumps ? initial_stub_capacity * 10 : initial_stub_capacity;
1100 int const_req = initial_const_capacity;
1102 int pad_req = NativeCall::instruction_size;
1103 // The extra spacing after the code is necessary on some platforms.
1104 // Sometimes we need to patch in a jump after the last instruction,
1105 // if the nmethod has been deoptimized. (See 4932387, 4894843.)
1107 // Compute the byte offset where we can store the deopt pc.
1108 if (fixed_slots() != 0) {
1109 _orig_pc_slot_offset_in_bytes = _regalloc->reg2offset(OptoReg::stack2reg(_orig_pc_slot));
1110 }
1112 // Compute prolog code size
1113 _method_size = 0;
1114 _frame_slots = OptoReg::reg2stack(_matcher->_old_SP)+_regalloc->_framesize;
1115 #if defined(IA64) && !defined(AIX)
1116 if (save_argument_registers()) {
1117 // 4815101: this is a stub with implicit and unknown precision fp args.
1118 // The usual spill mechanism can only generate stfd's in this case, which
1119 // doesn't work if the fp reg to spill contains a single-precision denorm.
1120 // Instead, we hack around the normal spill mechanism using stfspill's and
1121 // ldffill's in the MachProlog and MachEpilog emit methods. We allocate
1122 // space here for the fp arg regs (f8-f15) we're going to thusly spill.
1123 //
1124 // If we ever implement 16-byte 'registers' == stack slots, we can
1125 // get rid of this hack and have SpillCopy generate stfspill/ldffill
1126 // instead of stfd/stfs/ldfd/ldfs.
1127 _frame_slots += 8*(16/BytesPerInt);
1128 }
1129 #endif
1130 assert(_frame_slots >= 0 && _frame_slots < 1000000, "sanity check");
1132 if (has_mach_constant_base_node()) {
1133 uint add_size = 0;
1134 // Fill the constant table.
1135 // Note: This must happen before shorten_branches.
1136 for (uint i = 0; i < _cfg->number_of_blocks(); i++) {
1137 Block* b = _cfg->get_block(i);
1139 for (uint j = 0; j < b->number_of_nodes(); j++) {
1140 Node* n = b->get_node(j);
1142 // If the node is a MachConstantNode evaluate the constant
1143 // value section.
1144 if (n->is_MachConstant()) {
1145 MachConstantNode* machcon = n->as_MachConstant();
1146 machcon->eval_constant(C);
1147 } else if (n->is_Mach()) {
1148 // On Power there are more nodes that issue constants.
1149 add_size += (n->as_Mach()->ins_num_consts() * 8);
1150 }
1151 }
1152 }
1154 // Calculate the offsets of the constants and the size of the
1155 // constant table (including the padding to the next section).
1156 constant_table().calculate_offsets_and_size();
1157 const_req = constant_table().size() + add_size;
1158 }
1160 // Initialize the space for the BufferBlob used to find and verify
1161 // instruction size in MachNode::emit_size()
1162 init_scratch_buffer_blob(const_req);
1163 if (failing()) return NULL; // Out of memory
1165 // Pre-compute the length of blocks and replace
1166 // long branches with short if machine supports it.
1167 shorten_branches(blk_starts, code_req, locs_req, stub_req);
1169 // nmethod and CodeBuffer count stubs & constants as part of method's code.
1170 // class HandlerImpl is platform-specific and defined in the *.ad files.
1171 int exception_handler_req = HandlerImpl::size_exception_handler() + MAX_stubs_size; // add marginal slop for handler
1172 int deopt_handler_req = HandlerImpl::size_deopt_handler() + MAX_stubs_size; // add marginal slop for handler
1173 stub_req += MAX_stubs_size; // ensure per-stub margin
1174 code_req += MAX_inst_size; // ensure per-instruction margin
1176 if (StressCodeBuffers)
1177 code_req = const_req = stub_req = exception_handler_req = deopt_handler_req = 0x10; // force expansion
1179 int total_req =
1180 const_req +
1181 code_req +
1182 pad_req +
1183 stub_req +
1184 exception_handler_req +
1185 deopt_handler_req; // deopt handler
1187 if (has_method_handle_invokes())
1188 total_req += deopt_handler_req; // deopt MH handler
1190 CodeBuffer* cb = code_buffer();
1191 cb->initialize(total_req, locs_req);
1193 // Have we run out of code space?
1194 if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
1195 C->record_failure("CodeCache is full");
1196 return NULL;
1197 }
1198 // Configure the code buffer.
1199 cb->initialize_consts_size(const_req);
1200 cb->initialize_stubs_size(stub_req);
1201 cb->initialize_oop_recorder(env()->oop_recorder());
1203 // fill in the nop array for bundling computations
1204 MachNode *_nop_list[Bundle::_nop_count];
1205 Bundle::initialize_nops(_nop_list, this);
1207 return cb;
1208 }
1210 //------------------------------fill_buffer------------------------------------
1211 void Compile::fill_buffer(CodeBuffer* cb, uint* blk_starts) {
1212 // blk_starts[] contains offsets calculated during short branches processing,
1213 // offsets should not be increased during following steps.
1215 // Compute the size of first NumberOfLoopInstrToAlign instructions at head
1216 // of a loop. It is used to determine the padding for loop alignment.
1217 compute_loop_first_inst_sizes();
1219 // Create oopmap set.
1220 _oop_map_set = new OopMapSet();
1222 // !!!!! This preserves old handling of oopmaps for now
1223 debug_info()->set_oopmaps(_oop_map_set);
1225 uint nblocks = _cfg->number_of_blocks();
1226 // Count and start of implicit null check instructions
1227 uint inct_cnt = 0;
1228 uint *inct_starts = NEW_RESOURCE_ARRAY(uint, nblocks+1);
1230 // Count and start of calls
1231 uint *call_returns = NEW_RESOURCE_ARRAY(uint, nblocks+1);
1233 uint return_offset = 0;
1234 int nop_size = (new (this) MachNopNode())->size(_regalloc);
1236 int previous_offset = 0;
1237 int current_offset = 0;
1238 int last_call_offset = -1;
1239 int last_avoid_back_to_back_offset = -1;
1240 #ifdef ASSERT
1241 uint* jmp_target = NEW_RESOURCE_ARRAY(uint,nblocks);
1242 uint* jmp_offset = NEW_RESOURCE_ARRAY(uint,nblocks);
1243 uint* jmp_size = NEW_RESOURCE_ARRAY(uint,nblocks);
1244 uint* jmp_rule = NEW_RESOURCE_ARRAY(uint,nblocks);
1245 #endif
1247 // Create an array of unused labels, one for each basic block, if printing is enabled
1248 #ifndef PRODUCT
1249 int *node_offsets = NULL;
1250 uint node_offset_limit = unique();
1252 if (print_assembly())
1253 node_offsets = NEW_RESOURCE_ARRAY(int, node_offset_limit);
1254 #endif
1256 NonSafepointEmitter non_safepoints(this); // emit non-safepoints lazily
1258 // Emit the constant table.
1259 if (has_mach_constant_base_node()) {
1260 constant_table().emit(*cb);
1261 }
1263 // Create an array of labels, one for each basic block
1264 Label *blk_labels = NEW_RESOURCE_ARRAY(Label, nblocks+1);
1265 for (uint i=0; i <= nblocks; i++) {
1266 blk_labels[i].init();
1267 }
1269 // ------------------
1270 // Now fill in the code buffer
1271 Node *delay_slot = NULL;
1273 for (uint i = 0; i < nblocks; i++) {
1274 Block* block = _cfg->get_block(i);
1275 Node* head = block->head();
1277 // If this block needs to start aligned (i.e, can be reached other
1278 // than by falling-thru from the previous block), then force the
1279 // start of a new bundle.
1280 if (Pipeline::requires_bundling() && starts_bundle(head)) {
1281 cb->flush_bundle(true);
1282 }
1284 #ifdef ASSERT
1285 if (!block->is_connector()) {
1286 stringStream st;
1287 block->dump_head(_cfg, &st);
1288 MacroAssembler(cb).block_comment(st.as_string());
1289 }
1290 jmp_target[i] = 0;
1291 jmp_offset[i] = 0;
1292 jmp_size[i] = 0;
1293 jmp_rule[i] = 0;
1294 #endif
1295 int blk_offset = current_offset;
1297 // Define the label at the beginning of the basic block
1298 MacroAssembler(cb).bind(blk_labels[block->_pre_order]);
1300 uint last_inst = block->number_of_nodes();
1302 // Emit block normally, except for last instruction.
1303 // Emit means "dump code bits into code buffer".
1304 for (uint j = 0; j<last_inst; j++) {
1306 // Get the node
1307 Node* n = block->get_node(j);
1309 // See if delay slots are supported
1310 if (valid_bundle_info(n) &&
1311 node_bundling(n)->used_in_unconditional_delay()) {
1312 assert(delay_slot == NULL, "no use of delay slot node");
1313 assert(n->size(_regalloc) == Pipeline::instr_unit_size(), "delay slot instruction wrong size");
1315 delay_slot = n;
1316 continue;
1317 }
1319 // If this starts a new instruction group, then flush the current one
1320 // (but allow split bundles)
1321 if (Pipeline::requires_bundling() && starts_bundle(n))
1322 cb->flush_bundle(false);
1324 // The following logic is duplicated in the code ifdeffed for
1325 // ENABLE_ZAP_DEAD_LOCALS which appears above in this file. It
1326 // should be factored out. Or maybe dispersed to the nodes?
1328 // Special handling for SafePoint/Call Nodes
1329 bool is_mcall = false;
1330 if (n->is_Mach()) {
1331 MachNode *mach = n->as_Mach();
1332 is_mcall = n->is_MachCall();
1333 bool is_sfn = n->is_MachSafePoint();
1335 // If this requires all previous instructions be flushed, then do so
1336 if (is_sfn || is_mcall || mach->alignment_required() != 1) {
1337 cb->flush_bundle(true);
1338 current_offset = cb->insts_size();
1339 }
1341 // A padding may be needed again since a previous instruction
1342 // could be moved to delay slot.
1344 // align the instruction if necessary
1345 int padding = mach->compute_padding(current_offset);
1346 // Make sure safepoint node for polling is distinct from a call's
1347 // return by adding a nop if needed.
1348 if (is_sfn && !is_mcall && padding == 0 && current_offset == last_call_offset) {
1349 padding = nop_size;
1350 }
1351 if (padding == 0 && mach->avoid_back_to_back(MachNode::AVOID_BEFORE) &&
1352 current_offset == last_avoid_back_to_back_offset) {
1353 // Avoid back to back some instructions.
1354 padding = nop_size;
1355 }
1357 if(padding > 0) {
1358 assert((padding % nop_size) == 0, "padding is not a multiple of NOP size");
1359 int nops_cnt = padding / nop_size;
1360 MachNode *nop = new (this) MachNopNode(nops_cnt);
1361 block->insert_node(nop, j++);
1362 last_inst++;
1363 _cfg->map_node_to_block(nop, block);
1364 nop->emit(*cb, _regalloc);
1365 cb->flush_bundle(true);
1366 current_offset = cb->insts_size();
1367 }
1369 // Remember the start of the last call in a basic block
1370 if (is_mcall) {
1371 MachCallNode *mcall = mach->as_MachCall();
1373 // This destination address is NOT PC-relative
1374 mcall->method_set((intptr_t)mcall->entry_point());
1376 // Save the return address
1377 call_returns[block->_pre_order] = current_offset + mcall->ret_addr_offset();
1379 if (mcall->is_MachCallLeaf()) {
1380 is_mcall = false;
1381 is_sfn = false;
1382 }
1383 }
1385 // sfn will be valid whenever mcall is valid now because of inheritance
1386 if (is_sfn || is_mcall) {
1388 // Handle special safepoint nodes for synchronization
1389 if (!is_mcall) {
1390 MachSafePointNode *sfn = mach->as_MachSafePoint();
1391 // !!!!! Stubs only need an oopmap right now, so bail out
1392 if (sfn->jvms()->method() == NULL) {
1393 // Write the oopmap directly to the code blob??!!
1394 # ifdef ENABLE_ZAP_DEAD_LOCALS
1395 assert( !is_node_getting_a_safepoint(sfn), "logic does not match; false positive");
1396 # endif
1397 continue;
1398 }
1399 } // End synchronization
1401 non_safepoints.observe_safepoint(mach->as_MachSafePoint()->jvms(),
1402 current_offset);
1403 Process_OopMap_Node(mach, current_offset);
1404 } // End if safepoint
1406 // If this is a null check, then add the start of the previous instruction to the list
1407 else if( mach->is_MachNullCheck() ) {
1408 inct_starts[inct_cnt++] = previous_offset;
1409 }
1411 // If this is a branch, then fill in the label with the target BB's label
1412 else if (mach->is_MachBranch()) {
1413 // This requires the TRUE branch target be in succs[0]
1414 uint block_num = block->non_connector_successor(0)->_pre_order;
1416 // Try to replace long branch if delay slot is not used,
1417 // it is mostly for back branches since forward branch's
1418 // distance is not updated yet.
1419 bool delay_slot_is_used = valid_bundle_info(n) &&
1420 node_bundling(n)->use_unconditional_delay();
1421 if (!delay_slot_is_used && mach->may_be_short_branch()) {
1422 assert(delay_slot == NULL, "not expecting delay slot node");
1423 int br_size = n->size(_regalloc);
1424 int offset = blk_starts[block_num] - current_offset;
1425 if (block_num >= i) {
1426 // Current and following block's offset are not
1427 // finalized yet, adjust distance by the difference
1428 // between calculated and final offsets of current block.
1429 offset -= (blk_starts[i] - blk_offset);
1430 }
1431 // In the following code a nop could be inserted before
1432 // the branch which will increase the backward distance.
1433 bool needs_padding = (current_offset == last_avoid_back_to_back_offset);
1434 if (needs_padding && offset <= 0)
1435 offset -= nop_size;
1437 if (_matcher->is_short_branch_offset(mach->rule(), br_size, offset)) {
1438 // We've got a winner. Replace this branch.
1439 MachNode* replacement = mach->as_MachBranch()->short_branch_version(this);
1441 // Update the jmp_size.
1442 int new_size = replacement->size(_regalloc);
1443 assert((br_size - new_size) >= (int)nop_size, "short_branch size should be smaller");
1444 // Insert padding between avoid_back_to_back branches.
1445 if (needs_padding && replacement->avoid_back_to_back(MachNode::AVOID_BEFORE)) {
1446 MachNode *nop = new (this) MachNopNode();
1447 block->insert_node(nop, j++);
1448 _cfg->map_node_to_block(nop, block);
1449 last_inst++;
1450 nop->emit(*cb, _regalloc);
1451 cb->flush_bundle(true);
1452 current_offset = cb->insts_size();
1453 }
1454 #ifdef ASSERT
1455 jmp_target[i] = block_num;
1456 jmp_offset[i] = current_offset - blk_offset;
1457 jmp_size[i] = new_size;
1458 jmp_rule[i] = mach->rule();
1459 #endif
1460 block->map_node(replacement, j);
1461 mach->subsume_by(replacement, C);
1462 n = replacement;
1463 mach = replacement;
1464 }
1465 }
1466 mach->as_MachBranch()->label_set( &blk_labels[block_num], block_num );
1467 } else if (mach->ideal_Opcode() == Op_Jump) {
1468 for (uint h = 0; h < block->_num_succs; h++) {
1469 Block* succs_block = block->_succs[h];
1470 for (uint j = 1; j < succs_block->num_preds(); j++) {
1471 Node* jpn = succs_block->pred(j);
1472 if (jpn->is_JumpProj() && jpn->in(0) == mach) {
1473 uint block_num = succs_block->non_connector()->_pre_order;
1474 Label *blkLabel = &blk_labels[block_num];
1475 mach->add_case_label(jpn->as_JumpProj()->proj_no(), blkLabel);
1476 }
1477 }
1478 }
1479 }
1480 #ifdef ASSERT
1481 // Check that oop-store precedes the card-mark
1482 else if (mach->ideal_Opcode() == Op_StoreCM) {
1483 uint storeCM_idx = j;
1484 int count = 0;
1485 for (uint prec = mach->req(); prec < mach->len(); prec++) {
1486 Node *oop_store = mach->in(prec); // Precedence edge
1487 if (oop_store == NULL) continue;
1488 count++;
1489 uint i4;
1490 for (i4 = 0; i4 < last_inst; ++i4) {
1491 if (block->get_node(i4) == oop_store) {
1492 break;
1493 }
1494 }
1495 // Note: This test can provide a false failure if other precedence
1496 // edges have been added to the storeCMNode.
1497 assert(i4 == last_inst || i4 < storeCM_idx, "CM card-mark executes before oop-store");
1498 }
1499 assert(count > 0, "storeCM expects at least one precedence edge");
1500 }
1501 #endif
1502 else if (!n->is_Proj()) {
1503 // Remember the beginning of the previous instruction, in case
1504 // it's followed by a flag-kill and a null-check. Happens on
1505 // Intel all the time, with add-to-memory kind of opcodes.
1506 previous_offset = current_offset;
1507 }
1509 // Not an else-if!
1510 // If this is a trap based cmp then add its offset to the list.
1511 if (mach->is_TrapBasedCheckNode()) {
1512 inct_starts[inct_cnt++] = current_offset;
1513 }
1514 }
1516 // Verify that there is sufficient space remaining
1517 cb->insts()->maybe_expand_to_ensure_remaining(MAX_inst_size);
1518 if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
1519 C->record_failure("CodeCache is full");
1520 return;
1521 }
1523 // Save the offset for the listing
1524 #ifndef PRODUCT
1525 if (node_offsets && n->_idx < node_offset_limit)
1526 node_offsets[n->_idx] = cb->insts_size();
1527 #endif
1529 // "Normal" instruction case
1530 DEBUG_ONLY( uint instr_offset = cb->insts_size(); )
1531 n->emit(*cb, _regalloc);
1532 current_offset = cb->insts_size();
1533 #ifdef MIPS64
1534 if (!n->is_Proj()) {
1535 // For MIPS, the first instruction of the previous node (usually a instruction sequence) sometime
1536 // is not the instruction which access memory. adjust is needed. previous_offset points to the
1537 // instruction which access memory. Instruction size is 4. cb->insts_size() and
1538 // cb->insts()->end() are the location of current instruction.
1539 int adjust = 4;
1540 NativeInstruction* inst = (NativeInstruction*) (cb->insts()->end() - 4);
1541 if (inst->is_sync()) {
1542 // a sync may be the last instruction, see store_B_immI_enc_sync
1543 adjust += 4;
1544 inst = (NativeInstruction*) (cb->insts()->end() - 8);
1545 }
1546 previous_offset = current_offset - adjust;
1547 }
1548 #endif
1550 // Above we only verified that there is enough space in the instruction section.
1551 // However, the instruction may emit stubs that cause code buffer expansion.
1552 // Bail out here if expansion failed due to a lack of code cache space.
1553 if (failing()) {
1554 return;
1555 }
1557 #ifdef ASSERT
1558 if (n->size(_regalloc) < (current_offset-instr_offset)) {
1559 n->dump();
1560 assert(false, "wrong size of mach node");
1561 }
1562 #endif
1563 non_safepoints.observe_instruction(n, current_offset);
1565 // mcall is last "call" that can be a safepoint
1566 // record it so we can see if a poll will directly follow it
1567 // in which case we'll need a pad to make the PcDesc sites unique
1568 // see 5010568. This can be slightly inaccurate but conservative
1569 // in the case that return address is not actually at current_offset.
1570 // This is a small price to pay.
1572 if (is_mcall) {
1573 last_call_offset = current_offset;
1574 }
1576 if (n->is_Mach() && n->as_Mach()->avoid_back_to_back(MachNode::AVOID_AFTER)) {
1577 // Avoid back to back some instructions.
1578 last_avoid_back_to_back_offset = current_offset;
1579 }
1581 // See if this instruction has a delay slot
1582 if (valid_bundle_info(n) && node_bundling(n)->use_unconditional_delay()) {
1583 assert(delay_slot != NULL, "expecting delay slot node");
1585 // Back up 1 instruction
1586 cb->set_insts_end(cb->insts_end() - Pipeline::instr_unit_size());
1588 // Save the offset for the listing
1589 #ifndef PRODUCT
1590 if (node_offsets && delay_slot->_idx < node_offset_limit)
1591 node_offsets[delay_slot->_idx] = cb->insts_size();
1592 #endif
1594 // Support a SafePoint in the delay slot
1595 if (delay_slot->is_MachSafePoint()) {
1596 MachNode *mach = delay_slot->as_Mach();
1597 // !!!!! Stubs only need an oopmap right now, so bail out
1598 if (!mach->is_MachCall() && mach->as_MachSafePoint()->jvms()->method() == NULL) {
1599 // Write the oopmap directly to the code blob??!!
1600 # ifdef ENABLE_ZAP_DEAD_LOCALS
1601 assert( !is_node_getting_a_safepoint(mach), "logic does not match; false positive");
1602 # endif
1603 delay_slot = NULL;
1604 continue;
1605 }
1607 int adjusted_offset = current_offset - Pipeline::instr_unit_size();
1608 non_safepoints.observe_safepoint(mach->as_MachSafePoint()->jvms(),
1609 adjusted_offset);
1610 // Generate an OopMap entry
1611 Process_OopMap_Node(mach, adjusted_offset);
1612 }
1614 // Insert the delay slot instruction
1615 delay_slot->emit(*cb, _regalloc);
1617 // Don't reuse it
1618 delay_slot = NULL;
1619 }
1621 } // End for all instructions in block
1623 // If the next block is the top of a loop, pad this block out to align
1624 // the loop top a little. Helps prevent pipe stalls at loop back branches.
1625 if (i < nblocks-1) {
1626 Block *nb = _cfg->get_block(i + 1);
1627 int padding = nb->alignment_padding(current_offset);
1628 if( padding > 0 ) {
1629 MachNode *nop = new (this) MachNopNode(padding / nop_size);
1630 block->insert_node(nop, block->number_of_nodes());
1631 _cfg->map_node_to_block(nop, block);
1632 nop->emit(*cb, _regalloc);
1633 current_offset = cb->insts_size();
1634 }
1635 }
1636 // Verify that the distance for generated before forward
1637 // short branches is still valid.
1638 guarantee((int)(blk_starts[i+1] - blk_starts[i]) >= (current_offset - blk_offset), "shouldn't increase block size");
1640 // Save new block start offset
1641 blk_starts[i] = blk_offset;
1642 } // End of for all blocks
1643 blk_starts[nblocks] = current_offset;
1645 non_safepoints.flush_at_end();
1647 // Offset too large?
1648 if (failing()) return;
1650 // Define a pseudo-label at the end of the code
1651 MacroAssembler(cb).bind( blk_labels[nblocks] );
1653 // Compute the size of the first block
1654 _first_block_size = blk_labels[1].loc_pos() - blk_labels[0].loc_pos();
1656 assert(cb->insts_size() < 500000, "method is unreasonably large");
1658 #ifdef ASSERT
1659 for (uint i = 0; i < nblocks; i++) { // For all blocks
1660 if (jmp_target[i] != 0) {
1661 int br_size = jmp_size[i];
1662 int offset = blk_starts[jmp_target[i]]-(blk_starts[i] + jmp_offset[i]);
1663 if (!_matcher->is_short_branch_offset(jmp_rule[i], br_size, offset)) {
1664 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]);
1665 assert(false, "Displacement too large for short jmp");
1666 }
1667 }
1668 }
1669 #endif
1671 #ifndef PRODUCT
1672 // Information on the size of the method, without the extraneous code
1673 Scheduling::increment_method_size(cb->insts_size());
1674 #endif
1676 // ------------------
1677 // Fill in exception table entries.
1678 FillExceptionTables(inct_cnt, call_returns, inct_starts, blk_labels);
1680 // Only java methods have exception handlers and deopt handlers
1681 // class HandlerImpl is platform-specific and defined in the *.ad files.
1682 if (_method) {
1683 // Emit the exception handler code.
1684 _code_offsets.set_value(CodeOffsets::Exceptions, HandlerImpl::emit_exception_handler(*cb));
1685 if (failing()) {
1686 return; // CodeBuffer::expand failed
1687 }
1688 // Emit the deopt handler code.
1689 _code_offsets.set_value(CodeOffsets::Deopt, HandlerImpl::emit_deopt_handler(*cb));
1691 // Emit the MethodHandle deopt handler code (if required).
1692 if (has_method_handle_invokes() && !failing()) {
1693 // We can use the same code as for the normal deopt handler, we
1694 // just need a different entry point address.
1695 _code_offsets.set_value(CodeOffsets::DeoptMH, HandlerImpl::emit_deopt_handler(*cb));
1696 }
1697 }
1699 // One last check for failed CodeBuffer::expand:
1700 if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
1701 C->record_failure("CodeCache is full");
1702 return;
1703 }
1705 #ifndef PRODUCT
1706 // Dump the assembly code, including basic-block numbers
1707 if (print_assembly()) {
1708 ttyLocker ttyl; // keep the following output all in one block
1709 if (!VMThread::should_terminate()) { // test this under the tty lock
1710 // This output goes directly to the tty, not the compiler log.
1711 // To enable tools to match it up with the compilation activity,
1712 // be sure to tag this tty output with the compile ID.
1713 if (xtty != NULL) {
1714 xtty->head("opto_assembly compile_id='%d'%s", compile_id(),
1715 is_osr_compilation() ? " compile_kind='osr'" :
1716 "");
1717 }
1718 if (method() != NULL) {
1719 method()->print_metadata();
1720 }
1721 dump_asm(node_offsets, node_offset_limit);
1722 if (xtty != NULL) {
1723 xtty->tail("opto_assembly");
1724 }
1725 }
1726 }
1727 #endif
1729 }
1731 void Compile::FillExceptionTables(uint cnt, uint *call_returns, uint *inct_starts, Label *blk_labels) {
1732 _inc_table.set_size(cnt);
1734 uint inct_cnt = 0;
1735 for (uint i = 0; i < _cfg->number_of_blocks(); i++) {
1736 Block* block = _cfg->get_block(i);
1737 Node *n = NULL;
1738 int j;
1740 // Find the branch; ignore trailing NOPs.
1741 for (j = block->number_of_nodes() - 1; j >= 0; j--) {
1742 n = block->get_node(j);
1743 if (!n->is_Mach() || n->as_Mach()->ideal_Opcode() != Op_Con) {
1744 break;
1745 }
1746 }
1748 // If we didn't find anything, continue
1749 if (j < 0) {
1750 continue;
1751 }
1753 // Compute ExceptionHandlerTable subtable entry and add it
1754 // (skip empty blocks)
1755 if (n->is_Catch()) {
1757 // Get the offset of the return from the call
1758 uint call_return = call_returns[block->_pre_order];
1759 #ifdef ASSERT
1760 assert( call_return > 0, "no call seen for this basic block" );
1761 while (block->get_node(--j)->is_MachProj()) ;
1762 assert(block->get_node(j)->is_MachCall(), "CatchProj must follow call");
1763 #endif
1764 // last instruction is a CatchNode, find it's CatchProjNodes
1765 int nof_succs = block->_num_succs;
1766 // allocate space
1767 GrowableArray<intptr_t> handler_bcis(nof_succs);
1768 GrowableArray<intptr_t> handler_pcos(nof_succs);
1769 // iterate through all successors
1770 for (int j = 0; j < nof_succs; j++) {
1771 Block* s = block->_succs[j];
1772 bool found_p = false;
1773 for (uint k = 1; k < s->num_preds(); k++) {
1774 Node* pk = s->pred(k);
1775 if (pk->is_CatchProj() && pk->in(0) == n) {
1776 const CatchProjNode* p = pk->as_CatchProj();
1777 found_p = true;
1778 // add the corresponding handler bci & pco information
1779 if (p->_con != CatchProjNode::fall_through_index) {
1780 // p leads to an exception handler (and is not fall through)
1781 assert(s == _cfg->get_block(s->_pre_order), "bad numbering");
1782 // no duplicates, please
1783 if (!handler_bcis.contains(p->handler_bci())) {
1784 uint block_num = s->non_connector()->_pre_order;
1785 handler_bcis.append(p->handler_bci());
1786 handler_pcos.append(blk_labels[block_num].loc_pos());
1787 }
1788 }
1789 }
1790 }
1791 assert(found_p, "no matching predecessor found");
1792 // Note: Due to empty block removal, one block may have
1793 // several CatchProj inputs, from the same Catch.
1794 }
1796 // Set the offset of the return from the call
1797 _handler_table.add_subtable(call_return, &handler_bcis, NULL, &handler_pcos);
1798 continue;
1799 }
1801 // Handle implicit null exception table updates
1802 if (n->is_MachNullCheck()) {
1803 uint block_num = block->non_connector_successor(0)->_pre_order;
1804 _inc_table.append(inct_starts[inct_cnt++], blk_labels[block_num].loc_pos());
1805 continue;
1806 }
1807 // Handle implicit exception table updates: trap instructions.
1808 if (n->is_Mach() && n->as_Mach()->is_TrapBasedCheckNode()) {
1809 uint block_num = block->non_connector_successor(0)->_pre_order;
1810 _inc_table.append(inct_starts[inct_cnt++], blk_labels[block_num].loc_pos());
1811 continue;
1812 }
1813 } // End of for all blocks fill in exception table entries
1814 }
1816 // Static Variables
1817 #ifndef PRODUCT
1818 uint Scheduling::_total_nop_size = 0;
1819 uint Scheduling::_total_method_size = 0;
1820 uint Scheduling::_total_branches = 0;
1821 uint Scheduling::_total_unconditional_delays = 0;
1822 uint Scheduling::_total_instructions_per_bundle[Pipeline::_max_instrs_per_cycle+1];
1823 #endif
1825 // Initializer for class Scheduling
1827 Scheduling::Scheduling(Arena *arena, Compile &compile)
1828 : _arena(arena),
1829 _cfg(compile.cfg()),
1830 _regalloc(compile.regalloc()),
1831 _reg_node(arena),
1832 _bundle_instr_count(0),
1833 _bundle_cycle_number(0),
1834 _scheduled(arena),
1835 _available(arena),
1836 _next_node(NULL),
1837 _bundle_use(0, 0, resource_count, &_bundle_use_elements[0]),
1838 _pinch_free_list(arena)
1839 #ifndef PRODUCT
1840 , _branches(0)
1841 , _unconditional_delays(0)
1842 #endif
1843 {
1844 // Create a MachNopNode
1845 _nop = new (&compile) MachNopNode();
1847 // Now that the nops are in the array, save the count
1848 // (but allow entries for the nops)
1849 _node_bundling_limit = compile.unique();
1850 uint node_max = _regalloc->node_regs_max_index();
1852 compile.set_node_bundling_limit(_node_bundling_limit);
1854 // This one is persistent within the Compile class
1855 _node_bundling_base = NEW_ARENA_ARRAY(compile.comp_arena(), Bundle, node_max);
1857 // Allocate space for fixed-size arrays
1858 _node_latency = NEW_ARENA_ARRAY(arena, unsigned short, node_max);
1859 _uses = NEW_ARENA_ARRAY(arena, short, node_max);
1860 _current_latency = NEW_ARENA_ARRAY(arena, unsigned short, node_max);
1862 // Clear the arrays
1863 memset(_node_bundling_base, 0, node_max * sizeof(Bundle));
1864 memset(_node_latency, 0, node_max * sizeof(unsigned short));
1865 memset(_uses, 0, node_max * sizeof(short));
1866 memset(_current_latency, 0, node_max * sizeof(unsigned short));
1868 // Clear the bundling information
1869 memcpy(_bundle_use_elements, Pipeline_Use::elaborated_elements, sizeof(Pipeline_Use::elaborated_elements));
1871 // Get the last node
1872 Block* block = _cfg->get_block(_cfg->number_of_blocks() - 1);
1874 _next_node = block->get_node(block->number_of_nodes() - 1);
1875 }
1877 #ifndef PRODUCT
1878 // Scheduling destructor
1879 Scheduling::~Scheduling() {
1880 _total_branches += _branches;
1881 _total_unconditional_delays += _unconditional_delays;
1882 }
1883 #endif
1885 // Step ahead "i" cycles
1886 void Scheduling::step(uint i) {
1888 Bundle *bundle = node_bundling(_next_node);
1889 bundle->set_starts_bundle();
1891 // Update the bundle record, but leave the flags information alone
1892 if (_bundle_instr_count > 0) {
1893 bundle->set_instr_count(_bundle_instr_count);
1894 bundle->set_resources_used(_bundle_use.resourcesUsed());
1895 }
1897 // Update the state information
1898 _bundle_instr_count = 0;
1899 _bundle_cycle_number += i;
1900 _bundle_use.step(i);
1901 }
1903 void Scheduling::step_and_clear() {
1904 Bundle *bundle = node_bundling(_next_node);
1905 bundle->set_starts_bundle();
1907 // Update the bundle record
1908 if (_bundle_instr_count > 0) {
1909 bundle->set_instr_count(_bundle_instr_count);
1910 bundle->set_resources_used(_bundle_use.resourcesUsed());
1912 _bundle_cycle_number += 1;
1913 }
1915 // Clear the bundling information
1916 _bundle_instr_count = 0;
1917 _bundle_use.reset();
1919 memcpy(_bundle_use_elements,
1920 Pipeline_Use::elaborated_elements,
1921 sizeof(Pipeline_Use::elaborated_elements));
1922 }
1924 // Perform instruction scheduling and bundling over the sequence of
1925 // instructions in backwards order.
1926 void Compile::ScheduleAndBundle() {
1928 // Don't optimize this if it isn't a method
1929 if (!_method)
1930 return;
1932 // Don't optimize this if scheduling is disabled
1933 if (!do_scheduling())
1934 return;
1936 // Scheduling code works only with pairs (8 bytes) maximum.
1937 if (max_vector_size() > 8)
1938 return;
1940 NOT_PRODUCT( TracePhase t2("isched", &_t_instrSched, TimeCompiler); )
1942 // Create a data structure for all the scheduling information
1943 Scheduling scheduling(Thread::current()->resource_area(), *this);
1945 // Walk backwards over each basic block, computing the needed alignment
1946 // Walk over all the basic blocks
1947 scheduling.DoScheduling();
1948 }
1950 // Compute the latency of all the instructions. This is fairly simple,
1951 // because we already have a legal ordering. Walk over the instructions
1952 // from first to last, and compute the latency of the instruction based
1953 // on the latency of the preceding instruction(s).
1954 void Scheduling::ComputeLocalLatenciesForward(const Block *bb) {
1955 #ifndef PRODUCT
1956 if (_cfg->C->trace_opto_output())
1957 tty->print("# -> ComputeLocalLatenciesForward\n");
1958 #endif
1960 // Walk over all the schedulable instructions
1961 for( uint j=_bb_start; j < _bb_end; j++ ) {
1963 // This is a kludge, forcing all latency calculations to start at 1.
1964 // Used to allow latency 0 to force an instruction to the beginning
1965 // of the bb
1966 uint latency = 1;
1967 Node *use = bb->get_node(j);
1968 uint nlen = use->len();
1970 // Walk over all the inputs
1971 for ( uint k=0; k < nlen; k++ ) {
1972 Node *def = use->in(k);
1973 if (!def)
1974 continue;
1976 uint l = _node_latency[def->_idx] + use->latency(k);
1977 if (latency < l)
1978 latency = l;
1979 }
1981 _node_latency[use->_idx] = latency;
1983 #ifndef PRODUCT
1984 if (_cfg->C->trace_opto_output()) {
1985 tty->print("# latency %4d: ", latency);
1986 use->dump();
1987 }
1988 #endif
1989 }
1991 #ifndef PRODUCT
1992 if (_cfg->C->trace_opto_output())
1993 tty->print("# <- ComputeLocalLatenciesForward\n");
1994 #endif
1996 } // end ComputeLocalLatenciesForward
1998 // See if this node fits into the present instruction bundle
1999 bool Scheduling::NodeFitsInBundle(Node *n) {
2000 uint n_idx = n->_idx;
2002 // If this is the unconditional delay instruction, then it fits
2003 if (n == _unconditional_delay_slot) {
2004 #ifndef PRODUCT
2005 if (_cfg->C->trace_opto_output())
2006 tty->print("# NodeFitsInBundle [%4d]: TRUE; is in unconditional delay slot\n", n->_idx);
2007 #endif
2008 return (true);
2009 }
2011 // If the node cannot be scheduled this cycle, skip it
2012 if (_current_latency[n_idx] > _bundle_cycle_number) {
2013 #ifndef PRODUCT
2014 if (_cfg->C->trace_opto_output())
2015 tty->print("# NodeFitsInBundle [%4d]: FALSE; latency %4d > %d\n",
2016 n->_idx, _current_latency[n_idx], _bundle_cycle_number);
2017 #endif
2018 return (false);
2019 }
2021 const Pipeline *node_pipeline = n->pipeline();
2023 uint instruction_count = node_pipeline->instructionCount();
2024 if (node_pipeline->mayHaveNoCode() && n->size(_regalloc) == 0)
2025 instruction_count = 0;
2026 else if (node_pipeline->hasBranchDelay() && !_unconditional_delay_slot)
2027 instruction_count++;
2029 if (_bundle_instr_count + instruction_count > Pipeline::_max_instrs_per_cycle) {
2030 #ifndef PRODUCT
2031 if (_cfg->C->trace_opto_output())
2032 tty->print("# NodeFitsInBundle [%4d]: FALSE; too many instructions: %d > %d\n",
2033 n->_idx, _bundle_instr_count + instruction_count, Pipeline::_max_instrs_per_cycle);
2034 #endif
2035 return (false);
2036 }
2038 // Don't allow non-machine nodes to be handled this way
2039 if (!n->is_Mach() && instruction_count == 0)
2040 return (false);
2042 // See if there is any overlap
2043 uint delay = _bundle_use.full_latency(0, node_pipeline->resourceUse());
2045 if (delay > 0) {
2046 #ifndef PRODUCT
2047 if (_cfg->C->trace_opto_output())
2048 tty->print("# NodeFitsInBundle [%4d]: FALSE; functional units overlap\n", n_idx);
2049 #endif
2050 return false;
2051 }
2053 #ifndef PRODUCT
2054 if (_cfg->C->trace_opto_output())
2055 tty->print("# NodeFitsInBundle [%4d]: TRUE\n", n_idx);
2056 #endif
2058 return true;
2059 }
2061 Node * Scheduling::ChooseNodeToBundle() {
2062 uint siz = _available.size();
2064 if (siz == 0) {
2066 #ifndef PRODUCT
2067 if (_cfg->C->trace_opto_output())
2068 tty->print("# ChooseNodeToBundle: NULL\n");
2069 #endif
2070 return (NULL);
2071 }
2073 // Fast path, if only 1 instruction in the bundle
2074 if (siz == 1) {
2075 #ifndef PRODUCT
2076 if (_cfg->C->trace_opto_output()) {
2077 tty->print("# ChooseNodeToBundle (only 1): ");
2078 _available[0]->dump();
2079 }
2080 #endif
2081 return (_available[0]);
2082 }
2084 // Don't bother, if the bundle is already full
2085 if (_bundle_instr_count < Pipeline::_max_instrs_per_cycle) {
2086 for ( uint i = 0; i < siz; i++ ) {
2087 Node *n = _available[i];
2089 // Skip projections, we'll handle them another way
2090 if (n->is_Proj())
2091 continue;
2093 // This presupposed that instructions are inserted into the
2094 // available list in a legality order; i.e. instructions that
2095 // must be inserted first are at the head of the list
2096 if (NodeFitsInBundle(n)) {
2097 #ifndef PRODUCT
2098 if (_cfg->C->trace_opto_output()) {
2099 tty->print("# ChooseNodeToBundle: ");
2100 n->dump();
2101 }
2102 #endif
2103 return (n);
2104 }
2105 }
2106 }
2108 // Nothing fits in this bundle, choose the highest priority
2109 #ifndef PRODUCT
2110 if (_cfg->C->trace_opto_output()) {
2111 tty->print("# ChooseNodeToBundle: ");
2112 _available[0]->dump();
2113 }
2114 #endif
2116 return _available[0];
2117 }
2119 void Scheduling::AddNodeToAvailableList(Node *n) {
2120 assert( !n->is_Proj(), "projections never directly made available" );
2121 #ifndef PRODUCT
2122 if (_cfg->C->trace_opto_output()) {
2123 tty->print("# AddNodeToAvailableList: ");
2124 n->dump();
2125 }
2126 #endif
2128 int latency = _current_latency[n->_idx];
2130 // Insert in latency order (insertion sort)
2131 uint i;
2132 for ( i=0; i < _available.size(); i++ )
2133 if (_current_latency[_available[i]->_idx] > latency)
2134 break;
2136 // Special Check for compares following branches
2137 if( n->is_Mach() && _scheduled.size() > 0 ) {
2138 int op = n->as_Mach()->ideal_Opcode();
2139 Node *last = _scheduled[0];
2140 if( last->is_MachIf() && last->in(1) == n &&
2141 ( op == Op_CmpI ||
2142 op == Op_CmpU ||
2143 op == Op_CmpUL ||
2144 op == Op_CmpP ||
2145 op == Op_CmpF ||
2146 op == Op_CmpD ||
2147 op == Op_CmpL ) ) {
2149 // Recalculate position, moving to front of same latency
2150 for ( i=0 ; i < _available.size(); i++ )
2151 if (_current_latency[_available[i]->_idx] >= latency)
2152 break;
2153 }
2154 }
2156 // Insert the node in the available list
2157 _available.insert(i, n);
2159 #ifndef PRODUCT
2160 if (_cfg->C->trace_opto_output())
2161 dump_available();
2162 #endif
2163 }
2165 void Scheduling::DecrementUseCounts(Node *n, const Block *bb) {
2166 for ( uint i=0; i < n->len(); i++ ) {
2167 Node *def = n->in(i);
2168 if (!def) continue;
2169 if( def->is_Proj() ) // If this is a machine projection, then
2170 def = def->in(0); // propagate usage thru to the base instruction
2172 if(_cfg->get_block_for_node(def) != bb) { // Ignore if not block-local
2173 continue;
2174 }
2176 // Compute the latency
2177 uint l = _bundle_cycle_number + n->latency(i);
2178 if (_current_latency[def->_idx] < l)
2179 _current_latency[def->_idx] = l;
2181 // If this does not have uses then schedule it
2182 if ((--_uses[def->_idx]) == 0)
2183 AddNodeToAvailableList(def);
2184 }
2185 }
2187 void Scheduling::AddNodeToBundle(Node *n, const Block *bb) {
2188 #ifndef PRODUCT
2189 if (_cfg->C->trace_opto_output()) {
2190 tty->print("# AddNodeToBundle: ");
2191 n->dump();
2192 }
2193 #endif
2195 // Remove this from the available list
2196 uint i;
2197 for (i = 0; i < _available.size(); i++)
2198 if (_available[i] == n)
2199 break;
2200 assert(i < _available.size(), "entry in _available list not found");
2201 _available.remove(i);
2203 // See if this fits in the current bundle
2204 const Pipeline *node_pipeline = n->pipeline();
2205 const Pipeline_Use& node_usage = node_pipeline->resourceUse();
2207 // Check for instructions to be placed in the delay slot. We
2208 // do this before we actually schedule the current instruction,
2209 // because the delay slot follows the current instruction.
2210 if (Pipeline::_branch_has_delay_slot &&
2211 node_pipeline->hasBranchDelay() &&
2212 !_unconditional_delay_slot) {
2214 uint siz = _available.size();
2216 // Conditional branches can support an instruction that
2217 // is unconditionally executed and not dependent by the
2218 // branch, OR a conditionally executed instruction if
2219 // the branch is taken. In practice, this means that
2220 // the first instruction at the branch target is
2221 // copied to the delay slot, and the branch goes to
2222 // the instruction after that at the branch target
2223 if ( n->is_MachBranch() ) {
2225 assert( !n->is_MachNullCheck(), "should not look for delay slot for Null Check" );
2226 assert( !n->is_Catch(), "should not look for delay slot for Catch" );
2228 #ifndef PRODUCT
2229 _branches++;
2230 #endif
2232 // At least 1 instruction is on the available list
2233 // that is not dependent on the branch
2234 for (uint i = 0; i < siz; i++) {
2235 Node *d = _available[i];
2236 const Pipeline *avail_pipeline = d->pipeline();
2238 // Don't allow safepoints in the branch shadow, that will
2239 // cause a number of difficulties
2240 if ( avail_pipeline->instructionCount() == 1 &&
2241 !avail_pipeline->hasMultipleBundles() &&
2242 !avail_pipeline->hasBranchDelay() &&
2243 Pipeline::instr_has_unit_size() &&
2244 d->size(_regalloc) == Pipeline::instr_unit_size() &&
2245 NodeFitsInBundle(d) &&
2246 !node_bundling(d)->used_in_delay()) {
2248 if (d->is_Mach() && !d->is_MachSafePoint()) {
2249 // A node that fits in the delay slot was found, so we need to
2250 // set the appropriate bits in the bundle pipeline information so
2251 // that it correctly indicates resource usage. Later, when we
2252 // attempt to add this instruction to the bundle, we will skip
2253 // setting the resource usage.
2254 _unconditional_delay_slot = d;
2255 node_bundling(n)->set_use_unconditional_delay();
2256 node_bundling(d)->set_used_in_unconditional_delay();
2257 _bundle_use.add_usage(avail_pipeline->resourceUse());
2258 _current_latency[d->_idx] = _bundle_cycle_number;
2259 _next_node = d;
2260 ++_bundle_instr_count;
2261 #ifndef PRODUCT
2262 _unconditional_delays++;
2263 #endif
2264 break;
2265 }
2266 }
2267 }
2268 }
2270 // No delay slot, add a nop to the usage
2271 if (!_unconditional_delay_slot) {
2272 // See if adding an instruction in the delay slot will overflow
2273 // the bundle.
2274 if (!NodeFitsInBundle(_nop)) {
2275 #ifndef PRODUCT
2276 if (_cfg->C->trace_opto_output())
2277 tty->print("# *** STEP(1 instruction for delay slot) ***\n");
2278 #endif
2279 step(1);
2280 }
2282 _bundle_use.add_usage(_nop->pipeline()->resourceUse());
2283 _next_node = _nop;
2284 ++_bundle_instr_count;
2285 }
2287 // See if the instruction in the delay slot requires a
2288 // step of the bundles
2289 if (!NodeFitsInBundle(n)) {
2290 #ifndef PRODUCT
2291 if (_cfg->C->trace_opto_output())
2292 tty->print("# *** STEP(branch won't fit) ***\n");
2293 #endif
2294 // Update the state information
2295 _bundle_instr_count = 0;
2296 _bundle_cycle_number += 1;
2297 _bundle_use.step(1);
2298 }
2299 }
2301 // Get the number of instructions
2302 uint instruction_count = node_pipeline->instructionCount();
2303 if (node_pipeline->mayHaveNoCode() && n->size(_regalloc) == 0)
2304 instruction_count = 0;
2306 // Compute the latency information
2307 uint delay = 0;
2309 if (instruction_count > 0 || !node_pipeline->mayHaveNoCode()) {
2310 int relative_latency = _current_latency[n->_idx] - _bundle_cycle_number;
2311 if (relative_latency < 0)
2312 relative_latency = 0;
2314 delay = _bundle_use.full_latency(relative_latency, node_usage);
2316 // Does not fit in this bundle, start a new one
2317 if (delay > 0) {
2318 step(delay);
2320 #ifndef PRODUCT
2321 if (_cfg->C->trace_opto_output())
2322 tty->print("# *** STEP(%d) ***\n", delay);
2323 #endif
2324 }
2325 }
2327 // If this was placed in the delay slot, ignore it
2328 if (n != _unconditional_delay_slot) {
2330 if (delay == 0) {
2331 if (node_pipeline->hasMultipleBundles()) {
2332 #ifndef PRODUCT
2333 if (_cfg->C->trace_opto_output())
2334 tty->print("# *** STEP(multiple instructions) ***\n");
2335 #endif
2336 step(1);
2337 }
2339 else if (instruction_count + _bundle_instr_count > Pipeline::_max_instrs_per_cycle) {
2340 #ifndef PRODUCT
2341 if (_cfg->C->trace_opto_output())
2342 tty->print("# *** STEP(%d >= %d instructions) ***\n",
2343 instruction_count + _bundle_instr_count,
2344 Pipeline::_max_instrs_per_cycle);
2345 #endif
2346 step(1);
2347 }
2348 }
2350 if (node_pipeline->hasBranchDelay() && !_unconditional_delay_slot)
2351 _bundle_instr_count++;
2353 // Set the node's latency
2354 _current_latency[n->_idx] = _bundle_cycle_number;
2356 // Now merge the functional unit information
2357 if (instruction_count > 0 || !node_pipeline->mayHaveNoCode())
2358 _bundle_use.add_usage(node_usage);
2360 // Increment the number of instructions in this bundle
2361 _bundle_instr_count += instruction_count;
2363 // Remember this node for later
2364 if (n->is_Mach())
2365 _next_node = n;
2366 }
2368 // It's possible to have a BoxLock in the graph and in the _bbs mapping but
2369 // not in the bb->_nodes array. This happens for debug-info-only BoxLocks.
2370 // 'Schedule' them (basically ignore in the schedule) but do not insert them
2371 // into the block. All other scheduled nodes get put in the schedule here.
2372 int op = n->Opcode();
2373 if( (op == Op_Node && n->req() == 0) || // anti-dependence node OR
2374 (op != Op_Node && // Not an unused antidepedence node and
2375 // not an unallocated boxlock
2376 (OptoReg::is_valid(_regalloc->get_reg_first(n)) || op != Op_BoxLock)) ) {
2378 // Push any trailing projections
2379 if( bb->get_node(bb->number_of_nodes()-1) != n ) {
2380 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2381 Node *foi = n->fast_out(i);
2382 if( foi->is_Proj() )
2383 _scheduled.push(foi);
2384 }
2385 }
2387 // Put the instruction in the schedule list
2388 _scheduled.push(n);
2389 }
2391 #ifndef PRODUCT
2392 if (_cfg->C->trace_opto_output())
2393 dump_available();
2394 #endif
2396 // Walk all the definitions, decrementing use counts, and
2397 // if a definition has a 0 use count, place it in the available list.
2398 DecrementUseCounts(n,bb);
2399 }
2401 // This method sets the use count within a basic block. We will ignore all
2402 // uses outside the current basic block. As we are doing a backwards walk,
2403 // any node we reach that has a use count of 0 may be scheduled. This also
2404 // avoids the problem of cyclic references from phi nodes, as long as phi
2405 // nodes are at the front of the basic block. This method also initializes
2406 // the available list to the set of instructions that have no uses within this
2407 // basic block.
2408 void Scheduling::ComputeUseCount(const Block *bb) {
2409 #ifndef PRODUCT
2410 if (_cfg->C->trace_opto_output())
2411 tty->print("# -> ComputeUseCount\n");
2412 #endif
2414 // Clear the list of available and scheduled instructions, just in case
2415 _available.clear();
2416 _scheduled.clear();
2418 // No delay slot specified
2419 _unconditional_delay_slot = NULL;
2421 #ifdef ASSERT
2422 for( uint i=0; i < bb->number_of_nodes(); i++ )
2423 assert( _uses[bb->get_node(i)->_idx] == 0, "_use array not clean" );
2424 #endif
2426 // Force the _uses count to never go to zero for unscheduable pieces
2427 // of the block
2428 for( uint k = 0; k < _bb_start; k++ )
2429 _uses[bb->get_node(k)->_idx] = 1;
2430 for( uint l = _bb_end; l < bb->number_of_nodes(); l++ )
2431 _uses[bb->get_node(l)->_idx] = 1;
2433 // Iterate backwards over the instructions in the block. Don't count the
2434 // branch projections at end or the block header instructions.
2435 for( uint j = _bb_end-1; j >= _bb_start; j-- ) {
2436 Node *n = bb->get_node(j);
2437 if( n->is_Proj() ) continue; // Projections handled another way
2439 // Account for all uses
2440 for ( uint k = 0; k < n->len(); k++ ) {
2441 Node *inp = n->in(k);
2442 if (!inp) continue;
2443 assert(inp != n, "no cycles allowed" );
2444 if (_cfg->get_block_for_node(inp) == bb) { // Block-local use?
2445 if (inp->is_Proj()) { // Skip through Proj's
2446 inp = inp->in(0);
2447 }
2448 ++_uses[inp->_idx]; // Count 1 block-local use
2449 }
2450 }
2452 // If this instruction has a 0 use count, then it is available
2453 if (!_uses[n->_idx]) {
2454 _current_latency[n->_idx] = _bundle_cycle_number;
2455 AddNodeToAvailableList(n);
2456 }
2458 #ifndef PRODUCT
2459 if (_cfg->C->trace_opto_output()) {
2460 tty->print("# uses: %3d: ", _uses[n->_idx]);
2461 n->dump();
2462 }
2463 #endif
2464 }
2466 #ifndef PRODUCT
2467 if (_cfg->C->trace_opto_output())
2468 tty->print("# <- ComputeUseCount\n");
2469 #endif
2470 }
2472 // This routine performs scheduling on each basic block in reverse order,
2473 // using instruction latencies and taking into account function unit
2474 // availability.
2475 void Scheduling::DoScheduling() {
2476 #ifndef PRODUCT
2477 if (_cfg->C->trace_opto_output())
2478 tty->print("# -> DoScheduling\n");
2479 #endif
2481 Block *succ_bb = NULL;
2482 Block *bb;
2484 // Walk over all the basic blocks in reverse order
2485 for (int i = _cfg->number_of_blocks() - 1; i >= 0; succ_bb = bb, i--) {
2486 bb = _cfg->get_block(i);
2488 #ifndef PRODUCT
2489 if (_cfg->C->trace_opto_output()) {
2490 tty->print("# Schedule BB#%03d (initial)\n", i);
2491 for (uint j = 0; j < bb->number_of_nodes(); j++) {
2492 bb->get_node(j)->dump();
2493 }
2494 }
2495 #endif
2497 // On the head node, skip processing
2498 if (bb == _cfg->get_root_block()) {
2499 continue;
2500 }
2502 // Skip empty, connector blocks
2503 if (bb->is_connector())
2504 continue;
2506 // If the following block is not the sole successor of
2507 // this one, then reset the pipeline information
2508 if (bb->_num_succs != 1 || bb->non_connector_successor(0) != succ_bb) {
2509 #ifndef PRODUCT
2510 if (_cfg->C->trace_opto_output()) {
2511 tty->print("*** bundle start of next BB, node %d, for %d instructions\n",
2512 _next_node->_idx, _bundle_instr_count);
2513 }
2514 #endif
2515 step_and_clear();
2516 }
2518 // Leave untouched the starting instruction, any Phis, a CreateEx node
2519 // or Top. bb->get_node(_bb_start) is the first schedulable instruction.
2520 _bb_end = bb->number_of_nodes()-1;
2521 for( _bb_start=1; _bb_start <= _bb_end; _bb_start++ ) {
2522 Node *n = bb->get_node(_bb_start);
2523 // Things not matched, like Phinodes and ProjNodes don't get scheduled.
2524 // Also, MachIdealNodes do not get scheduled
2525 if( !n->is_Mach() ) continue; // Skip non-machine nodes
2526 MachNode *mach = n->as_Mach();
2527 int iop = mach->ideal_Opcode();
2528 if( iop == Op_CreateEx ) continue; // CreateEx is pinned
2529 if( iop == Op_Con ) continue; // Do not schedule Top
2530 if( iop == Op_Node && // Do not schedule PhiNodes, ProjNodes
2531 mach->pipeline() == MachNode::pipeline_class() &&
2532 !n->is_SpillCopy() && !n->is_MachMerge() ) // Breakpoints, Prolog, etc
2533 continue;
2534 break; // Funny loop structure to be sure...
2535 }
2536 // Compute last "interesting" instruction in block - last instruction we
2537 // might schedule. _bb_end points just after last schedulable inst. We
2538 // normally schedule conditional branches (despite them being forced last
2539 // in the block), because they have delay slots we can fill. Calls all
2540 // have their delay slots filled in the template expansions, so we don't
2541 // bother scheduling them.
2542 Node *last = bb->get_node(_bb_end);
2543 // Ignore trailing NOPs.
2544 while (_bb_end > 0 && last->is_Mach() &&
2545 last->as_Mach()->ideal_Opcode() == Op_Con) {
2546 last = bb->get_node(--_bb_end);
2547 }
2548 assert(!last->is_Mach() || last->as_Mach()->ideal_Opcode() != Op_Con, "");
2549 if( last->is_Catch() ||
2550 // Exclude unreachable path case when Halt node is in a separate block.
2551 (_bb_end > 1 && last->is_Mach() && last->as_Mach()->ideal_Opcode() == Op_Halt) ) {
2552 // There must be a prior call. Skip it.
2553 while( !bb->get_node(--_bb_end)->is_MachCall() ) {
2554 assert( bb->get_node(_bb_end)->is_MachProj(), "skipping projections after expected call" );
2555 }
2556 } else if( last->is_MachNullCheck() ) {
2557 // Backup so the last null-checked memory instruction is
2558 // outside the schedulable range. Skip over the nullcheck,
2559 // projection, and the memory nodes.
2560 Node *mem = last->in(1);
2561 do {
2562 _bb_end--;
2563 } while (mem != bb->get_node(_bb_end));
2564 } else {
2565 // Set _bb_end to point after last schedulable inst.
2566 _bb_end++;
2567 }
2569 assert( _bb_start <= _bb_end, "inverted block ends" );
2571 // Compute the register antidependencies for the basic block
2572 ComputeRegisterAntidependencies(bb);
2573 if (_cfg->C->failing()) return; // too many D-U pinch points
2575 // Compute intra-bb latencies for the nodes
2576 ComputeLocalLatenciesForward(bb);
2578 // Compute the usage within the block, and set the list of all nodes
2579 // in the block that have no uses within the block.
2580 ComputeUseCount(bb);
2582 // Schedule the remaining instructions in the block
2583 while ( _available.size() > 0 ) {
2584 Node *n = ChooseNodeToBundle();
2585 guarantee(n != NULL, "no nodes available");
2586 AddNodeToBundle(n,bb);
2587 }
2589 assert( _scheduled.size() == _bb_end - _bb_start, "wrong number of instructions" );
2590 #ifdef ASSERT
2591 for( uint l = _bb_start; l < _bb_end; l++ ) {
2592 Node *n = bb->get_node(l);
2593 uint m;
2594 for( m = 0; m < _bb_end-_bb_start; m++ )
2595 if( _scheduled[m] == n )
2596 break;
2597 assert( m < _bb_end-_bb_start, "instruction missing in schedule" );
2598 }
2599 #endif
2601 // Now copy the instructions (in reverse order) back to the block
2602 for ( uint k = _bb_start; k < _bb_end; k++ )
2603 bb->map_node(_scheduled[_bb_end-k-1], k);
2605 #ifndef PRODUCT
2606 if (_cfg->C->trace_opto_output()) {
2607 tty->print("# Schedule BB#%03d (final)\n", i);
2608 uint current = 0;
2609 for (uint j = 0; j < bb->number_of_nodes(); j++) {
2610 Node *n = bb->get_node(j);
2611 if( valid_bundle_info(n) ) {
2612 Bundle *bundle = node_bundling(n);
2613 if (bundle->instr_count() > 0 || bundle->flags() > 0) {
2614 tty->print("*** Bundle: ");
2615 bundle->dump();
2616 }
2617 n->dump();
2618 }
2619 }
2620 }
2621 #endif
2622 #ifdef ASSERT
2623 verify_good_schedule(bb,"after block local scheduling");
2624 #endif
2625 }
2627 #ifndef PRODUCT
2628 if (_cfg->C->trace_opto_output())
2629 tty->print("# <- DoScheduling\n");
2630 #endif
2632 // Record final node-bundling array location
2633 _regalloc->C->set_node_bundling_base(_node_bundling_base);
2635 } // end DoScheduling
2637 // Verify that no live-range used in the block is killed in the block by a
2638 // wrong DEF. This doesn't verify live-ranges that span blocks.
2640 // Check for edge existence. Used to avoid adding redundant precedence edges.
2641 static bool edge_from_to( Node *from, Node *to ) {
2642 for( uint i=0; i<from->len(); i++ )
2643 if( from->in(i) == to )
2644 return true;
2645 return false;
2646 }
2648 #ifdef ASSERT
2649 void Scheduling::verify_do_def( Node *n, OptoReg::Name def, const char *msg ) {
2650 // Check for bad kills
2651 if( OptoReg::is_valid(def) ) { // Ignore stores & control flow
2652 Node *prior_use = _reg_node[def];
2653 if( prior_use && !edge_from_to(prior_use,n) ) {
2654 tty->print("%s = ",OptoReg::as_VMReg(def)->name());
2655 n->dump();
2656 tty->print_cr("...");
2657 prior_use->dump();
2658 assert(edge_from_to(prior_use,n),msg);
2659 }
2660 _reg_node.map(def,NULL); // Kill live USEs
2661 }
2662 }
2664 void Scheduling::verify_good_schedule( Block *b, const char *msg ) {
2666 // Zap to something reasonable for the verify code
2667 _reg_node.clear();
2669 // Walk over the block backwards. Check to make sure each DEF doesn't
2670 // kill a live value (other than the one it's supposed to). Add each
2671 // USE to the live set.
2672 for( uint i = b->number_of_nodes()-1; i >= _bb_start; i-- ) {
2673 Node *n = b->get_node(i);
2674 int n_op = n->Opcode();
2675 if( n_op == Op_MachProj && n->ideal_reg() == MachProjNode::fat_proj ) {
2676 // Fat-proj kills a slew of registers
2677 RegMask rm = n->out_RegMask();// Make local copy
2678 while( rm.is_NotEmpty() ) {
2679 OptoReg::Name kill = rm.find_first_elem();
2680 rm.Remove(kill);
2681 verify_do_def( n, kill, msg );
2682 }
2683 } else if( n_op != Op_Node ) { // Avoid brand new antidependence nodes
2684 // Get DEF'd registers the normal way
2685 verify_do_def( n, _regalloc->get_reg_first(n), msg );
2686 verify_do_def( n, _regalloc->get_reg_second(n), msg );
2687 }
2689 // Now make all USEs live
2690 for( uint i=1; i<n->req(); i++ ) {
2691 Node *def = n->in(i);
2692 assert(def != 0, "input edge required");
2693 OptoReg::Name reg_lo = _regalloc->get_reg_first(def);
2694 OptoReg::Name reg_hi = _regalloc->get_reg_second(def);
2695 if( OptoReg::is_valid(reg_lo) ) {
2696 assert(!_reg_node[reg_lo] || edge_from_to(_reg_node[reg_lo],def), msg);
2697 _reg_node.map(reg_lo,n);
2698 }
2699 if( OptoReg::is_valid(reg_hi) ) {
2700 assert(!_reg_node[reg_hi] || edge_from_to(_reg_node[reg_hi],def), msg);
2701 _reg_node.map(reg_hi,n);
2702 }
2703 }
2705 }
2707 // Zap to something reasonable for the Antidependence code
2708 _reg_node.clear();
2709 }
2710 #endif
2712 // Conditionally add precedence edges. Avoid putting edges on Projs.
2713 static void add_prec_edge_from_to( Node *from, Node *to ) {
2714 if( from->is_Proj() ) { // Put precedence edge on Proj's input
2715 assert( from->req() == 1 && (from->len() == 1 || from->in(1)==0), "no precedence edges on projections" );
2716 from = from->in(0);
2717 }
2718 if( from != to && // No cycles (for things like LD L0,[L0+4] )
2719 !edge_from_to( from, to ) ) // Avoid duplicate edge
2720 from->add_prec(to);
2721 }
2723 void Scheduling::anti_do_def( Block *b, Node *def, OptoReg::Name def_reg, int is_def ) {
2724 if( !OptoReg::is_valid(def_reg) ) // Ignore stores & control flow
2725 return;
2727 Node *pinch = _reg_node[def_reg]; // Get pinch point
2728 if ((pinch == NULL) || _cfg->get_block_for_node(pinch) != b || // No pinch-point yet?
2729 is_def ) { // Check for a true def (not a kill)
2730 _reg_node.map(def_reg,def); // Record def/kill as the optimistic pinch-point
2731 return;
2732 }
2734 Node *kill = def; // Rename 'def' to more descriptive 'kill'
2735 debug_only( def = (Node*)0xdeadbeef; )
2737 // After some number of kills there _may_ be a later def
2738 Node *later_def = NULL;
2740 // Finding a kill requires a real pinch-point.
2741 // Check for not already having a pinch-point.
2742 // Pinch points are Op_Node's.
2743 if( pinch->Opcode() != Op_Node ) { // Or later-def/kill as pinch-point?
2744 later_def = pinch; // Must be def/kill as optimistic pinch-point
2745 if ( _pinch_free_list.size() > 0) {
2746 pinch = _pinch_free_list.pop();
2747 } else {
2748 pinch = new (_cfg->C) Node(1); // Pinch point to-be
2749 }
2750 if (pinch->_idx >= _regalloc->node_regs_max_index()) {
2751 _cfg->C->record_method_not_compilable("too many D-U pinch points");
2752 return;
2753 }
2754 _cfg->map_node_to_block(pinch, b); // Pretend it's valid in this block (lazy init)
2755 _reg_node.map(def_reg,pinch); // Record pinch-point
2756 //_regalloc->set_bad(pinch->_idx); // Already initialized this way.
2757 if( later_def->outcnt() == 0 || later_def->ideal_reg() == MachProjNode::fat_proj ) { // Distinguish def from kill
2758 pinch->init_req(0, _cfg->C->top()); // set not NULL for the next call
2759 add_prec_edge_from_to(later_def,pinch); // Add edge from kill to pinch
2760 later_def = NULL; // and no later def
2761 }
2762 pinch->set_req(0,later_def); // Hook later def so we can find it
2763 } else { // Else have valid pinch point
2764 if( pinch->in(0) ) // If there is a later-def
2765 later_def = pinch->in(0); // Get it
2766 }
2768 // Add output-dependence edge from later def to kill
2769 if( later_def ) // If there is some original def
2770 add_prec_edge_from_to(later_def,kill); // Add edge from def to kill
2772 // See if current kill is also a use, and so is forced to be the pinch-point.
2773 if( pinch->Opcode() == Op_Node ) {
2774 Node *uses = kill->is_Proj() ? kill->in(0) : kill;
2775 for( uint i=1; i<uses->req(); i++ ) {
2776 if( _regalloc->get_reg_first(uses->in(i)) == def_reg ||
2777 _regalloc->get_reg_second(uses->in(i)) == def_reg ) {
2778 // Yes, found a use/kill pinch-point
2779 pinch->set_req(0,NULL); //
2780 pinch->replace_by(kill); // Move anti-dep edges up
2781 pinch = kill;
2782 _reg_node.map(def_reg,pinch);
2783 return;
2784 }
2785 }
2786 }
2788 // Add edge from kill to pinch-point
2789 add_prec_edge_from_to(kill,pinch);
2790 }
2792 void Scheduling::anti_do_use( Block *b, Node *use, OptoReg::Name use_reg ) {
2793 if( !OptoReg::is_valid(use_reg) ) // Ignore stores & control flow
2794 return;
2795 Node *pinch = _reg_node[use_reg]; // Get pinch point
2796 // Check for no later def_reg/kill in block
2797 if ((pinch != NULL) && _cfg->get_block_for_node(pinch) == b &&
2798 // Use has to be block-local as well
2799 _cfg->get_block_for_node(use) == b) {
2800 if( pinch->Opcode() == Op_Node && // Real pinch-point (not optimistic?)
2801 pinch->req() == 1 ) { // pinch not yet in block?
2802 pinch->del_req(0); // yank pointer to later-def, also set flag
2803 // Insert the pinch-point in the block just after the last use
2804 b->insert_node(pinch, b->find_node(use) + 1);
2805 _bb_end++; // Increase size scheduled region in block
2806 }
2808 add_prec_edge_from_to(pinch,use);
2809 }
2810 }
2812 // We insert antidependences between the reads and following write of
2813 // allocated registers to prevent illegal code motion. Hopefully, the
2814 // number of added references should be fairly small, especially as we
2815 // are only adding references within the current basic block.
2816 void Scheduling::ComputeRegisterAntidependencies(Block *b) {
2818 #ifdef ASSERT
2819 verify_good_schedule(b,"before block local scheduling");
2820 #endif
2822 // A valid schedule, for each register independently, is an endless cycle
2823 // of: a def, then some uses (connected to the def by true dependencies),
2824 // then some kills (defs with no uses), finally the cycle repeats with a new
2825 // def. The uses are allowed to float relative to each other, as are the
2826 // kills. No use is allowed to slide past a kill (or def). This requires
2827 // antidependencies between all uses of a single def and all kills that
2828 // follow, up to the next def. More edges are redundant, because later defs
2829 // & kills are already serialized with true or antidependencies. To keep
2830 // the edge count down, we add a 'pinch point' node if there's more than
2831 // one use or more than one kill/def.
2833 // We add dependencies in one bottom-up pass.
2835 // For each instruction we handle it's DEFs/KILLs, then it's USEs.
2837 // For each DEF/KILL, we check to see if there's a prior DEF/KILL for this
2838 // register. If not, we record the DEF/KILL in _reg_node, the
2839 // register-to-def mapping. If there is a prior DEF/KILL, we insert a
2840 // "pinch point", a new Node that's in the graph but not in the block.
2841 // We put edges from the prior and current DEF/KILLs to the pinch point.
2842 // We put the pinch point in _reg_node. If there's already a pinch point
2843 // we merely add an edge from the current DEF/KILL to the pinch point.
2845 // After doing the DEF/KILLs, we handle USEs. For each used register, we
2846 // put an edge from the pinch point to the USE.
2848 // To be expedient, the _reg_node array is pre-allocated for the whole
2849 // compilation. _reg_node is lazily initialized; it either contains a NULL,
2850 // or a valid def/kill/pinch-point, or a leftover node from some prior
2851 // block. Leftover node from some prior block is treated like a NULL (no
2852 // prior def, so no anti-dependence needed). Valid def is distinguished by
2853 // it being in the current block.
2854 bool fat_proj_seen = false;
2855 uint last_safept = _bb_end-1;
2856 Node* end_node = (_bb_end-1 >= _bb_start) ? b->get_node(last_safept) : NULL;
2857 Node* last_safept_node = end_node;
2858 for( uint i = _bb_end-1; i >= _bb_start; i-- ) {
2859 Node *n = b->get_node(i);
2860 int is_def = n->outcnt(); // def if some uses prior to adding precedence edges
2861 if( n->is_MachProj() && n->ideal_reg() == MachProjNode::fat_proj ) {
2862 // Fat-proj kills a slew of registers
2863 // This can add edges to 'n' and obscure whether or not it was a def,
2864 // hence the is_def flag.
2865 fat_proj_seen = true;
2866 RegMask rm = n->out_RegMask();// Make local copy
2867 while( rm.is_NotEmpty() ) {
2868 OptoReg::Name kill = rm.find_first_elem();
2869 rm.Remove(kill);
2870 anti_do_def( b, n, kill, is_def );
2871 }
2872 } else {
2873 // Get DEF'd registers the normal way
2874 anti_do_def( b, n, _regalloc->get_reg_first(n), is_def );
2875 anti_do_def( b, n, _regalloc->get_reg_second(n), is_def );
2876 }
2878 // Kill projections on a branch should appear to occur on the
2879 // branch, not afterwards, so grab the masks from the projections
2880 // and process them.
2881 if (n->is_MachBranch() || n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_Jump) {
2882 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2883 Node* use = n->fast_out(i);
2884 if (use->is_Proj()) {
2885 RegMask rm = use->out_RegMask();// Make local copy
2886 while( rm.is_NotEmpty() ) {
2887 OptoReg::Name kill = rm.find_first_elem();
2888 rm.Remove(kill);
2889 anti_do_def( b, n, kill, false );
2890 }
2891 }
2892 }
2893 }
2895 // Check each register used by this instruction for a following DEF/KILL
2896 // that must occur afterward and requires an anti-dependence edge.
2897 for( uint j=0; j<n->req(); j++ ) {
2898 Node *def = n->in(j);
2899 if( def ) {
2900 assert( !def->is_MachProj() || def->ideal_reg() != MachProjNode::fat_proj, "" );
2901 anti_do_use( b, n, _regalloc->get_reg_first(def) );
2902 anti_do_use( b, n, _regalloc->get_reg_second(def) );
2903 }
2904 }
2905 // Do not allow defs of new derived values to float above GC
2906 // points unless the base is definitely available at the GC point.
2908 Node *m = b->get_node(i);
2910 // Add precedence edge from following safepoint to use of derived pointer
2911 if( last_safept_node != end_node &&
2912 m != last_safept_node) {
2913 for (uint k = 1; k < m->req(); k++) {
2914 const Type *t = m->in(k)->bottom_type();
2915 if( t->isa_oop_ptr() &&
2916 t->is_ptr()->offset() != 0 ) {
2917 last_safept_node->add_prec( m );
2918 break;
2919 }
2920 }
2921 }
2923 if( n->jvms() ) { // Precedence edge from derived to safept
2924 // Check if last_safept_node was moved by pinch-point insertion in anti_do_use()
2925 if( b->get_node(last_safept) != last_safept_node ) {
2926 last_safept = b->find_node(last_safept_node);
2927 }
2928 for( uint j=last_safept; j > i; j-- ) {
2929 Node *mach = b->get_node(j);
2930 if( mach->is_Mach() && mach->as_Mach()->ideal_Opcode() == Op_AddP )
2931 mach->add_prec( n );
2932 }
2933 last_safept = i;
2934 last_safept_node = m;
2935 }
2936 }
2938 if (fat_proj_seen) {
2939 // Garbage collect pinch nodes that were not consumed.
2940 // They are usually created by a fat kill MachProj for a call.
2941 garbage_collect_pinch_nodes();
2942 }
2943 }
2945 // Garbage collect pinch nodes for reuse by other blocks.
2946 //
2947 // The block scheduler's insertion of anti-dependence
2948 // edges creates many pinch nodes when the block contains
2949 // 2 or more Calls. A pinch node is used to prevent a
2950 // combinatorial explosion of edges. If a set of kills for a
2951 // register is anti-dependent on a set of uses (or defs), rather
2952 // than adding an edge in the graph between each pair of kill
2953 // and use (or def), a pinch is inserted between them:
2954 //
2955 // use1 use2 use3
2956 // \ | /
2957 // \ | /
2958 // pinch
2959 // / | \
2960 // / | \
2961 // kill1 kill2 kill3
2962 //
2963 // One pinch node is created per register killed when
2964 // the second call is encountered during a backwards pass
2965 // over the block. Most of these pinch nodes are never
2966 // wired into the graph because the register is never
2967 // used or def'ed in the block.
2968 //
2969 void Scheduling::garbage_collect_pinch_nodes() {
2970 #ifndef PRODUCT
2971 if (_cfg->C->trace_opto_output()) tty->print("Reclaimed pinch nodes:");
2972 #endif
2973 int trace_cnt = 0;
2974 for (uint k = 0; k < _reg_node.Size(); k++) {
2975 Node* pinch = _reg_node[k];
2976 if ((pinch != NULL) && pinch->Opcode() == Op_Node &&
2977 // no predecence input edges
2978 (pinch->req() == pinch->len() || pinch->in(pinch->req()) == NULL) ) {
2979 cleanup_pinch(pinch);
2980 _pinch_free_list.push(pinch);
2981 _reg_node.map(k, NULL);
2982 #ifndef PRODUCT
2983 if (_cfg->C->trace_opto_output()) {
2984 trace_cnt++;
2985 if (trace_cnt > 40) {
2986 tty->print("\n");
2987 trace_cnt = 0;
2988 }
2989 tty->print(" %d", pinch->_idx);
2990 }
2991 #endif
2992 }
2993 }
2994 #ifndef PRODUCT
2995 if (_cfg->C->trace_opto_output()) tty->print("\n");
2996 #endif
2997 }
2999 // Clean up a pinch node for reuse.
3000 void Scheduling::cleanup_pinch( Node *pinch ) {
3001 assert (pinch && pinch->Opcode() == Op_Node && pinch->req() == 1, "just checking");
3003 for (DUIterator_Last imin, i = pinch->last_outs(imin); i >= imin; ) {
3004 Node* use = pinch->last_out(i);
3005 uint uses_found = 0;
3006 for (uint j = use->req(); j < use->len(); j++) {
3007 if (use->in(j) == pinch) {
3008 use->rm_prec(j);
3009 uses_found++;
3010 }
3011 }
3012 assert(uses_found > 0, "must be a precedence edge");
3013 i -= uses_found; // we deleted 1 or more copies of this edge
3014 }
3015 // May have a later_def entry
3016 pinch->set_req(0, NULL);
3017 }
3019 #ifndef PRODUCT
3021 void Scheduling::dump_available() const {
3022 tty->print("#Availist ");
3023 for (uint i = 0; i < _available.size(); i++)
3024 tty->print(" N%d/l%d", _available[i]->_idx,_current_latency[_available[i]->_idx]);
3025 tty->cr();
3026 }
3028 // Print Scheduling Statistics
3029 void Scheduling::print_statistics() {
3030 // Print the size added by nops for bundling
3031 tty->print("Nops added %d bytes to total of %d bytes",
3032 _total_nop_size, _total_method_size);
3033 if (_total_method_size > 0)
3034 tty->print(", for %.2f%%",
3035 ((double)_total_nop_size) / ((double) _total_method_size) * 100.0);
3036 tty->print("\n");
3038 // Print the number of branch shadows filled
3039 if (Pipeline::_branch_has_delay_slot) {
3040 tty->print("Of %d branches, %d had unconditional delay slots filled",
3041 _total_branches, _total_unconditional_delays);
3042 if (_total_branches > 0)
3043 tty->print(", for %.2f%%",
3044 ((double)_total_unconditional_delays) / ((double)_total_branches) * 100.0);
3045 tty->print("\n");
3046 }
3048 uint total_instructions = 0, total_bundles = 0;
3050 for (uint i = 1; i <= Pipeline::_max_instrs_per_cycle; i++) {
3051 uint bundle_count = _total_instructions_per_bundle[i];
3052 total_instructions += bundle_count * i;
3053 total_bundles += bundle_count;
3054 }
3056 if (total_bundles > 0)
3057 tty->print("Average ILP (excluding nops) is %.2f\n",
3058 ((double)total_instructions) / ((double)total_bundles));
3059 }
3060 #endif