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