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