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