Fri, 29 Mar 2019 13:41:31 +0800
#8664 comments code style fix
Reviewed-by: aoqi
1 /*
2 * Copyright (c) 1998, 2018, 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 2018. These
27 * modifications are Copyright (c) 2018 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 MIPS
853 // safepoint_pc_offset should point to tha last instruction in safePoint.
854 // In X86 and sparc, their safePoints only contain one instruction.
855 // However, we should add current_offset with the size of safePoint in MIPS.
856 // 0x2d6ff22c: lw s2, 0x14(s2)
857 // last_pd->pc_offset()=308, pc_offset=304, bci=64
858 // last_pd->pc_offset()=312, pc_offset=312, bci=64
859 // src/hotspot/share/code/debugInfoRec.cpp:295, assert(last_pd->pc_offset() == pc_offset, "must be last pc")
860 //
861 // ;; Safepoint:
862 // ---> pc_offset=304
863 // 0x2d6ff230: lui at, 0x2b7a ; OopMap{s2=Oop s5=Oop t4=Oop off=308}
864 // ;*goto
865 // ; - java.util.Hashtable::get@64 (line 353)
866 // ---> last_pd(308)
867 // 0x2d6ff234: lw at, 0xffffc100(at) ;*goto
868 // ; - java.util.Hashtable::get@64 (line 353)
869 // ; {poll}
870 // 0x2d6ff238: addiu s0, zero, 0x0
871 safepoint_pc_offset += sfn->size(_regalloc) - 4;
872 #endif
873 debug_info()->add_safepoint(safepoint_pc_offset, sfn->_oop_map);
874 } else {
875 mcall = mach->as_MachCall();
877 // Is the call a MethodHandle call?
878 if (mcall->is_MachCallJava()) {
879 if (mcall->as_MachCallJava()->_method_handle_invoke) {
880 assert(has_method_handle_invokes(), "must have been set during call generation");
881 is_method_handle_invoke = true;
882 }
883 }
885 // Check if a call returns an object.
886 if (mcall->returns_pointer()) {
887 return_oop = true;
888 }
889 safepoint_pc_offset += mcall->ret_addr_offset();
890 debug_info()->add_safepoint(safepoint_pc_offset, mcall->_oop_map);
891 }
893 // Loop over the JVMState list to add scope information
894 // Do not skip safepoints with a NULL method, they need monitor info
895 JVMState* youngest_jvms = sfn->jvms();
896 int max_depth = youngest_jvms->depth();
898 // Allocate the object pool for scalar-replaced objects -- the map from
899 // small-integer keys (which can be recorded in the local and ostack
900 // arrays) to descriptions of the object state.
901 GrowableArray<ScopeValue*> *objs = new GrowableArray<ScopeValue*>();
903 // Visit scopes from oldest to youngest.
904 for (int depth = 1; depth <= max_depth; depth++) {
905 JVMState* jvms = youngest_jvms->of_depth(depth);
906 int idx;
907 ciMethod* method = jvms->has_method() ? jvms->method() : NULL;
908 // Safepoints that do not have method() set only provide oop-map and monitor info
909 // to support GC; these do not support deoptimization.
910 int num_locs = (method == NULL) ? 0 : jvms->loc_size();
911 int num_exps = (method == NULL) ? 0 : jvms->stk_size();
912 int num_mon = jvms->nof_monitors();
913 assert(method == NULL || jvms->bci() < 0 || num_locs == method->max_locals(),
914 "JVMS local count must match that of the method");
916 // Add Local and Expression Stack Information
918 // Insert locals into the locarray
919 GrowableArray<ScopeValue*> *locarray = new GrowableArray<ScopeValue*>(num_locs);
920 for( idx = 0; idx < num_locs; idx++ ) {
921 FillLocArray( idx, sfn, sfn->local(jvms, idx), locarray, objs );
922 }
924 // Insert expression stack entries into the exparray
925 GrowableArray<ScopeValue*> *exparray = new GrowableArray<ScopeValue*>(num_exps);
926 for( idx = 0; idx < num_exps; idx++ ) {
927 FillLocArray( idx, sfn, sfn->stack(jvms, idx), exparray, objs );
928 }
930 // Add in mappings of the monitors
931 assert( !method ||
932 !method->is_synchronized() ||
933 method->is_native() ||
934 num_mon > 0 ||
935 !GenerateSynchronizationCode,
936 "monitors must always exist for synchronized methods");
938 // Build the growable array of ScopeValues for exp stack
939 GrowableArray<MonitorValue*> *monarray = new GrowableArray<MonitorValue*>(num_mon);
941 // Loop over monitors and insert into array
942 for (idx = 0; idx < num_mon; idx++) {
943 // Grab the node that defines this monitor
944 Node* box_node = sfn->monitor_box(jvms, idx);
945 Node* obj_node = sfn->monitor_obj(jvms, idx);
947 // Create ScopeValue for object
948 ScopeValue *scval = NULL;
950 if (obj_node->is_SafePointScalarObject()) {
951 SafePointScalarObjectNode* spobj = obj_node->as_SafePointScalarObject();
952 scval = Compile::sv_for_node_id(objs, spobj->_idx);
953 if (scval == NULL) {
954 const Type *t = spobj->bottom_type();
955 ciKlass* cik = t->is_oopptr()->klass();
956 assert(cik->is_instance_klass() ||
957 cik->is_array_klass(), "Not supported allocation.");
958 ObjectValue* sv = new ObjectValue(spobj->_idx,
959 new ConstantOopWriteValue(cik->java_mirror()->constant_encoding()));
960 Compile::set_sv_for_object_node(objs, sv);
962 uint first_ind = spobj->first_index(youngest_jvms);
963 for (uint i = 0; i < spobj->n_fields(); i++) {
964 Node* fld_node = sfn->in(first_ind+i);
965 (void)FillLocArray(sv->field_values()->length(), sfn, fld_node, sv->field_values(), objs);
966 }
967 scval = sv;
968 }
969 } else if (!obj_node->is_Con()) {
970 OptoReg::Name obj_reg = _regalloc->get_reg_first(obj_node);
971 if( obj_node->bottom_type()->base() == Type::NarrowOop ) {
972 scval = new_loc_value( _regalloc, obj_reg, Location::narrowoop );
973 } else {
974 scval = new_loc_value( _regalloc, obj_reg, Location::oop );
975 }
976 } else {
977 const TypePtr *tp = obj_node->get_ptr_type();
978 scval = new ConstantOopWriteValue(tp->is_oopptr()->const_oop()->constant_encoding());
979 }
981 OptoReg::Name box_reg = BoxLockNode::reg(box_node);
982 Location basic_lock = Location::new_stk_loc(Location::normal,_regalloc->reg2offset(box_reg));
983 bool eliminated = (box_node->is_BoxLock() && box_node->as_BoxLock()->is_eliminated());
984 monarray->append(new MonitorValue(scval, basic_lock, eliminated));
985 }
987 // We dump the object pool first, since deoptimization reads it in first.
988 debug_info()->dump_object_pool(objs);
990 // Build first class objects to pass to scope
991 DebugToken *locvals = debug_info()->create_scope_values(locarray);
992 DebugToken *expvals = debug_info()->create_scope_values(exparray);
993 DebugToken *monvals = debug_info()->create_monitor_values(monarray);
995 // Make method available for all Safepoints
996 ciMethod* scope_method = method ? method : _method;
997 // Describe the scope here
998 assert(jvms->bci() >= InvocationEntryBci && jvms->bci() <= 0x10000, "must be a valid or entry BCI");
999 assert(!jvms->should_reexecute() || depth == max_depth, "reexecute allowed only for the youngest");
1000 // Now we can describe the scope.
1001 debug_info()->describe_scope(safepoint_pc_offset, scope_method, jvms->bci(), jvms->should_reexecute(), is_method_handle_invoke, return_oop, locvals, expvals, monvals);
1002 } // End jvms loop
1004 // Mark the end of the scope set.
1005 debug_info()->end_safepoint(safepoint_pc_offset);
1006 }
1010 // A simplified version of Process_OopMap_Node, to handle non-safepoints.
1011 class NonSafepointEmitter {
1012 Compile* C;
1013 JVMState* _pending_jvms;
1014 int _pending_offset;
1016 void emit_non_safepoint();
1018 public:
1019 NonSafepointEmitter(Compile* compile) {
1020 this->C = compile;
1021 _pending_jvms = NULL;
1022 _pending_offset = 0;
1023 }
1025 void observe_instruction(Node* n, int pc_offset) {
1026 if (!C->debug_info()->recording_non_safepoints()) return;
1028 Node_Notes* nn = C->node_notes_at(n->_idx);
1029 if (nn == NULL || nn->jvms() == NULL) return;
1030 if (_pending_jvms != NULL &&
1031 _pending_jvms->same_calls_as(nn->jvms())) {
1032 // Repeated JVMS? Stretch it up here.
1033 _pending_offset = pc_offset;
1034 } else {
1035 if (_pending_jvms != NULL &&
1036 _pending_offset < pc_offset) {
1037 emit_non_safepoint();
1038 }
1039 _pending_jvms = NULL;
1040 if (pc_offset > C->debug_info()->last_pc_offset()) {
1041 // This is the only way _pending_jvms can become non-NULL:
1042 _pending_jvms = nn->jvms();
1043 _pending_offset = pc_offset;
1044 }
1045 }
1046 }
1048 // Stay out of the way of real safepoints:
1049 void observe_safepoint(JVMState* jvms, int pc_offset) {
1050 if (_pending_jvms != NULL &&
1051 !_pending_jvms->same_calls_as(jvms) &&
1052 _pending_offset < pc_offset) {
1053 emit_non_safepoint();
1054 }
1055 _pending_jvms = NULL;
1056 }
1058 void flush_at_end() {
1059 if (_pending_jvms != NULL) {
1060 emit_non_safepoint();
1061 }
1062 _pending_jvms = NULL;
1063 }
1064 };
1066 void NonSafepointEmitter::emit_non_safepoint() {
1067 JVMState* youngest_jvms = _pending_jvms;
1068 int pc_offset = _pending_offset;
1070 // Clear it now:
1071 _pending_jvms = NULL;
1073 DebugInformationRecorder* debug_info = C->debug_info();
1074 assert(debug_info->recording_non_safepoints(), "sanity");
1076 debug_info->add_non_safepoint(pc_offset);
1077 int max_depth = youngest_jvms->depth();
1079 // Visit scopes from oldest to youngest.
1080 for (int depth = 1; depth <= max_depth; depth++) {
1081 JVMState* jvms = youngest_jvms->of_depth(depth);
1082 ciMethod* method = jvms->has_method() ? jvms->method() : NULL;
1083 assert(!jvms->should_reexecute() || depth==max_depth, "reexecute allowed only for the youngest");
1084 debug_info->describe_scope(pc_offset, method, jvms->bci(), jvms->should_reexecute());
1085 }
1087 // Mark the end of the scope set.
1088 debug_info->end_non_safepoint(pc_offset);
1089 }
1091 //------------------------------init_buffer------------------------------------
1092 CodeBuffer* Compile::init_buffer(uint* blk_starts) {
1094 // Set the initially allocated size
1095 int code_req = initial_code_capacity;
1096 int locs_req = initial_locs_capacity;
1097 int stub_req = TraceJumps ? initial_stub_capacity * 10 : initial_stub_capacity;
1098 int const_req = initial_const_capacity;
1100 int pad_req = NativeCall::instruction_size;
1101 // The extra spacing after the code is necessary on some platforms.
1102 // Sometimes we need to patch in a jump after the last instruction,
1103 // if the nmethod has been deoptimized. (See 4932387, 4894843.)
1105 // Compute the byte offset where we can store the deopt pc.
1106 if (fixed_slots() != 0) {
1107 _orig_pc_slot_offset_in_bytes = _regalloc->reg2offset(OptoReg::stack2reg(_orig_pc_slot));
1108 }
1110 // Compute prolog code size
1111 _method_size = 0;
1112 _frame_slots = OptoReg::reg2stack(_matcher->_old_SP)+_regalloc->_framesize;
1113 #if defined(IA64) && !defined(AIX)
1114 if (save_argument_registers()) {
1115 // 4815101: this is a stub with implicit and unknown precision fp args.
1116 // The usual spill mechanism can only generate stfd's in this case, which
1117 // doesn't work if the fp reg to spill contains a single-precision denorm.
1118 // Instead, we hack around the normal spill mechanism using stfspill's and
1119 // ldffill's in the MachProlog and MachEpilog emit methods. We allocate
1120 // space here for the fp arg regs (f8-f15) we're going to thusly spill.
1121 //
1122 // If we ever implement 16-byte 'registers' == stack slots, we can
1123 // get rid of this hack and have SpillCopy generate stfspill/ldffill
1124 // instead of stfd/stfs/ldfd/ldfs.
1125 _frame_slots += 8*(16/BytesPerInt);
1126 }
1127 #endif
1128 assert(_frame_slots >= 0 && _frame_slots < 1000000, "sanity check");
1130 if (has_mach_constant_base_node()) {
1131 uint add_size = 0;
1132 // Fill the constant table.
1133 // Note: This must happen before shorten_branches.
1134 for (uint i = 0; i < _cfg->number_of_blocks(); i++) {
1135 Block* b = _cfg->get_block(i);
1137 for (uint j = 0; j < b->number_of_nodes(); j++) {
1138 Node* n = b->get_node(j);
1140 // If the node is a MachConstantNode evaluate the constant
1141 // value section.
1142 if (n->is_MachConstant()) {
1143 MachConstantNode* machcon = n->as_MachConstant();
1144 machcon->eval_constant(C);
1145 } else if (n->is_Mach()) {
1146 // On Power there are more nodes that issue constants.
1147 add_size += (n->as_Mach()->ins_num_consts() * 8);
1148 }
1149 }
1150 }
1152 // Calculate the offsets of the constants and the size of the
1153 // constant table (including the padding to the next section).
1154 constant_table().calculate_offsets_and_size();
1155 const_req = constant_table().size() + add_size;
1156 }
1158 // Initialize the space for the BufferBlob used to find and verify
1159 // instruction size in MachNode::emit_size()
1160 init_scratch_buffer_blob(const_req);
1161 if (failing()) return NULL; // Out of memory
1163 // Pre-compute the length of blocks and replace
1164 // long branches with short if machine supports it.
1165 shorten_branches(blk_starts, code_req, locs_req, stub_req);
1167 // nmethod and CodeBuffer count stubs & constants as part of method's code.
1168 // class HandlerImpl is platform-specific and defined in the *.ad files.
1169 int exception_handler_req = HandlerImpl::size_exception_handler() + MAX_stubs_size; // add marginal slop for handler
1170 int deopt_handler_req = HandlerImpl::size_deopt_handler() + MAX_stubs_size; // add marginal slop for handler
1171 stub_req += MAX_stubs_size; // ensure per-stub margin
1172 code_req += MAX_inst_size; // ensure per-instruction margin
1174 if (StressCodeBuffers)
1175 code_req = const_req = stub_req = exception_handler_req = deopt_handler_req = 0x10; // force expansion
1177 int total_req =
1178 const_req +
1179 code_req +
1180 pad_req +
1181 stub_req +
1182 exception_handler_req +
1183 deopt_handler_req; // deopt handler
1185 if (has_method_handle_invokes())
1186 total_req += deopt_handler_req; // deopt MH handler
1188 CodeBuffer* cb = code_buffer();
1189 cb->initialize(total_req, locs_req);
1191 // Have we run out of code space?
1192 if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
1193 C->record_failure("CodeCache is full");
1194 return NULL;
1195 }
1196 // Configure the code buffer.
1197 cb->initialize_consts_size(const_req);
1198 cb->initialize_stubs_size(stub_req);
1199 cb->initialize_oop_recorder(env()->oop_recorder());
1201 // fill in the nop array for bundling computations
1202 MachNode *_nop_list[Bundle::_nop_count];
1203 Bundle::initialize_nops(_nop_list, this);
1205 return cb;
1206 }
1208 //------------------------------fill_buffer------------------------------------
1209 void Compile::fill_buffer(CodeBuffer* cb, uint* blk_starts) {
1210 // blk_starts[] contains offsets calculated during short branches processing,
1211 // offsets should not be increased during following steps.
1213 // Compute the size of first NumberOfLoopInstrToAlign instructions at head
1214 // of a loop. It is used to determine the padding for loop alignment.
1215 compute_loop_first_inst_sizes();
1217 // Create oopmap set.
1218 _oop_map_set = new OopMapSet();
1220 // !!!!! This preserves old handling of oopmaps for now
1221 debug_info()->set_oopmaps(_oop_map_set);
1223 uint nblocks = _cfg->number_of_blocks();
1224 // Count and start of implicit null check instructions
1225 uint inct_cnt = 0;
1226 uint *inct_starts = NEW_RESOURCE_ARRAY(uint, nblocks+1);
1228 // Count and start of calls
1229 uint *call_returns = NEW_RESOURCE_ARRAY(uint, nblocks+1);
1231 uint return_offset = 0;
1232 int nop_size = (new (this) MachNopNode())->size(_regalloc);
1234 int previous_offset = 0;
1235 int current_offset = 0;
1236 int last_call_offset = -1;
1237 int last_avoid_back_to_back_offset = -1;
1238 #ifdef ASSERT
1239 uint* jmp_target = NEW_RESOURCE_ARRAY(uint,nblocks);
1240 uint* jmp_offset = NEW_RESOURCE_ARRAY(uint,nblocks);
1241 uint* jmp_size = NEW_RESOURCE_ARRAY(uint,nblocks);
1242 uint* jmp_rule = NEW_RESOURCE_ARRAY(uint,nblocks);
1243 #endif
1245 // Create an array of unused labels, one for each basic block, if printing is enabled
1246 #ifndef PRODUCT
1247 int *node_offsets = NULL;
1248 uint node_offset_limit = unique();
1250 if (print_assembly())
1251 node_offsets = NEW_RESOURCE_ARRAY(int, node_offset_limit);
1252 #endif
1254 NonSafepointEmitter non_safepoints(this); // emit non-safepoints lazily
1256 // Emit the constant table.
1257 if (has_mach_constant_base_node()) {
1258 constant_table().emit(*cb);
1259 }
1261 // Create an array of labels, one for each basic block
1262 Label *blk_labels = NEW_RESOURCE_ARRAY(Label, nblocks+1);
1263 for (uint i=0; i <= nblocks; i++) {
1264 blk_labels[i].init();
1265 }
1267 // ------------------
1268 // Now fill in the code buffer
1269 Node *delay_slot = NULL;
1271 for (uint i = 0; i < nblocks; i++) {
1272 Block* block = _cfg->get_block(i);
1273 Node* head = block->head();
1275 // If this block needs to start aligned (i.e, can be reached other
1276 // than by falling-thru from the previous block), then force the
1277 // start of a new bundle.
1278 if (Pipeline::requires_bundling() && starts_bundle(head)) {
1279 cb->flush_bundle(true);
1280 }
1282 #ifdef ASSERT
1283 if (!block->is_connector()) {
1284 stringStream st;
1285 block->dump_head(_cfg, &st);
1286 MacroAssembler(cb).block_comment(st.as_string());
1287 }
1288 jmp_target[i] = 0;
1289 jmp_offset[i] = 0;
1290 jmp_size[i] = 0;
1291 jmp_rule[i] = 0;
1292 #endif
1293 int blk_offset = current_offset;
1295 // Define the label at the beginning of the basic block
1296 MacroAssembler(cb).bind(blk_labels[block->_pre_order]);
1298 uint last_inst = block->number_of_nodes();
1300 // Emit block normally, except for last instruction.
1301 // Emit means "dump code bits into code buffer".
1302 for (uint j = 0; j<last_inst; j++) {
1304 // Get the node
1305 Node* n = block->get_node(j);
1307 // See if delay slots are supported
1308 if (valid_bundle_info(n) &&
1309 node_bundling(n)->used_in_unconditional_delay()) {
1310 assert(delay_slot == NULL, "no use of delay slot node");
1311 assert(n->size(_regalloc) == Pipeline::instr_unit_size(), "delay slot instruction wrong size");
1313 delay_slot = n;
1314 continue;
1315 }
1317 // If this starts a new instruction group, then flush the current one
1318 // (but allow split bundles)
1319 if (Pipeline::requires_bundling() && starts_bundle(n))
1320 cb->flush_bundle(false);
1322 // The following logic is duplicated in the code ifdeffed for
1323 // ENABLE_ZAP_DEAD_LOCALS which appears above in this file. It
1324 // should be factored out. Or maybe dispersed to the nodes?
1326 // Special handling for SafePoint/Call Nodes
1327 bool is_mcall = false;
1328 if (n->is_Mach()) {
1329 MachNode *mach = n->as_Mach();
1330 is_mcall = n->is_MachCall();
1331 bool is_sfn = n->is_MachSafePoint();
1333 // If this requires all previous instructions be flushed, then do so
1334 if (is_sfn || is_mcall || mach->alignment_required() != 1) {
1335 cb->flush_bundle(true);
1336 current_offset = cb->insts_size();
1337 }
1339 // A padding may be needed again since a previous instruction
1340 // could be moved to delay slot.
1342 // align the instruction if necessary
1343 int padding = mach->compute_padding(current_offset);
1344 // Make sure safepoint node for polling is distinct from a call's
1345 // return by adding a nop if needed.
1346 if (is_sfn && !is_mcall && padding == 0 && current_offset == last_call_offset) {
1347 padding = nop_size;
1348 }
1349 if (padding == 0 && mach->avoid_back_to_back(MachNode::AVOID_BEFORE) &&
1350 current_offset == last_avoid_back_to_back_offset) {
1351 // Avoid back to back some instructions.
1352 padding = nop_size;
1353 }
1355 if(padding > 0) {
1356 assert((padding % nop_size) == 0, "padding is not a multiple of NOP size");
1357 int nops_cnt = padding / nop_size;
1358 MachNode *nop = new (this) MachNopNode(nops_cnt);
1359 block->insert_node(nop, j++);
1360 last_inst++;
1361 _cfg->map_node_to_block(nop, block);
1362 nop->emit(*cb, _regalloc);
1363 cb->flush_bundle(true);
1364 current_offset = cb->insts_size();
1365 }
1367 // Remember the start of the last call in a basic block
1368 if (is_mcall) {
1369 MachCallNode *mcall = mach->as_MachCall();
1371 // This destination address is NOT PC-relative
1372 mcall->method_set((intptr_t)mcall->entry_point());
1374 // Save the return address
1375 call_returns[block->_pre_order] = current_offset + mcall->ret_addr_offset();
1377 if (mcall->is_MachCallLeaf()) {
1378 is_mcall = false;
1379 is_sfn = false;
1380 }
1381 }
1383 // sfn will be valid whenever mcall is valid now because of inheritance
1384 if (is_sfn || is_mcall) {
1386 // Handle special safepoint nodes for synchronization
1387 if (!is_mcall) {
1388 MachSafePointNode *sfn = mach->as_MachSafePoint();
1389 // !!!!! Stubs only need an oopmap right now, so bail out
1390 if (sfn->jvms()->method() == NULL) {
1391 // Write the oopmap directly to the code blob??!!
1392 # ifdef ENABLE_ZAP_DEAD_LOCALS
1393 assert( !is_node_getting_a_safepoint(sfn), "logic does not match; false positive");
1394 # endif
1395 continue;
1396 }
1397 } // End synchronization
1399 non_safepoints.observe_safepoint(mach->as_MachSafePoint()->jvms(),
1400 current_offset);
1401 Process_OopMap_Node(mach, current_offset);
1402 } // End if safepoint
1404 // If this is a null check, then add the start of the previous instruction to the list
1405 else if( mach->is_MachNullCheck() ) {
1406 inct_starts[inct_cnt++] = previous_offset;
1407 }
1409 // If this is a branch, then fill in the label with the target BB's label
1410 else if (mach->is_MachBranch()) {
1411 // This requires the TRUE branch target be in succs[0]
1412 uint block_num = block->non_connector_successor(0)->_pre_order;
1414 // Try to replace long branch if delay slot is not used,
1415 // it is mostly for back branches since forward branch's
1416 // distance is not updated yet.
1417 bool delay_slot_is_used = valid_bundle_info(n) &&
1418 node_bundling(n)->use_unconditional_delay();
1419 if (!delay_slot_is_used && mach->may_be_short_branch()) {
1420 assert(delay_slot == NULL, "not expecting delay slot node");
1421 int br_size = n->size(_regalloc);
1422 int offset = blk_starts[block_num] - current_offset;
1423 if (block_num >= i) {
1424 // Current and following block's offset are not
1425 // finalized yet, adjust distance by the difference
1426 // between calculated and final offsets of current block.
1427 offset -= (blk_starts[i] - blk_offset);
1428 }
1429 // In the following code a nop could be inserted before
1430 // the branch which will increase the backward distance.
1431 bool needs_padding = (current_offset == last_avoid_back_to_back_offset);
1432 if (needs_padding && offset <= 0)
1433 offset -= nop_size;
1435 if (_matcher->is_short_branch_offset(mach->rule(), br_size, offset)) {
1436 // We've got a winner. Replace this branch.
1437 MachNode* replacement = mach->as_MachBranch()->short_branch_version(this);
1439 // Update the jmp_size.
1440 int new_size = replacement->size(_regalloc);
1441 assert((br_size - new_size) >= (int)nop_size, "short_branch size should be smaller");
1442 // Insert padding between avoid_back_to_back branches.
1443 if (needs_padding && replacement->avoid_back_to_back(MachNode::AVOID_BEFORE)) {
1444 MachNode *nop = new (this) MachNopNode();
1445 block->insert_node(nop, j++);
1446 _cfg->map_node_to_block(nop, block);
1447 last_inst++;
1448 nop->emit(*cb, _regalloc);
1449 cb->flush_bundle(true);
1450 current_offset = cb->insts_size();
1451 }
1452 #ifdef ASSERT
1453 jmp_target[i] = block_num;
1454 jmp_offset[i] = current_offset - blk_offset;
1455 jmp_size[i] = new_size;
1456 jmp_rule[i] = mach->rule();
1457 #endif
1458 block->map_node(replacement, j);
1459 mach->subsume_by(replacement, C);
1460 n = replacement;
1461 mach = replacement;
1462 }
1463 }
1464 mach->as_MachBranch()->label_set( &blk_labels[block_num], block_num );
1465 } else if (mach->ideal_Opcode() == Op_Jump) {
1466 for (uint h = 0; h < block->_num_succs; h++) {
1467 Block* succs_block = block->_succs[h];
1468 for (uint j = 1; j < succs_block->num_preds(); j++) {
1469 Node* jpn = succs_block->pred(j);
1470 if (jpn->is_JumpProj() && jpn->in(0) == mach) {
1471 uint block_num = succs_block->non_connector()->_pre_order;
1472 Label *blkLabel = &blk_labels[block_num];
1473 mach->add_case_label(jpn->as_JumpProj()->proj_no(), blkLabel);
1474 }
1475 }
1476 }
1477 }
1478 #ifdef ASSERT
1479 // Check that oop-store precedes the card-mark
1480 else if (mach->ideal_Opcode() == Op_StoreCM) {
1481 uint storeCM_idx = j;
1482 int count = 0;
1483 for (uint prec = mach->req(); prec < mach->len(); prec++) {
1484 Node *oop_store = mach->in(prec); // Precedence edge
1485 if (oop_store == NULL) continue;
1486 count++;
1487 uint i4;
1488 for (i4 = 0; i4 < last_inst; ++i4) {
1489 if (block->get_node(i4) == oop_store) {
1490 break;
1491 }
1492 }
1493 // Note: This test can provide a false failure if other precedence
1494 // edges have been added to the storeCMNode.
1495 assert(i4 == last_inst || i4 < storeCM_idx, "CM card-mark executes before oop-store");
1496 }
1497 assert(count > 0, "storeCM expects at least one precedence edge");
1498 }
1499 #endif
1500 else if (!n->is_Proj()) {
1501 // Remember the beginning of the previous instruction, in case
1502 // it's followed by a flag-kill and a null-check. Happens on
1503 // Intel all the time, with add-to-memory kind of opcodes.
1504 previous_offset = current_offset;
1505 }
1507 // Not an else-if!
1508 // If this is a trap based cmp then add its offset to the list.
1509 if (mach->is_TrapBasedCheckNode()) {
1510 inct_starts[inct_cnt++] = current_offset;
1511 }
1512 }
1514 // Verify that there is sufficient space remaining
1515 cb->insts()->maybe_expand_to_ensure_remaining(MAX_inst_size);
1516 if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
1517 C->record_failure("CodeCache is full");
1518 return;
1519 }
1521 // Save the offset for the listing
1522 #ifndef PRODUCT
1523 if (node_offsets && n->_idx < node_offset_limit)
1524 node_offsets[n->_idx] = cb->insts_size();
1525 #endif
1527 // "Normal" instruction case
1528 DEBUG_ONLY( uint instr_offset = cb->insts_size(); )
1529 n->emit(*cb, _regalloc);
1530 current_offset = cb->insts_size();
1531 #ifdef MIPS
1532 if (!n->is_Proj()) {
1533 // For MIPS, the first instruction of the previous node (usually a instruction sequence) sometime
1534 // is not the instruction which access memory. adjust is needed. previous_offset points to the
1535 // instruction which access memory. Instruction size is 4. cb->insts_size() and
1536 // cb->insts()->end() are the location of current instruction.
1537 int adjust = 4;
1538 NativeInstruction* inst = (NativeInstruction*) (cb->insts()->end() - 4);
1539 if (inst->is_sync()) {
1540 // a sync may be the last instruction, see store_B_immI_enc_sync
1541 adjust += 4;
1542 inst = (NativeInstruction*) (cb->insts()->end() - 8);
1543 }
1544 previous_offset = current_offset - adjust;
1545 }
1546 #endif
1548 // Above we only verified that there is enough space in the instruction section.
1549 // However, the instruction may emit stubs that cause code buffer expansion.
1550 // Bail out here if expansion failed due to a lack of code cache space.
1551 if (failing()) {
1552 return;
1553 }
1555 #ifdef ASSERT
1556 if (n->size(_regalloc) < (current_offset-instr_offset)) {
1557 n->dump();
1558 assert(false, "wrong size of mach node");
1559 }
1560 #endif
1561 non_safepoints.observe_instruction(n, current_offset);
1563 // mcall is last "call" that can be a safepoint
1564 // record it so we can see if a poll will directly follow it
1565 // in which case we'll need a pad to make the PcDesc sites unique
1566 // see 5010568. This can be slightly inaccurate but conservative
1567 // in the case that return address is not actually at current_offset.
1568 // This is a small price to pay.
1570 if (is_mcall) {
1571 last_call_offset = current_offset;
1572 }
1574 if (n->is_Mach() && n->as_Mach()->avoid_back_to_back(MachNode::AVOID_AFTER)) {
1575 // Avoid back to back some instructions.
1576 last_avoid_back_to_back_offset = current_offset;
1577 }
1579 // See if this instruction has a delay slot
1580 if (valid_bundle_info(n) && node_bundling(n)->use_unconditional_delay()) {
1581 assert(delay_slot != NULL, "expecting delay slot node");
1583 // Back up 1 instruction
1584 cb->set_insts_end(cb->insts_end() - Pipeline::instr_unit_size());
1586 // Save the offset for the listing
1587 #ifndef PRODUCT
1588 if (node_offsets && delay_slot->_idx < node_offset_limit)
1589 node_offsets[delay_slot->_idx] = cb->insts_size();
1590 #endif
1592 // Support a SafePoint in the delay slot
1593 if (delay_slot->is_MachSafePoint()) {
1594 MachNode *mach = delay_slot->as_Mach();
1595 // !!!!! Stubs only need an oopmap right now, so bail out
1596 if (!mach->is_MachCall() && mach->as_MachSafePoint()->jvms()->method() == NULL) {
1597 // Write the oopmap directly to the code blob??!!
1598 # ifdef ENABLE_ZAP_DEAD_LOCALS
1599 assert( !is_node_getting_a_safepoint(mach), "logic does not match; false positive");
1600 # endif
1601 delay_slot = NULL;
1602 continue;
1603 }
1605 int adjusted_offset = current_offset - Pipeline::instr_unit_size();
1606 non_safepoints.observe_safepoint(mach->as_MachSafePoint()->jvms(),
1607 adjusted_offset);
1608 // Generate an OopMap entry
1609 Process_OopMap_Node(mach, adjusted_offset);
1610 }
1612 // Insert the delay slot instruction
1613 delay_slot->emit(*cb, _regalloc);
1615 // Don't reuse it
1616 delay_slot = NULL;
1617 }
1619 } // End for all instructions in block
1621 // If the next block is the top of a loop, pad this block out to align
1622 // the loop top a little. Helps prevent pipe stalls at loop back branches.
1623 if (i < nblocks-1) {
1624 Block *nb = _cfg->get_block(i + 1);
1625 int padding = nb->alignment_padding(current_offset);
1626 if( padding > 0 ) {
1627 MachNode *nop = new (this) MachNopNode(padding / nop_size);
1628 block->insert_node(nop, block->number_of_nodes());
1629 _cfg->map_node_to_block(nop, block);
1630 nop->emit(*cb, _regalloc);
1631 current_offset = cb->insts_size();
1632 }
1633 }
1634 // Verify that the distance for generated before forward
1635 // short branches is still valid.
1636 guarantee((int)(blk_starts[i+1] - blk_starts[i]) >= (current_offset - blk_offset), "shouldn't increase block size");
1638 // Save new block start offset
1639 blk_starts[i] = blk_offset;
1640 } // End of for all blocks
1641 blk_starts[nblocks] = current_offset;
1643 non_safepoints.flush_at_end();
1645 // Offset too large?
1646 if (failing()) return;
1648 // Define a pseudo-label at the end of the code
1649 MacroAssembler(cb).bind( blk_labels[nblocks] );
1651 // Compute the size of the first block
1652 _first_block_size = blk_labels[1].loc_pos() - blk_labels[0].loc_pos();
1654 assert(cb->insts_size() < 500000, "method is unreasonably large");
1656 #ifdef ASSERT
1657 for (uint i = 0; i < nblocks; i++) { // For all blocks
1658 if (jmp_target[i] != 0) {
1659 int br_size = jmp_size[i];
1660 int offset = blk_starts[jmp_target[i]]-(blk_starts[i] + jmp_offset[i]);
1661 if (!_matcher->is_short_branch_offset(jmp_rule[i], br_size, offset)) {
1662 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]);
1663 assert(false, "Displacement too large for short jmp");
1664 }
1665 }
1666 }
1667 #endif
1669 #ifndef PRODUCT
1670 // Information on the size of the method, without the extraneous code
1671 Scheduling::increment_method_size(cb->insts_size());
1672 #endif
1674 // ------------------
1675 // Fill in exception table entries.
1676 FillExceptionTables(inct_cnt, call_returns, inct_starts, blk_labels);
1678 // Only java methods have exception handlers and deopt handlers
1679 // class HandlerImpl is platform-specific and defined in the *.ad files.
1680 if (_method) {
1681 // Emit the exception handler code.
1682 _code_offsets.set_value(CodeOffsets::Exceptions, HandlerImpl::emit_exception_handler(*cb));
1683 if (failing()) {
1684 return; // CodeBuffer::expand failed
1685 }
1686 // Emit the deopt handler code.
1687 _code_offsets.set_value(CodeOffsets::Deopt, HandlerImpl::emit_deopt_handler(*cb));
1689 // Emit the MethodHandle deopt handler code (if required).
1690 if (has_method_handle_invokes() && !failing()) {
1691 // We can use the same code as for the normal deopt handler, we
1692 // just need a different entry point address.
1693 _code_offsets.set_value(CodeOffsets::DeoptMH, HandlerImpl::emit_deopt_handler(*cb));
1694 }
1695 }
1697 // One last check for failed CodeBuffer::expand:
1698 if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
1699 C->record_failure("CodeCache is full");
1700 return;
1701 }
1703 #ifndef PRODUCT
1704 // Dump the assembly code, including basic-block numbers
1705 if (print_assembly()) {
1706 ttyLocker ttyl; // keep the following output all in one block
1707 if (!VMThread::should_terminate()) { // test this under the tty lock
1708 // This output goes directly to the tty, not the compiler log.
1709 // To enable tools to match it up with the compilation activity,
1710 // be sure to tag this tty output with the compile ID.
1711 if (xtty != NULL) {
1712 xtty->head("opto_assembly compile_id='%d'%s", compile_id(),
1713 is_osr_compilation() ? " compile_kind='osr'" :
1714 "");
1715 }
1716 if (method() != NULL) {
1717 method()->print_metadata();
1718 }
1719 dump_asm(node_offsets, node_offset_limit);
1720 if (xtty != NULL) {
1721 xtty->tail("opto_assembly");
1722 }
1723 }
1724 }
1725 #endif
1727 }
1729 void Compile::FillExceptionTables(uint cnt, uint *call_returns, uint *inct_starts, Label *blk_labels) {
1730 _inc_table.set_size(cnt);
1732 uint inct_cnt = 0;
1733 for (uint i = 0; i < _cfg->number_of_blocks(); i++) {
1734 Block* block = _cfg->get_block(i);
1735 Node *n = NULL;
1736 int j;
1738 // Find the branch; ignore trailing NOPs.
1739 for (j = block->number_of_nodes() - 1; j >= 0; j--) {
1740 n = block->get_node(j);
1741 if (!n->is_Mach() || n->as_Mach()->ideal_Opcode() != Op_Con) {
1742 break;
1743 }
1744 }
1746 // If we didn't find anything, continue
1747 if (j < 0) {
1748 continue;
1749 }
1751 // Compute ExceptionHandlerTable subtable entry and add it
1752 // (skip empty blocks)
1753 if (n->is_Catch()) {
1755 // Get the offset of the return from the call
1756 uint call_return = call_returns[block->_pre_order];
1757 #ifdef ASSERT
1758 assert( call_return > 0, "no call seen for this basic block" );
1759 while (block->get_node(--j)->is_MachProj()) ;
1760 assert(block->get_node(j)->is_MachCall(), "CatchProj must follow call");
1761 #endif
1762 // last instruction is a CatchNode, find it's CatchProjNodes
1763 int nof_succs = block->_num_succs;
1764 // allocate space
1765 GrowableArray<intptr_t> handler_bcis(nof_succs);
1766 GrowableArray<intptr_t> handler_pcos(nof_succs);
1767 // iterate through all successors
1768 for (int j = 0; j < nof_succs; j++) {
1769 Block* s = block->_succs[j];
1770 bool found_p = false;
1771 for (uint k = 1; k < s->num_preds(); k++) {
1772 Node* pk = s->pred(k);
1773 if (pk->is_CatchProj() && pk->in(0) == n) {
1774 const CatchProjNode* p = pk->as_CatchProj();
1775 found_p = true;
1776 // add the corresponding handler bci & pco information
1777 if (p->_con != CatchProjNode::fall_through_index) {
1778 // p leads to an exception handler (and is not fall through)
1779 assert(s == _cfg->get_block(s->_pre_order), "bad numbering");
1780 // no duplicates, please
1781 if (!handler_bcis.contains(p->handler_bci())) {
1782 uint block_num = s->non_connector()->_pre_order;
1783 handler_bcis.append(p->handler_bci());
1784 handler_pcos.append(blk_labels[block_num].loc_pos());
1785 }
1786 }
1787 }
1788 }
1789 assert(found_p, "no matching predecessor found");
1790 // Note: Due to empty block removal, one block may have
1791 // several CatchProj inputs, from the same Catch.
1792 }
1794 // Set the offset of the return from the call
1795 _handler_table.add_subtable(call_return, &handler_bcis, NULL, &handler_pcos);
1796 continue;
1797 }
1799 // Handle implicit null exception table updates
1800 if (n->is_MachNullCheck()) {
1801 uint block_num = block->non_connector_successor(0)->_pre_order;
1802 _inc_table.append(inct_starts[inct_cnt++], blk_labels[block_num].loc_pos());
1803 continue;
1804 }
1805 // Handle implicit exception table updates: trap instructions.
1806 if (n->is_Mach() && n->as_Mach()->is_TrapBasedCheckNode()) {
1807 uint block_num = block->non_connector_successor(0)->_pre_order;
1808 _inc_table.append(inct_starts[inct_cnt++], blk_labels[block_num].loc_pos());
1809 continue;
1810 }
1811 } // End of for all blocks fill in exception table entries
1812 }
1814 // Static Variables
1815 #ifndef PRODUCT
1816 uint Scheduling::_total_nop_size = 0;
1817 uint Scheduling::_total_method_size = 0;
1818 uint Scheduling::_total_branches = 0;
1819 uint Scheduling::_total_unconditional_delays = 0;
1820 uint Scheduling::_total_instructions_per_bundle[Pipeline::_max_instrs_per_cycle+1];
1821 #endif
1823 // Initializer for class Scheduling
1825 Scheduling::Scheduling(Arena *arena, Compile &compile)
1826 : _arena(arena),
1827 _cfg(compile.cfg()),
1828 _regalloc(compile.regalloc()),
1829 _reg_node(arena),
1830 _bundle_instr_count(0),
1831 _bundle_cycle_number(0),
1832 _scheduled(arena),
1833 _available(arena),
1834 _next_node(NULL),
1835 _bundle_use(0, 0, resource_count, &_bundle_use_elements[0]),
1836 _pinch_free_list(arena)
1837 #ifndef PRODUCT
1838 , _branches(0)
1839 , _unconditional_delays(0)
1840 #endif
1841 {
1842 // Create a MachNopNode
1843 _nop = new (&compile) MachNopNode();
1845 // Now that the nops are in the array, save the count
1846 // (but allow entries for the nops)
1847 _node_bundling_limit = compile.unique();
1848 uint node_max = _regalloc->node_regs_max_index();
1850 compile.set_node_bundling_limit(_node_bundling_limit);
1852 // This one is persistent within the Compile class
1853 _node_bundling_base = NEW_ARENA_ARRAY(compile.comp_arena(), Bundle, node_max);
1855 // Allocate space for fixed-size arrays
1856 _node_latency = NEW_ARENA_ARRAY(arena, unsigned short, node_max);
1857 _uses = NEW_ARENA_ARRAY(arena, short, node_max);
1858 _current_latency = NEW_ARENA_ARRAY(arena, unsigned short, node_max);
1860 // Clear the arrays
1861 memset(_node_bundling_base, 0, node_max * sizeof(Bundle));
1862 memset(_node_latency, 0, node_max * sizeof(unsigned short));
1863 memset(_uses, 0, node_max * sizeof(short));
1864 memset(_current_latency, 0, node_max * sizeof(unsigned short));
1866 // Clear the bundling information
1867 memcpy(_bundle_use_elements, Pipeline_Use::elaborated_elements, sizeof(Pipeline_Use::elaborated_elements));
1869 // Get the last node
1870 Block* block = _cfg->get_block(_cfg->number_of_blocks() - 1);
1872 _next_node = block->get_node(block->number_of_nodes() - 1);
1873 }
1875 #ifndef PRODUCT
1876 // Scheduling destructor
1877 Scheduling::~Scheduling() {
1878 _total_branches += _branches;
1879 _total_unconditional_delays += _unconditional_delays;
1880 }
1881 #endif
1883 // Step ahead "i" cycles
1884 void Scheduling::step(uint i) {
1886 Bundle *bundle = node_bundling(_next_node);
1887 bundle->set_starts_bundle();
1889 // Update the bundle record, but leave the flags information alone
1890 if (_bundle_instr_count > 0) {
1891 bundle->set_instr_count(_bundle_instr_count);
1892 bundle->set_resources_used(_bundle_use.resourcesUsed());
1893 }
1895 // Update the state information
1896 _bundle_instr_count = 0;
1897 _bundle_cycle_number += i;
1898 _bundle_use.step(i);
1899 }
1901 void Scheduling::step_and_clear() {
1902 Bundle *bundle = node_bundling(_next_node);
1903 bundle->set_starts_bundle();
1905 // Update the bundle record
1906 if (_bundle_instr_count > 0) {
1907 bundle->set_instr_count(_bundle_instr_count);
1908 bundle->set_resources_used(_bundle_use.resourcesUsed());
1910 _bundle_cycle_number += 1;
1911 }
1913 // Clear the bundling information
1914 _bundle_instr_count = 0;
1915 _bundle_use.reset();
1917 memcpy(_bundle_use_elements,
1918 Pipeline_Use::elaborated_elements,
1919 sizeof(Pipeline_Use::elaborated_elements));
1920 }
1922 // Perform instruction scheduling and bundling over the sequence of
1923 // instructions in backwards order.
1924 void Compile::ScheduleAndBundle() {
1926 // Don't optimize this if it isn't a method
1927 if (!_method)
1928 return;
1930 // Don't optimize this if scheduling is disabled
1931 if (!do_scheduling())
1932 return;
1934 // Scheduling code works only with pairs (8 bytes) maximum.
1935 if (max_vector_size() > 8)
1936 return;
1938 NOT_PRODUCT( TracePhase t2("isched", &_t_instrSched, TimeCompiler); )
1940 // Create a data structure for all the scheduling information
1941 Scheduling scheduling(Thread::current()->resource_area(), *this);
1943 // Walk backwards over each basic block, computing the needed alignment
1944 // Walk over all the basic blocks
1945 scheduling.DoScheduling();
1946 }
1948 // Compute the latency of all the instructions. This is fairly simple,
1949 // because we already have a legal ordering. Walk over the instructions
1950 // from first to last, and compute the latency of the instruction based
1951 // on the latency of the preceding instruction(s).
1952 void Scheduling::ComputeLocalLatenciesForward(const Block *bb) {
1953 #ifndef PRODUCT
1954 if (_cfg->C->trace_opto_output())
1955 tty->print("# -> ComputeLocalLatenciesForward\n");
1956 #endif
1958 // Walk over all the schedulable instructions
1959 for( uint j=_bb_start; j < _bb_end; j++ ) {
1961 // This is a kludge, forcing all latency calculations to start at 1.
1962 // Used to allow latency 0 to force an instruction to the beginning
1963 // of the bb
1964 uint latency = 1;
1965 Node *use = bb->get_node(j);
1966 uint nlen = use->len();
1968 // Walk over all the inputs
1969 for ( uint k=0; k < nlen; k++ ) {
1970 Node *def = use->in(k);
1971 if (!def)
1972 continue;
1974 uint l = _node_latency[def->_idx] + use->latency(k);
1975 if (latency < l)
1976 latency = l;
1977 }
1979 _node_latency[use->_idx] = latency;
1981 #ifndef PRODUCT
1982 if (_cfg->C->trace_opto_output()) {
1983 tty->print("# latency %4d: ", latency);
1984 use->dump();
1985 }
1986 #endif
1987 }
1989 #ifndef PRODUCT
1990 if (_cfg->C->trace_opto_output())
1991 tty->print("# <- ComputeLocalLatenciesForward\n");
1992 #endif
1994 } // end ComputeLocalLatenciesForward
1996 // See if this node fits into the present instruction bundle
1997 bool Scheduling::NodeFitsInBundle(Node *n) {
1998 uint n_idx = n->_idx;
2000 // If this is the unconditional delay instruction, then it fits
2001 if (n == _unconditional_delay_slot) {
2002 #ifndef PRODUCT
2003 if (_cfg->C->trace_opto_output())
2004 tty->print("# NodeFitsInBundle [%4d]: TRUE; is in unconditional delay slot\n", n->_idx);
2005 #endif
2006 return (true);
2007 }
2009 // If the node cannot be scheduled this cycle, skip it
2010 if (_current_latency[n_idx] > _bundle_cycle_number) {
2011 #ifndef PRODUCT
2012 if (_cfg->C->trace_opto_output())
2013 tty->print("# NodeFitsInBundle [%4d]: FALSE; latency %4d > %d\n",
2014 n->_idx, _current_latency[n_idx], _bundle_cycle_number);
2015 #endif
2016 return (false);
2017 }
2019 const Pipeline *node_pipeline = n->pipeline();
2021 uint instruction_count = node_pipeline->instructionCount();
2022 if (node_pipeline->mayHaveNoCode() && n->size(_regalloc) == 0)
2023 instruction_count = 0;
2024 else if (node_pipeline->hasBranchDelay() && !_unconditional_delay_slot)
2025 instruction_count++;
2027 if (_bundle_instr_count + instruction_count > Pipeline::_max_instrs_per_cycle) {
2028 #ifndef PRODUCT
2029 if (_cfg->C->trace_opto_output())
2030 tty->print("# NodeFitsInBundle [%4d]: FALSE; too many instructions: %d > %d\n",
2031 n->_idx, _bundle_instr_count + instruction_count, Pipeline::_max_instrs_per_cycle);
2032 #endif
2033 return (false);
2034 }
2036 // Don't allow non-machine nodes to be handled this way
2037 if (!n->is_Mach() && instruction_count == 0)
2038 return (false);
2040 // See if there is any overlap
2041 uint delay = _bundle_use.full_latency(0, node_pipeline->resourceUse());
2043 if (delay > 0) {
2044 #ifndef PRODUCT
2045 if (_cfg->C->trace_opto_output())
2046 tty->print("# NodeFitsInBundle [%4d]: FALSE; functional units overlap\n", n_idx);
2047 #endif
2048 return false;
2049 }
2051 #ifndef PRODUCT
2052 if (_cfg->C->trace_opto_output())
2053 tty->print("# NodeFitsInBundle [%4d]: TRUE\n", n_idx);
2054 #endif
2056 return true;
2057 }
2059 Node * Scheduling::ChooseNodeToBundle() {
2060 uint siz = _available.size();
2062 if (siz == 0) {
2064 #ifndef PRODUCT
2065 if (_cfg->C->trace_opto_output())
2066 tty->print("# ChooseNodeToBundle: NULL\n");
2067 #endif
2068 return (NULL);
2069 }
2071 // Fast path, if only 1 instruction in the bundle
2072 if (siz == 1) {
2073 #ifndef PRODUCT
2074 if (_cfg->C->trace_opto_output()) {
2075 tty->print("# ChooseNodeToBundle (only 1): ");
2076 _available[0]->dump();
2077 }
2078 #endif
2079 return (_available[0]);
2080 }
2082 // Don't bother, if the bundle is already full
2083 if (_bundle_instr_count < Pipeline::_max_instrs_per_cycle) {
2084 for ( uint i = 0; i < siz; i++ ) {
2085 Node *n = _available[i];
2087 // Skip projections, we'll handle them another way
2088 if (n->is_Proj())
2089 continue;
2091 // This presupposed that instructions are inserted into the
2092 // available list in a legality order; i.e. instructions that
2093 // must be inserted first are at the head of the list
2094 if (NodeFitsInBundle(n)) {
2095 #ifndef PRODUCT
2096 if (_cfg->C->trace_opto_output()) {
2097 tty->print("# ChooseNodeToBundle: ");
2098 n->dump();
2099 }
2100 #endif
2101 return (n);
2102 }
2103 }
2104 }
2106 // Nothing fits in this bundle, choose the highest priority
2107 #ifndef PRODUCT
2108 if (_cfg->C->trace_opto_output()) {
2109 tty->print("# ChooseNodeToBundle: ");
2110 _available[0]->dump();
2111 }
2112 #endif
2114 return _available[0];
2115 }
2117 void Scheduling::AddNodeToAvailableList(Node *n) {
2118 assert( !n->is_Proj(), "projections never directly made available" );
2119 #ifndef PRODUCT
2120 if (_cfg->C->trace_opto_output()) {
2121 tty->print("# AddNodeToAvailableList: ");
2122 n->dump();
2123 }
2124 #endif
2126 int latency = _current_latency[n->_idx];
2128 // Insert in latency order (insertion sort)
2129 uint i;
2130 for ( i=0; i < _available.size(); i++ )
2131 if (_current_latency[_available[i]->_idx] > latency)
2132 break;
2134 // Special Check for compares following branches
2135 if( n->is_Mach() && _scheduled.size() > 0 ) {
2136 int op = n->as_Mach()->ideal_Opcode();
2137 Node *last = _scheduled[0];
2138 if( last->is_MachIf() && last->in(1) == n &&
2139 ( op == Op_CmpI ||
2140 op == Op_CmpU ||
2141 op == Op_CmpUL ||
2142 op == Op_CmpP ||
2143 op == Op_CmpF ||
2144 op == Op_CmpD ||
2145 op == Op_CmpL ) ) {
2147 // Recalculate position, moving to front of same latency
2148 for ( i=0 ; i < _available.size(); i++ )
2149 if (_current_latency[_available[i]->_idx] >= latency)
2150 break;
2151 }
2152 }
2154 // Insert the node in the available list
2155 _available.insert(i, n);
2157 #ifndef PRODUCT
2158 if (_cfg->C->trace_opto_output())
2159 dump_available();
2160 #endif
2161 }
2163 void Scheduling::DecrementUseCounts(Node *n, const Block *bb) {
2164 for ( uint i=0; i < n->len(); i++ ) {
2165 Node *def = n->in(i);
2166 if (!def) continue;
2167 if( def->is_Proj() ) // If this is a machine projection, then
2168 def = def->in(0); // propagate usage thru to the base instruction
2170 if(_cfg->get_block_for_node(def) != bb) { // Ignore if not block-local
2171 continue;
2172 }
2174 // Compute the latency
2175 uint l = _bundle_cycle_number + n->latency(i);
2176 if (_current_latency[def->_idx] < l)
2177 _current_latency[def->_idx] = l;
2179 // If this does not have uses then schedule it
2180 if ((--_uses[def->_idx]) == 0)
2181 AddNodeToAvailableList(def);
2182 }
2183 }
2185 void Scheduling::AddNodeToBundle(Node *n, const Block *bb) {
2186 #ifndef PRODUCT
2187 if (_cfg->C->trace_opto_output()) {
2188 tty->print("# AddNodeToBundle: ");
2189 n->dump();
2190 }
2191 #endif
2193 // Remove this from the available list
2194 uint i;
2195 for (i = 0; i < _available.size(); i++)
2196 if (_available[i] == n)
2197 break;
2198 assert(i < _available.size(), "entry in _available list not found");
2199 _available.remove(i);
2201 // See if this fits in the current bundle
2202 const Pipeline *node_pipeline = n->pipeline();
2203 const Pipeline_Use& node_usage = node_pipeline->resourceUse();
2205 // Check for instructions to be placed in the delay slot. We
2206 // do this before we actually schedule the current instruction,
2207 // because the delay slot follows the current instruction.
2208 if (Pipeline::_branch_has_delay_slot &&
2209 node_pipeline->hasBranchDelay() &&
2210 !_unconditional_delay_slot) {
2212 uint siz = _available.size();
2214 // Conditional branches can support an instruction that
2215 // is unconditionally executed and not dependent by the
2216 // branch, OR a conditionally executed instruction if
2217 // the branch is taken. In practice, this means that
2218 // the first instruction at the branch target is
2219 // copied to the delay slot, and the branch goes to
2220 // the instruction after that at the branch target
2221 if ( n->is_MachBranch() ) {
2223 assert( !n->is_MachNullCheck(), "should not look for delay slot for Null Check" );
2224 assert( !n->is_Catch(), "should not look for delay slot for Catch" );
2226 #ifndef PRODUCT
2227 _branches++;
2228 #endif
2230 // At least 1 instruction is on the available list
2231 // that is not dependent on the branch
2232 for (uint i = 0; i < siz; i++) {
2233 Node *d = _available[i];
2234 const Pipeline *avail_pipeline = d->pipeline();
2236 // Don't allow safepoints in the branch shadow, that will
2237 // cause a number of difficulties
2238 if ( avail_pipeline->instructionCount() == 1 &&
2239 !avail_pipeline->hasMultipleBundles() &&
2240 !avail_pipeline->hasBranchDelay() &&
2241 Pipeline::instr_has_unit_size() &&
2242 d->size(_regalloc) == Pipeline::instr_unit_size() &&
2243 NodeFitsInBundle(d) &&
2244 !node_bundling(d)->used_in_delay()) {
2246 if (d->is_Mach() && !d->is_MachSafePoint()) {
2247 // A node that fits in the delay slot was found, so we need to
2248 // set the appropriate bits in the bundle pipeline information so
2249 // that it correctly indicates resource usage. Later, when we
2250 // attempt to add this instruction to the bundle, we will skip
2251 // setting the resource usage.
2252 _unconditional_delay_slot = d;
2253 node_bundling(n)->set_use_unconditional_delay();
2254 node_bundling(d)->set_used_in_unconditional_delay();
2255 _bundle_use.add_usage(avail_pipeline->resourceUse());
2256 _current_latency[d->_idx] = _bundle_cycle_number;
2257 _next_node = d;
2258 ++_bundle_instr_count;
2259 #ifndef PRODUCT
2260 _unconditional_delays++;
2261 #endif
2262 break;
2263 }
2264 }
2265 }
2266 }
2268 // No delay slot, add a nop to the usage
2269 if (!_unconditional_delay_slot) {
2270 // See if adding an instruction in the delay slot will overflow
2271 // the bundle.
2272 if (!NodeFitsInBundle(_nop)) {
2273 #ifndef PRODUCT
2274 if (_cfg->C->trace_opto_output())
2275 tty->print("# *** STEP(1 instruction for delay slot) ***\n");
2276 #endif
2277 step(1);
2278 }
2280 _bundle_use.add_usage(_nop->pipeline()->resourceUse());
2281 _next_node = _nop;
2282 ++_bundle_instr_count;
2283 }
2285 // See if the instruction in the delay slot requires a
2286 // step of the bundles
2287 if (!NodeFitsInBundle(n)) {
2288 #ifndef PRODUCT
2289 if (_cfg->C->trace_opto_output())
2290 tty->print("# *** STEP(branch won't fit) ***\n");
2291 #endif
2292 // Update the state information
2293 _bundle_instr_count = 0;
2294 _bundle_cycle_number += 1;
2295 _bundle_use.step(1);
2296 }
2297 }
2299 // Get the number of instructions
2300 uint instruction_count = node_pipeline->instructionCount();
2301 if (node_pipeline->mayHaveNoCode() && n->size(_regalloc) == 0)
2302 instruction_count = 0;
2304 // Compute the latency information
2305 uint delay = 0;
2307 if (instruction_count > 0 || !node_pipeline->mayHaveNoCode()) {
2308 int relative_latency = _current_latency[n->_idx] - _bundle_cycle_number;
2309 if (relative_latency < 0)
2310 relative_latency = 0;
2312 delay = _bundle_use.full_latency(relative_latency, node_usage);
2314 // Does not fit in this bundle, start a new one
2315 if (delay > 0) {
2316 step(delay);
2318 #ifndef PRODUCT
2319 if (_cfg->C->trace_opto_output())
2320 tty->print("# *** STEP(%d) ***\n", delay);
2321 #endif
2322 }
2323 }
2325 // If this was placed in the delay slot, ignore it
2326 if (n != _unconditional_delay_slot) {
2328 if (delay == 0) {
2329 if (node_pipeline->hasMultipleBundles()) {
2330 #ifndef PRODUCT
2331 if (_cfg->C->trace_opto_output())
2332 tty->print("# *** STEP(multiple instructions) ***\n");
2333 #endif
2334 step(1);
2335 }
2337 else if (instruction_count + _bundle_instr_count > Pipeline::_max_instrs_per_cycle) {
2338 #ifndef PRODUCT
2339 if (_cfg->C->trace_opto_output())
2340 tty->print("# *** STEP(%d >= %d instructions) ***\n",
2341 instruction_count + _bundle_instr_count,
2342 Pipeline::_max_instrs_per_cycle);
2343 #endif
2344 step(1);
2345 }
2346 }
2348 if (node_pipeline->hasBranchDelay() && !_unconditional_delay_slot)
2349 _bundle_instr_count++;
2351 // Set the node's latency
2352 _current_latency[n->_idx] = _bundle_cycle_number;
2354 // Now merge the functional unit information
2355 if (instruction_count > 0 || !node_pipeline->mayHaveNoCode())
2356 _bundle_use.add_usage(node_usage);
2358 // Increment the number of instructions in this bundle
2359 _bundle_instr_count += instruction_count;
2361 // Remember this node for later
2362 if (n->is_Mach())
2363 _next_node = n;
2364 }
2366 // It's possible to have a BoxLock in the graph and in the _bbs mapping but
2367 // not in the bb->_nodes array. This happens for debug-info-only BoxLocks.
2368 // 'Schedule' them (basically ignore in the schedule) but do not insert them
2369 // into the block. All other scheduled nodes get put in the schedule here.
2370 int op = n->Opcode();
2371 if( (op == Op_Node && n->req() == 0) || // anti-dependence node OR
2372 (op != Op_Node && // Not an unused antidepedence node and
2373 // not an unallocated boxlock
2374 (OptoReg::is_valid(_regalloc->get_reg_first(n)) || op != Op_BoxLock)) ) {
2376 // Push any trailing projections
2377 if( bb->get_node(bb->number_of_nodes()-1) != n ) {
2378 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2379 Node *foi = n->fast_out(i);
2380 if( foi->is_Proj() )
2381 _scheduled.push(foi);
2382 }
2383 }
2385 // Put the instruction in the schedule list
2386 _scheduled.push(n);
2387 }
2389 #ifndef PRODUCT
2390 if (_cfg->C->trace_opto_output())
2391 dump_available();
2392 #endif
2394 // Walk all the definitions, decrementing use counts, and
2395 // if a definition has a 0 use count, place it in the available list.
2396 DecrementUseCounts(n,bb);
2397 }
2399 // This method sets the use count within a basic block. We will ignore all
2400 // uses outside the current basic block. As we are doing a backwards walk,
2401 // any node we reach that has a use count of 0 may be scheduled. This also
2402 // avoids the problem of cyclic references from phi nodes, as long as phi
2403 // nodes are at the front of the basic block. This method also initializes
2404 // the available list to the set of instructions that have no uses within this
2405 // basic block.
2406 void Scheduling::ComputeUseCount(const Block *bb) {
2407 #ifndef PRODUCT
2408 if (_cfg->C->trace_opto_output())
2409 tty->print("# -> ComputeUseCount\n");
2410 #endif
2412 // Clear the list of available and scheduled instructions, just in case
2413 _available.clear();
2414 _scheduled.clear();
2416 // No delay slot specified
2417 _unconditional_delay_slot = NULL;
2419 #ifdef ASSERT
2420 for( uint i=0; i < bb->number_of_nodes(); i++ )
2421 assert( _uses[bb->get_node(i)->_idx] == 0, "_use array not clean" );
2422 #endif
2424 // Force the _uses count to never go to zero for unscheduable pieces
2425 // of the block
2426 for( uint k = 0; k < _bb_start; k++ )
2427 _uses[bb->get_node(k)->_idx] = 1;
2428 for( uint l = _bb_end; l < bb->number_of_nodes(); l++ )
2429 _uses[bb->get_node(l)->_idx] = 1;
2431 // Iterate backwards over the instructions in the block. Don't count the
2432 // branch projections at end or the block header instructions.
2433 for( uint j = _bb_end-1; j >= _bb_start; j-- ) {
2434 Node *n = bb->get_node(j);
2435 if( n->is_Proj() ) continue; // Projections handled another way
2437 // Account for all uses
2438 for ( uint k = 0; k < n->len(); k++ ) {
2439 Node *inp = n->in(k);
2440 if (!inp) continue;
2441 assert(inp != n, "no cycles allowed" );
2442 if (_cfg->get_block_for_node(inp) == bb) { // Block-local use?
2443 if (inp->is_Proj()) { // Skip through Proj's
2444 inp = inp->in(0);
2445 }
2446 ++_uses[inp->_idx]; // Count 1 block-local use
2447 }
2448 }
2450 // If this instruction has a 0 use count, then it is available
2451 if (!_uses[n->_idx]) {
2452 _current_latency[n->_idx] = _bundle_cycle_number;
2453 AddNodeToAvailableList(n);
2454 }
2456 #ifndef PRODUCT
2457 if (_cfg->C->trace_opto_output()) {
2458 tty->print("# uses: %3d: ", _uses[n->_idx]);
2459 n->dump();
2460 }
2461 #endif
2462 }
2464 #ifndef PRODUCT
2465 if (_cfg->C->trace_opto_output())
2466 tty->print("# <- ComputeUseCount\n");
2467 #endif
2468 }
2470 // This routine performs scheduling on each basic block in reverse order,
2471 // using instruction latencies and taking into account function unit
2472 // availability.
2473 void Scheduling::DoScheduling() {
2474 #ifndef PRODUCT
2475 if (_cfg->C->trace_opto_output())
2476 tty->print("# -> DoScheduling\n");
2477 #endif
2479 Block *succ_bb = NULL;
2480 Block *bb;
2482 // Walk over all the basic blocks in reverse order
2483 for (int i = _cfg->number_of_blocks() - 1; i >= 0; succ_bb = bb, i--) {
2484 bb = _cfg->get_block(i);
2486 #ifndef PRODUCT
2487 if (_cfg->C->trace_opto_output()) {
2488 tty->print("# Schedule BB#%03d (initial)\n", i);
2489 for (uint j = 0; j < bb->number_of_nodes(); j++) {
2490 bb->get_node(j)->dump();
2491 }
2492 }
2493 #endif
2495 // On the head node, skip processing
2496 if (bb == _cfg->get_root_block()) {
2497 continue;
2498 }
2500 // Skip empty, connector blocks
2501 if (bb->is_connector())
2502 continue;
2504 // If the following block is not the sole successor of
2505 // this one, then reset the pipeline information
2506 if (bb->_num_succs != 1 || bb->non_connector_successor(0) != succ_bb) {
2507 #ifndef PRODUCT
2508 if (_cfg->C->trace_opto_output()) {
2509 tty->print("*** bundle start of next BB, node %d, for %d instructions\n",
2510 _next_node->_idx, _bundle_instr_count);
2511 }
2512 #endif
2513 step_and_clear();
2514 }
2516 // Leave untouched the starting instruction, any Phis, a CreateEx node
2517 // or Top. bb->get_node(_bb_start) is the first schedulable instruction.
2518 _bb_end = bb->number_of_nodes()-1;
2519 for( _bb_start=1; _bb_start <= _bb_end; _bb_start++ ) {
2520 Node *n = bb->get_node(_bb_start);
2521 // Things not matched, like Phinodes and ProjNodes don't get scheduled.
2522 // Also, MachIdealNodes do not get scheduled
2523 if( !n->is_Mach() ) continue; // Skip non-machine nodes
2524 MachNode *mach = n->as_Mach();
2525 int iop = mach->ideal_Opcode();
2526 if( iop == Op_CreateEx ) continue; // CreateEx is pinned
2527 if( iop == Op_Con ) continue; // Do not schedule Top
2528 if( iop == Op_Node && // Do not schedule PhiNodes, ProjNodes
2529 mach->pipeline() == MachNode::pipeline_class() &&
2530 !n->is_SpillCopy() && !n->is_MachMerge() ) // Breakpoints, Prolog, etc
2531 continue;
2532 break; // Funny loop structure to be sure...
2533 }
2534 // Compute last "interesting" instruction in block - last instruction we
2535 // might schedule. _bb_end points just after last schedulable inst. We
2536 // normally schedule conditional branches (despite them being forced last
2537 // in the block), because they have delay slots we can fill. Calls all
2538 // have their delay slots filled in the template expansions, so we don't
2539 // bother scheduling them.
2540 Node *last = bb->get_node(_bb_end);
2541 // Ignore trailing NOPs.
2542 while (_bb_end > 0 && last->is_Mach() &&
2543 last->as_Mach()->ideal_Opcode() == Op_Con) {
2544 last = bb->get_node(--_bb_end);
2545 }
2546 assert(!last->is_Mach() || last->as_Mach()->ideal_Opcode() != Op_Con, "");
2547 if( last->is_Catch() ||
2548 // Exclude unreachable path case when Halt node is in a separate block.
2549 (_bb_end > 1 && last->is_Mach() && last->as_Mach()->ideal_Opcode() == Op_Halt) ) {
2550 // There must be a prior call. Skip it.
2551 while( !bb->get_node(--_bb_end)->is_MachCall() ) {
2552 assert( bb->get_node(_bb_end)->is_MachProj(), "skipping projections after expected call" );
2553 }
2554 } else if( last->is_MachNullCheck() ) {
2555 // Backup so the last null-checked memory instruction is
2556 // outside the schedulable range. Skip over the nullcheck,
2557 // projection, and the memory nodes.
2558 Node *mem = last->in(1);
2559 do {
2560 _bb_end--;
2561 } while (mem != bb->get_node(_bb_end));
2562 } else {
2563 // Set _bb_end to point after last schedulable inst.
2564 _bb_end++;
2565 }
2567 assert( _bb_start <= _bb_end, "inverted block ends" );
2569 // Compute the register antidependencies for the basic block
2570 ComputeRegisterAntidependencies(bb);
2571 if (_cfg->C->failing()) return; // too many D-U pinch points
2573 // Compute intra-bb latencies for the nodes
2574 ComputeLocalLatenciesForward(bb);
2576 // Compute the usage within the block, and set the list of all nodes
2577 // in the block that have no uses within the block.
2578 ComputeUseCount(bb);
2580 // Schedule the remaining instructions in the block
2581 while ( _available.size() > 0 ) {
2582 Node *n = ChooseNodeToBundle();
2583 guarantee(n != NULL, "no nodes available");
2584 AddNodeToBundle(n,bb);
2585 }
2587 assert( _scheduled.size() == _bb_end - _bb_start, "wrong number of instructions" );
2588 #ifdef ASSERT
2589 for( uint l = _bb_start; l < _bb_end; l++ ) {
2590 Node *n = bb->get_node(l);
2591 uint m;
2592 for( m = 0; m < _bb_end-_bb_start; m++ )
2593 if( _scheduled[m] == n )
2594 break;
2595 assert( m < _bb_end-_bb_start, "instruction missing in schedule" );
2596 }
2597 #endif
2599 // Now copy the instructions (in reverse order) back to the block
2600 for ( uint k = _bb_start; k < _bb_end; k++ )
2601 bb->map_node(_scheduled[_bb_end-k-1], k);
2603 #ifndef PRODUCT
2604 if (_cfg->C->trace_opto_output()) {
2605 tty->print("# Schedule BB#%03d (final)\n", i);
2606 uint current = 0;
2607 for (uint j = 0; j < bb->number_of_nodes(); j++) {
2608 Node *n = bb->get_node(j);
2609 if( valid_bundle_info(n) ) {
2610 Bundle *bundle = node_bundling(n);
2611 if (bundle->instr_count() > 0 || bundle->flags() > 0) {
2612 tty->print("*** Bundle: ");
2613 bundle->dump();
2614 }
2615 n->dump();
2616 }
2617 }
2618 }
2619 #endif
2620 #ifdef ASSERT
2621 verify_good_schedule(bb,"after block local scheduling");
2622 #endif
2623 }
2625 #ifndef PRODUCT
2626 if (_cfg->C->trace_opto_output())
2627 tty->print("# <- DoScheduling\n");
2628 #endif
2630 // Record final node-bundling array location
2631 _regalloc->C->set_node_bundling_base(_node_bundling_base);
2633 } // end DoScheduling
2635 // Verify that no live-range used in the block is killed in the block by a
2636 // wrong DEF. This doesn't verify live-ranges that span blocks.
2638 // Check for edge existence. Used to avoid adding redundant precedence edges.
2639 static bool edge_from_to( Node *from, Node *to ) {
2640 for( uint i=0; i<from->len(); i++ )
2641 if( from->in(i) == to )
2642 return true;
2643 return false;
2644 }
2646 #ifdef ASSERT
2647 void Scheduling::verify_do_def( Node *n, OptoReg::Name def, const char *msg ) {
2648 // Check for bad kills
2649 if( OptoReg::is_valid(def) ) { // Ignore stores & control flow
2650 Node *prior_use = _reg_node[def];
2651 if( prior_use && !edge_from_to(prior_use,n) ) {
2652 tty->print("%s = ",OptoReg::as_VMReg(def)->name());
2653 n->dump();
2654 tty->print_cr("...");
2655 prior_use->dump();
2656 assert(edge_from_to(prior_use,n),msg);
2657 }
2658 _reg_node.map(def,NULL); // Kill live USEs
2659 }
2660 }
2662 void Scheduling::verify_good_schedule( Block *b, const char *msg ) {
2664 // Zap to something reasonable for the verify code
2665 _reg_node.clear();
2667 // Walk over the block backwards. Check to make sure each DEF doesn't
2668 // kill a live value (other than the one it's supposed to). Add each
2669 // USE to the live set.
2670 for( uint i = b->number_of_nodes()-1; i >= _bb_start; i-- ) {
2671 Node *n = b->get_node(i);
2672 int n_op = n->Opcode();
2673 if( n_op == Op_MachProj && n->ideal_reg() == MachProjNode::fat_proj ) {
2674 // Fat-proj kills a slew of registers
2675 RegMask rm = n->out_RegMask();// Make local copy
2676 while( rm.is_NotEmpty() ) {
2677 OptoReg::Name kill = rm.find_first_elem();
2678 rm.Remove(kill);
2679 verify_do_def( n, kill, msg );
2680 }
2681 } else if( n_op != Op_Node ) { // Avoid brand new antidependence nodes
2682 // Get DEF'd registers the normal way
2683 verify_do_def( n, _regalloc->get_reg_first(n), msg );
2684 verify_do_def( n, _regalloc->get_reg_second(n), msg );
2685 }
2687 // Now make all USEs live
2688 for( uint i=1; i<n->req(); i++ ) {
2689 Node *def = n->in(i);
2690 assert(def != 0, "input edge required");
2691 OptoReg::Name reg_lo = _regalloc->get_reg_first(def);
2692 OptoReg::Name reg_hi = _regalloc->get_reg_second(def);
2693 if( OptoReg::is_valid(reg_lo) ) {
2694 assert(!_reg_node[reg_lo] || edge_from_to(_reg_node[reg_lo],def), msg);
2695 _reg_node.map(reg_lo,n);
2696 }
2697 if( OptoReg::is_valid(reg_hi) ) {
2698 assert(!_reg_node[reg_hi] || edge_from_to(_reg_node[reg_hi],def), msg);
2699 _reg_node.map(reg_hi,n);
2700 }
2701 }
2703 }
2705 // Zap to something reasonable for the Antidependence code
2706 _reg_node.clear();
2707 }
2708 #endif
2710 // Conditionally add precedence edges. Avoid putting edges on Projs.
2711 static void add_prec_edge_from_to( Node *from, Node *to ) {
2712 if( from->is_Proj() ) { // Put precedence edge on Proj's input
2713 assert( from->req() == 1 && (from->len() == 1 || from->in(1)==0), "no precedence edges on projections" );
2714 from = from->in(0);
2715 }
2716 if( from != to && // No cycles (for things like LD L0,[L0+4] )
2717 !edge_from_to( from, to ) ) // Avoid duplicate edge
2718 from->add_prec(to);
2719 }
2721 void Scheduling::anti_do_def( Block *b, Node *def, OptoReg::Name def_reg, int is_def ) {
2722 if( !OptoReg::is_valid(def_reg) ) // Ignore stores & control flow
2723 return;
2725 Node *pinch = _reg_node[def_reg]; // Get pinch point
2726 if ((pinch == NULL) || _cfg->get_block_for_node(pinch) != b || // No pinch-point yet?
2727 is_def ) { // Check for a true def (not a kill)
2728 _reg_node.map(def_reg,def); // Record def/kill as the optimistic pinch-point
2729 return;
2730 }
2732 Node *kill = def; // Rename 'def' to more descriptive 'kill'
2733 debug_only( def = (Node*)((intptr_t)0xdeadbeef); )
2735 // After some number of kills there _may_ be a later def
2736 Node *later_def = NULL;
2738 // Finding a kill requires a real pinch-point.
2739 // Check for not already having a pinch-point.
2740 // Pinch points are Op_Node's.
2741 if( pinch->Opcode() != Op_Node ) { // Or later-def/kill as pinch-point?
2742 later_def = pinch; // Must be def/kill as optimistic pinch-point
2743 if ( _pinch_free_list.size() > 0) {
2744 pinch = _pinch_free_list.pop();
2745 } else {
2746 pinch = new (_cfg->C) Node(1); // Pinch point to-be
2747 }
2748 if (pinch->_idx >= _regalloc->node_regs_max_index()) {
2749 _cfg->C->record_method_not_compilable("too many D-U pinch points");
2750 return;
2751 }
2752 _cfg->map_node_to_block(pinch, b); // Pretend it's valid in this block (lazy init)
2753 _reg_node.map(def_reg,pinch); // Record pinch-point
2754 //_regalloc->set_bad(pinch->_idx); // Already initialized this way.
2755 if( later_def->outcnt() == 0 || later_def->ideal_reg() == MachProjNode::fat_proj ) { // Distinguish def from kill
2756 pinch->init_req(0, _cfg->C->top()); // set not NULL for the next call
2757 add_prec_edge_from_to(later_def,pinch); // Add edge from kill to pinch
2758 later_def = NULL; // and no later def
2759 }
2760 pinch->set_req(0,later_def); // Hook later def so we can find it
2761 } else { // Else have valid pinch point
2762 if( pinch->in(0) ) // If there is a later-def
2763 later_def = pinch->in(0); // Get it
2764 }
2766 // Add output-dependence edge from later def to kill
2767 if( later_def ) // If there is some original def
2768 add_prec_edge_from_to(later_def,kill); // Add edge from def to kill
2770 // See if current kill is also a use, and so is forced to be the pinch-point.
2771 if( pinch->Opcode() == Op_Node ) {
2772 Node *uses = kill->is_Proj() ? kill->in(0) : kill;
2773 for( uint i=1; i<uses->req(); i++ ) {
2774 if( _regalloc->get_reg_first(uses->in(i)) == def_reg ||
2775 _regalloc->get_reg_second(uses->in(i)) == def_reg ) {
2776 // Yes, found a use/kill pinch-point
2777 pinch->set_req(0,NULL); //
2778 pinch->replace_by(kill); // Move anti-dep edges up
2779 pinch = kill;
2780 _reg_node.map(def_reg,pinch);
2781 return;
2782 }
2783 }
2784 }
2786 // Add edge from kill to pinch-point
2787 add_prec_edge_from_to(kill,pinch);
2788 }
2790 void Scheduling::anti_do_use( Block *b, Node *use, OptoReg::Name use_reg ) {
2791 if( !OptoReg::is_valid(use_reg) ) // Ignore stores & control flow
2792 return;
2793 Node *pinch = _reg_node[use_reg]; // Get pinch point
2794 // Check for no later def_reg/kill in block
2795 if ((pinch != NULL) && _cfg->get_block_for_node(pinch) == b &&
2796 // Use has to be block-local as well
2797 _cfg->get_block_for_node(use) == b) {
2798 if( pinch->Opcode() == Op_Node && // Real pinch-point (not optimistic?)
2799 pinch->req() == 1 ) { // pinch not yet in block?
2800 pinch->del_req(0); // yank pointer to later-def, also set flag
2801 // Insert the pinch-point in the block just after the last use
2802 b->insert_node(pinch, b->find_node(use) + 1);
2803 _bb_end++; // Increase size scheduled region in block
2804 }
2806 add_prec_edge_from_to(pinch,use);
2807 }
2808 }
2810 // We insert antidependences between the reads and following write of
2811 // allocated registers to prevent illegal code motion. Hopefully, the
2812 // number of added references should be fairly small, especially as we
2813 // are only adding references within the current basic block.
2814 void Scheduling::ComputeRegisterAntidependencies(Block *b) {
2816 #ifdef ASSERT
2817 verify_good_schedule(b,"before block local scheduling");
2818 #endif
2820 // A valid schedule, for each register independently, is an endless cycle
2821 // of: a def, then some uses (connected to the def by true dependencies),
2822 // then some kills (defs with no uses), finally the cycle repeats with a new
2823 // def. The uses are allowed to float relative to each other, as are the
2824 // kills. No use is allowed to slide past a kill (or def). This requires
2825 // antidependencies between all uses of a single def and all kills that
2826 // follow, up to the next def. More edges are redundant, because later defs
2827 // & kills are already serialized with true or antidependencies. To keep
2828 // the edge count down, we add a 'pinch point' node if there's more than
2829 // one use or more than one kill/def.
2831 // We add dependencies in one bottom-up pass.
2833 // For each instruction we handle it's DEFs/KILLs, then it's USEs.
2835 // For each DEF/KILL, we check to see if there's a prior DEF/KILL for this
2836 // register. If not, we record the DEF/KILL in _reg_node, the
2837 // register-to-def mapping. If there is a prior DEF/KILL, we insert a
2838 // "pinch point", a new Node that's in the graph but not in the block.
2839 // We put edges from the prior and current DEF/KILLs to the pinch point.
2840 // We put the pinch point in _reg_node. If there's already a pinch point
2841 // we merely add an edge from the current DEF/KILL to the pinch point.
2843 // After doing the DEF/KILLs, we handle USEs. For each used register, we
2844 // put an edge from the pinch point to the USE.
2846 // To be expedient, the _reg_node array is pre-allocated for the whole
2847 // compilation. _reg_node is lazily initialized; it either contains a NULL,
2848 // or a valid def/kill/pinch-point, or a leftover node from some prior
2849 // block. Leftover node from some prior block is treated like a NULL (no
2850 // prior def, so no anti-dependence needed). Valid def is distinguished by
2851 // it being in the current block.
2852 bool fat_proj_seen = false;
2853 uint last_safept = _bb_end-1;
2854 Node* end_node = (_bb_end-1 >= _bb_start) ? b->get_node(last_safept) : NULL;
2855 Node* last_safept_node = end_node;
2856 for( uint i = _bb_end-1; i >= _bb_start; i-- ) {
2857 Node *n = b->get_node(i);
2858 int is_def = n->outcnt(); // def if some uses prior to adding precedence edges
2859 if( n->is_MachProj() && n->ideal_reg() == MachProjNode::fat_proj ) {
2860 // Fat-proj kills a slew of registers
2861 // This can add edges to 'n' and obscure whether or not it was a def,
2862 // hence the is_def flag.
2863 fat_proj_seen = true;
2864 RegMask rm = n->out_RegMask();// Make local copy
2865 while( rm.is_NotEmpty() ) {
2866 OptoReg::Name kill = rm.find_first_elem();
2867 rm.Remove(kill);
2868 anti_do_def( b, n, kill, is_def );
2869 }
2870 } else {
2871 // Get DEF'd registers the normal way
2872 anti_do_def( b, n, _regalloc->get_reg_first(n), is_def );
2873 anti_do_def( b, n, _regalloc->get_reg_second(n), is_def );
2874 }
2876 // Kill projections on a branch should appear to occur on the
2877 // branch, not afterwards, so grab the masks from the projections
2878 // and process them.
2879 if (n->is_MachBranch() || n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_Jump) {
2880 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2881 Node* use = n->fast_out(i);
2882 if (use->is_Proj()) {
2883 RegMask rm = use->out_RegMask();// Make local copy
2884 while( rm.is_NotEmpty() ) {
2885 OptoReg::Name kill = rm.find_first_elem();
2886 rm.Remove(kill);
2887 anti_do_def( b, n, kill, false );
2888 }
2889 }
2890 }
2891 }
2893 // Check each register used by this instruction for a following DEF/KILL
2894 // that must occur afterward and requires an anti-dependence edge.
2895 for( uint j=0; j<n->req(); j++ ) {
2896 Node *def = n->in(j);
2897 if( def ) {
2898 assert( !def->is_MachProj() || def->ideal_reg() != MachProjNode::fat_proj, "" );
2899 anti_do_use( b, n, _regalloc->get_reg_first(def) );
2900 anti_do_use( b, n, _regalloc->get_reg_second(def) );
2901 }
2902 }
2903 // Do not allow defs of new derived values to float above GC
2904 // points unless the base is definitely available at the GC point.
2906 Node *m = b->get_node(i);
2908 // Add precedence edge from following safepoint to use of derived pointer
2909 if( last_safept_node != end_node &&
2910 m != last_safept_node) {
2911 for (uint k = 1; k < m->req(); k++) {
2912 const Type *t = m->in(k)->bottom_type();
2913 if( t->isa_oop_ptr() &&
2914 t->is_ptr()->offset() != 0 ) {
2915 last_safept_node->add_prec( m );
2916 break;
2917 }
2918 }
2919 }
2921 if( n->jvms() ) { // Precedence edge from derived to safept
2922 // Check if last_safept_node was moved by pinch-point insertion in anti_do_use()
2923 if( b->get_node(last_safept) != last_safept_node ) {
2924 last_safept = b->find_node(last_safept_node);
2925 }
2926 for( uint j=last_safept; j > i; j-- ) {
2927 Node *mach = b->get_node(j);
2928 if( mach->is_Mach() && mach->as_Mach()->ideal_Opcode() == Op_AddP )
2929 mach->add_prec( n );
2930 }
2931 last_safept = i;
2932 last_safept_node = m;
2933 }
2934 }
2936 if (fat_proj_seen) {
2937 // Garbage collect pinch nodes that were not consumed.
2938 // They are usually created by a fat kill MachProj for a call.
2939 garbage_collect_pinch_nodes();
2940 }
2941 }
2943 // Garbage collect pinch nodes for reuse by other blocks.
2944 //
2945 // The block scheduler's insertion of anti-dependence
2946 // edges creates many pinch nodes when the block contains
2947 // 2 or more Calls. A pinch node is used to prevent a
2948 // combinatorial explosion of edges. If a set of kills for a
2949 // register is anti-dependent on a set of uses (or defs), rather
2950 // than adding an edge in the graph between each pair of kill
2951 // and use (or def), a pinch is inserted between them:
2952 //
2953 // use1 use2 use3
2954 // \ | /
2955 // \ | /
2956 // pinch
2957 // / | \
2958 // / | \
2959 // kill1 kill2 kill3
2960 //
2961 // One pinch node is created per register killed when
2962 // the second call is encountered during a backwards pass
2963 // over the block. Most of these pinch nodes are never
2964 // wired into the graph because the register is never
2965 // used or def'ed in the block.
2966 //
2967 void Scheduling::garbage_collect_pinch_nodes() {
2968 #ifndef PRODUCT
2969 if (_cfg->C->trace_opto_output()) tty->print("Reclaimed pinch nodes:");
2970 #endif
2971 int trace_cnt = 0;
2972 for (uint k = 0; k < _reg_node.Size(); k++) {
2973 Node* pinch = _reg_node[k];
2974 if ((pinch != NULL) && pinch->Opcode() == Op_Node &&
2975 // no predecence input edges
2976 (pinch->req() == pinch->len() || pinch->in(pinch->req()) == NULL) ) {
2977 cleanup_pinch(pinch);
2978 _pinch_free_list.push(pinch);
2979 _reg_node.map(k, NULL);
2980 #ifndef PRODUCT
2981 if (_cfg->C->trace_opto_output()) {
2982 trace_cnt++;
2983 if (trace_cnt > 40) {
2984 tty->print("\n");
2985 trace_cnt = 0;
2986 }
2987 tty->print(" %d", pinch->_idx);
2988 }
2989 #endif
2990 }
2991 }
2992 #ifndef PRODUCT
2993 if (_cfg->C->trace_opto_output()) tty->print("\n");
2994 #endif
2995 }
2997 // Clean up a pinch node for reuse.
2998 void Scheduling::cleanup_pinch( Node *pinch ) {
2999 assert (pinch && pinch->Opcode() == Op_Node && pinch->req() == 1, "just checking");
3001 for (DUIterator_Last imin, i = pinch->last_outs(imin); i >= imin; ) {
3002 Node* use = pinch->last_out(i);
3003 uint uses_found = 0;
3004 for (uint j = use->req(); j < use->len(); j++) {
3005 if (use->in(j) == pinch) {
3006 use->rm_prec(j);
3007 uses_found++;
3008 }
3009 }
3010 assert(uses_found > 0, "must be a precedence edge");
3011 i -= uses_found; // we deleted 1 or more copies of this edge
3012 }
3013 // May have a later_def entry
3014 pinch->set_req(0, NULL);
3015 }
3017 #ifndef PRODUCT
3019 void Scheduling::dump_available() const {
3020 tty->print("#Availist ");
3021 for (uint i = 0; i < _available.size(); i++)
3022 tty->print(" N%d/l%d", _available[i]->_idx,_current_latency[_available[i]->_idx]);
3023 tty->cr();
3024 }
3026 // Print Scheduling Statistics
3027 void Scheduling::print_statistics() {
3028 // Print the size added by nops for bundling
3029 tty->print("Nops added %d bytes to total of %d bytes",
3030 _total_nop_size, _total_method_size);
3031 if (_total_method_size > 0)
3032 tty->print(", for %.2f%%",
3033 ((double)_total_nop_size) / ((double) _total_method_size) * 100.0);
3034 tty->print("\n");
3036 // Print the number of branch shadows filled
3037 if (Pipeline::_branch_has_delay_slot) {
3038 tty->print("Of %d branches, %d had unconditional delay slots filled",
3039 _total_branches, _total_unconditional_delays);
3040 if (_total_branches > 0)
3041 tty->print(", for %.2f%%",
3042 ((double)_total_unconditional_delays) / ((double)_total_branches) * 100.0);
3043 tty->print("\n");
3044 }
3046 uint total_instructions = 0, total_bundles = 0;
3048 for (uint i = 1; i <= Pipeline::_max_instrs_per_cycle; i++) {
3049 uint bundle_count = _total_instructions_per_bundle[i];
3050 total_instructions += bundle_count * i;
3051 total_bundles += bundle_count;
3052 }
3054 if (total_bundles > 0)
3055 tty->print("Average ILP (excluding nops) is %.2f\n",
3056 ((double)total_instructions) / ((double)total_bundles));
3057 }
3058 #endif