1 /*
2 * Copyright (c) 2005, 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 "c1/c1_CFGPrinter.hpp"
26 #include "c1/c1_CodeStubs.hpp"
27 #include "c1/c1_Compilation.hpp"
28 #include "c1/c1_FrameMap.hpp"
29 #include "c1/c1_IR.hpp"
30 #include "c1/c1_LinearScan.hpp"
31 #include "c1/c1_LIRGenerator.hpp"
32 #include "c1/c1_ValueStack.hpp"
33 #include "code/vmreg.inline.hpp"
34 #include "runtime/timerTrace.hpp"
35 #include "utilities/bitMap.inline.hpp"
36
37 #ifndef PRODUCT
38
39 static LinearScanStatistic _stat_before_alloc;
40 static LinearScanStatistic _stat_after_asign;
41 static LinearScanStatistic _stat_final;
42
43 static LinearScanTimers _total_timer;
44
45 // helper macro for short definition of timer
46 #define TIME_LINEAR_SCAN(timer_name) TraceTime _block_timer("", _total_timer.timer(LinearScanTimers::timer_name), TimeLinearScan, Verbose);
47
48 #else
49 #define TIME_LINEAR_SCAN(timer_name)
50 #endif
51
52 #ifdef ASSERT
53
54 // helper macro for short definition of trace-output inside code
55 #define TRACE_LINEAR_SCAN(level, code) \
56 if (TraceLinearScanLevel >= level) { \
57 code; \
58 }
59 #else
60 #define TRACE_LINEAR_SCAN(level, code)
61 #endif
62
63 // Map BasicType to spill size in 32-bit words, matching VMReg's notion of words
64 #ifdef _LP64
65 static int type2spill_size[T_CONFLICT+1]={ -1, 0, 0, 0, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 2, 0, 2, 1, 2, 1, -1};
66 #else
67 static int type2spill_size[T_CONFLICT+1]={ -1, 0, 0, 0, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 0, 1, -1, 1, 1, -1};
68 #endif
69
70
71 // Implementation of LinearScan
72
73 LinearScan::LinearScan(IR* ir, LIRGenerator* gen, FrameMap* frame_map)
74 : _compilation(ir->compilation())
75 , _ir(ir)
76 , _gen(gen)
77 , _frame_map(frame_map)
78 , _cached_blocks(*ir->linear_scan_order())
79 , _num_virtual_regs(gen->max_virtual_register_number())
80 , _has_fpu_registers(false)
81 , _num_calls(-1)
82 , _max_spills(0)
83 , _unused_spill_slot(-1)
84 , _intervals(0) // initialized later with correct length
85 , _new_intervals_from_allocation(nullptr)
86 , _sorted_intervals(nullptr)
87 , _needs_full_resort(false)
88 , _lir_ops(0) // initialized later with correct length
89 , _block_of_op(0) // initialized later with correct length
90 , _has_info(0)
91 , _has_call(0)
92 , _interval_in_loop(0) // initialized later with correct length
93 , _scope_value_cache(0) // initialized later with correct length
94 {
95 assert(this->ir() != nullptr, "check if valid");
96 assert(this->compilation() != nullptr, "check if valid");
97 assert(this->gen() != nullptr, "check if valid");
98 assert(this->frame_map() != nullptr, "check if valid");
99 }
100
101
102 // ********** functions for converting LIR-Operands to register numbers
103 //
104 // Emulate a flat register file comprising physical integer registers,
105 // physical floating-point registers and virtual registers, in that order.
106 // Virtual registers already have appropriate numbers, since V0 is
107 // the number of physical registers.
108 // Returns -1 for hi word if opr is a single word operand.
109 //
110 // Note: the inverse operation (calculating an operand for register numbers)
111 // is done in calc_operand_for_interval()
112
113 int LinearScan::reg_num(LIR_Opr opr) {
114 assert(opr->is_register(), "should not call this otherwise");
115
116 if (opr->is_virtual_register()) {
117 assert(opr->vreg_number() >= nof_regs, "found a virtual register with a fixed-register number");
118 return opr->vreg_number();
119 } else if (opr->is_single_cpu()) {
120 return opr->cpu_regnr();
121 } else if (opr->is_double_cpu()) {
122 return opr->cpu_regnrLo();
123 #ifdef X86
124 } else if (opr->is_single_xmm()) {
125 return opr->fpu_regnr() + pd_first_xmm_reg;
126 } else if (opr->is_double_xmm()) {
127 return opr->fpu_regnrLo() + pd_first_xmm_reg;
128 #endif
129 } else if (opr->is_single_fpu()) {
130 return opr->fpu_regnr() + pd_first_fpu_reg;
131 } else if (opr->is_double_fpu()) {
132 return opr->fpu_regnrLo() + pd_first_fpu_reg;
133 } else {
134 ShouldNotReachHere();
135 return -1;
136 }
137 }
138
139 int LinearScan::reg_numHi(LIR_Opr opr) {
140 assert(opr->is_register(), "should not call this otherwise");
141
142 if (opr->is_virtual_register()) {
143 return -1;
144 } else if (opr->is_single_cpu()) {
145 return -1;
146 } else if (opr->is_double_cpu()) {
147 return opr->cpu_regnrHi();
148 #ifdef X86
149 } else if (opr->is_single_xmm()) {
150 return -1;
151 } else if (opr->is_double_xmm()) {
152 return -1;
153 #endif
154 } else if (opr->is_single_fpu()) {
155 return -1;
156 } else if (opr->is_double_fpu()) {
157 return opr->fpu_regnrHi() + pd_first_fpu_reg;
158 } else {
159 ShouldNotReachHere();
160 return -1;
161 }
162 }
163
164
165 // ********** functions for classification of intervals
166
167 bool LinearScan::is_precolored_interval(const Interval* i) {
168 return i->reg_num() < LinearScan::nof_regs;
169 }
170
171 bool LinearScan::is_virtual_interval(const Interval* i) {
172 return i->reg_num() >= LIR_Opr::vreg_base;
173 }
174
175 bool LinearScan::is_precolored_cpu_interval(const Interval* i) {
176 return i->reg_num() < LinearScan::nof_cpu_regs;
177 }
178
179 bool LinearScan::is_virtual_cpu_interval(const Interval* i) {
180 #if defined(__SOFTFP__) || defined(E500V2)
181 return i->reg_num() >= LIR_Opr::vreg_base;
182 #else
183 return i->reg_num() >= LIR_Opr::vreg_base && (i->type() != T_FLOAT && i->type() != T_DOUBLE);
184 #endif // __SOFTFP__ or E500V2
185 }
186
187 bool LinearScan::is_precolored_fpu_interval(const Interval* i) {
188 return i->reg_num() >= LinearScan::nof_cpu_regs && i->reg_num() < LinearScan::nof_regs;
189 }
190
191 bool LinearScan::is_virtual_fpu_interval(const Interval* i) {
192 #if defined(__SOFTFP__) || defined(E500V2)
193 return false;
194 #else
195 return i->reg_num() >= LIR_Opr::vreg_base && (i->type() == T_FLOAT || i->type() == T_DOUBLE);
196 #endif // __SOFTFP__ or E500V2
197 }
198
199 bool LinearScan::is_in_fpu_register(const Interval* i) {
200 // fixed intervals not needed for FPU stack allocation
201 return i->reg_num() >= nof_regs && pd_first_fpu_reg <= i->assigned_reg() && i->assigned_reg() <= pd_last_fpu_reg;
202 }
203
204 bool LinearScan::is_oop_interval(const Interval* i) {
205 // fixed intervals never contain oops
206 return i->reg_num() >= nof_regs && i->type() == T_OBJECT;
207 }
208
209
210 // ********** General helper functions
211
212 // compute next unused stack index that can be used for spilling
213 int LinearScan::allocate_spill_slot(bool double_word) {
214 int spill_slot;
215 if (double_word) {
216 if ((_max_spills & 1) == 1) {
217 // alignment of double-word values
218 // the hole because of the alignment is filled with the next single-word value
219 assert(_unused_spill_slot == -1, "wasting a spill slot");
220 _unused_spill_slot = _max_spills;
221 _max_spills++;
222 }
223 spill_slot = _max_spills;
224 _max_spills += 2;
225
226 } else if (_unused_spill_slot != -1) {
227 // re-use hole that was the result of a previous double-word alignment
228 spill_slot = _unused_spill_slot;
229 _unused_spill_slot = -1;
230
231 } else {
232 spill_slot = _max_spills;
233 _max_spills++;
234 }
235
236 int result = spill_slot + LinearScan::nof_regs + frame_map()->argcount();
237
238 // if too many slots used, bailout compilation.
239 if (result > 2000) {
240 bailout("too many stack slots used");
241 }
242
243 return result;
244 }
245
246 void LinearScan::assign_spill_slot(Interval* it) {
247 // assign the canonical spill slot of the parent (if a part of the interval
248 // is already spilled) or allocate a new spill slot
249 if (it->canonical_spill_slot() >= 0) {
250 it->assign_reg(it->canonical_spill_slot());
251 } else {
252 int spill = allocate_spill_slot(type2spill_size[it->type()] == 2);
253 it->set_canonical_spill_slot(spill);
254 it->assign_reg(spill);
255 }
256 }
257
258 void LinearScan::propagate_spill_slots() {
259 if (!frame_map()->finalize_frame(max_spills(), compilation()->needs_stack_repair())) {
260 bailout("frame too large");
261 }
262 }
263
264 // create a new interval with a predefined reg_num
265 // (only used for parent intervals that are created during the building phase)
266 Interval* LinearScan::create_interval(int reg_num) {
267 assert(_intervals.at(reg_num) == nullptr, "overwriting existing interval");
268
269 Interval* interval = new Interval(reg_num);
270 _intervals.at_put(reg_num, interval);
271
272 // assign register number for precolored intervals
273 if (reg_num < LIR_Opr::vreg_base) {
274 interval->assign_reg(reg_num);
275 }
276 return interval;
277 }
278
279 // assign a new reg_num to the interval and append it to the list of intervals
280 // (only used for child intervals that are created during register allocation)
281 void LinearScan::append_interval(Interval* it) {
282 it->set_reg_num(_intervals.length());
283 _intervals.append(it);
284 IntervalList* new_intervals = _new_intervals_from_allocation;
285 if (new_intervals == nullptr) {
286 new_intervals = _new_intervals_from_allocation = new IntervalList();
287 }
288 new_intervals->append(it);
289 }
290
291 // copy the vreg-flags if an interval is split
292 void LinearScan::copy_register_flags(Interval* from, Interval* to) {
293 if (gen()->is_vreg_flag_set(from->reg_num(), LIRGenerator::byte_reg)) {
294 gen()->set_vreg_flag(to->reg_num(), LIRGenerator::byte_reg);
295 }
296 if (gen()->is_vreg_flag_set(from->reg_num(), LIRGenerator::callee_saved)) {
297 gen()->set_vreg_flag(to->reg_num(), LIRGenerator::callee_saved);
298 }
299
300 // Note: do not copy the must_start_in_memory flag because it is not necessary for child
301 // intervals (only the very beginning of the interval must be in memory)
302 }
303
304
305 // ********** spill move optimization
306 // eliminate moves from register to stack if stack slot is known to be correct
307
308 // called during building of intervals
309 void LinearScan::change_spill_definition_pos(Interval* interval, int def_pos) {
310 assert(interval->is_split_parent(), "can only be called for split parents");
311
312 switch (interval->spill_state()) {
313 case noDefinitionFound:
314 assert(interval->spill_definition_pos() == -1, "must no be set before");
315 interval->set_spill_definition_pos(def_pos);
316 interval->set_spill_state(oneDefinitionFound);
317 break;
318
319 case oneDefinitionFound:
320 assert(def_pos <= interval->spill_definition_pos(), "positions are processed in reverse order when intervals are created");
321 if (def_pos < interval->spill_definition_pos() - 2) {
322 // second definition found, so no spill optimization possible for this interval
323 interval->set_spill_state(noOptimization);
324 } else {
325 // two consecutive definitions (because of two-operand LIR form)
326 assert(block_of_op_with_id(def_pos) == block_of_op_with_id(interval->spill_definition_pos()), "block must be equal");
327 }
328 break;
329
330 case noOptimization:
331 // nothing to do
332 break;
333
334 default:
335 assert(false, "other states not allowed at this time");
336 }
337 }
338
339 // called during register allocation
340 void LinearScan::change_spill_state(Interval* interval, int spill_pos) {
341 switch (interval->spill_state()) {
342 case oneDefinitionFound: {
343 int def_loop_depth = block_of_op_with_id(interval->spill_definition_pos())->loop_depth();
344 int spill_loop_depth = block_of_op_with_id(spill_pos)->loop_depth();
345
346 if (def_loop_depth < spill_loop_depth) {
347 // the loop depth of the spilling position is higher then the loop depth
348 // at the definition of the interval -> move write to memory out of loop
349 // by storing at definitin of the interval
350 interval->set_spill_state(storeAtDefinition);
351 } else {
352 // the interval is currently spilled only once, so for now there is no
353 // reason to store the interval at the definition
354 interval->set_spill_state(oneMoveInserted);
355 }
356 break;
357 }
358
359 case oneMoveInserted: {
360 // the interval is spilled more then once, so it is better to store it to
361 // memory at the definition
362 interval->set_spill_state(storeAtDefinition);
363 break;
364 }
365
366 case storeAtDefinition:
367 case startInMemory:
368 case noOptimization:
369 case noDefinitionFound:
370 // nothing to do
371 break;
372
373 default:
374 assert(false, "other states not allowed at this time");
375 }
376 }
377
378
379 bool LinearScan::must_store_at_definition(const Interval* i) {
380 return i->is_split_parent() && i->spill_state() == storeAtDefinition;
381 }
382
383 // called once before assignment of register numbers
384 void LinearScan::eliminate_spill_moves() {
385 TIME_LINEAR_SCAN(timer_eliminate_spill_moves);
386 TRACE_LINEAR_SCAN(3, tty->print_cr("***** Eliminating unnecessary spill moves"));
387
388 // collect all intervals that must be stored after their definion.
389 // the list is sorted by Interval::spill_definition_pos
390 Interval* interval;
391 Interval* temp_list;
392 create_unhandled_lists(&interval, &temp_list, must_store_at_definition, nullptr);
393
394 #ifdef ASSERT
395 Interval* prev = nullptr;
396 Interval* temp = interval;
397 while (temp != Interval::end()) {
398 assert(temp->spill_definition_pos() > 0, "invalid spill definition pos");
399 if (prev != nullptr) {
400 assert(temp->from() >= prev->from(), "intervals not sorted");
401 assert(temp->spill_definition_pos() >= prev->spill_definition_pos(), "when intervals are sorted by from, then they must also be sorted by spill_definition_pos");
402 }
403
404 assert(temp->canonical_spill_slot() >= LinearScan::nof_regs, "interval has no spill slot assigned");
405 assert(temp->spill_definition_pos() >= temp->from(), "invalid order");
406 assert(temp->spill_definition_pos() <= temp->from() + 2, "only intervals defined once at their start-pos can be optimized");
407
408 TRACE_LINEAR_SCAN(4, tty->print_cr("interval %d (from %d to %d) must be stored at %d", temp->reg_num(), temp->from(), temp->to(), temp->spill_definition_pos()));
409
410 temp = temp->next();
411 }
412 #endif
413
414 LIR_InsertionBuffer insertion_buffer;
415 int num_blocks = block_count();
416 for (int i = 0; i < num_blocks; i++) {
417 BlockBegin* block = block_at(i);
418 LIR_OpList* instructions = block->lir()->instructions_list();
419 int num_inst = instructions->length();
420 bool has_new = false;
421
422 // iterate all instructions of the block. skip the first because it is always a label
423 for (int j = 1; j < num_inst; j++) {
424 LIR_Op* op = instructions->at(j);
425 int op_id = op->id();
426
427 if (op_id == -1) {
428 // remove move from register to stack if the stack slot is guaranteed to be correct.
429 // only moves that have been inserted by LinearScan can be removed.
430 assert(op->code() == lir_move, "only moves can have a op_id of -1");
431 assert(op->as_Op1() != nullptr, "move must be LIR_Op1");
432 assert(op->as_Op1()->result_opr()->is_virtual(), "LinearScan inserts only moves to virtual registers");
433
434 LIR_Op1* op1 = (LIR_Op1*)op;
435 Interval* interval = interval_at(op1->result_opr()->vreg_number());
436
437 if (interval->assigned_reg() >= LinearScan::nof_regs && interval->always_in_memory()) {
438 // move target is a stack slot that is always correct, so eliminate instruction
439 TRACE_LINEAR_SCAN(4, tty->print_cr("eliminating move from interval %d to %d", op1->in_opr()->vreg_number(), op1->result_opr()->vreg_number()));
440 instructions->at_put(j, nullptr); // null-instructions are deleted by assign_reg_num
441 }
442
443 } else {
444 // insert move from register to stack just after the beginning of the interval
445 assert(interval == Interval::end() || interval->spill_definition_pos() >= op_id, "invalid order");
446 assert(interval == Interval::end() || (interval->is_split_parent() && interval->spill_state() == storeAtDefinition), "invalid interval");
447
448 while (interval != Interval::end() && interval->spill_definition_pos() == op_id) {
449 if (!has_new) {
450 // prepare insertion buffer (appended when all instructions of the block are processed)
451 insertion_buffer.init(block->lir());
452 has_new = true;
453 }
454
455 LIR_Opr from_opr = operand_for_interval(interval);
456 LIR_Opr to_opr = canonical_spill_opr(interval);
457 assert(from_opr->is_fixed_cpu() || from_opr->is_fixed_fpu(), "from operand must be a register");
458 assert(to_opr->is_stack(), "to operand must be a stack slot");
459
460 insertion_buffer.move(j, from_opr, to_opr);
461 TRACE_LINEAR_SCAN(4, tty->print_cr("inserting move after definition of interval %d to stack slot %d at op_id %d", interval->reg_num(), interval->canonical_spill_slot() - LinearScan::nof_regs, op_id));
462
463 interval = interval->next();
464 }
465 }
466 } // end of instruction iteration
467
468 if (has_new) {
469 block->lir()->append(&insertion_buffer);
470 }
471 } // end of block iteration
472
473 assert(interval == Interval::end(), "missed an interval");
474 }
475
476
477 // ********** Phase 1: number all instructions in all blocks
478 // Compute depth-first and linear scan block orders, and number LIR_Op nodes for linear scan.
479
480 void LinearScan::number_instructions() {
481 {
482 // dummy-timer to measure the cost of the timer itself
483 // (this time is then subtracted from all other timers to get the real value)
484 TIME_LINEAR_SCAN(timer_do_nothing);
485 }
486 TIME_LINEAR_SCAN(timer_number_instructions);
487
488 // Assign IDs to LIR nodes and build a mapping, lir_ops, from ID to LIR_Op node.
489 int num_blocks = block_count();
490 int num_instructions = 0;
491 int i;
492 for (i = 0; i < num_blocks; i++) {
493 num_instructions += block_at(i)->lir()->instructions_list()->length();
494 }
495
496 // initialize with correct length
497 _lir_ops = LIR_OpArray(num_instructions, num_instructions, nullptr);
498 _block_of_op = BlockBeginArray(num_instructions, num_instructions, nullptr);
499
500 int op_id = 0;
501 int idx = 0;
502
503 for (i = 0; i < num_blocks; i++) {
504 BlockBegin* block = block_at(i);
505 block->set_first_lir_instruction_id(op_id);
506 LIR_OpList* instructions = block->lir()->instructions_list();
507
508 int num_inst = instructions->length();
509 for (int j = 0; j < num_inst; j++) {
510 LIR_Op* op = instructions->at(j);
511 op->set_id(op_id);
512
513 _lir_ops.at_put(idx, op);
514 _block_of_op.at_put(idx, block);
515 assert(lir_op_with_id(op_id) == op, "must match");
516
517 idx++;
518 op_id += 2; // numbering of lir_ops by two
519 }
520 block->set_last_lir_instruction_id(op_id - 2);
521 }
522 assert(idx == num_instructions, "must match");
523 assert(idx * 2 == op_id, "must match");
524
525 _has_call.initialize(num_instructions);
526 _has_info.initialize(num_instructions);
527 }
528
529
530 // ********** Phase 2: compute local live sets separately for each block
531 // (sets live_gen and live_kill for each block)
532
533 void LinearScan::set_live_gen_kill(Value value, LIR_Op* op, BitMap& live_gen, BitMap& live_kill) {
534 LIR_Opr opr = value->operand();
535 Constant* con = value->as_Constant();
536
537 // check some asumptions about debug information
538 assert(!value->type()->is_illegal(), "if this local is used by the interpreter it shouldn't be of indeterminate type");
539 assert(con == nullptr || opr->is_virtual() || opr->is_constant() || opr->is_illegal(), "assumption: Constant instructions have only constant operands");
540 assert(con != nullptr || opr->is_virtual(), "assumption: non-Constant instructions have only virtual operands");
541
542 if ((con == nullptr || con->is_pinned()) && opr->is_register()) {
543 assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
544 int reg = opr->vreg_number();
545 if (!live_kill.at(reg)) {
546 live_gen.set_bit(reg);
547 TRACE_LINEAR_SCAN(4, tty->print_cr(" Setting live_gen for value %c%d, LIR op_id %d, register number %d", value->type()->tchar(), value->id(), op->id(), reg));
548 }
549 }
550 }
551
552
553 void LinearScan::compute_local_live_sets() {
554 TIME_LINEAR_SCAN(timer_compute_local_live_sets);
555
556 int num_blocks = block_count();
557 int live_size = live_set_size();
558 bool local_has_fpu_registers = false;
559 int local_num_calls = 0;
560 LIR_OpVisitState visitor;
561
562 BitMap2D local_interval_in_loop = BitMap2D(_num_virtual_regs, num_loops());
563
564 // iterate all blocks
565 for (int i = 0; i < num_blocks; i++) {
566 BlockBegin* block = block_at(i);
567
568 ResourceBitMap live_gen(live_size);
569 ResourceBitMap live_kill(live_size);
570
571 if (block->is_set(BlockBegin::exception_entry_flag)) {
572 // Phi functions at the begin of an exception handler are
573 // implicitly defined (= killed) at the beginning of the block.
574 for_each_phi_fun(block, phi,
575 if (!phi->is_illegal()) { live_kill.set_bit(phi->operand()->vreg_number()); }
576 );
577 }
578
579 LIR_OpList* instructions = block->lir()->instructions_list();
580 int num_inst = instructions->length();
581
582 // iterate all instructions of the block. skip the first because it is always a label
583 assert(visitor.no_operands(instructions->at(0)), "first operation must always be a label");
584 for (int j = 1; j < num_inst; j++) {
585 LIR_Op* op = instructions->at(j);
586
587 // visit operation to collect all operands
588 visitor.visit(op);
589
590 if (visitor.has_call()) {
591 _has_call.set_bit(op->id() >> 1);
592 local_num_calls++;
593 }
594 if (visitor.info_count() > 0) {
595 _has_info.set_bit(op->id() >> 1);
596 }
597
598 // iterate input operands of instruction
599 int k, n, reg;
600 n = visitor.opr_count(LIR_OpVisitState::inputMode);
601 for (k = 0; k < n; k++) {
602 LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::inputMode, k);
603 assert(opr->is_register(), "visitor should only return register operands");
604
605 if (opr->is_virtual_register()) {
606 assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
607 reg = opr->vreg_number();
608 if (!live_kill.at(reg)) {
609 live_gen.set_bit(reg);
610 TRACE_LINEAR_SCAN(4, tty->print_cr(" Setting live_gen for register %d at instruction %d", reg, op->id()));
611 }
612 if (block->loop_index() >= 0) {
613 local_interval_in_loop.set_bit(reg, block->loop_index());
614 }
615 local_has_fpu_registers = local_has_fpu_registers || opr->is_virtual_fpu();
616 }
617
618 #ifdef ASSERT
619 // fixed intervals are never live at block boundaries, so
620 // they need not be processed in live sets.
621 // this is checked by these assertions to be sure about it.
622 // the entry block may have incoming values in registers, which is ok.
623 if (!opr->is_virtual_register() && block != ir()->start()) {
624 reg = reg_num(opr);
625 if (is_processed_reg_num(reg)) {
626 assert(live_kill.at(reg), "using fixed register that is not defined in this block");
627 }
628 reg = reg_numHi(opr);
629 if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
630 assert(live_kill.at(reg), "using fixed register that is not defined in this block");
631 }
632 }
633 #endif
634 }
635
636 // Add uses of live locals from interpreter's point of view for proper debug information generation
637 n = visitor.info_count();
638 for (k = 0; k < n; k++) {
639 CodeEmitInfo* info = visitor.info_at(k);
640 ValueStack* stack = info->stack();
641 for_each_state_value(stack, value,
642 set_live_gen_kill(value, op, live_gen, live_kill);
643 local_has_fpu_registers = local_has_fpu_registers || value->type()->is_float_kind();
644 );
645 }
646
647 // iterate temp operands of instruction
648 n = visitor.opr_count(LIR_OpVisitState::tempMode);
649 for (k = 0; k < n; k++) {
650 LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::tempMode, k);
651 assert(opr->is_register(), "visitor should only return register operands");
652
653 if (opr->is_virtual_register()) {
654 assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
655 reg = opr->vreg_number();
656 live_kill.set_bit(reg);
657 if (block->loop_index() >= 0) {
658 local_interval_in_loop.set_bit(reg, block->loop_index());
659 }
660 local_has_fpu_registers = local_has_fpu_registers || opr->is_virtual_fpu();
661 }
662
663 #ifdef ASSERT
664 // fixed intervals are never live at block boundaries, so
665 // they need not be processed in live sets
666 // process them only in debug mode so that this can be checked
667 if (!opr->is_virtual_register()) {
668 reg = reg_num(opr);
669 if (is_processed_reg_num(reg)) {
670 live_kill.set_bit(reg_num(opr));
671 }
672 reg = reg_numHi(opr);
673 if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
674 live_kill.set_bit(reg);
675 }
676 }
677 #endif
678 }
679
680 // iterate output operands of instruction
681 n = visitor.opr_count(LIR_OpVisitState::outputMode);
682 for (k = 0; k < n; k++) {
683 LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::outputMode, k);
684 assert(opr->is_register(), "visitor should only return register operands");
685
686 if (opr->is_virtual_register()) {
687 assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
688 reg = opr->vreg_number();
689 live_kill.set_bit(reg);
690 if (block->loop_index() >= 0) {
691 local_interval_in_loop.set_bit(reg, block->loop_index());
692 }
693 local_has_fpu_registers = local_has_fpu_registers || opr->is_virtual_fpu();
694 }
695
696 #ifdef ASSERT
697 // fixed intervals are never live at block boundaries, so
698 // they need not be processed in live sets
699 // process them only in debug mode so that this can be checked
700 if (!opr->is_virtual_register()) {
701 reg = reg_num(opr);
702 if (is_processed_reg_num(reg)) {
703 live_kill.set_bit(reg_num(opr));
704 }
705 reg = reg_numHi(opr);
706 if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
707 live_kill.set_bit(reg);
708 }
709 }
710 #endif
711 }
712 } // end of instruction iteration
713
714 block->set_live_gen (live_gen);
715 block->set_live_kill(live_kill);
716 block->set_live_in (ResourceBitMap(live_size));
717 block->set_live_out (ResourceBitMap(live_size));
718
719 TRACE_LINEAR_SCAN(4, tty->print("live_gen B%d ", block->block_id()); print_bitmap(block->live_gen()));
720 TRACE_LINEAR_SCAN(4, tty->print("live_kill B%d ", block->block_id()); print_bitmap(block->live_kill()));
721 } // end of block iteration
722
723 // propagate local calculated information into LinearScan object
724 _has_fpu_registers = local_has_fpu_registers;
725 compilation()->set_has_fpu_code(local_has_fpu_registers);
726
727 _num_calls = local_num_calls;
728 _interval_in_loop = local_interval_in_loop;
729 }
730
731
732 // ********** Phase 3: perform a backward dataflow analysis to compute global live sets
733 // (sets live_in and live_out for each block)
734
735 void LinearScan::compute_global_live_sets() {
736 TIME_LINEAR_SCAN(timer_compute_global_live_sets);
737
738 int num_blocks = block_count();
739 bool change_occurred;
740 bool change_occurred_in_block;
741 int iteration_count = 0;
742 ResourceBitMap live_out(live_set_size()); // scratch set for calculations
743
744 // Perform a backward dataflow analysis to compute live_out and live_in for each block.
745 // The loop is executed until a fixpoint is reached (no changes in an iteration)
746 // Exception handlers must be processed because not all live values are
747 // present in the state array, e.g. because of global value numbering
748 do {
749 change_occurred = false;
750
751 // iterate all blocks in reverse order
752 for (int i = num_blocks - 1; i >= 0; i--) {
753 BlockBegin* block = block_at(i);
754
755 change_occurred_in_block = false;
756
757 // live_out(block) is the union of live_in(sux), for successors sux of block
758 int n = block->number_of_sux();
759 int e = block->number_of_exception_handlers();
760 if (n + e > 0) {
761 // block has successors
762 if (n > 0) {
763 live_out.set_from(block->sux_at(0)->live_in());
764 for (int j = 1; j < n; j++) {
765 live_out.set_union(block->sux_at(j)->live_in());
766 }
767 } else {
768 live_out.clear();
769 }
770 for (int j = 0; j < e; j++) {
771 live_out.set_union(block->exception_handler_at(j)->live_in());
772 }
773
774 if (!block->live_out().is_same(live_out)) {
775 // A change occurred. Swap the old and new live out sets to avoid copying.
776 ResourceBitMap temp = block->live_out();
777 block->set_live_out(live_out);
778 live_out = temp;
779
780 change_occurred = true;
781 change_occurred_in_block = true;
782 }
783 }
784
785 if (iteration_count == 0 || change_occurred_in_block) {
786 // live_in(block) is the union of live_gen(block) with (live_out(block) & !live_kill(block))
787 // note: live_in has to be computed only in first iteration or if live_out has changed!
788 ResourceBitMap live_in = block->live_in();
789 live_in.set_from(block->live_out());
790 live_in.set_difference(block->live_kill());
791 live_in.set_union(block->live_gen());
792 }
793
794 #ifdef ASSERT
795 if (TraceLinearScanLevel >= 4) {
796 char c = ' ';
797 if (iteration_count == 0 || change_occurred_in_block) {
798 c = '*';
799 }
800 tty->print("(%d) live_in%c B%d ", iteration_count, c, block->block_id()); print_bitmap(block->live_in());
801 tty->print("(%d) live_out%c B%d ", iteration_count, c, block->block_id()); print_bitmap(block->live_out());
802 }
803 #endif
804 }
805 iteration_count++;
806
807 if (change_occurred && iteration_count > 50) {
808 BAILOUT("too many iterations in compute_global_live_sets");
809 }
810 } while (change_occurred);
811
812
813 #ifdef ASSERT
814 // check that fixed intervals are not live at block boundaries
815 // (live set must be empty at fixed intervals)
816 for (int i = 0; i < num_blocks; i++) {
817 BlockBegin* block = block_at(i);
818 for (int j = 0; j < LIR_Opr::vreg_base; j++) {
819 assert(block->live_in().at(j) == false, "live_in set of fixed register must be empty");
820 assert(block->live_out().at(j) == false, "live_out set of fixed register must be empty");
821 assert(block->live_gen().at(j) == false, "live_gen set of fixed register must be empty");
822 }
823 }
824 #endif
825
826 // check that the live_in set of the first block is empty
827 ResourceBitMap live_in_args(ir()->start()->live_in().size());
828 if (!ir()->start()->live_in().is_same(live_in_args)) {
829 #ifdef ASSERT
830 tty->print_cr("Error: live_in set of first block must be empty (when this fails, virtual registers are used before they are defined)");
831 tty->print_cr("affected registers:");
832 print_bitmap(ir()->start()->live_in());
833
834 // print some additional information to simplify debugging
835 for (unsigned int i = 0; i < ir()->start()->live_in().size(); i++) {
836 if (ir()->start()->live_in().at(i)) {
837 Instruction* instr = gen()->instruction_for_vreg(i);
838 tty->print_cr("* vreg %d (HIR instruction %c%d)", i, instr == nullptr ? ' ' : instr->type()->tchar(), instr == nullptr ? 0 : instr->id());
839
840 for (int j = 0; j < num_blocks; j++) {
841 BlockBegin* block = block_at(j);
842 if (block->live_gen().at(i)) {
843 tty->print_cr(" used in block B%d", block->block_id());
844 }
845 if (block->live_kill().at(i)) {
846 tty->print_cr(" defined in block B%d", block->block_id());
847 }
848 }
849 }
850 }
851
852 #endif
853 // when this fails, virtual registers are used before they are defined.
854 assert(false, "live_in set of first block must be empty");
855 // bailout of if this occurs in product mode.
856 bailout("live_in set of first block not empty");
857 }
858 }
859
860
861 // ********** Phase 4: build intervals
862 // (fills the list _intervals)
863
864 void LinearScan::add_use(Value value, int from, int to, IntervalUseKind use_kind) {
865 assert(!value->type()->is_illegal(), "if this value is used by the interpreter it shouldn't be of indeterminate type");
866 LIR_Opr opr = value->operand();
867 Constant* con = value->as_Constant();
868
869 if ((con == nullptr || con->is_pinned()) && opr->is_register()) {
870 assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
871 add_use(opr, from, to, use_kind);
872 }
873 }
874
875
876 void LinearScan::add_def(LIR_Opr opr, int def_pos, IntervalUseKind use_kind) {
877 TRACE_LINEAR_SCAN(2, tty->print(" def "); opr->print(tty); tty->print_cr(" def_pos %d (%d)", def_pos, use_kind));
878 assert(opr->is_register(), "should not be called otherwise");
879
880 if (opr->is_virtual_register()) {
881 assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
882 add_def(opr->vreg_number(), def_pos, use_kind, opr->type_register());
883
884 } else {
885 int reg = reg_num(opr);
886 if (is_processed_reg_num(reg)) {
887 add_def(reg, def_pos, use_kind, opr->type_register());
888 }
889 reg = reg_numHi(opr);
890 if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
891 add_def(reg, def_pos, use_kind, opr->type_register());
892 }
893 }
894 }
895
896 void LinearScan::add_use(LIR_Opr opr, int from, int to, IntervalUseKind use_kind) {
897 TRACE_LINEAR_SCAN(2, tty->print(" use "); opr->print(tty); tty->print_cr(" from %d to %d (%d)", from, to, use_kind));
898 assert(opr->is_register(), "should not be called otherwise");
899
900 if (opr->is_virtual_register()) {
901 assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
902 add_use(opr->vreg_number(), from, to, use_kind, opr->type_register());
903
904 } else {
905 int reg = reg_num(opr);
906 if (is_processed_reg_num(reg)) {
907 add_use(reg, from, to, use_kind, opr->type_register());
908 }
909 reg = reg_numHi(opr);
910 if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
911 add_use(reg, from, to, use_kind, opr->type_register());
912 }
913 }
914 }
915
916 void LinearScan::add_temp(LIR_Opr opr, int temp_pos, IntervalUseKind use_kind) {
917 TRACE_LINEAR_SCAN(2, tty->print(" temp "); opr->print(tty); tty->print_cr(" temp_pos %d (%d)", temp_pos, use_kind));
918 assert(opr->is_register(), "should not be called otherwise");
919
920 if (opr->is_virtual_register()) {
921 assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
922 add_temp(opr->vreg_number(), temp_pos, use_kind, opr->type_register());
923
924 } else {
925 int reg = reg_num(opr);
926 if (is_processed_reg_num(reg)) {
927 add_temp(reg, temp_pos, use_kind, opr->type_register());
928 }
929 reg = reg_numHi(opr);
930 if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
931 add_temp(reg, temp_pos, use_kind, opr->type_register());
932 }
933 }
934 }
935
936
937 void LinearScan::add_def(int reg_num, int def_pos, IntervalUseKind use_kind, BasicType type) {
938 Interval* interval = interval_at(reg_num);
939 if (interval != nullptr) {
940 assert(interval->reg_num() == reg_num, "wrong interval");
941
942 if (type != T_ILLEGAL) {
943 interval->set_type(type);
944 }
945
946 Range* r = interval->first();
947 if (r->from() <= def_pos) {
948 // Update the starting point (when a range is first created for a use, its
949 // start is the beginning of the current block until a def is encountered.)
950 r->set_from(def_pos);
951 interval->add_use_pos(def_pos, use_kind);
952
953 } else {
954 // Dead value - make vacuous interval
955 // also add use_kind for dead intervals
956 interval->add_range(def_pos, def_pos + 1);
957 interval->add_use_pos(def_pos, use_kind);
958 TRACE_LINEAR_SCAN(2, tty->print_cr("Warning: def of reg %d at %d occurs without use", reg_num, def_pos));
959 }
960
961 } else {
962 // Dead value - make vacuous interval
963 // also add use_kind for dead intervals
964 interval = create_interval(reg_num);
965 if (type != T_ILLEGAL) {
966 interval->set_type(type);
967 }
968
969 interval->add_range(def_pos, def_pos + 1);
970 interval->add_use_pos(def_pos, use_kind);
971 TRACE_LINEAR_SCAN(2, tty->print_cr("Warning: dead value %d at %d in live intervals", reg_num, def_pos));
972 }
973
974 change_spill_definition_pos(interval, def_pos);
975 if (use_kind == noUse && interval->spill_state() <= startInMemory) {
976 // detection of method-parameters and roundfp-results
977 // TODO: move this directly to position where use-kind is computed
978 interval->set_spill_state(startInMemory);
979 }
980 }
981
982 void LinearScan::add_use(int reg_num, int from, int to, IntervalUseKind use_kind, BasicType type) {
983 Interval* interval = interval_at(reg_num);
984 if (interval == nullptr) {
985 interval = create_interval(reg_num);
986 }
987 assert(interval->reg_num() == reg_num, "wrong interval");
988
989 if (type != T_ILLEGAL) {
990 interval->set_type(type);
991 }
992
993 interval->add_range(from, to);
994 interval->add_use_pos(to, use_kind);
995 }
996
997 void LinearScan::add_temp(int reg_num, int temp_pos, IntervalUseKind use_kind, BasicType type) {
998 Interval* interval = interval_at(reg_num);
999 if (interval == nullptr) {
1000 interval = create_interval(reg_num);
1001 }
1002 assert(interval->reg_num() == reg_num, "wrong interval");
1003
1004 if (type != T_ILLEGAL) {
1005 interval->set_type(type);
1006 }
1007
1008 interval->add_range(temp_pos, temp_pos + 1);
1009 interval->add_use_pos(temp_pos, use_kind);
1010 }
1011
1012
1013 // the results of this functions are used for optimizing spilling and reloading
1014 // if the functions return shouldHaveRegister and the interval is spilled,
1015 // it is not reloaded to a register.
1016 IntervalUseKind LinearScan::use_kind_of_output_operand(LIR_Op* op, LIR_Opr opr) {
1017 if (op->code() == lir_move) {
1018 assert(op->as_Op1() != nullptr, "lir_move must be LIR_Op1");
1019 LIR_Op1* move = (LIR_Op1*)op;
1020 LIR_Opr res = move->result_opr();
1021 bool result_in_memory = res->is_virtual() && gen()->is_vreg_flag_set(res->vreg_number(), LIRGenerator::must_start_in_memory);
1022
1023 if (result_in_memory) {
1024 // Begin of an interval with must_start_in_memory set.
1025 // This interval will always get a stack slot first, so return noUse.
1026 return noUse;
1027
1028 } else if (move->in_opr()->is_stack()) {
1029 // method argument (condition must be equal to handle_method_arguments)
1030 return noUse;
1031
1032 } else if (move->in_opr()->is_register() && move->result_opr()->is_register()) {
1033 // Move from register to register
1034 if (block_of_op_with_id(op->id())->is_set(BlockBegin::osr_entry_flag)) {
1035 // special handling of phi-function moves inside osr-entry blocks
1036 // input operand must have a register instead of output operand (leads to better register allocation)
1037 return shouldHaveRegister;
1038 }
1039 }
1040 }
1041
1042 if (opr->is_virtual() &&
1043 gen()->is_vreg_flag_set(opr->vreg_number(), LIRGenerator::must_start_in_memory)) {
1044 // result is a stack-slot, so prevent immediate reloading
1045 return noUse;
1046 }
1047
1048 // all other operands require a register
1049 return mustHaveRegister;
1050 }
1051
1052 IntervalUseKind LinearScan::use_kind_of_input_operand(LIR_Op* op, LIR_Opr opr) {
1053 if (op->code() == lir_move) {
1054 assert(op->as_Op1() != nullptr, "lir_move must be LIR_Op1");
1055 LIR_Op1* move = (LIR_Op1*)op;
1056 LIR_Opr res = move->result_opr();
1057 bool result_in_memory = res->is_virtual() && gen()->is_vreg_flag_set(res->vreg_number(), LIRGenerator::must_start_in_memory);
1058
1059 if (result_in_memory) {
1060 // Move to an interval with must_start_in_memory set.
1061 // To avoid moves from stack to stack (not allowed) force the input operand to a register
1062 return mustHaveRegister;
1063
1064 } else if (move->in_opr()->is_register() && move->result_opr()->is_register()) {
1065 // Move from register to register
1066 if (block_of_op_with_id(op->id())->is_set(BlockBegin::osr_entry_flag)) {
1067 // special handling of phi-function moves inside osr-entry blocks
1068 // input operand must have a register instead of output operand (leads to better register allocation)
1069 return mustHaveRegister;
1070 }
1071
1072 // The input operand is not forced to a register (moves from stack to register are allowed),
1073 // but it is faster if the input operand is in a register
1074 return shouldHaveRegister;
1075 }
1076 }
1077
1078
1079 #if defined(X86) || defined(S390)
1080 if (op->code() == lir_cmove) {
1081 // conditional moves can handle stack operands
1082 assert(op->result_opr()->is_register(), "result must always be in a register");
1083 return shouldHaveRegister;
1084 }
1085
1086 // optimizations for second input operand of arithmehtic operations on Intel
1087 // this operand is allowed to be on the stack in some cases
1088 BasicType opr_type = opr->type_register();
1089 if (opr_type == T_FLOAT || opr_type == T_DOUBLE) {
1090 // SSE float instruction
1091 switch (op->code()) {
1092 case lir_cmp:
1093 case lir_add:
1094 case lir_sub:
1095 case lir_mul:
1096 case lir_div:
1097 {
1098 assert(op->as_Op2() != nullptr, "must be LIR_Op2");
1099 LIR_Op2* op2 = (LIR_Op2*)op;
1100 if (op2->in_opr1() != op2->in_opr2() && op2->in_opr2() == opr) {
1101 assert((op2->result_opr()->is_register() || op->code() == lir_cmp) && op2->in_opr1()->is_register(), "cannot mark second operand as stack if others are not in register");
1102 return shouldHaveRegister;
1103 }
1104 }
1105 default:
1106 break;
1107 }
1108 // We want to sometimes use logical operations on pointers, in particular in GC barriers.
1109 // Since 64bit logical operations do not current support operands on stack, we have to make sure
1110 // T_OBJECT doesn't get spilled along with T_LONG.
1111 } else if (opr_type != T_LONG LP64_ONLY(&& opr_type != T_OBJECT)) {
1112 // integer instruction (note: long operands must always be in register)
1113 switch (op->code()) {
1114 case lir_cmp:
1115 case lir_add:
1116 case lir_sub:
1117 case lir_logic_and:
1118 case lir_logic_or:
1119 case lir_logic_xor:
1120 {
1121 assert(op->as_Op2() != nullptr, "must be LIR_Op2");
1122 LIR_Op2* op2 = (LIR_Op2*)op;
1123 if (op2->in_opr1() != op2->in_opr2() && op2->in_opr2() == opr) {
1124 assert((op2->result_opr()->is_register() || op->code() == lir_cmp) && op2->in_opr1()->is_register(), "cannot mark second operand as stack if others are not in register");
1125 return shouldHaveRegister;
1126 }
1127 }
1128 default:
1129 break;
1130 }
1131 }
1132 #endif // X86 || S390
1133
1134 // all other operands require a register
1135 return mustHaveRegister;
1136 }
1137
1138
1139 void LinearScan::handle_method_arguments(LIR_Op* op) {
1140 // special handling for method arguments (moves from stack to virtual register):
1141 // the interval gets no register assigned, but the stack slot.
1142 // it is split before the first use by the register allocator.
1143
1144 if (op->code() == lir_move) {
1145 assert(op->as_Op1() != nullptr, "must be LIR_Op1");
1146 LIR_Op1* move = (LIR_Op1*)op;
1147
1148 if (move->in_opr()->is_stack()) {
1149 #ifdef ASSERT
1150 int arg_size = compilation()->method()->arg_size();
1151 LIR_Opr o = move->in_opr();
1152 if (o->is_single_stack()) {
1153 assert(o->single_stack_ix() >= 0 && o->single_stack_ix() < arg_size, "out of range");
1154 } else if (o->is_double_stack()) {
1155 assert(o->double_stack_ix() >= 0 && o->double_stack_ix() < arg_size, "out of range");
1156 } else {
1157 ShouldNotReachHere();
1158 }
1159
1160 assert(move->id() > 0, "invalid id");
1161 assert(block_of_op_with_id(move->id())->number_of_preds() == 0, "move from stack must be in first block");
1162 assert(move->result_opr()->is_virtual(), "result of move must be a virtual register");
1163
1164 TRACE_LINEAR_SCAN(4, tty->print_cr("found move from stack slot %d to vreg %d", o->is_single_stack() ? o->single_stack_ix() : o->double_stack_ix(), reg_num(move->result_opr())));
1165 #endif
1166
1167 Interval* interval = interval_at(reg_num(move->result_opr()));
1168
1169 int stack_slot = LinearScan::nof_regs + (move->in_opr()->is_single_stack() ? move->in_opr()->single_stack_ix() : move->in_opr()->double_stack_ix());
1170 interval->set_canonical_spill_slot(stack_slot);
1171 interval->assign_reg(stack_slot);
1172 }
1173 }
1174 }
1175
1176 void LinearScan::handle_doubleword_moves(LIR_Op* op) {
1177 // special handling for doubleword move from memory to register:
1178 // in this case the registers of the input address and the result
1179 // registers must not overlap -> add a temp range for the input registers
1180 if (op->code() == lir_move) {
1181 assert(op->as_Op1() != nullptr, "must be LIR_Op1");
1182 LIR_Op1* move = (LIR_Op1*)op;
1183
1184 if (move->result_opr()->is_double_cpu() && move->in_opr()->is_pointer()) {
1185 LIR_Address* address = move->in_opr()->as_address_ptr();
1186 if (address != nullptr) {
1187 if (address->base()->is_valid()) {
1188 add_temp(address->base(), op->id(), noUse);
1189 }
1190 if (address->index()->is_valid()) {
1191 add_temp(address->index(), op->id(), noUse);
1192 }
1193 }
1194 }
1195 }
1196 }
1197
1198 void LinearScan::add_register_hints(LIR_Op* op) {
1199 switch (op->code()) {
1200 case lir_move: // fall through
1201 case lir_convert: {
1202 assert(op->as_Op1() != nullptr, "lir_move, lir_convert must be LIR_Op1");
1203 LIR_Op1* move = (LIR_Op1*)op;
1204
1205 LIR_Opr move_from = move->in_opr();
1206 LIR_Opr move_to = move->result_opr();
1207
1208 if (move_to->is_register() && move_from->is_register()) {
1209 Interval* from = interval_at(reg_num(move_from));
1210 Interval* to = interval_at(reg_num(move_to));
1211 if (from != nullptr && to != nullptr) {
1212 to->set_register_hint(from);
1213 TRACE_LINEAR_SCAN(4, tty->print_cr("operation at op_id %d: added hint from interval %d to %d", move->id(), from->reg_num(), to->reg_num()));
1214 }
1215 }
1216 break;
1217 }
1218 case lir_cmove: {
1219 assert(op->as_Op4() != nullptr, "lir_cmove must be LIR_Op4");
1220 LIR_Op4* cmove = (LIR_Op4*)op;
1221
1222 LIR_Opr move_from = cmove->in_opr1();
1223 LIR_Opr move_to = cmove->result_opr();
1224
1225 if (move_to->is_register() && move_from->is_register()) {
1226 Interval* from = interval_at(reg_num(move_from));
1227 Interval* to = interval_at(reg_num(move_to));
1228 if (from != nullptr && to != nullptr) {
1229 to->set_register_hint(from);
1230 TRACE_LINEAR_SCAN(4, tty->print_cr("operation at op_id %d: added hint from interval %d to %d", cmove->id(), from->reg_num(), to->reg_num()));
1231 }
1232 }
1233 break;
1234 }
1235 default:
1236 break;
1237 }
1238 }
1239
1240
1241 void LinearScan::build_intervals() {
1242 TIME_LINEAR_SCAN(timer_build_intervals);
1243
1244 // initialize interval list with expected number of intervals
1245 // (32 is added to have some space for split children without having to resize the list)
1246 _intervals = IntervalList(num_virtual_regs() + 32);
1247 // initialize all slots that are used by build_intervals
1248 _intervals.at_put_grow(num_virtual_regs() - 1, nullptr, nullptr);
1249
1250 // create a list with all caller-save registers (cpu, fpu, xmm)
1251 // when an instruction is a call, a temp range is created for all these registers
1252 int num_caller_save_registers = 0;
1253 int caller_save_registers[LinearScan::nof_regs];
1254
1255 int i;
1256 for (i = 0; i < FrameMap::nof_caller_save_cpu_regs(); i++) {
1257 LIR_Opr opr = FrameMap::caller_save_cpu_reg_at(i);
1258 assert(opr->is_valid() && opr->is_register(), "FrameMap should not return invalid operands");
1259 assert(reg_numHi(opr) == -1, "missing addition of range for hi-register");
1260 caller_save_registers[num_caller_save_registers++] = reg_num(opr);
1261 }
1262
1263 // temp ranges for fpu registers are only created when the method has
1264 // virtual fpu operands. Otherwise no allocation for fpu registers is
1265 // performed and so the temp ranges would be useless
1266 if (has_fpu_registers()) {
1267 #ifndef X86
1268 for (i = 0; i < FrameMap::nof_caller_save_fpu_regs; i++) {
1269 LIR_Opr opr = FrameMap::caller_save_fpu_reg_at(i);
1270 assert(opr->is_valid() && opr->is_register(), "FrameMap should not return invalid operands");
1271 assert(reg_numHi(opr) == -1, "missing addition of range for hi-register");
1272 caller_save_registers[num_caller_save_registers++] = reg_num(opr);
1273 }
1274 #else
1275 int num_caller_save_xmm_regs = FrameMap::get_num_caller_save_xmms();
1276 for (i = 0; i < num_caller_save_xmm_regs; i ++) {
1277 LIR_Opr opr = FrameMap::caller_save_xmm_reg_at(i);
1278 assert(opr->is_valid() && opr->is_register(), "FrameMap should not return invalid operands");
1279 assert(reg_numHi(opr) == -1, "missing addition of range for hi-register");
1280 caller_save_registers[num_caller_save_registers++] = reg_num(opr);
1281 }
1282 #endif // X86
1283 }
1284 assert(num_caller_save_registers <= LinearScan::nof_regs, "out of bounds");
1285
1286
1287 LIR_OpVisitState visitor;
1288
1289 // iterate all blocks in reverse order
1290 for (i = block_count() - 1; i >= 0; i--) {
1291 BlockBegin* block = block_at(i);
1292 LIR_OpList* instructions = block->lir()->instructions_list();
1293 int block_from = block->first_lir_instruction_id();
1294 int block_to = block->last_lir_instruction_id();
1295
1296 assert(block_from == instructions->at(0)->id(), "must be");
1297 assert(block_to == instructions->at(instructions->length() - 1)->id(), "must be");
1298
1299 // Update intervals for registers live at the end of this block;
1300 ResourceBitMap& live = block->live_out();
1301 auto updater = [&](BitMap::idx_t index) {
1302 int number = static_cast<int>(index);
1303 assert(number >= LIR_Opr::vreg_base, "fixed intervals must not be live on block bounds");
1304 TRACE_LINEAR_SCAN(2, tty->print_cr("live in %d to %d", number, block_to + 2));
1305
1306 add_use(number, block_from, block_to + 2, noUse, T_ILLEGAL);
1307
1308 // add special use positions for loop-end blocks when the
1309 // interval is used anywhere inside this loop. It's possible
1310 // that the block was part of a non-natural loop, so it might
1311 // have an invalid loop index.
1312 if (block->is_set(BlockBegin::linear_scan_loop_end_flag) &&
1313 block->loop_index() != -1 &&
1314 is_interval_in_loop(number, block->loop_index())) {
1315 interval_at(number)->add_use_pos(block_to + 1, loopEndMarker);
1316 }
1317 };
1318 live.iterate(updater);
1319
1320 // iterate all instructions of the block in reverse order.
1321 // skip the first instruction because it is always a label
1322 // definitions of intervals are processed before uses
1323 assert(visitor.no_operands(instructions->at(0)), "first operation must always be a label");
1324 for (int j = instructions->length() - 1; j >= 1; j--) {
1325 LIR_Op* op = instructions->at(j);
1326 int op_id = op->id();
1327
1328 // visit operation to collect all operands
1329 visitor.visit(op);
1330
1331 // add a temp range for each register if operation destroys caller-save registers
1332 if (visitor.has_call()) {
1333 for (int k = 0; k < num_caller_save_registers; k++) {
1334 add_temp(caller_save_registers[k], op_id, noUse, T_ILLEGAL);
1335 }
1336 TRACE_LINEAR_SCAN(4, tty->print_cr("operation destroys all caller-save registers"));
1337 }
1338
1339 // Add any platform dependent temps
1340 pd_add_temps(op);
1341
1342 // visit definitions (output and temp operands)
1343 int k, n;
1344 n = visitor.opr_count(LIR_OpVisitState::outputMode);
1345 for (k = 0; k < n; k++) {
1346 LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::outputMode, k);
1347 assert(opr->is_register(), "visitor should only return register operands");
1348 add_def(opr, op_id, use_kind_of_output_operand(op, opr));
1349 }
1350
1351 n = visitor.opr_count(LIR_OpVisitState::tempMode);
1352 for (k = 0; k < n; k++) {
1353 LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::tempMode, k);
1354 assert(opr->is_register(), "visitor should only return register operands");
1355 add_temp(opr, op_id, mustHaveRegister);
1356 }
1357
1358 // visit uses (input operands)
1359 n = visitor.opr_count(LIR_OpVisitState::inputMode);
1360 for (k = 0; k < n; k++) {
1361 LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::inputMode, k);
1362 assert(opr->is_register(), "visitor should only return register operands");
1363 add_use(opr, block_from, op_id, use_kind_of_input_operand(op, opr));
1364 }
1365
1366 // Add uses of live locals from interpreter's point of view for proper
1367 // debug information generation
1368 // Treat these operands as temp values (if the life range is extended
1369 // to a call site, the value would be in a register at the call otherwise)
1370 n = visitor.info_count();
1371 for (k = 0; k < n; k++) {
1372 CodeEmitInfo* info = visitor.info_at(k);
1373 ValueStack* stack = info->stack();
1374 for_each_state_value(stack, value,
1375 add_use(value, block_from, op_id + 1, noUse);
1376 );
1377 }
1378
1379 // special steps for some instructions (especially moves)
1380 handle_method_arguments(op);
1381 handle_doubleword_moves(op);
1382 add_register_hints(op);
1383
1384 } // end of instruction iteration
1385 } // end of block iteration
1386
1387
1388 // add the range [0, 1[ to all fixed intervals
1389 // -> the register allocator need not handle unhandled fixed intervals
1390 for (int n = 0; n < LinearScan::nof_regs; n++) {
1391 Interval* interval = interval_at(n);
1392 if (interval != nullptr) {
1393 interval->add_range(0, 1);
1394 }
1395 }
1396 }
1397
1398
1399 // ********** Phase 5: actual register allocation
1400
1401 int LinearScan::interval_cmp(Interval** a, Interval** b) {
1402 if (*a != nullptr) {
1403 if (*b != nullptr) {
1404 return (*a)->from() - (*b)->from();
1405 } else {
1406 return -1;
1407 }
1408 } else {
1409 if (*b != nullptr) {
1410 return 1;
1411 } else {
1412 return 0;
1413 }
1414 }
1415 }
1416
1417 #ifdef ASSERT
1418 static int interval_cmp(Interval* const& l, Interval* const& r) {
1419 return l->from() - r->from();
1420 }
1421
1422 static bool find_interval(Interval* interval, IntervalArray* intervals) {
1423 bool found;
1424 int idx = intervals->find_sorted<Interval*, interval_cmp>(interval, found);
1425
1426 if (!found) {
1427 return false;
1428 }
1429
1430 int from = interval->from();
1431
1432 // The index we've found using binary search is pointing to an interval
1433 // that is defined in the same place as the interval we were looking for.
1434 // So now we have to look around that index and find exact interval.
1435 for (int i = idx; i >= 0; i--) {
1436 if (intervals->at(i) == interval) {
1437 return true;
1438 }
1439 if (intervals->at(i)->from() != from) {
1440 break;
1441 }
1442 }
1443
1444 for (int i = idx + 1; i < intervals->length(); i++) {
1445 if (intervals->at(i) == interval) {
1446 return true;
1447 }
1448 if (intervals->at(i)->from() != from) {
1449 break;
1450 }
1451 }
1452
1453 return false;
1454 }
1455
1456 bool LinearScan::is_sorted(IntervalArray* intervals) {
1457 int from = -1;
1458 int null_count = 0;
1459
1460 for (int i = 0; i < intervals->length(); i++) {
1461 Interval* it = intervals->at(i);
1462 if (it != nullptr) {
1463 assert(from <= it->from(), "Intervals are unordered");
1464 from = it->from();
1465 } else {
1466 null_count++;
1467 }
1468 }
1469
1470 assert(null_count == 0, "Sorted intervals should not contain nulls");
1471
1472 null_count = 0;
1473
1474 for (int i = 0; i < interval_count(); i++) {
1475 Interval* interval = interval_at(i);
1476 if (interval != nullptr) {
1477 assert(find_interval(interval, intervals), "Lists do not contain same intervals");
1478 } else {
1479 null_count++;
1480 }
1481 }
1482
1483 assert(interval_count() - null_count == intervals->length(),
1484 "Sorted list should contain the same amount of non-null intervals as unsorted list");
1485
1486 return true;
1487 }
1488 #endif
1489
1490 void LinearScan::add_to_list(Interval** first, Interval** prev, Interval* interval) {
1491 if (*prev != nullptr) {
1492 (*prev)->set_next(interval);
1493 } else {
1494 *first = interval;
1495 }
1496 *prev = interval;
1497 }
1498
1499 void LinearScan::create_unhandled_lists(Interval** list1, Interval** list2, bool (is_list1)(const Interval* i), bool (is_list2)(const Interval* i)) {
1500 assert(is_sorted(_sorted_intervals), "interval list is not sorted");
1501
1502 *list1 = *list2 = Interval::end();
1503
1504 Interval* list1_prev = nullptr;
1505 Interval* list2_prev = nullptr;
1506 Interval* v;
1507
1508 const int n = _sorted_intervals->length();
1509 for (int i = 0; i < n; i++) {
1510 v = _sorted_intervals->at(i);
1511 if (v == nullptr) continue;
1512
1513 if (is_list1(v)) {
1514 add_to_list(list1, &list1_prev, v);
1515 } else if (is_list2 == nullptr || is_list2(v)) {
1516 add_to_list(list2, &list2_prev, v);
1517 }
1518 }
1519
1520 if (list1_prev != nullptr) list1_prev->set_next(Interval::end());
1521 if (list2_prev != nullptr) list2_prev->set_next(Interval::end());
1522
1523 assert(list1_prev == nullptr || list1_prev->next() == Interval::end(), "linear list ends not with sentinel");
1524 assert(list2_prev == nullptr || list2_prev->next() == Interval::end(), "linear list ends not with sentinel");
1525 }
1526
1527
1528 void LinearScan::sort_intervals_before_allocation() {
1529 TIME_LINEAR_SCAN(timer_sort_intervals_before);
1530
1531 if (_needs_full_resort) {
1532 // There is no known reason why this should occur but just in case...
1533 assert(false, "should never occur");
1534 // Re-sort existing interval list because an Interval::from() has changed
1535 _sorted_intervals->sort(interval_cmp);
1536 _needs_full_resort = false;
1537 }
1538
1539 IntervalList* unsorted_list = &_intervals;
1540 int unsorted_len = unsorted_list->length();
1541 int sorted_len = 0;
1542 int unsorted_idx;
1543 int sorted_idx = 0;
1544 int sorted_from_max = -1;
1545
1546 // calc number of items for sorted list (sorted list must not contain null values)
1547 for (unsorted_idx = 0; unsorted_idx < unsorted_len; unsorted_idx++) {
1548 if (unsorted_list->at(unsorted_idx) != nullptr) {
1549 sorted_len++;
1550 }
1551 }
1552 IntervalArray* sorted_list = new IntervalArray(sorted_len, sorted_len, nullptr);
1553
1554 // special sorting algorithm: the original interval-list is almost sorted,
1555 // only some intervals are swapped. So this is much faster than a complete QuickSort
1556 for (unsorted_idx = 0; unsorted_idx < unsorted_len; unsorted_idx++) {
1557 Interval* cur_interval = unsorted_list->at(unsorted_idx);
1558
1559 if (cur_interval != nullptr) {
1560 int cur_from = cur_interval->from();
1561
1562 if (sorted_from_max <= cur_from) {
1563 sorted_list->at_put(sorted_idx++, cur_interval);
1564 sorted_from_max = cur_interval->from();
1565 } else {
1566 // the assumption that the intervals are already sorted failed,
1567 // so this interval must be sorted in manually
1568 int j;
1569 for (j = sorted_idx - 1; j >= 0 && cur_from < sorted_list->at(j)->from(); j--) {
1570 sorted_list->at_put(j + 1, sorted_list->at(j));
1571 }
1572 sorted_list->at_put(j + 1, cur_interval);
1573 sorted_idx++;
1574 }
1575 }
1576 }
1577 _sorted_intervals = sorted_list;
1578 assert(is_sorted(_sorted_intervals), "intervals unsorted");
1579 }
1580
1581 void LinearScan::sort_intervals_after_allocation() {
1582 TIME_LINEAR_SCAN(timer_sort_intervals_after);
1583
1584 if (_needs_full_resort) {
1585 // Re-sort existing interval list because an Interval::from() has changed
1586 _sorted_intervals->sort(interval_cmp);
1587 _needs_full_resort = false;
1588 }
1589
1590 IntervalArray* old_list = _sorted_intervals;
1591 IntervalList* new_list = _new_intervals_from_allocation;
1592 int old_len = old_list->length();
1593 int new_len = new_list == nullptr ? 0 : new_list->length();
1594
1595 if (new_len == 0) {
1596 // no intervals have been added during allocation, so sorted list is already up to date
1597 assert(is_sorted(_sorted_intervals), "intervals unsorted");
1598 return;
1599 }
1600
1601 // conventional sort-algorithm for new intervals
1602 new_list->sort(interval_cmp);
1603
1604 // merge old and new list (both already sorted) into one combined list
1605 int combined_list_len = old_len + new_len;
1606 IntervalArray* combined_list = new IntervalArray(combined_list_len, combined_list_len, nullptr);
1607 int old_idx = 0;
1608 int new_idx = 0;
1609
1610 while (old_idx + new_idx < old_len + new_len) {
1611 if (new_idx >= new_len || (old_idx < old_len && old_list->at(old_idx)->from() <= new_list->at(new_idx)->from())) {
1612 combined_list->at_put(old_idx + new_idx, old_list->at(old_idx));
1613 old_idx++;
1614 } else {
1615 combined_list->at_put(old_idx + new_idx, new_list->at(new_idx));
1616 new_idx++;
1617 }
1618 }
1619
1620 _sorted_intervals = combined_list;
1621 assert(is_sorted(_sorted_intervals), "intervals unsorted");
1622 }
1623
1624
1625 void LinearScan::allocate_registers() {
1626 TIME_LINEAR_SCAN(timer_allocate_registers);
1627
1628 Interval* precolored_cpu_intervals, *not_precolored_cpu_intervals;
1629 Interval* precolored_fpu_intervals, *not_precolored_fpu_intervals;
1630
1631 // collect cpu intervals
1632 create_unhandled_lists(&precolored_cpu_intervals, ¬_precolored_cpu_intervals,
1633 is_precolored_cpu_interval, is_virtual_cpu_interval);
1634
1635 // collect fpu intervals
1636 create_unhandled_lists(&precolored_fpu_intervals, ¬_precolored_fpu_intervals,
1637 is_precolored_fpu_interval, is_virtual_fpu_interval);
1638 // this fpu interval collection cannot be moved down below with the allocation section as
1639 // the cpu_lsw.walk() changes interval positions.
1640
1641 if (!has_fpu_registers()) {
1642 #ifdef ASSERT
1643 assert(not_precolored_fpu_intervals == Interval::end(), "missed an uncolored fpu interval");
1644 #else
1645 if (not_precolored_fpu_intervals != Interval::end()) {
1646 BAILOUT("missed an uncolored fpu interval");
1647 }
1648 #endif
1649 }
1650
1651 // allocate cpu registers
1652 LinearScanWalker cpu_lsw(this, precolored_cpu_intervals, not_precolored_cpu_intervals);
1653 cpu_lsw.walk();
1654 cpu_lsw.finish_allocation();
1655
1656 if (has_fpu_registers()) {
1657 // allocate fpu registers
1658 LinearScanWalker fpu_lsw(this, precolored_fpu_intervals, not_precolored_fpu_intervals);
1659 fpu_lsw.walk();
1660 fpu_lsw.finish_allocation();
1661 }
1662 }
1663
1664
1665 // ********** Phase 6: resolve data flow
1666 // (insert moves at edges between blocks if intervals have been split)
1667
1668 // wrapper for Interval::split_child_at_op_id that performs a bailout in product mode
1669 // instead of returning null
1670 Interval* LinearScan::split_child_at_op_id(Interval* interval, int op_id, LIR_OpVisitState::OprMode mode) {
1671 Interval* result = interval->split_child_at_op_id(op_id, mode);
1672 if (result != nullptr) {
1673 return result;
1674 }
1675
1676 assert(false, "must find an interval, but do a clean bailout in product mode");
1677 result = new Interval(LIR_Opr::vreg_base);
1678 result->assign_reg(0);
1679 result->set_type(T_INT);
1680 BAILOUT_("LinearScan: interval is null", result);
1681 }
1682
1683
1684 Interval* LinearScan::interval_at_block_begin(BlockBegin* block, int reg_num) {
1685 assert(LinearScan::nof_regs <= reg_num && reg_num < num_virtual_regs(), "register number out of bounds");
1686 assert(interval_at(reg_num) != nullptr, "no interval found");
1687
1688 return split_child_at_op_id(interval_at(reg_num), block->first_lir_instruction_id(), LIR_OpVisitState::outputMode);
1689 }
1690
1691 Interval* LinearScan::interval_at_block_end(BlockBegin* block, int reg_num) {
1692 assert(LinearScan::nof_regs <= reg_num && reg_num < num_virtual_regs(), "register number out of bounds");
1693 assert(interval_at(reg_num) != nullptr, "no interval found");
1694
1695 return split_child_at_op_id(interval_at(reg_num), block->last_lir_instruction_id() + 1, LIR_OpVisitState::outputMode);
1696 }
1697
1698 Interval* LinearScan::interval_at_op_id(int reg_num, int op_id) {
1699 assert(LinearScan::nof_regs <= reg_num && reg_num < num_virtual_regs(), "register number out of bounds");
1700 assert(interval_at(reg_num) != nullptr, "no interval found");
1701
1702 return split_child_at_op_id(interval_at(reg_num), op_id, LIR_OpVisitState::inputMode);
1703 }
1704
1705
1706 void LinearScan::resolve_collect_mappings(BlockBegin* from_block, BlockBegin* to_block, MoveResolver &move_resolver) {
1707 DEBUG_ONLY(move_resolver.check_empty());
1708
1709 // visit all registers where the live_at_edge bit is set
1710 const ResourceBitMap& live_at_edge = to_block->live_in();
1711 auto visitor = [&](BitMap::idx_t index) {
1712 int r = static_cast<int>(index);
1713 assert(r < num_virtual_regs(), "live information set for not existing interval");
1714 assert(from_block->live_out().at(r) && to_block->live_in().at(r), "interval not live at this edge");
1715
1716 Interval* from_interval = interval_at_block_end(from_block, r);
1717 Interval* to_interval = interval_at_block_begin(to_block, r);
1718
1719 if (from_interval != to_interval && (from_interval->assigned_reg() != to_interval->assigned_reg() || from_interval->assigned_regHi() != to_interval->assigned_regHi())) {
1720 // need to insert move instruction
1721 move_resolver.add_mapping(from_interval, to_interval);
1722 }
1723 };
1724 live_at_edge.iterate(visitor, 0, live_set_size());
1725 }
1726
1727
1728 void LinearScan::resolve_find_insert_pos(BlockBegin* from_block, BlockBegin* to_block, MoveResolver &move_resolver) {
1729 if (from_block->number_of_sux() <= 1) {
1730 TRACE_LINEAR_SCAN(4, tty->print_cr("inserting moves at end of from_block B%d", from_block->block_id()));
1731
1732 LIR_OpList* instructions = from_block->lir()->instructions_list();
1733 LIR_OpBranch* branch = instructions->last()->as_OpBranch();
1734 if (branch != nullptr) {
1735 // insert moves before branch
1736 assert(branch->cond() == lir_cond_always, "block does not end with an unconditional jump");
1737 move_resolver.set_insert_position(from_block->lir(), instructions->length() - 2);
1738 } else {
1739 move_resolver.set_insert_position(from_block->lir(), instructions->length() - 1);
1740 }
1741
1742 } else {
1743 TRACE_LINEAR_SCAN(4, tty->print_cr("inserting moves at beginning of to_block B%d", to_block->block_id()));
1744 #ifdef ASSERT
1745 assert(from_block->lir()->instructions_list()->at(0)->as_OpLabel() != nullptr, "block does not start with a label");
1746
1747 // because the number of predecessor edges matches the number of
1748 // successor edges, blocks which are reached by switch statements
1749 // may have be more than one predecessor but it will be guaranteed
1750 // that all predecessors will be the same.
1751 for (int i = 0; i < to_block->number_of_preds(); i++) {
1752 assert(from_block == to_block->pred_at(i), "all critical edges must be broken");
1753 }
1754 #endif
1755
1756 move_resolver.set_insert_position(to_block->lir(), 0);
1757 }
1758 }
1759
1760
1761 // insert necessary moves (spilling or reloading) at edges between blocks if interval has been split
1762 void LinearScan::resolve_data_flow() {
1763 TIME_LINEAR_SCAN(timer_resolve_data_flow);
1764
1765 int num_blocks = block_count();
1766 MoveResolver move_resolver(this);
1767 ResourceBitMap block_completed(num_blocks);
1768 ResourceBitMap already_resolved(num_blocks);
1769
1770 int i;
1771 for (i = 0; i < num_blocks; i++) {
1772 BlockBegin* block = block_at(i);
1773
1774 // check if block has only one predecessor and only one successor
1775 if (block->number_of_preds() == 1 && block->number_of_sux() == 1 && block->number_of_exception_handlers() == 0) {
1776 LIR_OpList* instructions = block->lir()->instructions_list();
1777 assert(instructions->at(0)->code() == lir_label, "block must start with label");
1778 assert(instructions->last()->code() == lir_branch, "block with successors must end with branch");
1779 assert(instructions->last()->as_OpBranch()->cond() == lir_cond_always, "block with successor must end with unconditional branch");
1780
1781 // check if block is empty (only label and branch)
1782 if (instructions->length() == 2) {
1783 BlockBegin* pred = block->pred_at(0);
1784 BlockBegin* sux = block->sux_at(0);
1785
1786 // prevent optimization of two consecutive blocks
1787 if (!block_completed.at(pred->linear_scan_number()) && !block_completed.at(sux->linear_scan_number())) {
1788 TRACE_LINEAR_SCAN(3, tty->print_cr("**** optimizing empty block B%d (pred: B%d, sux: B%d)", block->block_id(), pred->block_id(), sux->block_id()));
1789 block_completed.set_bit(block->linear_scan_number());
1790
1791 // directly resolve between pred and sux (without looking at the empty block between)
1792 resolve_collect_mappings(pred, sux, move_resolver);
1793 if (move_resolver.has_mappings()) {
1794 move_resolver.set_insert_position(block->lir(), 0);
1795 move_resolver.resolve_and_append_moves();
1796 }
1797 }
1798 }
1799 }
1800 }
1801
1802
1803 for (i = 0; i < num_blocks; i++) {
1804 if (!block_completed.at(i)) {
1805 BlockBegin* from_block = block_at(i);
1806 already_resolved.set_from(block_completed);
1807
1808 int num_sux = from_block->number_of_sux();
1809 for (int s = 0; s < num_sux; s++) {
1810 BlockBegin* to_block = from_block->sux_at(s);
1811
1812 // check for duplicate edges between the same blocks (can happen with switch blocks)
1813 if (!already_resolved.at(to_block->linear_scan_number())) {
1814 TRACE_LINEAR_SCAN(3, tty->print_cr("**** processing edge between B%d and B%d", from_block->block_id(), to_block->block_id()));
1815 already_resolved.set_bit(to_block->linear_scan_number());
1816
1817 // collect all intervals that have been split between from_block and to_block
1818 resolve_collect_mappings(from_block, to_block, move_resolver);
1819 if (move_resolver.has_mappings()) {
1820 resolve_find_insert_pos(from_block, to_block, move_resolver);
1821 move_resolver.resolve_and_append_moves();
1822 }
1823 }
1824 }
1825 }
1826 }
1827 }
1828
1829
1830 void LinearScan::resolve_exception_entry(BlockBegin* block, int reg_num, MoveResolver &move_resolver) {
1831 if (interval_at(reg_num) == nullptr) {
1832 // if a phi function is never used, no interval is created -> ignore this
1833 return;
1834 }
1835
1836 Interval* interval = interval_at_block_begin(block, reg_num);
1837 int reg = interval->assigned_reg();
1838 int regHi = interval->assigned_regHi();
1839
1840 if ((reg < nof_regs && interval->always_in_memory())) {
1841 // the interval is split to get a short range that is located on the stack
1842 // in the following case:
1843 // * the interval started in memory (e.g. method parameter), but is currently in a register
1844 // this is an optimization for exception handling that reduces the number of moves that
1845 // are necessary for resolving the states when an exception uses this exception handler
1846
1847 // range that will be spilled to memory
1848 int from_op_id = block->first_lir_instruction_id();
1849 int to_op_id = from_op_id + 1; // short live range of length 1
1850 assert(interval->from() <= from_op_id && interval->to() >= to_op_id,
1851 "no split allowed between exception entry and first instruction");
1852
1853 if (interval->from() != from_op_id) {
1854 // the part before from_op_id is unchanged
1855 interval = interval->split(from_op_id);
1856 interval->assign_reg(reg, regHi);
1857 append_interval(interval);
1858 } else {
1859 _needs_full_resort = true;
1860 }
1861 assert(interval->from() == from_op_id, "must be true now");
1862
1863 Interval* spilled_part = interval;
1864 if (interval->to() != to_op_id) {
1865 // the part after to_op_id is unchanged
1866 spilled_part = interval->split_from_start(to_op_id);
1867 append_interval(spilled_part);
1868 move_resolver.add_mapping(spilled_part, interval);
1869 }
1870 assign_spill_slot(spilled_part);
1871
1872 assert(spilled_part->from() == from_op_id && spilled_part->to() == to_op_id, "just checking");
1873 }
1874 }
1875
1876 void LinearScan::resolve_exception_entry(BlockBegin* block, MoveResolver &move_resolver) {
1877 assert(block->is_set(BlockBegin::exception_entry_flag), "should not call otherwise");
1878 DEBUG_ONLY(move_resolver.check_empty());
1879
1880 // visit all registers where the live_in bit is set
1881 auto resolver = [&](BitMap::idx_t index) {
1882 int r = static_cast<int>(index);
1883 resolve_exception_entry(block, r, move_resolver);
1884 };
1885 block->live_in().iterate(resolver, 0, live_set_size());
1886
1887 // the live_in bits are not set for phi functions of the xhandler entry, so iterate them separately
1888 for_each_phi_fun(block, phi,
1889 if (!phi->is_illegal()) { resolve_exception_entry(block, phi->operand()->vreg_number(), move_resolver); }
1890 );
1891
1892 if (move_resolver.has_mappings()) {
1893 // insert moves after first instruction
1894 move_resolver.set_insert_position(block->lir(), 0);
1895 move_resolver.resolve_and_append_moves();
1896 }
1897 }
1898
1899
1900 void LinearScan::resolve_exception_edge(XHandler* handler, int throwing_op_id, int reg_num, Phi* phi, MoveResolver &move_resolver) {
1901 if (interval_at(reg_num) == nullptr) {
1902 // if a phi function is never used, no interval is created -> ignore this
1903 return;
1904 }
1905
1906 // the computation of to_interval is equal to resolve_collect_mappings,
1907 // but from_interval is more complicated because of phi functions
1908 BlockBegin* to_block = handler->entry_block();
1909 Interval* to_interval = interval_at_block_begin(to_block, reg_num);
1910
1911 if (phi != nullptr) {
1912 // phi function of the exception entry block
1913 // no moves are created for this phi function in the LIR_Generator, so the
1914 // interval at the throwing instruction must be searched using the operands
1915 // of the phi function
1916 Value from_value = phi->operand_at(handler->phi_operand());
1917 if (from_value == nullptr) {
1918 // We have reached here in a kotlin application running with JVMTI
1919 // capability "can_access_local_variables".
1920 // The illegal state is not yet propagated to this phi. Do it here.
1921 phi->make_illegal();
1922 // We can skip the illegal phi edge.
1923 return;
1924 }
1925
1926 // with phi functions it can happen that the same from_value is used in
1927 // multiple mappings, so notify move-resolver that this is allowed
1928 move_resolver.set_multiple_reads_allowed();
1929
1930 Constant* con = from_value->as_Constant();
1931 if (con != nullptr && (!con->is_pinned() || con->operand()->is_constant())) {
1932 // Need a mapping from constant to interval if unpinned (may have no register) or if the operand is a constant (no register).
1933 move_resolver.add_mapping(LIR_OprFact::value_type(con->type()), to_interval);
1934 } else {
1935 // search split child at the throwing op_id
1936 Interval* from_interval = interval_at_op_id(from_value->operand()->vreg_number(), throwing_op_id);
1937 move_resolver.add_mapping(from_interval, to_interval);
1938 }
1939 } else {
1940 // no phi function, so use reg_num also for from_interval
1941 // search split child at the throwing op_id
1942 Interval* from_interval = interval_at_op_id(reg_num, throwing_op_id);
1943 if (from_interval != to_interval) {
1944 // optimization to reduce number of moves: when to_interval is on stack and
1945 // the stack slot is known to be always correct, then no move is necessary
1946 if (!from_interval->always_in_memory() || from_interval->canonical_spill_slot() != to_interval->assigned_reg()) {
1947 move_resolver.add_mapping(from_interval, to_interval);
1948 }
1949 }
1950 }
1951 }
1952
1953 void LinearScan::resolve_exception_edge(XHandler* handler, int throwing_op_id, MoveResolver &move_resolver) {
1954 TRACE_LINEAR_SCAN(4, tty->print_cr("resolving exception handler B%d: throwing_op_id=%d", handler->entry_block()->block_id(), throwing_op_id));
1955
1956 DEBUG_ONLY(move_resolver.check_empty());
1957 assert(handler->lir_op_id() == -1, "already processed this xhandler");
1958 DEBUG_ONLY(handler->set_lir_op_id(throwing_op_id));
1959 assert(handler->entry_code() == nullptr, "code already present");
1960
1961 // visit all registers where the live_in bit is set
1962 BlockBegin* block = handler->entry_block();
1963 auto resolver = [&](BitMap::idx_t index) {
1964 int r = static_cast<int>(index);
1965 resolve_exception_edge(handler, throwing_op_id, r, nullptr, move_resolver);
1966 };
1967 block->live_in().iterate(resolver, 0, live_set_size());
1968
1969 // the live_in bits are not set for phi functions of the xhandler entry, so iterate them separately
1970 for_each_phi_fun(block, phi,
1971 if (!phi->is_illegal()) { resolve_exception_edge(handler, throwing_op_id, phi->operand()->vreg_number(), phi, move_resolver); }
1972 );
1973
1974 if (move_resolver.has_mappings()) {
1975 LIR_List* entry_code = new LIR_List(compilation());
1976 move_resolver.set_insert_position(entry_code, 0);
1977 move_resolver.resolve_and_append_moves();
1978
1979 entry_code->jump(handler->entry_block());
1980 handler->set_entry_code(entry_code);
1981 }
1982 }
1983
1984
1985 void LinearScan::resolve_exception_handlers() {
1986 MoveResolver move_resolver(this);
1987 LIR_OpVisitState visitor;
1988 int num_blocks = block_count();
1989
1990 int i;
1991 for (i = 0; i < num_blocks; i++) {
1992 BlockBegin* block = block_at(i);
1993 if (block->is_set(BlockBegin::exception_entry_flag)) {
1994 resolve_exception_entry(block, move_resolver);
1995 }
1996 }
1997
1998 for (i = 0; i < num_blocks; i++) {
1999 BlockBegin* block = block_at(i);
2000 LIR_List* ops = block->lir();
2001 int num_ops = ops->length();
2002
2003 // iterate all instructions of the block. skip the first because it is always a label
2004 assert(visitor.no_operands(ops->at(0)), "first operation must always be a label");
2005 for (int j = 1; j < num_ops; j++) {
2006 LIR_Op* op = ops->at(j);
2007 int op_id = op->id();
2008
2009 if (op_id != -1 && has_info(op_id)) {
2010 // visit operation to collect all operands
2011 visitor.visit(op);
2012 assert(visitor.info_count() > 0, "should not visit otherwise");
2013
2014 XHandlers* xhandlers = visitor.all_xhandler();
2015 int n = xhandlers->length();
2016 for (int k = 0; k < n; k++) {
2017 resolve_exception_edge(xhandlers->handler_at(k), op_id, move_resolver);
2018 }
2019
2020 #ifdef ASSERT
2021 } else {
2022 visitor.visit(op);
2023 assert(visitor.all_xhandler()->length() == 0, "missed exception handler");
2024 #endif
2025 }
2026 }
2027 }
2028 }
2029
2030
2031 // ********** Phase 7: assign register numbers back to LIR
2032 // (includes computation of debug information and oop maps)
2033
2034 VMReg LinearScan::vm_reg_for_interval(Interval* interval) {
2035 VMReg reg = interval->cached_vm_reg();
2036 if (!reg->is_valid() ) {
2037 reg = vm_reg_for_operand(operand_for_interval(interval));
2038 interval->set_cached_vm_reg(reg);
2039 }
2040 assert(reg == vm_reg_for_operand(operand_for_interval(interval)), "wrong cached value");
2041 return reg;
2042 }
2043
2044 VMReg LinearScan::vm_reg_for_operand(LIR_Opr opr) {
2045 assert(opr->is_oop(), "currently only implemented for oop operands");
2046 return frame_map()->regname(opr);
2047 }
2048
2049
2050 LIR_Opr LinearScan::operand_for_interval(Interval* interval) {
2051 LIR_Opr opr = interval->cached_opr();
2052 if (opr->is_illegal()) {
2053 opr = calc_operand_for_interval(interval);
2054 interval->set_cached_opr(opr);
2055 }
2056
2057 assert(opr == calc_operand_for_interval(interval), "wrong cached value");
2058 return opr;
2059 }
2060
2061 LIR_Opr LinearScan::calc_operand_for_interval(const Interval* interval) {
2062 int assigned_reg = interval->assigned_reg();
2063 BasicType type = interval->type();
2064
2065 if (assigned_reg >= nof_regs) {
2066 // stack slot
2067 assert(interval->assigned_regHi() == any_reg, "must not have hi register");
2068 return LIR_OprFact::stack(assigned_reg - nof_regs, type);
2069
2070 } else {
2071 // register
2072 switch (type) {
2073 case T_OBJECT: {
2074 assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");
2075 assert(interval->assigned_regHi() == any_reg, "must not have hi register");
2076 return LIR_OprFact::single_cpu_oop(assigned_reg);
2077 }
2078
2079 case T_ADDRESS: {
2080 assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");
2081 assert(interval->assigned_regHi() == any_reg, "must not have hi register");
2082 return LIR_OprFact::single_cpu_address(assigned_reg);
2083 }
2084
2085 case T_METADATA: {
2086 assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");
2087 assert(interval->assigned_regHi() == any_reg, "must not have hi register");
2088 return LIR_OprFact::single_cpu_metadata(assigned_reg);
2089 }
2090
2091 #ifdef __SOFTFP__
2092 case T_FLOAT: // fall through
2093 #endif // __SOFTFP__
2094 case T_INT: {
2095 assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");
2096 assert(interval->assigned_regHi() == any_reg, "must not have hi register");
2097 return LIR_OprFact::single_cpu(assigned_reg);
2098 }
2099
2100 #ifdef __SOFTFP__
2101 case T_DOUBLE: // fall through
2102 #endif // __SOFTFP__
2103 case T_LONG: {
2104 int assigned_regHi = interval->assigned_regHi();
2105 assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");
2106 assert(num_physical_regs(T_LONG) == 1 ||
2107 (assigned_regHi >= pd_first_cpu_reg && assigned_regHi <= pd_last_cpu_reg), "no cpu register");
2108
2109 assert(assigned_reg != assigned_regHi, "invalid allocation");
2110 assert(num_physical_regs(T_LONG) == 1 || assigned_reg < assigned_regHi,
2111 "register numbers must be sorted (ensure that e.g. a move from eax,ebx to ebx,eax can not occur)");
2112 assert((assigned_regHi != any_reg) ^ (num_physical_regs(T_LONG) == 1), "must be match");
2113 if (requires_adjacent_regs(T_LONG)) {
2114 assert(assigned_reg % 2 == 0 && assigned_reg + 1 == assigned_regHi, "must be sequential and even");
2115 }
2116
2117 #ifdef _LP64
2118 return LIR_OprFact::double_cpu(assigned_reg, assigned_reg);
2119 #else
2120 return LIR_OprFact::double_cpu(assigned_reg, assigned_regHi);
2121 #endif // LP64
2122 }
2123
2124 #ifndef __SOFTFP__
2125 case T_FLOAT: {
2126 #ifdef X86
2127 int last_xmm_reg = pd_last_xmm_reg;
2128 if (UseAVX < 3) {
2129 last_xmm_reg = pd_first_xmm_reg + (pd_nof_xmm_regs_frame_map / 2) - 1;
2130 }
2131 assert(assigned_reg >= pd_first_xmm_reg && assigned_reg <= last_xmm_reg, "no xmm register");
2132 assert(interval->assigned_regHi() == any_reg, "must not have hi register");
2133 return LIR_OprFact::single_xmm(assigned_reg - pd_first_xmm_reg);
2134 #else
2135 assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");
2136 assert(interval->assigned_regHi() == any_reg, "must not have hi register");
2137 return LIR_OprFact::single_fpu(assigned_reg - pd_first_fpu_reg);
2138 #endif // !X86
2139 }
2140
2141 case T_DOUBLE: {
2142 #if defined(X86)
2143 int last_xmm_reg = pd_last_xmm_reg;
2144 if (UseAVX < 3) {
2145 last_xmm_reg = pd_first_xmm_reg + (pd_nof_xmm_regs_frame_map / 2) - 1;
2146 }
2147 assert(assigned_reg >= pd_first_xmm_reg && assigned_reg <= last_xmm_reg, "no xmm register");
2148 assert(interval->assigned_regHi() == any_reg, "must not have hi register (double xmm values are stored in one register)");
2149 LIR_Opr result = LIR_OprFact::double_xmm(assigned_reg - pd_first_xmm_reg);
2150 #elif defined(ARM32)
2151 assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");
2152 assert(interval->assigned_regHi() >= pd_first_fpu_reg && interval->assigned_regHi() <= pd_last_fpu_reg, "no fpu register");
2153 assert(assigned_reg % 2 == 0 && assigned_reg + 1 == interval->assigned_regHi(), "must be sequential and even");
2154 LIR_Opr result = LIR_OprFact::double_fpu(assigned_reg - pd_first_fpu_reg, interval->assigned_regHi() - pd_first_fpu_reg);
2155 #else
2156 assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");
2157 assert(interval->assigned_regHi() == any_reg, "must not have hi register (double fpu values are stored in one register on Intel)");
2158 LIR_Opr result = LIR_OprFact::double_fpu(assigned_reg - pd_first_fpu_reg);
2159 #endif
2160 return result;
2161 }
2162 #endif // __SOFTFP__
2163
2164 default: {
2165 ShouldNotReachHere();
2166 return LIR_OprFact::illegalOpr;
2167 }
2168 }
2169 }
2170 }
2171
2172 LIR_Opr LinearScan::canonical_spill_opr(Interval* interval) {
2173 assert(interval->canonical_spill_slot() >= nof_regs, "canonical spill slot not set");
2174 return LIR_OprFact::stack(interval->canonical_spill_slot() - nof_regs, interval->type());
2175 }
2176
2177 LIR_Opr LinearScan::color_lir_opr(LIR_Opr opr, int op_id, LIR_OpVisitState::OprMode mode) {
2178 assert(opr->is_virtual(), "should not call this otherwise");
2179
2180 Interval* interval = interval_at(opr->vreg_number());
2181 assert(interval != nullptr, "interval must exist");
2182
2183 if (op_id != -1) {
2184 #ifdef ASSERT
2185 BlockBegin* block = block_of_op_with_id(op_id);
2186 if (block->number_of_sux() <= 1 && op_id == block->last_lir_instruction_id()) {
2187 // check if spill moves could have been appended at the end of this block, but
2188 // before the branch instruction. So the split child information for this branch would
2189 // be incorrect.
2190 LIR_OpBranch* branch = block->lir()->instructions_list()->last()->as_OpBranch();
2191 if (branch != nullptr) {
2192 if (block->live_out().at(opr->vreg_number())) {
2193 assert(branch->cond() == lir_cond_always, "block does not end with an unconditional jump");
2194 assert(false, "can't get split child for the last branch of a block because the information would be incorrect (moves are inserted before the branch in resolve_data_flow)");
2195 }
2196 }
2197 }
2198 #endif
2199
2200 // operands are not changed when an interval is split during allocation,
2201 // so search the right interval here
2202 interval = split_child_at_op_id(interval, op_id, mode);
2203 }
2204
2205 LIR_Opr res = operand_for_interval(interval);
2206
2207 #ifdef X86
2208 // new semantic for is_last_use: not only set on definite end of interval,
2209 // but also before hole
2210 // This may still miss some cases (e.g. for dead values), but it is not necessary that the
2211 // last use information is completely correct
2212 // information is only needed for fpu stack allocation
2213 if (res->is_fpu_register()) {
2214 if (opr->is_last_use() || op_id == interval->to() || (op_id != -1 && interval->has_hole_between(op_id, op_id + 1))) {
2215 assert(op_id == -1 || !is_block_begin(op_id), "holes at begin of block may also result from control flow");
2216 res = res->make_last_use();
2217 }
2218 }
2219 #endif
2220
2221 assert(!gen()->is_vreg_flag_set(opr->vreg_number(), LIRGenerator::callee_saved) || !FrameMap::is_caller_save_register(res), "bad allocation");
2222
2223 return res;
2224 }
2225
2226
2227 #ifdef ASSERT
2228 // some methods used to check correctness of debug information
2229
2230 void assert_no_register_values(GrowableArray<ScopeValue*>* values) {
2231 if (values == nullptr) {
2232 return;
2233 }
2234
2235 for (int i = 0; i < values->length(); i++) {
2236 ScopeValue* value = values->at(i);
2237
2238 if (value->is_location()) {
2239 Location location = ((LocationValue*)value)->location();
2240 assert(location.where() == Location::on_stack, "value is in register");
2241 }
2242 }
2243 }
2244
2245 void assert_no_register_values(GrowableArray<MonitorValue*>* values) {
2246 if (values == nullptr) {
2247 return;
2248 }
2249
2250 for (int i = 0; i < values->length(); i++) {
2251 MonitorValue* value = values->at(i);
2252
2253 if (value->owner()->is_location()) {
2254 Location location = ((LocationValue*)value->owner())->location();
2255 assert(location.where() == Location::on_stack, "owner is in register");
2256 }
2257 assert(value->basic_lock().where() == Location::on_stack, "basic_lock is in register");
2258 }
2259 }
2260
2261 static void assert_equal(Location l1, Location l2) {
2262 assert(l1.where() == l2.where() && l1.type() == l2.type() && l1.offset() == l2.offset(), "");
2263 }
2264
2265 static void assert_equal(ScopeValue* v1, ScopeValue* v2) {
2266 if (v1->is_location()) {
2267 assert(v2->is_location(), "");
2268 assert_equal(((LocationValue*)v1)->location(), ((LocationValue*)v2)->location());
2269 } else if (v1->is_constant_int()) {
2270 assert(v2->is_constant_int(), "");
2271 assert(((ConstantIntValue*)v1)->value() == ((ConstantIntValue*)v2)->value(), "");
2272 } else if (v1->is_constant_double()) {
2273 assert(v2->is_constant_double(), "");
2274 assert(((ConstantDoubleValue*)v1)->value() == ((ConstantDoubleValue*)v2)->value(), "");
2275 } else if (v1->is_constant_long()) {
2276 assert(v2->is_constant_long(), "");
2277 assert(((ConstantLongValue*)v1)->value() == ((ConstantLongValue*)v2)->value(), "");
2278 } else if (v1->is_constant_oop()) {
2279 assert(v2->is_constant_oop(), "");
2280 assert(((ConstantOopWriteValue*)v1)->value() == ((ConstantOopWriteValue*)v2)->value(), "");
2281 } else {
2282 ShouldNotReachHere();
2283 }
2284 }
2285
2286 static void assert_equal(MonitorValue* m1, MonitorValue* m2) {
2287 assert_equal(m1->owner(), m2->owner());
2288 assert_equal(m1->basic_lock(), m2->basic_lock());
2289 }
2290
2291 static void assert_equal(IRScopeDebugInfo* d1, IRScopeDebugInfo* d2) {
2292 assert(d1->scope() == d2->scope(), "not equal");
2293 assert(d1->bci() == d2->bci(), "not equal");
2294
2295 if (d1->locals() != nullptr) {
2296 assert(d1->locals() != nullptr && d2->locals() != nullptr, "not equal");
2297 assert(d1->locals()->length() == d2->locals()->length(), "not equal");
2298 for (int i = 0; i < d1->locals()->length(); i++) {
2299 assert_equal(d1->locals()->at(i), d2->locals()->at(i));
2300 }
2301 } else {
2302 assert(d1->locals() == nullptr && d2->locals() == nullptr, "not equal");
2303 }
2304
2305 if (d1->expressions() != nullptr) {
2306 assert(d1->expressions() != nullptr && d2->expressions() != nullptr, "not equal");
2307 assert(d1->expressions()->length() == d2->expressions()->length(), "not equal");
2308 for (int i = 0; i < d1->expressions()->length(); i++) {
2309 assert_equal(d1->expressions()->at(i), d2->expressions()->at(i));
2310 }
2311 } else {
2312 assert(d1->expressions() == nullptr && d2->expressions() == nullptr, "not equal");
2313 }
2314
2315 if (d1->monitors() != nullptr) {
2316 assert(d1->monitors() != nullptr && d2->monitors() != nullptr, "not equal");
2317 assert(d1->monitors()->length() == d2->monitors()->length(), "not equal");
2318 for (int i = 0; i < d1->monitors()->length(); i++) {
2319 assert_equal(d1->monitors()->at(i), d2->monitors()->at(i));
2320 }
2321 } else {
2322 assert(d1->monitors() == nullptr && d2->monitors() == nullptr, "not equal");
2323 }
2324
2325 if (d1->caller() != nullptr) {
2326 assert(d1->caller() != nullptr && d2->caller() != nullptr, "not equal");
2327 assert_equal(d1->caller(), d2->caller());
2328 } else {
2329 assert(d1->caller() == nullptr && d2->caller() == nullptr, "not equal");
2330 }
2331 }
2332
2333 static void check_stack_depth(CodeEmitInfo* info, int stack_end) {
2334 if (info->stack()->bci() != SynchronizationEntryBCI && !info->scope()->method()->is_native()) {
2335 Bytecodes::Code code = info->scope()->method()->java_code_at_bci(info->stack()->bci());
2336 switch (code) {
2337 case Bytecodes::_ifnull : // fall through
2338 case Bytecodes::_ifnonnull : // fall through
2339 case Bytecodes::_ifeq : // fall through
2340 case Bytecodes::_ifne : // fall through
2341 case Bytecodes::_iflt : // fall through
2342 case Bytecodes::_ifge : // fall through
2343 case Bytecodes::_ifgt : // fall through
2344 case Bytecodes::_ifle : // fall through
2345 case Bytecodes::_if_icmpeq : // fall through
2346 case Bytecodes::_if_icmpne : // fall through
2347 case Bytecodes::_if_icmplt : // fall through
2348 case Bytecodes::_if_icmpge : // fall through
2349 case Bytecodes::_if_icmpgt : // fall through
2350 case Bytecodes::_if_icmple : // fall through
2351 case Bytecodes::_if_acmpeq : // fall through
2352 case Bytecodes::_if_acmpne :
2353 assert(stack_end >= -Bytecodes::depth(code), "must have non-empty expression stack at if bytecode");
2354 break;
2355 default:
2356 break;
2357 }
2358 }
2359 }
2360
2361 #endif // ASSERT
2362
2363
2364 IntervalWalker* LinearScan::init_compute_oop_maps() {
2365 // setup lists of potential oops for walking
2366 Interval* oop_intervals;
2367 Interval* non_oop_intervals;
2368
2369 create_unhandled_lists(&oop_intervals, &non_oop_intervals, is_oop_interval, nullptr);
2370
2371 // intervals that have no oops inside need not to be processed
2372 // to ensure a walking until the last instruction id, add a dummy interval
2373 // with a high operation id
2374 non_oop_intervals = new Interval(any_reg);
2375 non_oop_intervals->add_range(max_jint - 2, max_jint - 1);
2376
2377 return new IntervalWalker(this, oop_intervals, non_oop_intervals);
2378 }
2379
2380
2381 OopMap* LinearScan::compute_oop_map(IntervalWalker* iw, LIR_Op* op, CodeEmitInfo* info, bool is_call_site) {
2382 TRACE_LINEAR_SCAN(3, tty->print_cr("creating oop map at op_id %d", op->id()));
2383
2384 // walk before the current operation -> intervals that start at
2385 // the operation (= output operands of the operation) are not
2386 // included in the oop map
2387 iw->walk_before(op->id());
2388
2389 int frame_size = frame_map()->framesize();
2390 int arg_count = frame_map()->oop_map_arg_count();
2391 OopMap* map = new OopMap(frame_size, arg_count);
2392
2393 // Iterate through active intervals
2394 for (Interval* interval = iw->active_first(fixedKind); interval != Interval::end(); interval = interval->next()) {
2395 int assigned_reg = interval->assigned_reg();
2396
2397 assert(interval->current_from() <= op->id() && op->id() <= interval->current_to(), "interval should not be active otherwise");
2398 assert(interval->assigned_regHi() == any_reg, "oop must be single word");
2399 assert(interval->reg_num() >= LIR_Opr::vreg_base, "fixed interval found");
2400
2401 // Check if this range covers the instruction. Intervals that
2402 // start or end at the current operation are not included in the
2403 // oop map, except in the case of patching moves. For patching
2404 // moves, any intervals which end at this instruction are included
2405 // in the oop map since we may safepoint while doing the patch
2406 // before we've consumed the inputs.
2407 if (op->is_patching() || op->id() < interval->current_to()) {
2408
2409 // caller-save registers must not be included into oop-maps at calls
2410 assert(!is_call_site || assigned_reg >= nof_regs || !is_caller_save(assigned_reg), "interval is in a caller-save register at a call -> register will be overwritten");
2411
2412 VMReg name = vm_reg_for_interval(interval);
2413 set_oop(map, name);
2414
2415 // Spill optimization: when the stack value is guaranteed to be always correct,
2416 // then it must be added to the oop map even if the interval is currently in a register
2417 if (interval->always_in_memory() &&
2418 op->id() > interval->spill_definition_pos() &&
2419 interval->assigned_reg() != interval->canonical_spill_slot()) {
2420 assert(interval->spill_definition_pos() > 0, "position not set correctly");
2421 assert(interval->canonical_spill_slot() >= LinearScan::nof_regs, "no spill slot assigned");
2422 assert(interval->assigned_reg() < LinearScan::nof_regs, "interval is on stack, so stack slot is registered twice");
2423
2424 set_oop(map, frame_map()->slot_regname(interval->canonical_spill_slot() - LinearScan::nof_regs));
2425 }
2426 }
2427 }
2428
2429 // add oops from lock stack
2430 assert(info->stack() != nullptr, "CodeEmitInfo must always have a stack");
2431 int locks_count = info->stack()->total_locks_size();
2432 for (int i = 0; i < locks_count; i++) {
2433 set_oop(map, frame_map()->monitor_object_regname(i));
2434 }
2435
2436 return map;
2437 }
2438
2439
2440 void LinearScan::compute_oop_map(IntervalWalker* iw, const LIR_OpVisitState &visitor, LIR_Op* op) {
2441 assert(visitor.info_count() > 0, "no oop map needed");
2442
2443 // compute oop_map only for first CodeEmitInfo
2444 // because it is (in most cases) equal for all other infos of the same operation
2445 CodeEmitInfo* first_info = visitor.info_at(0);
2446 OopMap* first_oop_map = compute_oop_map(iw, op, first_info, visitor.has_call());
2447
2448 for (int i = 0; i < visitor.info_count(); i++) {
2449 CodeEmitInfo* info = visitor.info_at(i);
2450 OopMap* oop_map = first_oop_map;
2451
2452 // compute worst case interpreter size in case of a deoptimization
2453 _compilation->update_interpreter_frame_size(info->interpreter_frame_size());
2454
2455 if (info->stack()->locks_size() != first_info->stack()->locks_size()) {
2456 // this info has a different number of locks then the precomputed oop map
2457 // (possible for lock and unlock instructions) -> compute oop map with
2458 // correct lock information
2459 oop_map = compute_oop_map(iw, op, info, visitor.has_call());
2460 }
2461
2462 if (info->_oop_map == nullptr) {
2463 info->_oop_map = oop_map;
2464 } else {
2465 // a CodeEmitInfo can not be shared between different LIR-instructions
2466 // because interval splitting can occur anywhere between two instructions
2467 // and so the oop maps must be different
2468 // -> check if the already set oop_map is exactly the one calculated for this operation
2469 assert(info->_oop_map == oop_map, "same CodeEmitInfo used for multiple LIR instructions");
2470 }
2471 }
2472 }
2473
2474
2475 // frequently used constants
2476 // Allocate them with new so they are never destroyed (otherwise, a
2477 // forced exit could destroy these objects while they are still in
2478 // use).
2479 ConstantOopWriteValue* LinearScan::_oop_null_scope_value = new (mtCompiler) ConstantOopWriteValue(nullptr);
2480 ConstantIntValue* LinearScan::_int_m1_scope_value = new (mtCompiler) ConstantIntValue(-1);
2481 ConstantIntValue* LinearScan::_int_0_scope_value = new (mtCompiler) ConstantIntValue((jint)0);
2482 ConstantIntValue* LinearScan::_int_1_scope_value = new (mtCompiler) ConstantIntValue(1);
2483 ConstantIntValue* LinearScan::_int_2_scope_value = new (mtCompiler) ConstantIntValue(2);
2484 LocationValue* _illegal_value = new (mtCompiler) LocationValue(Location());
2485
2486 void LinearScan::init_compute_debug_info() {
2487 // cache for frequently used scope values
2488 // (cpu registers and stack slots)
2489 int cache_size = (LinearScan::nof_cpu_regs + frame_map()->argcount() + max_spills()) * 2;
2490 _scope_value_cache = ScopeValueArray(cache_size, cache_size, nullptr);
2491 }
2492
2493 MonitorValue* LinearScan::location_for_monitor_index(int monitor_index) {
2494 Location loc;
2495 if (!frame_map()->location_for_monitor_object(monitor_index, &loc)) {
2496 bailout("too large frame");
2497 }
2498 ScopeValue* object_scope_value = new LocationValue(loc);
2499
2500 if (!frame_map()->location_for_monitor_lock(monitor_index, &loc)) {
2501 bailout("too large frame");
2502 }
2503 return new MonitorValue(object_scope_value, loc);
2504 }
2505
2506 LocationValue* LinearScan::location_for_name(int name, Location::Type loc_type) {
2507 Location loc;
2508 if (!frame_map()->locations_for_slot(name, loc_type, &loc)) {
2509 bailout("too large frame");
2510 }
2511 return new LocationValue(loc);
2512 }
2513
2514
2515 int LinearScan::append_scope_value_for_constant(LIR_Opr opr, GrowableArray<ScopeValue*>* scope_values) {
2516 assert(opr->is_constant(), "should not be called otherwise");
2517
2518 LIR_Const* c = opr->as_constant_ptr();
2519 BasicType t = c->type();
2520 switch (t) {
2521 case T_OBJECT: {
2522 jobject value = c->as_jobject();
2523 if (value == nullptr) {
2524 scope_values->append(_oop_null_scope_value);
2525 } else {
2526 scope_values->append(new ConstantOopWriteValue(c->as_jobject()));
2527 }
2528 return 1;
2529 }
2530
2531 case T_INT: // fall through
2532 case T_FLOAT: {
2533 int value = c->as_jint_bits();
2534 switch (value) {
2535 case -1: scope_values->append(_int_m1_scope_value); break;
2536 case 0: scope_values->append(_int_0_scope_value); break;
2537 case 1: scope_values->append(_int_1_scope_value); break;
2538 case 2: scope_values->append(_int_2_scope_value); break;
2539 default: scope_values->append(new ConstantIntValue(c->as_jint_bits())); break;
2540 }
2541 return 1;
2542 }
2543
2544 case T_LONG: // fall through
2545 case T_DOUBLE: {
2546 #ifdef _LP64
2547 scope_values->append(_int_0_scope_value);
2548 scope_values->append(new ConstantLongValue(c->as_jlong_bits()));
2549 #else
2550 if (hi_word_offset_in_bytes > lo_word_offset_in_bytes) {
2551 scope_values->append(new ConstantIntValue(c->as_jint_hi_bits()));
2552 scope_values->append(new ConstantIntValue(c->as_jint_lo_bits()));
2553 } else {
2554 scope_values->append(new ConstantIntValue(c->as_jint_lo_bits()));
2555 scope_values->append(new ConstantIntValue(c->as_jint_hi_bits()));
2556 }
2557 #endif
2558 return 2;
2559 }
2560
2561 case T_ADDRESS: {
2562 #ifdef _LP64
2563 scope_values->append(new ConstantLongValue(c->as_jint()));
2564 #else
2565 scope_values->append(new ConstantIntValue(c->as_jint()));
2566 #endif
2567 return 1;
2568 }
2569
2570 default:
2571 ShouldNotReachHere();
2572 return -1;
2573 }
2574 }
2575
2576 int LinearScan::append_scope_value_for_operand(LIR_Opr opr, GrowableArray<ScopeValue*>* scope_values) {
2577 if (opr->is_single_stack()) {
2578 int stack_idx = opr->single_stack_ix();
2579 bool is_oop = opr->is_oop_register();
2580 int cache_idx = (stack_idx + LinearScan::nof_cpu_regs) * 2 + (is_oop ? 1 : 0);
2581
2582 ScopeValue* sv = _scope_value_cache.at(cache_idx);
2583 if (sv == nullptr) {
2584 Location::Type loc_type = is_oop ? Location::oop : Location::normal;
2585 sv = location_for_name(stack_idx, loc_type);
2586 _scope_value_cache.at_put(cache_idx, sv);
2587 }
2588
2589 // check if cached value is correct
2590 DEBUG_ONLY(assert_equal(sv, location_for_name(stack_idx, is_oop ? Location::oop : Location::normal)));
2591
2592 scope_values->append(sv);
2593 return 1;
2594
2595 } else if (opr->is_single_cpu()) {
2596 bool is_oop = opr->is_oop_register();
2597 int cache_idx = opr->cpu_regnr() * 2 + (is_oop ? 1 : 0);
2598 Location::Type int_loc_type = NOT_LP64(Location::normal) LP64_ONLY(Location::int_in_long);
2599
2600 ScopeValue* sv = _scope_value_cache.at(cache_idx);
2601 if (sv == nullptr) {
2602 Location::Type loc_type = is_oop ? Location::oop : int_loc_type;
2603 VMReg rname = frame_map()->regname(opr);
2604 sv = new LocationValue(Location::new_reg_loc(loc_type, rname));
2605 _scope_value_cache.at_put(cache_idx, sv);
2606 }
2607
2608 // check if cached value is correct
2609 DEBUG_ONLY(assert_equal(sv, new LocationValue(Location::new_reg_loc(is_oop ? Location::oop : int_loc_type, frame_map()->regname(opr)))));
2610
2611 scope_values->append(sv);
2612 return 1;
2613
2614 #ifdef X86
2615 } else if (opr->is_single_xmm()) {
2616 VMReg rname = opr->as_xmm_float_reg()->as_VMReg();
2617 LocationValue* sv = new LocationValue(Location::new_reg_loc(Location::normal, rname));
2618
2619 scope_values->append(sv);
2620 return 1;
2621 #endif
2622
2623 } else if (opr->is_single_fpu()) {
2624 #if defined(AMD64)
2625 assert(false, "FPU not used on x86-64");
2626 #endif
2627 Location::Type loc_type = float_saved_as_double ? Location::float_in_dbl : Location::normal;
2628 VMReg rname = frame_map()->fpu_regname(opr->fpu_regnr());
2629 #ifndef __SOFTFP__
2630 #ifndef VM_LITTLE_ENDIAN
2631 // On S390 a (single precision) float value occupies only the high
2632 // word of the full double register. So when the double register is
2633 // stored to memory (e.g. by the RegisterSaver), then the float value
2634 // is found at offset 0. I.e. the code below is not needed on S390.
2635 #ifndef S390
2636 if (! float_saved_as_double) {
2637 // On big endian system, we may have an issue if float registers use only
2638 // the low half of the (same) double registers.
2639 // Both the float and the double could have the same regnr but would correspond
2640 // to two different addresses once saved.
2641
2642 // get next safely (no assertion checks)
2643 VMReg next = VMRegImpl::as_VMReg(1+rname->value());
2644 if (next->is_reg() &&
2645 (next->as_FloatRegister() == rname->as_FloatRegister())) {
2646 // the back-end does use the same numbering for the double and the float
2647 rname = next; // VMReg for the low bits, e.g. the real VMReg for the float
2648 }
2649 }
2650 #endif // !S390
2651 #endif
2652 #endif
2653 LocationValue* sv = new LocationValue(Location::new_reg_loc(loc_type, rname));
2654
2655 scope_values->append(sv);
2656 return 1;
2657
2658 } else {
2659 // double-size operands
2660
2661 ScopeValue* first;
2662 ScopeValue* second;
2663
2664 if (opr->is_double_stack()) {
2665 #ifdef _LP64
2666 Location loc1;
2667 Location::Type loc_type = opr->type() == T_LONG ? Location::lng : Location::dbl;
2668 if (!frame_map()->locations_for_slot(opr->double_stack_ix(), loc_type, &loc1, nullptr)) {
2669 bailout("too large frame");
2670 }
2671
2672 first = new LocationValue(loc1);
2673 second = _int_0_scope_value;
2674 #else
2675 Location loc1, loc2;
2676 if (!frame_map()->locations_for_slot(opr->double_stack_ix(), Location::normal, &loc1, &loc2)) {
2677 bailout("too large frame");
2678 }
2679 first = new LocationValue(loc1);
2680 second = new LocationValue(loc2);
2681 #endif // _LP64
2682
2683 } else if (opr->is_double_cpu()) {
2684 #ifdef _LP64
2685 VMReg rname_first = opr->as_register_lo()->as_VMReg();
2686 first = new LocationValue(Location::new_reg_loc(Location::lng, rname_first));
2687 second = _int_0_scope_value;
2688 #else
2689 VMReg rname_first = opr->as_register_lo()->as_VMReg();
2690 VMReg rname_second = opr->as_register_hi()->as_VMReg();
2691
2692 if (hi_word_offset_in_bytes < lo_word_offset_in_bytes) {
2693 // lo/hi and swapped relative to first and second, so swap them
2694 VMReg tmp = rname_first;
2695 rname_first = rname_second;
2696 rname_second = tmp;
2697 }
2698
2699 first = new LocationValue(Location::new_reg_loc(Location::normal, rname_first));
2700 second = new LocationValue(Location::new_reg_loc(Location::normal, rname_second));
2701 #endif //_LP64
2702
2703
2704 #ifdef X86
2705 } else if (opr->is_double_xmm()) {
2706 assert(opr->fpu_regnrLo() == opr->fpu_regnrHi(), "assumed in calculation");
2707 VMReg rname_first = opr->as_xmm_double_reg()->as_VMReg();
2708 # ifdef _LP64
2709 first = new LocationValue(Location::new_reg_loc(Location::dbl, rname_first));
2710 second = _int_0_scope_value;
2711 # else
2712 first = new LocationValue(Location::new_reg_loc(Location::normal, rname_first));
2713 // %%% This is probably a waste but we'll keep things as they were for now
2714 if (true) {
2715 VMReg rname_second = rname_first->next();
2716 second = new LocationValue(Location::new_reg_loc(Location::normal, rname_second));
2717 }
2718 # endif
2719 #endif
2720
2721 } else if (opr->is_double_fpu()) {
2722 // On SPARC, fpu_regnrLo/fpu_regnrHi represents the two halves of
2723 // the double as float registers in the native ordering. On X86,
2724 // fpu_regnrLo is a FPU stack slot whose VMReg represents
2725 // the low-order word of the double and fpu_regnrLo + 1 is the
2726 // name for the other half. *first and *second must represent the
2727 // least and most significant words, respectively.
2728
2729 #ifdef AMD64
2730 assert(false, "FPU not used on x86-64");
2731 #endif
2732 #ifdef ARM32
2733 assert(opr->fpu_regnrHi() == opr->fpu_regnrLo() + 1, "assumed in calculation (only fpu_regnrLo is used)");
2734 #endif
2735
2736 #ifdef VM_LITTLE_ENDIAN
2737 VMReg rname_first = frame_map()->fpu_regname(opr->fpu_regnrLo());
2738 #else
2739 VMReg rname_first = frame_map()->fpu_regname(opr->fpu_regnrHi());
2740 #endif
2741
2742 #ifdef _LP64
2743 first = new LocationValue(Location::new_reg_loc(Location::dbl, rname_first));
2744 second = _int_0_scope_value;
2745 #else
2746 first = new LocationValue(Location::new_reg_loc(Location::normal, rname_first));
2747 // %%% This is probably a waste but we'll keep things as they were for now
2748 if (true) {
2749 VMReg rname_second = rname_first->next();
2750 second = new LocationValue(Location::new_reg_loc(Location::normal, rname_second));
2751 }
2752 #endif
2753
2754 } else {
2755 ShouldNotReachHere();
2756 first = nullptr;
2757 second = nullptr;
2758 }
2759
2760 assert(first != nullptr && second != nullptr, "must be set");
2761 // The convention the interpreter uses is that the second local
2762 // holds the first raw word of the native double representation.
2763 // This is actually reasonable, since locals and stack arrays
2764 // grow downwards in all implementations.
2765 // (If, on some machine, the interpreter's Java locals or stack
2766 // were to grow upwards, the embedded doubles would be word-swapped.)
2767 scope_values->append(second);
2768 scope_values->append(first);
2769 return 2;
2770 }
2771 }
2772
2773
2774 int LinearScan::append_scope_value(int op_id, Value value, GrowableArray<ScopeValue*>* scope_values) {
2775 if (value != nullptr) {
2776 LIR_Opr opr = value->operand();
2777 Constant* con = value->as_Constant();
2778
2779 assert(con == nullptr || opr->is_virtual() || opr->is_constant() || opr->is_illegal(), "assumption: Constant instructions have only constant operands (or illegal if constant is optimized away)");
2780 assert(con != nullptr || opr->is_virtual(), "assumption: non-Constant instructions have only virtual operands");
2781
2782 if (con != nullptr && !con->is_pinned() && !opr->is_constant()) {
2783 // Unpinned constants may have a virtual operand for a part of the lifetime
2784 // or may be illegal when it was optimized away,
2785 // so always use a constant operand
2786 opr = LIR_OprFact::value_type(con->type());
2787 }
2788 assert(opr->is_virtual() || opr->is_constant(), "other cases not allowed here");
2789
2790 if (opr->is_virtual()) {
2791 LIR_OpVisitState::OprMode mode = LIR_OpVisitState::inputMode;
2792
2793 BlockBegin* block = block_of_op_with_id(op_id);
2794 if (block->number_of_sux() == 1 && op_id == block->last_lir_instruction_id()) {
2795 // generating debug information for the last instruction of a block.
2796 // if this instruction is a branch, spill moves are inserted before this branch
2797 // and so the wrong operand would be returned (spill moves at block boundaries are not
2798 // considered in the live ranges of intervals)
2799 // Solution: use the first op_id of the branch target block instead.
2800 if (block->lir()->instructions_list()->last()->as_OpBranch() != nullptr) {
2801 if (block->live_out().at(opr->vreg_number())) {
2802 op_id = block->sux_at(0)->first_lir_instruction_id();
2803 mode = LIR_OpVisitState::outputMode;
2804 }
2805 }
2806 }
2807
2808 // Get current location of operand
2809 // The operand must be live because debug information is considered when building the intervals
2810 // if the interval is not live, color_lir_opr will cause an assertion failure
2811 opr = color_lir_opr(opr, op_id, mode);
2812 assert(!has_call(op_id) || opr->is_stack() || !is_caller_save(reg_num(opr)), "can not have caller-save register operands at calls");
2813
2814 // Append to ScopeValue array
2815 return append_scope_value_for_operand(opr, scope_values);
2816
2817 } else {
2818 assert(value->as_Constant() != nullptr, "all other instructions have only virtual operands");
2819 assert(opr->is_constant(), "operand must be constant");
2820
2821 return append_scope_value_for_constant(opr, scope_values);
2822 }
2823 } else {
2824 // append a dummy value because real value not needed
2825 scope_values->append(_illegal_value);
2826 return 1;
2827 }
2828 }
2829
2830
2831 IRScopeDebugInfo* LinearScan::compute_debug_info_for_scope(int op_id, IRScope* cur_scope, ValueStack* cur_state, ValueStack* innermost_state) {
2832 IRScopeDebugInfo* caller_debug_info = nullptr;
2833
2834 ValueStack* caller_state = cur_state->caller_state();
2835 if (caller_state != nullptr) {
2836 // process recursively to compute outermost scope first
2837 caller_debug_info = compute_debug_info_for_scope(op_id, cur_scope->caller(), caller_state, innermost_state);
2838 }
2839
2840 // initialize these to null.
2841 // If we don't need deopt info or there are no locals, expressions or monitors,
2842 // then these get recorded as no information and avoids the allocation of 0 length arrays.
2843 GrowableArray<ScopeValue*>* locals = nullptr;
2844 GrowableArray<ScopeValue*>* expressions = nullptr;
2845 GrowableArray<MonitorValue*>* monitors = nullptr;
2846
2847 // describe local variable values
2848 int nof_locals = cur_state->locals_size();
2849 if (nof_locals > 0) {
2850 locals = new GrowableArray<ScopeValue*>(nof_locals);
2851
2852 int pos = 0;
2853 while (pos < nof_locals) {
2854 assert(pos < cur_state->locals_size(), "why not?");
2855
2856 Value local = cur_state->local_at(pos);
2857 pos += append_scope_value(op_id, local, locals);
2858
2859 assert(locals->length() == pos, "must match");
2860 }
2861 assert(locals->length() == nof_locals, "wrong number of locals");
2862 }
2863 assert(nof_locals == cur_scope->method()->max_locals(), "wrong number of locals");
2864 assert(nof_locals == cur_state->locals_size(), "wrong number of locals");
2865
2866 // describe expression stack
2867 int nof_stack = cur_state->stack_size();
2868 if (nof_stack > 0) {
2869 expressions = new GrowableArray<ScopeValue*>(nof_stack);
2870
2871 int pos = 0;
2872 while (pos < nof_stack) {
2873 Value expression = cur_state->stack_at(pos);
2874 pos += append_scope_value(op_id, expression, expressions);
2875
2876 assert(expressions->length() == pos, "must match");
2877 }
2878 assert(expressions->length() == cur_state->stack_size(), "wrong number of stack entries");
2879 }
2880
2881 // describe monitors
2882 int nof_locks = cur_state->locks_size();
2883 if (nof_locks > 0) {
2884 int lock_offset = cur_state->caller_state() != nullptr ? cur_state->caller_state()->total_locks_size() : 0;
2885 monitors = new GrowableArray<MonitorValue*>(nof_locks);
2886 for (int i = 0; i < nof_locks; i++) {
2887 monitors->append(location_for_monitor_index(lock_offset + i));
2888 }
2889 }
2890
2891 return new IRScopeDebugInfo(cur_scope, cur_state->bci(), locals, expressions, monitors, caller_debug_info, cur_state->should_reexecute());
2892 }
2893
2894
2895 void LinearScan::compute_debug_info(CodeEmitInfo* info, int op_id) {
2896 TRACE_LINEAR_SCAN(3, tty->print_cr("creating debug information at op_id %d", op_id));
2897
2898 IRScope* innermost_scope = info->scope();
2899 ValueStack* innermost_state = info->stack();
2900
2901 assert(innermost_scope != nullptr && innermost_state != nullptr, "why is it missing?");
2902
2903 DEBUG_ONLY(check_stack_depth(info, innermost_state->stack_size()));
2904
2905 if (info->_scope_debug_info == nullptr) {
2906 // compute debug information
2907 info->_scope_debug_info = compute_debug_info_for_scope(op_id, innermost_scope, innermost_state, innermost_state);
2908 } else {
2909 // debug information already set. Check that it is correct from the current point of view
2910 DEBUG_ONLY(assert_equal(info->_scope_debug_info, compute_debug_info_for_scope(op_id, innermost_scope, innermost_state, innermost_state)));
2911 }
2912 }
2913
2914
2915 void LinearScan::assign_reg_num(LIR_OpList* instructions, IntervalWalker* iw) {
2916 LIR_OpVisitState visitor;
2917 int num_inst = instructions->length();
2918 bool has_dead = false;
2919
2920 for (int j = 0; j < num_inst; j++) {
2921 LIR_Op* op = instructions->at(j);
2922 if (op == nullptr) { // this can happen when spill-moves are removed in eliminate_spill_moves
2923 has_dead = true;
2924 continue;
2925 }
2926 int op_id = op->id();
2927
2928 // visit instruction to get list of operands
2929 visitor.visit(op);
2930
2931 // iterate all modes of the visitor and process all virtual operands
2932 for_each_visitor_mode(mode) {
2933 int n = visitor.opr_count(mode);
2934 for (int k = 0; k < n; k++) {
2935 LIR_Opr opr = visitor.opr_at(mode, k);
2936 if (opr->is_virtual_register()) {
2937 visitor.set_opr_at(mode, k, color_lir_opr(opr, op_id, mode));
2938 }
2939 }
2940 }
2941
2942 if (visitor.info_count() > 0) {
2943 // exception handling
2944 if (compilation()->has_exception_handlers()) {
2945 XHandlers* xhandlers = visitor.all_xhandler();
2946 int n = xhandlers->length();
2947 for (int k = 0; k < n; k++) {
2948 XHandler* handler = xhandlers->handler_at(k);
2949 if (handler->entry_code() != nullptr) {
2950 assign_reg_num(handler->entry_code()->instructions_list(), nullptr);
2951 }
2952 }
2953 } else {
2954 assert(visitor.all_xhandler()->length() == 0, "missed exception handler");
2955 }
2956
2957 // compute oop map
2958 assert(iw != nullptr, "needed for compute_oop_map");
2959 compute_oop_map(iw, visitor, op);
2960
2961 // compute debug information
2962 int n = visitor.info_count();
2963 for (int k = 0; k < n; k++) {
2964 compute_debug_info(visitor.info_at(k), op_id);
2965 }
2966 }
2967
2968 #ifdef ASSERT
2969 // make sure we haven't made the op invalid.
2970 op->verify();
2971 #endif
2972
2973 // remove useless moves
2974 if (op->code() == lir_move) {
2975 assert(op->as_Op1() != nullptr, "move must be LIR_Op1");
2976 LIR_Op1* move = (LIR_Op1*)op;
2977 LIR_Opr src = move->in_opr();
2978 LIR_Opr dst = move->result_opr();
2979 if (dst == src ||
2980 (!dst->is_pointer() && !src->is_pointer() &&
2981 src->is_same_register(dst))) {
2982 instructions->at_put(j, nullptr);
2983 has_dead = true;
2984 }
2985 }
2986 }
2987
2988 if (has_dead) {
2989 // iterate all instructions of the block and remove all null-values.
2990 int insert_point = 0;
2991 for (int j = 0; j < num_inst; j++) {
2992 LIR_Op* op = instructions->at(j);
2993 if (op != nullptr) {
2994 if (insert_point != j) {
2995 instructions->at_put(insert_point, op);
2996 }
2997 insert_point++;
2998 }
2999 }
3000 instructions->trunc_to(insert_point);
3001 }
3002 }
3003
3004 void LinearScan::assign_reg_num() {
3005 TIME_LINEAR_SCAN(timer_assign_reg_num);
3006
3007 init_compute_debug_info();
3008 IntervalWalker* iw = init_compute_oop_maps();
3009
3010 int num_blocks = block_count();
3011 for (int i = 0; i < num_blocks; i++) {
3012 BlockBegin* block = block_at(i);
3013 assign_reg_num(block->lir()->instructions_list(), iw);
3014 }
3015 }
3016
3017
3018 void LinearScan::do_linear_scan() {
3019 number_instructions();
3020
3021 NOT_PRODUCT(print_lir(1, "Before Register Allocation"));
3022
3023 compute_local_live_sets();
3024 compute_global_live_sets();
3025 CHECK_BAILOUT();
3026
3027 build_intervals();
3028 CHECK_BAILOUT();
3029 sort_intervals_before_allocation();
3030
3031 NOT_PRODUCT(print_intervals("Before Register Allocation"));
3032 NOT_PRODUCT(LinearScanStatistic::compute(this, _stat_before_alloc));
3033
3034 allocate_registers();
3035 CHECK_BAILOUT();
3036
3037 resolve_data_flow();
3038 if (compilation()->has_exception_handlers()) {
3039 resolve_exception_handlers();
3040 }
3041 // fill in number of spill slots into frame_map
3042 propagate_spill_slots();
3043 CHECK_BAILOUT();
3044
3045 NOT_PRODUCT(print_intervals("After Register Allocation"));
3046 NOT_PRODUCT(print_lir(2, "LIR after register allocation:"));
3047
3048 sort_intervals_after_allocation();
3049
3050 DEBUG_ONLY(verify());
3051
3052 eliminate_spill_moves();
3053 assign_reg_num();
3054 CHECK_BAILOUT();
3055
3056 NOT_PRODUCT(print_lir(2, "LIR after assignment of register numbers:"));
3057 NOT_PRODUCT(LinearScanStatistic::compute(this, _stat_after_asign));
3058
3059 #ifndef RISCV
3060 // Disable these optimizations on riscv temporarily, because it does not
3061 // work when the comparison operands are bound to branches or cmoves.
3062 { TIME_LINEAR_SCAN(timer_optimize_lir);
3063
3064 EdgeMoveOptimizer::optimize(ir()->code());
3065 ControlFlowOptimizer::optimize(ir()->code());
3066 // check that cfg is still correct after optimizations
3067 ir()->verify();
3068 }
3069 #endif
3070
3071 NOT_PRODUCT(print_lir(1, "Before Code Generation", false));
3072 NOT_PRODUCT(LinearScanStatistic::compute(this, _stat_final));
3073 }
3074
3075
3076 // ********** Printing functions
3077
3078 #ifndef PRODUCT
3079
3080 void LinearScan::print_timers(double total) {
3081 _total_timer.print(total);
3082 }
3083
3084 void LinearScan::print_statistics() {
3085 _stat_before_alloc.print("before allocation");
3086 _stat_after_asign.print("after assignment of register");
3087 _stat_final.print("after optimization");
3088 }
3089
3090 void LinearScan::print_bitmap(BitMap& b) {
3091 for (unsigned int i = 0; i < b.size(); i++) {
3092 if (b.at(i)) tty->print("%d ", i);
3093 }
3094 tty->cr();
3095 }
3096
3097 void LinearScan::print_intervals(const char* label) {
3098 if (TraceLinearScanLevel >= 1) {
3099 int i;
3100 tty->cr();
3101 tty->print_cr("%s", label);
3102
3103 for (i = 0; i < interval_count(); i++) {
3104 Interval* interval = interval_at(i);
3105 if (interval != nullptr) {
3106 interval->print();
3107 }
3108 }
3109
3110 tty->cr();
3111 tty->print_cr("--- Basic Blocks ---");
3112 for (i = 0; i < block_count(); i++) {
3113 BlockBegin* block = block_at(i);
3114 tty->print("B%d [%d, %d, %d, %d] ", block->block_id(), block->first_lir_instruction_id(), block->last_lir_instruction_id(), block->loop_index(), block->loop_depth());
3115 }
3116 tty->cr();
3117 tty->cr();
3118 }
3119
3120 if (PrintCFGToFile) {
3121 CFGPrinter::print_intervals(&_intervals, label);
3122 }
3123 }
3124
3125 void LinearScan::print_lir(int level, const char* label, bool hir_valid) {
3126 if (TraceLinearScanLevel >= level) {
3127 tty->cr();
3128 tty->print_cr("%s", label);
3129 print_LIR(ir()->linear_scan_order());
3130 tty->cr();
3131 }
3132
3133 if (level == 1 && PrintCFGToFile) {
3134 CFGPrinter::print_cfg(ir()->linear_scan_order(), label, hir_valid, true);
3135 }
3136 }
3137
3138 void LinearScan::print_reg_num(outputStream* out, int reg_num) {
3139 if (reg_num == -1) {
3140 out->print("[ANY]");
3141 return;
3142 } else if (reg_num >= LIR_Opr::vreg_base) {
3143 out->print("[VREG %d]", reg_num);
3144 return;
3145 }
3146
3147 LIR_Opr opr = get_operand(reg_num);
3148 assert(opr->is_valid(), "unknown register");
3149 opr->print(out);
3150 }
3151
3152 LIR_Opr LinearScan::get_operand(int reg_num) {
3153 LIR_Opr opr = LIR_OprFact::illegal();
3154
3155 #ifdef X86
3156 int last_xmm_reg = pd_last_xmm_reg;
3157 #ifdef _LP64
3158 if (UseAVX < 3) {
3159 last_xmm_reg = pd_first_xmm_reg + (pd_nof_xmm_regs_frame_map / 2) - 1;
3160 }
3161 #endif
3162 #endif
3163 if (reg_num >= pd_first_cpu_reg && reg_num <= pd_last_cpu_reg) {
3164 opr = LIR_OprFact::single_cpu(reg_num);
3165 } else if (reg_num >= pd_first_fpu_reg && reg_num <= pd_last_fpu_reg) {
3166 opr = LIR_OprFact::single_fpu(reg_num - pd_first_fpu_reg);
3167 #ifdef X86
3168 } else if (reg_num >= pd_first_xmm_reg && reg_num <= last_xmm_reg) {
3169 opr = LIR_OprFact::single_xmm(reg_num - pd_first_xmm_reg);
3170 #endif
3171 } else {
3172 // reg_num == -1 or a virtual register, return the illegal operand
3173 }
3174 return opr;
3175 }
3176
3177 Interval* LinearScan::find_interval_at(int reg_num) const {
3178 if (reg_num < 0 || reg_num >= _intervals.length()) {
3179 return nullptr;
3180 }
3181 return interval_at(reg_num);
3182 }
3183
3184 #endif // PRODUCT
3185
3186
3187 // ********** verification functions for allocation
3188 // (check that all intervals have a correct register and that no registers are overwritten)
3189 #ifdef ASSERT
3190
3191 void LinearScan::verify() {
3192 TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying intervals ******************************************"));
3193 verify_intervals();
3194
3195 TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying that no oops are in fixed intervals ****************"));
3196 verify_no_oops_in_fixed_intervals();
3197
3198 TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying that unpinned constants are not alive across block boundaries"));
3199 verify_constants();
3200
3201 TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying register allocation ********************************"));
3202 verify_registers();
3203
3204 TRACE_LINEAR_SCAN(2, tty->print_cr("********* no errors found **********************************************"));
3205 }
3206
3207 void LinearScan::verify_intervals() {
3208 int len = interval_count();
3209 bool has_error = false;
3210
3211 for (int i = 0; i < len; i++) {
3212 Interval* i1 = interval_at(i);
3213 if (i1 == nullptr) continue;
3214
3215 i1->check_split_children();
3216
3217 if (i1->reg_num() != i) {
3218 tty->print_cr("Interval %d is on position %d in list", i1->reg_num(), i); i1->print(); tty->cr();
3219 has_error = true;
3220 }
3221
3222 if (i1->reg_num() >= LIR_Opr::vreg_base && i1->type() == T_ILLEGAL) {
3223 tty->print_cr("Interval %d has no type assigned", i1->reg_num()); i1->print(); tty->cr();
3224 has_error = true;
3225 }
3226
3227 if (i1->assigned_reg() == any_reg) {
3228 tty->print_cr("Interval %d has no register assigned", i1->reg_num()); i1->print(); tty->cr();
3229 has_error = true;
3230 }
3231
3232 if (i1->assigned_reg() == i1->assigned_regHi()) {
3233 tty->print_cr("Interval %d: low and high register equal", i1->reg_num()); i1->print(); tty->cr();
3234 has_error = true;
3235 }
3236
3237 if (!is_processed_reg_num(i1->assigned_reg())) {
3238 tty->print_cr("Can not have an Interval for an ignored register"); i1->print(); tty->cr();
3239 has_error = true;
3240 }
3241
3242 // special intervals that are created in MoveResolver
3243 // -> ignore them because the range information has no meaning there
3244 if (i1->from() == 1 && i1->to() == 2) continue;
3245
3246 if (i1->first() == Range::end()) {
3247 tty->print_cr("Interval %d has no Range", i1->reg_num()); i1->print(); tty->cr();
3248 has_error = true;
3249 }
3250
3251 for (Range* r = i1->first(); r != Range::end(); r = r->next()) {
3252 if (r->from() >= r->to()) {
3253 tty->print_cr("Interval %d has zero length range", i1->reg_num()); i1->print(); tty->cr();
3254 has_error = true;
3255 }
3256 }
3257
3258 for (int j = i + 1; j < len; j++) {
3259 Interval* i2 = interval_at(j);
3260 if (i2 == nullptr || (i2->from() == 1 && i2->to() == 2)) continue;
3261
3262 int r1 = i1->assigned_reg();
3263 int r1Hi = i1->assigned_regHi();
3264 int r2 = i2->assigned_reg();
3265 int r2Hi = i2->assigned_regHi();
3266 if ((r1 == r2 || r1 == r2Hi || (r1Hi != any_reg && (r1Hi == r2 || r1Hi == r2Hi))) && i1->intersects(i2)) {
3267 tty->print_cr("Intervals %d and %d overlap and have the same register assigned", i1->reg_num(), i2->reg_num());
3268 i1->print(); tty->cr();
3269 i2->print(); tty->cr();
3270 has_error = true;
3271 }
3272 }
3273 }
3274
3275 assert(has_error == false, "register allocation invalid");
3276 }
3277
3278
3279 void LinearScan::verify_no_oops_in_fixed_intervals() {
3280 Interval* fixed_intervals;
3281 Interval* other_intervals;
3282 create_unhandled_lists(&fixed_intervals, &other_intervals, is_precolored_cpu_interval, nullptr);
3283
3284 // to ensure a walking until the last instruction id, add a dummy interval
3285 // with a high operation id
3286 other_intervals = new Interval(any_reg);
3287 other_intervals->add_range(max_jint - 2, max_jint - 1);
3288 IntervalWalker* iw = new IntervalWalker(this, fixed_intervals, other_intervals);
3289
3290 LIR_OpVisitState visitor;
3291 for (int i = 0; i < block_count(); i++) {
3292 BlockBegin* block = block_at(i);
3293
3294 LIR_OpList* instructions = block->lir()->instructions_list();
3295
3296 for (int j = 0; j < instructions->length(); j++) {
3297 LIR_Op* op = instructions->at(j);
3298 int op_id = op->id();
3299
3300 visitor.visit(op);
3301
3302 if (visitor.info_count() > 0) {
3303 iw->walk_before(op->id());
3304 bool check_live = true;
3305 if (op->code() == lir_move) {
3306 LIR_Op1* move = (LIR_Op1*)op;
3307 check_live = (move->patch_code() == lir_patch_none);
3308 }
3309 LIR_OpBranch* branch = op->as_OpBranch();
3310 if (branch != nullptr && branch->stub() != nullptr && branch->stub()->is_exception_throw_stub()) {
3311 // Don't bother checking the stub in this case since the
3312 // exception stub will never return to normal control flow.
3313 check_live = false;
3314 }
3315
3316 // Make sure none of the fixed registers is live across an
3317 // oopmap since we can't handle that correctly.
3318 if (check_live) {
3319 for (Interval* interval = iw->active_first(fixedKind);
3320 interval != Interval::end();
3321 interval = interval->next()) {
3322 if (interval->current_to() > op->id() + 1) {
3323 // This interval is live out of this op so make sure
3324 // that this interval represents some value that's
3325 // referenced by this op either as an input or output.
3326 bool ok = false;
3327 for_each_visitor_mode(mode) {
3328 int n = visitor.opr_count(mode);
3329 for (int k = 0; k < n; k++) {
3330 LIR_Opr opr = visitor.opr_at(mode, k);
3331 if (opr->is_fixed_cpu()) {
3332 if (interval_at(reg_num(opr)) == interval) {
3333 ok = true;
3334 break;
3335 }
3336 int hi = reg_numHi(opr);
3337 if (hi != -1 && interval_at(hi) == interval) {
3338 ok = true;
3339 break;
3340 }
3341 }
3342 }
3343 }
3344 assert(ok, "fixed intervals should never be live across an oopmap point");
3345 }
3346 }
3347 }
3348 }
3349
3350 // oop-maps at calls do not contain registers, so check is not needed
3351 if (!visitor.has_call()) {
3352
3353 for_each_visitor_mode(mode) {
3354 int n = visitor.opr_count(mode);
3355 for (int k = 0; k < n; k++) {
3356 LIR_Opr opr = visitor.opr_at(mode, k);
3357
3358 if (opr->is_fixed_cpu() && opr->is_oop()) {
3359 // operand is a non-virtual cpu register and contains an oop
3360 TRACE_LINEAR_SCAN(4, op->print_on(tty); tty->print("checking operand "); opr->print(); tty->cr());
3361
3362 Interval* interval = interval_at(reg_num(opr));
3363 assert(interval != nullptr, "no interval");
3364
3365 if (mode == LIR_OpVisitState::inputMode) {
3366 if (interval->to() >= op_id + 1) {
3367 assert(interval->to() < op_id + 2 ||
3368 interval->has_hole_between(op_id, op_id + 2),
3369 "oop input operand live after instruction");
3370 }
3371 } else if (mode == LIR_OpVisitState::outputMode) {
3372 if (interval->from() <= op_id - 1) {
3373 assert(interval->has_hole_between(op_id - 1, op_id),
3374 "oop input operand live after instruction");
3375 }
3376 }
3377 }
3378 }
3379 }
3380 }
3381 }
3382 }
3383 }
3384
3385
3386 void LinearScan::verify_constants() {
3387 int num_regs = num_virtual_regs();
3388 int size = live_set_size();
3389 int num_blocks = block_count();
3390
3391 for (int i = 0; i < num_blocks; i++) {
3392 BlockBegin* block = block_at(i);
3393 ResourceBitMap& live_at_edge = block->live_in();
3394
3395 // visit all registers where the live_at_edge bit is set
3396 auto visitor = [&](BitMap::idx_t index) {
3397 int r = static_cast<int>(index);
3398 TRACE_LINEAR_SCAN(4, tty->print("checking interval %d of block B%d", r, block->block_id()));
3399
3400 Value value = gen()->instruction_for_vreg(r);
3401
3402 assert(value != nullptr, "all intervals live across block boundaries must have Value");
3403 assert(value->operand()->is_register() && value->operand()->is_virtual(), "value must have virtual operand");
3404 assert(value->operand()->vreg_number() == r, "register number must match");
3405 // TKR assert(value->as_Constant() == nullptr || value->is_pinned(), "only pinned constants can be alive across block boundaries");
3406 };
3407 live_at_edge.iterate(visitor, 0, size);
3408 }
3409 }
3410
3411
3412 class RegisterVerifier: public StackObj {
3413 private:
3414 LinearScan* _allocator;
3415 BlockList _work_list; // all blocks that must be processed
3416 IntervalsList _saved_states; // saved information of previous check
3417
3418 // simplified access to methods of LinearScan
3419 Compilation* compilation() const { return _allocator->compilation(); }
3420 Interval* interval_at(int reg_num) const { return _allocator->interval_at(reg_num); }
3421 int reg_num(LIR_Opr opr) const { return _allocator->reg_num(opr); }
3422
3423 // currently, only registers are processed
3424 int state_size() { return LinearScan::nof_regs; }
3425
3426 // accessors
3427 IntervalList* state_for_block(BlockBegin* block) { return _saved_states.at(block->block_id()); }
3428 void set_state_for_block(BlockBegin* block, IntervalList* saved_state) { _saved_states.at_put(block->block_id(), saved_state); }
3429 void add_to_work_list(BlockBegin* block) { if (!_work_list.contains(block)) _work_list.append(block); }
3430
3431 // helper functions
3432 IntervalList* copy(IntervalList* input_state);
3433 void state_put(IntervalList* input_state, int reg, Interval* interval);
3434 bool check_state(IntervalList* input_state, int reg, Interval* interval);
3435
3436 void process_block(BlockBegin* block);
3437 void process_xhandler(XHandler* xhandler, IntervalList* input_state);
3438 void process_successor(BlockBegin* block, IntervalList* input_state);
3439 void process_operations(LIR_List* ops, IntervalList* input_state);
3440
3441 public:
3442 RegisterVerifier(LinearScan* allocator)
3443 : _allocator(allocator)
3444 , _work_list(16)
3445 , _saved_states(BlockBegin::number_of_blocks(), BlockBegin::number_of_blocks(), nullptr)
3446 { }
3447
3448 void verify(BlockBegin* start);
3449 };
3450
3451
3452 // entry function from LinearScan that starts the verification
3453 void LinearScan::verify_registers() {
3454 RegisterVerifier verifier(this);
3455 verifier.verify(block_at(0));
3456 }
3457
3458
3459 void RegisterVerifier::verify(BlockBegin* start) {
3460 // setup input registers (method arguments) for first block
3461 int input_state_len = state_size();
3462 IntervalList* input_state = new IntervalList(input_state_len, input_state_len, nullptr);
3463 CallingConvention* args = compilation()->frame_map()->incoming_arguments();
3464 for (int n = 0; n < args->length(); n++) {
3465 LIR_Opr opr = args->at(n);
3466 if (opr->is_register()) {
3467 Interval* interval = interval_at(reg_num(opr));
3468
3469 if (interval->assigned_reg() < state_size()) {
3470 input_state->at_put(interval->assigned_reg(), interval);
3471 }
3472 if (interval->assigned_regHi() != LinearScan::any_reg && interval->assigned_regHi() < state_size()) {
3473 input_state->at_put(interval->assigned_regHi(), interval);
3474 }
3475 }
3476 }
3477
3478 set_state_for_block(start, input_state);
3479 add_to_work_list(start);
3480
3481 // main loop for verification
3482 do {
3483 BlockBegin* block = _work_list.at(0);
3484 _work_list.remove_at(0);
3485
3486 process_block(block);
3487 } while (!_work_list.is_empty());
3488 }
3489
3490 void RegisterVerifier::process_block(BlockBegin* block) {
3491 TRACE_LINEAR_SCAN(2, tty->cr(); tty->print_cr("process_block B%d", block->block_id()));
3492
3493 // must copy state because it is modified
3494 IntervalList* input_state = copy(state_for_block(block));
3495
3496 if (TraceLinearScanLevel >= 4) {
3497 tty->print_cr("Input-State of intervals:");
3498 tty->print(" ");
3499 for (int i = 0; i < state_size(); i++) {
3500 if (input_state->at(i) != nullptr) {
3501 tty->print(" %4d", input_state->at(i)->reg_num());
3502 } else {
3503 tty->print(" __");
3504 }
3505 }
3506 tty->cr();
3507 tty->cr();
3508 }
3509
3510 // process all operations of the block
3511 process_operations(block->lir(), input_state);
3512
3513 // iterate all successors
3514 for (int i = 0; i < block->number_of_sux(); i++) {
3515 process_successor(block->sux_at(i), input_state);
3516 }
3517 }
3518
3519 void RegisterVerifier::process_xhandler(XHandler* xhandler, IntervalList* input_state) {
3520 TRACE_LINEAR_SCAN(2, tty->print_cr("process_xhandler B%d", xhandler->entry_block()->block_id()));
3521
3522 // must copy state because it is modified
3523 input_state = copy(input_state);
3524
3525 if (xhandler->entry_code() != nullptr) {
3526 process_operations(xhandler->entry_code(), input_state);
3527 }
3528 process_successor(xhandler->entry_block(), input_state);
3529 }
3530
3531 void RegisterVerifier::process_successor(BlockBegin* block, IntervalList* input_state) {
3532 IntervalList* saved_state = state_for_block(block);
3533
3534 if (saved_state != nullptr) {
3535 // this block was already processed before.
3536 // check if new input_state is consistent with saved_state
3537
3538 bool saved_state_correct = true;
3539 for (int i = 0; i < state_size(); i++) {
3540 if (input_state->at(i) != saved_state->at(i)) {
3541 // current input_state and previous saved_state assume a different
3542 // interval in this register -> assume that this register is invalid
3543 if (saved_state->at(i) != nullptr) {
3544 // invalidate old calculation only if it assumed that
3545 // register was valid. when the register was already invalid,
3546 // then the old calculation was correct.
3547 saved_state_correct = false;
3548 saved_state->at_put(i, nullptr);
3549
3550 TRACE_LINEAR_SCAN(4, tty->print_cr("process_successor B%d: invalidating slot %d", block->block_id(), i));
3551 }
3552 }
3553 }
3554
3555 if (saved_state_correct) {
3556 // already processed block with correct input_state
3557 TRACE_LINEAR_SCAN(2, tty->print_cr("process_successor B%d: previous visit already correct", block->block_id()));
3558 } else {
3559 // must re-visit this block
3560 TRACE_LINEAR_SCAN(2, tty->print_cr("process_successor B%d: must re-visit because input state changed", block->block_id()));
3561 add_to_work_list(block);
3562 }
3563
3564 } else {
3565 // block was not processed before, so set initial input_state
3566 TRACE_LINEAR_SCAN(2, tty->print_cr("process_successor B%d: initial visit", block->block_id()));
3567
3568 set_state_for_block(block, copy(input_state));
3569 add_to_work_list(block);
3570 }
3571 }
3572
3573
3574 IntervalList* RegisterVerifier::copy(IntervalList* input_state) {
3575 IntervalList* copy_state = new IntervalList(input_state->length());
3576 copy_state->appendAll(input_state);
3577 return copy_state;
3578 }
3579
3580 void RegisterVerifier::state_put(IntervalList* input_state, int reg, Interval* interval) {
3581 if (reg != LinearScan::any_reg && reg < state_size()) {
3582 if (interval != nullptr) {
3583 TRACE_LINEAR_SCAN(4, tty->print_cr(" reg[%d] = %d", reg, interval->reg_num()));
3584 } else if (input_state->at(reg) != nullptr) {
3585 TRACE_LINEAR_SCAN(4, tty->print_cr(" reg[%d] = null", reg));
3586 }
3587
3588 input_state->at_put(reg, interval);
3589 }
3590 }
3591
3592 bool RegisterVerifier::check_state(IntervalList* input_state, int reg, Interval* interval) {
3593 if (reg != LinearScan::any_reg && reg < state_size()) {
3594 if (input_state->at(reg) != interval) {
3595 tty->print_cr("!! Error in register allocation: register %d does not contain interval %d", reg, interval->reg_num());
3596 return true;
3597 }
3598 }
3599 return false;
3600 }
3601
3602 void RegisterVerifier::process_operations(LIR_List* ops, IntervalList* input_state) {
3603 // visit all instructions of the block
3604 LIR_OpVisitState visitor;
3605 bool has_error = false;
3606
3607 for (int i = 0; i < ops->length(); i++) {
3608 LIR_Op* op = ops->at(i);
3609 visitor.visit(op);
3610
3611 TRACE_LINEAR_SCAN(4, op->print_on(tty));
3612
3613 // check if input operands are correct
3614 int j;
3615 int n = visitor.opr_count(LIR_OpVisitState::inputMode);
3616 for (j = 0; j < n; j++) {
3617 LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::inputMode, j);
3618 if (opr->is_register() && LinearScan::is_processed_reg_num(reg_num(opr))) {
3619 Interval* interval = interval_at(reg_num(opr));
3620 if (op->id() != -1) {
3621 interval = interval->split_child_at_op_id(op->id(), LIR_OpVisitState::inputMode);
3622 }
3623
3624 has_error |= check_state(input_state, interval->assigned_reg(), interval->split_parent());
3625 has_error |= check_state(input_state, interval->assigned_regHi(), interval->split_parent());
3626
3627 // When an operand is marked with is_last_use, then the fpu stack allocator
3628 // removes the register from the fpu stack -> the register contains no value
3629 if (opr->is_last_use()) {
3630 state_put(input_state, interval->assigned_reg(), nullptr);
3631 state_put(input_state, interval->assigned_regHi(), nullptr);
3632 }
3633 }
3634 }
3635
3636 // invalidate all caller save registers at calls
3637 if (visitor.has_call()) {
3638 for (j = 0; j < FrameMap::nof_caller_save_cpu_regs(); j++) {
3639 state_put(input_state, reg_num(FrameMap::caller_save_cpu_reg_at(j)), nullptr);
3640 }
3641 for (j = 0; j < FrameMap::nof_caller_save_fpu_regs; j++) {
3642 state_put(input_state, reg_num(FrameMap::caller_save_fpu_reg_at(j)), nullptr);
3643 }
3644
3645 #ifdef X86
3646 int num_caller_save_xmm_regs = FrameMap::get_num_caller_save_xmms();
3647 for (j = 0; j < num_caller_save_xmm_regs; j++) {
3648 state_put(input_state, reg_num(FrameMap::caller_save_xmm_reg_at(j)), nullptr);
3649 }
3650 #endif
3651 }
3652
3653 // process xhandler before output and temp operands
3654 XHandlers* xhandlers = visitor.all_xhandler();
3655 n = xhandlers->length();
3656 for (int k = 0; k < n; k++) {
3657 process_xhandler(xhandlers->handler_at(k), input_state);
3658 }
3659
3660 // set temp operands (some operations use temp operands also as output operands, so can't set them null)
3661 n = visitor.opr_count(LIR_OpVisitState::tempMode);
3662 for (j = 0; j < n; j++) {
3663 LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::tempMode, j);
3664 if (opr->is_register() && LinearScan::is_processed_reg_num(reg_num(opr))) {
3665 Interval* interval = interval_at(reg_num(opr));
3666 if (op->id() != -1) {
3667 interval = interval->split_child_at_op_id(op->id(), LIR_OpVisitState::tempMode);
3668 }
3669
3670 state_put(input_state, interval->assigned_reg(), interval->split_parent());
3671 state_put(input_state, interval->assigned_regHi(), interval->split_parent());
3672 }
3673 }
3674
3675 // set output operands
3676 n = visitor.opr_count(LIR_OpVisitState::outputMode);
3677 for (j = 0; j < n; j++) {
3678 LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::outputMode, j);
3679 if (opr->is_register() && LinearScan::is_processed_reg_num(reg_num(opr))) {
3680 Interval* interval = interval_at(reg_num(opr));
3681 if (op->id() != -1) {
3682 interval = interval->split_child_at_op_id(op->id(), LIR_OpVisitState::outputMode);
3683 }
3684
3685 state_put(input_state, interval->assigned_reg(), interval->split_parent());
3686 state_put(input_state, interval->assigned_regHi(), interval->split_parent());
3687 }
3688 }
3689 }
3690 assert(has_error == false, "Error in register allocation");
3691 }
3692
3693 #endif // ASSERT
3694
3695
3696
3697 // **** Implementation of MoveResolver ******************************
3698
3699 MoveResolver::MoveResolver(LinearScan* allocator) :
3700 _allocator(allocator),
3701 _insert_list(nullptr),
3702 _insert_idx(-1),
3703 _insertion_buffer(),
3704 _mapping_from(8),
3705 _mapping_from_opr(8),
3706 _mapping_to(8),
3707 _multiple_reads_allowed(false)
3708 {
3709 for (int i = 0; i < LinearScan::nof_regs; i++) {
3710 _register_blocked[i] = 0;
3711 }
3712 DEBUG_ONLY(check_empty());
3713 }
3714
3715
3716 #ifdef ASSERT
3717
3718 void MoveResolver::check_empty() {
3719 assert(_mapping_from.length() == 0 && _mapping_from_opr.length() == 0 && _mapping_to.length() == 0, "list must be empty before and after processing");
3720 for (int i = 0; i < LinearScan::nof_regs; i++) {
3721 assert(register_blocked(i) == 0, "register map must be empty before and after processing");
3722 }
3723 assert(_multiple_reads_allowed == false, "must have default value");
3724 }
3725
3726 void MoveResolver::verify_before_resolve() {
3727 assert(_mapping_from.length() == _mapping_from_opr.length(), "length must be equal");
3728 assert(_mapping_from.length() == _mapping_to.length(), "length must be equal");
3729 assert(_insert_list != nullptr && _insert_idx != -1, "insert position not set");
3730
3731 int i, j;
3732 if (!_multiple_reads_allowed) {
3733 for (i = 0; i < _mapping_from.length(); i++) {
3734 for (j = i + 1; j < _mapping_from.length(); j++) {
3735 assert(_mapping_from.at(i) == nullptr || _mapping_from.at(i) != _mapping_from.at(j), "cannot read from same interval twice");
3736 }
3737 }
3738 }
3739
3740 for (i = 0; i < _mapping_to.length(); i++) {
3741 for (j = i + 1; j < _mapping_to.length(); j++) {
3742 assert(_mapping_to.at(i) != _mapping_to.at(j), "cannot write to same interval twice");
3743 }
3744 }
3745
3746
3747 ResourceBitMap used_regs(LinearScan::nof_regs + allocator()->frame_map()->argcount() + allocator()->max_spills());
3748 if (!_multiple_reads_allowed) {
3749 for (i = 0; i < _mapping_from.length(); i++) {
3750 Interval* it = _mapping_from.at(i);
3751 if (it != nullptr) {
3752 assert(!used_regs.at(it->assigned_reg()), "cannot read from same register twice");
3753 used_regs.set_bit(it->assigned_reg());
3754
3755 if (it->assigned_regHi() != LinearScan::any_reg) {
3756 assert(!used_regs.at(it->assigned_regHi()), "cannot read from same register twice");
3757 used_regs.set_bit(it->assigned_regHi());
3758 }
3759 }
3760 }
3761 }
3762
3763 used_regs.clear();
3764 for (i = 0; i < _mapping_to.length(); i++) {
3765 Interval* it = _mapping_to.at(i);
3766 assert(!used_regs.at(it->assigned_reg()), "cannot write to same register twice");
3767 used_regs.set_bit(it->assigned_reg());
3768
3769 if (it->assigned_regHi() != LinearScan::any_reg) {
3770 assert(!used_regs.at(it->assigned_regHi()), "cannot write to same register twice");
3771 used_regs.set_bit(it->assigned_regHi());
3772 }
3773 }
3774
3775 used_regs.clear();
3776 for (i = 0; i < _mapping_from.length(); i++) {
3777 Interval* it = _mapping_from.at(i);
3778 if (it != nullptr && it->assigned_reg() >= LinearScan::nof_regs) {
3779 used_regs.set_bit(it->assigned_reg());
3780 }
3781 }
3782 for (i = 0; i < _mapping_to.length(); i++) {
3783 Interval* it = _mapping_to.at(i);
3784 assert(!used_regs.at(it->assigned_reg()) || it->assigned_reg() == _mapping_from.at(i)->assigned_reg(), "stack slots used in _mapping_from must be disjoint to _mapping_to");
3785 }
3786 }
3787
3788 #endif // ASSERT
3789
3790
3791 // mark assigned_reg and assigned_regHi of the interval as blocked
3792 void MoveResolver::block_registers(Interval* it) {
3793 int reg = it->assigned_reg();
3794 if (reg < LinearScan::nof_regs) {
3795 assert(_multiple_reads_allowed || register_blocked(reg) == 0, "register already marked as used");
3796 set_register_blocked(reg, 1);
3797 }
3798 reg = it->assigned_regHi();
3799 if (reg != LinearScan::any_reg && reg < LinearScan::nof_regs) {
3800 assert(_multiple_reads_allowed || register_blocked(reg) == 0, "register already marked as used");
3801 set_register_blocked(reg, 1);
3802 }
3803 }
3804
3805 // mark assigned_reg and assigned_regHi of the interval as unblocked
3806 void MoveResolver::unblock_registers(Interval* it) {
3807 int reg = it->assigned_reg();
3808 if (reg < LinearScan::nof_regs) {
3809 assert(register_blocked(reg) > 0, "register already marked as unused");
3810 set_register_blocked(reg, -1);
3811 }
3812 reg = it->assigned_regHi();
3813 if (reg != LinearScan::any_reg && reg < LinearScan::nof_regs) {
3814 assert(register_blocked(reg) > 0, "register already marked as unused");
3815 set_register_blocked(reg, -1);
3816 }
3817 }
3818
3819 // check if assigned_reg and assigned_regHi of the to-interval are not blocked (or only blocked by from)
3820 bool MoveResolver::save_to_process_move(Interval* from, Interval* to) {
3821 int from_reg = -1;
3822 int from_regHi = -1;
3823 if (from != nullptr) {
3824 from_reg = from->assigned_reg();
3825 from_regHi = from->assigned_regHi();
3826 }
3827
3828 int reg = to->assigned_reg();
3829 if (reg < LinearScan::nof_regs) {
3830 if (register_blocked(reg) > 1 || (register_blocked(reg) == 1 && reg != from_reg && reg != from_regHi)) {
3831 return false;
3832 }
3833 }
3834 reg = to->assigned_regHi();
3835 if (reg != LinearScan::any_reg && reg < LinearScan::nof_regs) {
3836 if (register_blocked(reg) > 1 || (register_blocked(reg) == 1 && reg != from_reg && reg != from_regHi)) {
3837 return false;
3838 }
3839 }
3840
3841 return true;
3842 }
3843
3844
3845 void MoveResolver::create_insertion_buffer(LIR_List* list) {
3846 assert(!_insertion_buffer.initialized(), "overwriting existing buffer");
3847 _insertion_buffer.init(list);
3848 }
3849
3850 void MoveResolver::append_insertion_buffer() {
3851 if (_insertion_buffer.initialized()) {
3852 _insertion_buffer.lir_list()->append(&_insertion_buffer);
3853 }
3854 assert(!_insertion_buffer.initialized(), "must be uninitialized now");
3855
3856 _insert_list = nullptr;
3857 _insert_idx = -1;
3858 }
3859
3860 void MoveResolver::insert_move(Interval* from_interval, Interval* to_interval) {
3861 assert(from_interval->reg_num() != to_interval->reg_num(), "from and to interval equal");
3862 assert(from_interval->type() == to_interval->type(), "move between different types");
3863 assert(_insert_list != nullptr && _insert_idx != -1, "must setup insert position first");
3864 assert(_insertion_buffer.lir_list() == _insert_list, "wrong insertion buffer");
3865
3866 LIR_Opr from_opr = get_virtual_register(from_interval);
3867 LIR_Opr to_opr = get_virtual_register(to_interval);
3868
3869 if (!_multiple_reads_allowed) {
3870 // the last_use flag is an optimization for FPU stack allocation. When the same
3871 // input interval is used in more than one move, then it is too difficult to determine
3872 // if this move is really the last use.
3873 from_opr = from_opr->make_last_use();
3874 }
3875 _insertion_buffer.move(_insert_idx, from_opr, to_opr);
3876
3877 TRACE_LINEAR_SCAN(4, tty->print_cr("MoveResolver: inserted move from register %d (%d, %d) to %d (%d, %d)", from_interval->reg_num(), from_interval->assigned_reg(), from_interval->assigned_regHi(), to_interval->reg_num(), to_interval->assigned_reg(), to_interval->assigned_regHi()));
3878 }
3879
3880 void MoveResolver::insert_move(LIR_Opr from_opr, Interval* to_interval) {
3881 assert(from_opr->type() == to_interval->type(), "move between different types");
3882 assert(_insert_list != nullptr && _insert_idx != -1, "must setup insert position first");
3883 assert(_insertion_buffer.lir_list() == _insert_list, "wrong insertion buffer");
3884
3885 LIR_Opr to_opr = get_virtual_register(to_interval);
3886 _insertion_buffer.move(_insert_idx, from_opr, to_opr);
3887
3888 TRACE_LINEAR_SCAN(4, tty->print("MoveResolver: inserted move from constant "); from_opr->print(); tty->print_cr(" to %d (%d, %d)", to_interval->reg_num(), to_interval->assigned_reg(), to_interval->assigned_regHi()));
3889 }
3890
3891 LIR_Opr MoveResolver::get_virtual_register(Interval* interval) {
3892 // Add a little fudge factor for the bailout since the bailout is only checked periodically. This allows us to hand out
3893 // a few extra registers before we really run out which helps to avoid to trip over assertions.
3894 int reg_num = interval->reg_num();
3895 if (reg_num + 20 >= LIR_Opr::vreg_max) {
3896 _allocator->bailout("out of virtual registers in linear scan");
3897 if (reg_num + 2 >= LIR_Opr::vreg_max) {
3898 // Wrap it around and continue until bailout really happens to avoid hitting assertions.
3899 reg_num = LIR_Opr::vreg_base;
3900 }
3901 }
3902 LIR_Opr vreg = LIR_OprFact::virtual_register(reg_num, interval->type());
3903 assert(vreg != LIR_OprFact::illegal(), "ran out of virtual registers");
3904 return vreg;
3905 }
3906
3907 void MoveResolver::resolve_mappings() {
3908 TRACE_LINEAR_SCAN(4, tty->print_cr("MoveResolver: resolving mappings for Block B%d, index %d", _insert_list->block() != nullptr ? _insert_list->block()->block_id() : -1, _insert_idx));
3909 DEBUG_ONLY(verify_before_resolve());
3910
3911 // Block all registers that are used as input operands of a move.
3912 // When a register is blocked, no move to this register is emitted.
3913 // This is necessary for detecting cycles in moves.
3914 int i;
3915 for (i = _mapping_from.length() - 1; i >= 0; i--) {
3916 Interval* from_interval = _mapping_from.at(i);
3917 if (from_interval != nullptr) {
3918 block_registers(from_interval);
3919 }
3920 }
3921
3922 int spill_candidate = -1;
3923 while (_mapping_from.length() > 0) {
3924 bool processed_interval = false;
3925
3926 for (i = _mapping_from.length() - 1; i >= 0; i--) {
3927 Interval* from_interval = _mapping_from.at(i);
3928 Interval* to_interval = _mapping_to.at(i);
3929
3930 if (save_to_process_move(from_interval, to_interval)) {
3931 // this interval can be processed because target is free
3932 if (from_interval != nullptr) {
3933 insert_move(from_interval, to_interval);
3934 unblock_registers(from_interval);
3935 } else {
3936 insert_move(_mapping_from_opr.at(i), to_interval);
3937 }
3938 _mapping_from.remove_at(i);
3939 _mapping_from_opr.remove_at(i);
3940 _mapping_to.remove_at(i);
3941
3942 processed_interval = true;
3943 } else if (from_interval != nullptr && from_interval->assigned_reg() < LinearScan::nof_regs) {
3944 // this interval cannot be processed now because target is not free
3945 // it starts in a register, so it is a possible candidate for spilling
3946 spill_candidate = i;
3947 }
3948 }
3949
3950 if (!processed_interval) {
3951 // no move could be processed because there is a cycle in the move list
3952 // (e.g. r1 -> r2, r2 -> r1), so one interval must be spilled to memory
3953 guarantee(spill_candidate != -1, "no interval in register for spilling found");
3954
3955 // create a new spill interval and assign a stack slot to it
3956 Interval* from_interval = _mapping_from.at(spill_candidate);
3957 Interval* spill_interval = new Interval(-1);
3958 spill_interval->set_type(from_interval->type());
3959
3960 // add a dummy range because real position is difficult to calculate
3961 // Note: this range is a special case when the integrity of the allocation is checked
3962 spill_interval->add_range(1, 2);
3963
3964 // do not allocate a new spill slot for temporary interval, but
3965 // use spill slot assigned to from_interval. Otherwise moves from
3966 // one stack slot to another can happen (not allowed by LIR_Assembler
3967 int spill_slot = from_interval->canonical_spill_slot();
3968 if (spill_slot < 0) {
3969 spill_slot = allocator()->allocate_spill_slot(type2spill_size[spill_interval->type()] == 2);
3970 from_interval->set_canonical_spill_slot(spill_slot);
3971 }
3972 spill_interval->assign_reg(spill_slot);
3973 allocator()->append_interval(spill_interval);
3974
3975 TRACE_LINEAR_SCAN(4, tty->print_cr("created new Interval %d for spilling", spill_interval->reg_num()));
3976
3977 // insert a move from register to stack and update the mapping
3978 insert_move(from_interval, spill_interval);
3979 _mapping_from.at_put(spill_candidate, spill_interval);
3980 unblock_registers(from_interval);
3981 }
3982 }
3983
3984 // reset to default value
3985 _multiple_reads_allowed = false;
3986
3987 // check that all intervals have been processed
3988 DEBUG_ONLY(check_empty());
3989 }
3990
3991
3992 void MoveResolver::set_insert_position(LIR_List* insert_list, int insert_idx) {
3993 TRACE_LINEAR_SCAN(4, tty->print_cr("MoveResolver: setting insert position to Block B%d, index %d", insert_list->block() != nullptr ? insert_list->block()->block_id() : -1, insert_idx));
3994 assert(_insert_list == nullptr && _insert_idx == -1, "use move_insert_position instead of set_insert_position when data already set");
3995
3996 create_insertion_buffer(insert_list);
3997 _insert_list = insert_list;
3998 _insert_idx = insert_idx;
3999 }
4000
4001 void MoveResolver::move_insert_position(LIR_List* insert_list, int insert_idx) {
4002 TRACE_LINEAR_SCAN(4, tty->print_cr("MoveResolver: moving insert position to Block B%d, index %d", insert_list->block() != nullptr ? insert_list->block()->block_id() : -1, insert_idx));
4003
4004 if (_insert_list != nullptr && (insert_list != _insert_list || insert_idx != _insert_idx)) {
4005 // insert position changed -> resolve current mappings
4006 resolve_mappings();
4007 }
4008
4009 if (insert_list != _insert_list) {
4010 // block changed -> append insertion_buffer because it is
4011 // bound to a specific block and create a new insertion_buffer
4012 append_insertion_buffer();
4013 create_insertion_buffer(insert_list);
4014 }
4015
4016 _insert_list = insert_list;
4017 _insert_idx = insert_idx;
4018 }
4019
4020 void MoveResolver::add_mapping(Interval* from_interval, Interval* to_interval) {
4021 TRACE_LINEAR_SCAN(4, tty->print_cr("MoveResolver: adding mapping from %d (%d, %d) to %d (%d, %d)", from_interval->reg_num(), from_interval->assigned_reg(), from_interval->assigned_regHi(), to_interval->reg_num(), to_interval->assigned_reg(), to_interval->assigned_regHi()));
4022
4023 _mapping_from.append(from_interval);
4024 _mapping_from_opr.append(LIR_OprFact::illegalOpr);
4025 _mapping_to.append(to_interval);
4026 }
4027
4028
4029 void MoveResolver::add_mapping(LIR_Opr from_opr, Interval* to_interval) {
4030 TRACE_LINEAR_SCAN(4, tty->print("MoveResolver: adding mapping from "); from_opr->print(); tty->print_cr(" to %d (%d, %d)", to_interval->reg_num(), to_interval->assigned_reg(), to_interval->assigned_regHi()));
4031 assert(from_opr->is_constant(), "only for constants");
4032
4033 _mapping_from.append(nullptr);
4034 _mapping_from_opr.append(from_opr);
4035 _mapping_to.append(to_interval);
4036 }
4037
4038 void MoveResolver::resolve_and_append_moves() {
4039 if (has_mappings()) {
4040 resolve_mappings();
4041 }
4042 append_insertion_buffer();
4043 }
4044
4045
4046
4047 // **** Implementation of Range *************************************
4048
4049 Range::Range(int from, int to, Range* next) :
4050 _from(from),
4051 _to(to),
4052 _next(next)
4053 {
4054 }
4055
4056 // initialize sentinel
4057 Range* Range::_end = nullptr;
4058 void Range::initialize() {
4059 assert(_end == nullptr, "Range initialized more than once");
4060 alignas(Range) static uint8_t end_storage[sizeof(Range)];
4061 _end = ::new(static_cast<void*>(end_storage)) Range(max_jint, max_jint, nullptr);
4062 }
4063
4064 int Range::intersects_at(Range* r2) const {
4065 const Range* r1 = this;
4066
4067 assert(r1 != nullptr && r2 != nullptr, "null ranges not allowed");
4068 assert(r1 != _end && r2 != _end, "empty ranges not allowed");
4069
4070 do {
4071 if (r1->from() < r2->from()) {
4072 if (r1->to() <= r2->from()) {
4073 r1 = r1->next(); if (r1 == _end) return -1;
4074 } else {
4075 return r2->from();
4076 }
4077 } else if (r2->from() < r1->from()) {
4078 if (r2->to() <= r1->from()) {
4079 r2 = r2->next(); if (r2 == _end) return -1;
4080 } else {
4081 return r1->from();
4082 }
4083 } else { // r1->from() == r2->from()
4084 if (r1->from() == r1->to()) {
4085 r1 = r1->next(); if (r1 == _end) return -1;
4086 } else if (r2->from() == r2->to()) {
4087 r2 = r2->next(); if (r2 == _end) return -1;
4088 } else {
4089 return r1->from();
4090 }
4091 }
4092 } while (true);
4093 }
4094
4095 #ifndef PRODUCT
4096 void Range::print(outputStream* out) const {
4097 out->print("[%d, %d[ ", _from, _to);
4098 }
4099 #endif
4100
4101
4102
4103 // **** Implementation of Interval **********************************
4104
4105 // initialize sentinel
4106 Interval* Interval::_end = nullptr;
4107 void Interval::initialize() {
4108 Range::initialize();
4109 assert(_end == nullptr, "Interval initialized more than once");
4110 alignas(Interval) static uint8_t end_storage[sizeof(Interval)];
4111 _end = ::new(static_cast<void*>(end_storage)) Interval(-1);
4112 }
4113
4114 Interval::Interval(int reg_num) :
4115 _reg_num(reg_num),
4116 _type(T_ILLEGAL),
4117 _first(Range::end()),
4118 _use_pos_and_kinds(12),
4119 _current(Range::end()),
4120 _next(_end),
4121 _state(invalidState),
4122 _assigned_reg(LinearScan::any_reg),
4123 _assigned_regHi(LinearScan::any_reg),
4124 _cached_to(-1),
4125 _cached_opr(LIR_OprFact::illegalOpr),
4126 _cached_vm_reg(VMRegImpl::Bad()),
4127 _split_children(nullptr),
4128 _canonical_spill_slot(-1),
4129 _insert_move_when_activated(false),
4130 _spill_state(noDefinitionFound),
4131 _spill_definition_pos(-1),
4132 _register_hint(nullptr)
4133 {
4134 _split_parent = this;
4135 _current_split_child = this;
4136 }
4137
4138 int Interval::calc_to() {
4139 assert(_first != Range::end(), "interval has no range");
4140
4141 Range* r = _first;
4142 while (r->next() != Range::end()) {
4143 r = r->next();
4144 }
4145 return r->to();
4146 }
4147
4148
4149 #ifdef ASSERT
4150 // consistency check of split-children
4151 void Interval::check_split_children() {
4152 if (_split_children != nullptr && _split_children->length() > 0) {
4153 assert(is_split_parent(), "only split parents can have children");
4154
4155 for (int i = 0; i < _split_children->length(); i++) {
4156 Interval* i1 = _split_children->at(i);
4157
4158 assert(i1->split_parent() == this, "not a split child of this interval");
4159 assert(i1->type() == type(), "must be equal for all split children");
4160 assert(i1->canonical_spill_slot() == canonical_spill_slot(), "must be equal for all split children");
4161
4162 for (int j = i + 1; j < _split_children->length(); j++) {
4163 Interval* i2 = _split_children->at(j);
4164
4165 assert(i1->reg_num() != i2->reg_num(), "same register number");
4166
4167 if (i1->from() < i2->from()) {
4168 assert(i1->to() <= i2->from() && i1->to() < i2->to(), "intervals overlapping");
4169 } else {
4170 assert(i2->from() < i1->from(), "intervals start at same op_id");
4171 assert(i2->to() <= i1->from() && i2->to() < i1->to(), "intervals overlapping");
4172 }
4173 }
4174 }
4175 }
4176 }
4177 #endif // ASSERT
4178
4179 Interval* Interval::register_hint(bool search_split_child) const {
4180 if (!search_split_child) {
4181 return _register_hint;
4182 }
4183
4184 if (_register_hint != nullptr) {
4185 assert(_register_hint->is_split_parent(), "only split parents are valid hint registers");
4186
4187 if (_register_hint->assigned_reg() >= 0 && _register_hint->assigned_reg() < LinearScan::nof_regs) {
4188 return _register_hint;
4189
4190 } else if (_register_hint->_split_children != nullptr && _register_hint->_split_children->length() > 0) {
4191 // search the first split child that has a register assigned
4192 int len = _register_hint->_split_children->length();
4193 for (int i = 0; i < len; i++) {
4194 Interval* cur = _register_hint->_split_children->at(i);
4195
4196 if (cur->assigned_reg() >= 0 && cur->assigned_reg() < LinearScan::nof_regs) {
4197 return cur;
4198 }
4199 }
4200 }
4201 }
4202
4203 // no hint interval found that has a register assigned
4204 return nullptr;
4205 }
4206
4207
4208 Interval* Interval::split_child_at_op_id(int op_id, LIR_OpVisitState::OprMode mode) {
4209 assert(is_split_parent(), "can only be called for split parents");
4210 assert(op_id >= 0, "invalid op_id (method can not be called for spill moves)");
4211
4212 Interval* result;
4213 if (_split_children == nullptr || _split_children->length() == 0) {
4214 result = this;
4215 } else {
4216 result = nullptr;
4217 int len = _split_children->length();
4218
4219 // in outputMode, the end of the interval (op_id == cur->to()) is not valid
4220 int to_offset = (mode == LIR_OpVisitState::outputMode ? 0 : 1);
4221
4222 int i;
4223 for (i = 0; i < len; i++) {
4224 Interval* cur = _split_children->at(i);
4225 if (cur->from() <= op_id && op_id < cur->to() + to_offset) {
4226 if (i > 0) {
4227 // exchange current split child to start of list (faster access for next call)
4228 _split_children->at_put(i, _split_children->at(0));
4229 _split_children->at_put(0, cur);
4230 }
4231
4232 // interval found
4233 result = cur;
4234 break;
4235 }
4236 }
4237
4238 #ifdef ASSERT
4239 for (i = 0; i < len; i++) {
4240 Interval* tmp = _split_children->at(i);
4241 if (tmp != result && tmp->from() <= op_id && op_id < tmp->to() + to_offset) {
4242 tty->print_cr("two valid result intervals found for op_id %d: %d and %d", op_id, result->reg_num(), tmp->reg_num());
4243 result->print();
4244 tmp->print();
4245 assert(false, "two valid result intervals found");
4246 }
4247 }
4248 #endif
4249 }
4250
4251 assert(result != nullptr, "no matching interval found");
4252 assert(result->covers(op_id, mode), "op_id not covered by interval");
4253
4254 return result;
4255 }
4256
4257
4258 // returns the last split child that ends before the given op_id
4259 Interval* Interval::split_child_before_op_id(int op_id) {
4260 assert(op_id >= 0, "invalid op_id");
4261
4262 Interval* parent = split_parent();
4263 Interval* result = nullptr;
4264
4265 assert(parent->_split_children != nullptr, "no split children available");
4266 int len = parent->_split_children->length();
4267 assert(len > 0, "no split children available");
4268
4269 for (int i = len - 1; i >= 0; i--) {
4270 Interval* cur = parent->_split_children->at(i);
4271 if (cur->to() <= op_id && (result == nullptr || result->to() < cur->to())) {
4272 result = cur;
4273 }
4274 }
4275
4276 assert(result != nullptr, "no split child found");
4277 return result;
4278 }
4279
4280
4281 // Note: use positions are sorted descending -> first use has highest index
4282 int Interval::first_usage(IntervalUseKind min_use_kind) const {
4283 assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");
4284
4285 for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {
4286 if (_use_pos_and_kinds.at(i + 1) >= min_use_kind) {
4287 return _use_pos_and_kinds.at(i);
4288 }
4289 }
4290 return max_jint;
4291 }
4292
4293 int Interval::next_usage(IntervalUseKind min_use_kind, int from) const {
4294 assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");
4295
4296 for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {
4297 if (_use_pos_and_kinds.at(i) >= from && _use_pos_and_kinds.at(i + 1) >= min_use_kind) {
4298 return _use_pos_and_kinds.at(i);
4299 }
4300 }
4301 return max_jint;
4302 }
4303
4304 int Interval::next_usage_exact(IntervalUseKind exact_use_kind, int from) const {
4305 assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");
4306
4307 for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {
4308 if (_use_pos_and_kinds.at(i) >= from && _use_pos_and_kinds.at(i + 1) == exact_use_kind) {
4309 return _use_pos_and_kinds.at(i);
4310 }
4311 }
4312 return max_jint;
4313 }
4314
4315 int Interval::previous_usage(IntervalUseKind min_use_kind, int from) const {
4316 assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");
4317
4318 int prev = 0;
4319 for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {
4320 if (_use_pos_and_kinds.at(i) > from) {
4321 return prev;
4322 }
4323 if (_use_pos_and_kinds.at(i + 1) >= min_use_kind) {
4324 prev = _use_pos_and_kinds.at(i);
4325 }
4326 }
4327 return prev;
4328 }
4329
4330 void Interval::add_use_pos(int pos, IntervalUseKind use_kind) {
4331 assert(covers(pos, LIR_OpVisitState::inputMode), "use position not covered by live range");
4332
4333 // do not add use positions for precolored intervals because
4334 // they are never used
4335 if (use_kind != noUse && reg_num() >= LIR_Opr::vreg_base) {
4336 #ifdef ASSERT
4337 assert(_use_pos_and_kinds.length() % 2 == 0, "must be");
4338 for (int i = 0; i < _use_pos_and_kinds.length(); i += 2) {
4339 assert(pos <= _use_pos_and_kinds.at(i), "already added a use-position with lower position");
4340 assert(_use_pos_and_kinds.at(i + 1) >= firstValidKind && _use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");
4341 if (i > 0) {
4342 assert(_use_pos_and_kinds.at(i) < _use_pos_and_kinds.at(i - 2), "not sorted descending");
4343 }
4344 }
4345 #endif
4346
4347 // Note: add_use is called in descending order, so list gets sorted
4348 // automatically by just appending new use positions
4349 int len = _use_pos_and_kinds.length();
4350 if (len == 0 || _use_pos_and_kinds.at(len - 2) > pos) {
4351 _use_pos_and_kinds.append(pos);
4352 _use_pos_and_kinds.append(use_kind);
4353 } else if (_use_pos_and_kinds.at(len - 1) < use_kind) {
4354 assert(_use_pos_and_kinds.at(len - 2) == pos, "list not sorted correctly");
4355 _use_pos_and_kinds.at_put(len - 1, use_kind);
4356 }
4357 }
4358 }
4359
4360 void Interval::add_range(int from, int to) {
4361 assert(from < to, "invalid range");
4362 assert(first() == Range::end() || to < first()->next()->from(), "not inserting at begin of interval");
4363 assert(from <= first()->to(), "not inserting at begin of interval");
4364
4365 if (first()->from() <= to) {
4366 // join intersecting ranges
4367 first()->set_from(MIN2(from, first()->from()));
4368 first()->set_to (MAX2(to, first()->to()));
4369 } else {
4370 // insert new range
4371 _first = new Range(from, to, first());
4372 }
4373 }
4374
4375 Interval* Interval::new_split_child() {
4376 // allocate new interval
4377 Interval* result = new Interval(-1);
4378 result->set_type(type());
4379
4380 Interval* parent = split_parent();
4381 result->_split_parent = parent;
4382 result->set_register_hint(parent);
4383
4384 // insert new interval in children-list of parent
4385 if (parent->_split_children == nullptr) {
4386 assert(is_split_parent(), "list must be initialized at first split");
4387
4388 parent->_split_children = new IntervalList(4);
4389 parent->_split_children->append(this);
4390 }
4391 parent->_split_children->append(result);
4392
4393 return result;
4394 }
4395
4396 // split this interval at the specified position and return
4397 // the remainder as a new interval.
4398 //
4399 // when an interval is split, a bi-directional link is established between the original interval
4400 // (the split parent) and the intervals that are split off this interval (the split children)
4401 // When a split child is split again, the new created interval is also a direct child
4402 // of the original parent (there is no tree of split children stored, but a flat list)
4403 // All split children are spilled to the same stack slot (stored in _canonical_spill_slot)
4404 //
4405 // Note: The new interval has no valid reg_num
4406 Interval* Interval::split(int split_pos) {
4407 assert(LinearScan::is_virtual_interval(this), "cannot split fixed intervals");
4408
4409 // allocate new interval
4410 Interval* result = new_split_child();
4411
4412 // split the ranges
4413 Range* prev = nullptr;
4414 Range* cur = _first;
4415 while (cur != Range::end() && cur->to() <= split_pos) {
4416 prev = cur;
4417 cur = cur->next();
4418 }
4419 assert(cur != Range::end(), "split interval after end of last range");
4420
4421 if (cur->from() < split_pos) {
4422 result->_first = new Range(split_pos, cur->to(), cur->next());
4423 cur->set_to(split_pos);
4424 cur->set_next(Range::end());
4425
4426 } else {
4427 assert(prev != nullptr, "split before start of first range");
4428 result->_first = cur;
4429 prev->set_next(Range::end());
4430 }
4431 result->_current = result->_first;
4432 _cached_to = -1; // clear cached value
4433
4434 // split list of use positions
4435 int total_len = _use_pos_and_kinds.length();
4436 int start_idx = total_len - 2;
4437 while (start_idx >= 0 && _use_pos_and_kinds.at(start_idx) < split_pos) {
4438 start_idx -= 2;
4439 }
4440
4441 intStack new_use_pos_and_kinds(total_len - start_idx);
4442 int i;
4443 for (i = start_idx + 2; i < total_len; i++) {
4444 new_use_pos_and_kinds.append(_use_pos_and_kinds.at(i));
4445 }
4446
4447 _use_pos_and_kinds.trunc_to(start_idx + 2);
4448 result->_use_pos_and_kinds = _use_pos_and_kinds;
4449 _use_pos_and_kinds = new_use_pos_and_kinds;
4450
4451 #ifdef ASSERT
4452 assert(_use_pos_and_kinds.length() % 2 == 0, "must have use kind for each use pos");
4453 assert(result->_use_pos_and_kinds.length() % 2 == 0, "must have use kind for each use pos");
4454 assert(_use_pos_and_kinds.length() + result->_use_pos_and_kinds.length() == total_len, "missed some entries");
4455
4456 for (i = 0; i < _use_pos_and_kinds.length(); i += 2) {
4457 assert(_use_pos_and_kinds.at(i) < split_pos, "must be");
4458 assert(_use_pos_and_kinds.at(i + 1) >= firstValidKind && _use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");
4459 }
4460 for (i = 0; i < result->_use_pos_and_kinds.length(); i += 2) {
4461 assert(result->_use_pos_and_kinds.at(i) >= split_pos, "must be");
4462 assert(result->_use_pos_and_kinds.at(i + 1) >= firstValidKind && result->_use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");
4463 }
4464 #endif
4465
4466 return result;
4467 }
4468
4469 // split this interval at the specified position and return
4470 // the head as a new interval (the original interval is the tail)
4471 //
4472 // Currently, only the first range can be split, and the new interval
4473 // must not have split positions
4474 Interval* Interval::split_from_start(int split_pos) {
4475 assert(LinearScan::is_virtual_interval(this), "cannot split fixed intervals");
4476 assert(split_pos > from() && split_pos < to(), "can only split inside interval");
4477 assert(split_pos > _first->from() && split_pos <= _first->to(), "can only split inside first range");
4478 assert(first_usage(noUse) > split_pos, "can not split when use positions are present");
4479
4480 // allocate new interval
4481 Interval* result = new_split_child();
4482
4483 // the new created interval has only one range (checked by assertion above),
4484 // so the splitting of the ranges is very simple
4485 result->add_range(_first->from(), split_pos);
4486
4487 if (split_pos == _first->to()) {
4488 assert(_first->next() != Range::end(), "must not be at end");
4489 _first = _first->next();
4490 } else {
4491 _first->set_from(split_pos);
4492 }
4493
4494 return result;
4495 }
4496
4497
4498 // returns true if the op_id is inside the interval
4499 bool Interval::covers(int op_id, LIR_OpVisitState::OprMode mode) const {
4500 Range* cur = _first;
4501
4502 while (cur != Range::end() && cur->to() < op_id) {
4503 cur = cur->next();
4504 }
4505 if (cur != Range::end()) {
4506 assert(cur->to() != cur->next()->from(), "ranges not separated");
4507
4508 if (mode == LIR_OpVisitState::outputMode) {
4509 return cur->from() <= op_id && op_id < cur->to();
4510 } else {
4511 return cur->from() <= op_id && op_id <= cur->to();
4512 }
4513 }
4514 return false;
4515 }
4516
4517 // returns true if the interval has any hole between hole_from and hole_to
4518 // (even if the hole has only the length 1)
4519 bool Interval::has_hole_between(int hole_from, int hole_to) {
4520 assert(hole_from < hole_to, "check");
4521 assert(from() <= hole_from && hole_to <= to(), "index out of interval");
4522
4523 Range* cur = _first;
4524 while (cur != Range::end()) {
4525 assert(cur->to() < cur->next()->from(), "no space between ranges");
4526
4527 // hole-range starts before this range -> hole
4528 if (hole_from < cur->from()) {
4529 return true;
4530
4531 // hole-range completely inside this range -> no hole
4532 } else if (hole_to <= cur->to()) {
4533 return false;
4534
4535 // overlapping of hole-range with this range -> hole
4536 } else if (hole_from <= cur->to()) {
4537 return true;
4538 }
4539
4540 cur = cur->next();
4541 }
4542
4543 return false;
4544 }
4545
4546 // Check if there is an intersection with any of the split children of 'interval'
4547 bool Interval::intersects_any_children_of(Interval* interval) const {
4548 if (interval->_split_children != nullptr) {
4549 for (int i = 0; i < interval->_split_children->length(); i++) {
4550 if (intersects(interval->_split_children->at(i))) {
4551 return true;
4552 }
4553 }
4554 }
4555 return false;
4556 }
4557
4558
4559 #ifndef PRODUCT
4560 void Interval::print_on(outputStream* out, bool is_cfg_printer) const {
4561 const char* SpillState2Name[] = { "no definition", "no spill store", "one spill store", "store at definition", "start in memory", "no optimization" };
4562 const char* UseKind2Name[] = { "N", "L", "S", "M" };
4563
4564 const char* type_name;
4565 if (reg_num() < LIR_Opr::vreg_base) {
4566 type_name = "fixed";
4567 } else {
4568 type_name = type2name(type());
4569 }
4570 out->print("%d %s ", reg_num(), type_name);
4571
4572 if (is_cfg_printer) {
4573 // Special version for compatibility with C1 Visualizer.
4574 LIR_Opr opr = LinearScan::get_operand(reg_num());
4575 if (opr->is_valid()) {
4576 out->print("\"");
4577 opr->print(out);
4578 out->print("\" ");
4579 }
4580 } else {
4581 // Improved output for normal debugging.
4582 if (reg_num() < LIR_Opr::vreg_base) {
4583 LinearScan::print_reg_num(out, assigned_reg());
4584 } else if (assigned_reg() != -1 && (LinearScan::num_physical_regs(type()) == 1 || assigned_regHi() != -1)) {
4585 LinearScan::calc_operand_for_interval(this)->print(out);
4586 } else {
4587 // Virtual register that has no assigned register yet.
4588 out->print("[ANY]");
4589 }
4590 out->print(" ");
4591 }
4592 out->print("%d %d ", split_parent()->reg_num(), (register_hint(false) != nullptr ? register_hint(false)->reg_num() : -1));
4593
4594 // print ranges
4595 Range* cur = _first;
4596 while (cur != Range::end()) {
4597 cur->print(out);
4598 cur = cur->next();
4599 assert(cur != nullptr, "range list not closed with range sentinel");
4600 }
4601
4602 // print use positions
4603 int prev = 0;
4604 assert(_use_pos_and_kinds.length() % 2 == 0, "must be");
4605 for (int i =_use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {
4606 assert(_use_pos_and_kinds.at(i + 1) >= firstValidKind && _use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");
4607 assert(prev < _use_pos_and_kinds.at(i), "use positions not sorted");
4608
4609 out->print("%d %s ", _use_pos_and_kinds.at(i), UseKind2Name[_use_pos_and_kinds.at(i + 1)]);
4610 prev = _use_pos_and_kinds.at(i);
4611 }
4612
4613 out->print(" \"%s\"", SpillState2Name[spill_state()]);
4614 out->cr();
4615 }
4616
4617 void Interval::print_parent() const {
4618 if (_split_parent != this) {
4619 _split_parent->print_on(tty);
4620 } else {
4621 tty->print_cr("Parent: this");
4622 }
4623 }
4624
4625 void Interval::print_children() const {
4626 if (_split_children == nullptr) {
4627 tty->print_cr("Children: []");
4628 } else {
4629 tty->print_cr("Children:");
4630 for (int i = 0; i < _split_children->length(); i++) {
4631 tty->print("%d: ", i);
4632 _split_children->at(i)->print_on(tty);
4633 }
4634 }
4635 }
4636 #endif // NOT PRODUCT
4637
4638
4639
4640
4641 // **** Implementation of IntervalWalker ****************************
4642
4643 IntervalWalker::IntervalWalker(LinearScan* allocator, Interval* unhandled_fixed_first, Interval* unhandled_any_first)
4644 : _compilation(allocator->compilation())
4645 , _allocator(allocator)
4646 {
4647 _unhandled_first[fixedKind] = unhandled_fixed_first;
4648 _unhandled_first[anyKind] = unhandled_any_first;
4649 _active_first[fixedKind] = Interval::end();
4650 _inactive_first[fixedKind] = Interval::end();
4651 _active_first[anyKind] = Interval::end();
4652 _inactive_first[anyKind] = Interval::end();
4653 _current_position = -1;
4654 _current = nullptr;
4655 next_interval();
4656 }
4657
4658
4659 // append interval in order of current range from()
4660 void IntervalWalker::append_sorted(Interval** list, Interval* interval) {
4661 Interval* prev = nullptr;
4662 Interval* cur = *list;
4663 while (cur->current_from() < interval->current_from()) {
4664 prev = cur; cur = cur->next();
4665 }
4666 if (prev == nullptr) {
4667 *list = interval;
4668 } else {
4669 prev->set_next(interval);
4670 }
4671 interval->set_next(cur);
4672 }
4673
4674 void IntervalWalker::append_to_unhandled(Interval** list, Interval* interval) {
4675 assert(interval->from() >= current()->current_from(), "cannot append new interval before current walk position");
4676
4677 Interval* prev = nullptr;
4678 Interval* cur = *list;
4679 while (cur->from() < interval->from() || (cur->from() == interval->from() && cur->first_usage(noUse) < interval->first_usage(noUse))) {
4680 prev = cur; cur = cur->next();
4681 }
4682 if (prev == nullptr) {
4683 *list = interval;
4684 } else {
4685 prev->set_next(interval);
4686 }
4687 interval->set_next(cur);
4688 }
4689
4690
4691 inline bool IntervalWalker::remove_from_list(Interval** list, Interval* i) {
4692 while (*list != Interval::end() && *list != i) {
4693 list = (*list)->next_addr();
4694 }
4695 if (*list != Interval::end()) {
4696 assert(*list == i, "check");
4697 *list = (*list)->next();
4698 return true;
4699 } else {
4700 return false;
4701 }
4702 }
4703
4704 void IntervalWalker::remove_from_list(Interval* i) {
4705 bool deleted;
4706
4707 if (i->state() == activeState) {
4708 deleted = remove_from_list(active_first_addr(anyKind), i);
4709 } else {
4710 assert(i->state() == inactiveState, "invalid state");
4711 deleted = remove_from_list(inactive_first_addr(anyKind), i);
4712 }
4713
4714 assert(deleted, "interval has not been found in list");
4715 }
4716
4717
4718 void IntervalWalker::walk_to(IntervalState state, int from) {
4719 assert (state == activeState || state == inactiveState, "wrong state");
4720 for_each_interval_kind(kind) {
4721 Interval** prev = state == activeState ? active_first_addr(kind) : inactive_first_addr(kind);
4722 Interval* next = *prev;
4723 while (next->current_from() <= from) {
4724 Interval* cur = next;
4725 next = cur->next();
4726
4727 bool range_has_changed = false;
4728 while (cur->current_to() <= from) {
4729 cur->next_range();
4730 range_has_changed = true;
4731 }
4732
4733 // also handle move from inactive list to active list
4734 range_has_changed = range_has_changed || (state == inactiveState && cur->current_from() <= from);
4735
4736 if (range_has_changed) {
4737 // remove cur from list
4738 *prev = next;
4739 if (cur->current_at_end()) {
4740 // move to handled state (not maintained as a list)
4741 cur->set_state(handledState);
4742 DEBUG_ONLY(interval_moved(cur, kind, state, handledState);)
4743 } else if (cur->current_from() <= from){
4744 // sort into active list
4745 append_sorted(active_first_addr(kind), cur);
4746 cur->set_state(activeState);
4747 if (*prev == cur) {
4748 assert(state == activeState, "check");
4749 prev = cur->next_addr();
4750 }
4751 DEBUG_ONLY(interval_moved(cur, kind, state, activeState);)
4752 } else {
4753 // sort into inactive list
4754 append_sorted(inactive_first_addr(kind), cur);
4755 cur->set_state(inactiveState);
4756 if (*prev == cur) {
4757 assert(state == inactiveState, "check");
4758 prev = cur->next_addr();
4759 }
4760 DEBUG_ONLY(interval_moved(cur, kind, state, inactiveState);)
4761 }
4762 } else {
4763 prev = cur->next_addr();
4764 continue;
4765 }
4766 }
4767 }
4768 }
4769
4770
4771 void IntervalWalker::next_interval() {
4772 IntervalKind kind;
4773 Interval* any = _unhandled_first[anyKind];
4774 Interval* fixed = _unhandled_first[fixedKind];
4775
4776 if (any != Interval::end()) {
4777 // intervals may start at same position -> prefer fixed interval
4778 kind = fixed != Interval::end() && fixed->from() <= any->from() ? fixedKind : anyKind;
4779
4780 assert((kind == fixedKind && fixed->from() <= any->from()) ||
4781 (kind == anyKind && any->from() <= fixed->from()), "wrong interval!!!");
4782 assert(any == Interval::end() || fixed == Interval::end() || any->from() != fixed->from() || kind == fixedKind, "if fixed and any-Interval start at same position, fixed must be processed first");
4783
4784 } else if (fixed != Interval::end()) {
4785 kind = fixedKind;
4786 } else {
4787 _current = nullptr; return;
4788 }
4789 _current_kind = kind;
4790 _current = _unhandled_first[kind];
4791 _unhandled_first[kind] = _current->next();
4792 _current->set_next(Interval::end());
4793 _current->rewind_range();
4794 }
4795
4796
4797 void IntervalWalker::walk_to(int lir_op_id) {
4798 assert(_current_position <= lir_op_id, "can not walk backwards");
4799 while (current() != nullptr) {
4800 bool is_active = current()->from() <= lir_op_id;
4801 int id = is_active ? current()->from() : lir_op_id;
4802
4803 TRACE_LINEAR_SCAN(2, if (_current_position < id) { tty->cr(); tty->print_cr("walk_to(%d) **************************************************************", id); })
4804
4805 // set _current_position prior to call of walk_to
4806 _current_position = id;
4807
4808 // call walk_to even if _current_position == id
4809 walk_to(activeState, id);
4810 walk_to(inactiveState, id);
4811
4812 if (is_active) {
4813 current()->set_state(activeState);
4814 if (activate_current()) {
4815 append_sorted(active_first_addr(current_kind()), current());
4816 DEBUG_ONLY(interval_moved(current(), current_kind(), unhandledState, activeState);)
4817 }
4818
4819 next_interval();
4820 } else {
4821 return;
4822 }
4823 }
4824 }
4825
4826 #ifdef ASSERT
4827 void IntervalWalker::interval_moved(Interval* interval, IntervalKind kind, IntervalState from, IntervalState to) {
4828 if (TraceLinearScanLevel >= 4) {
4829 #define print_state(state) \
4830 switch(state) {\
4831 case unhandledState: tty->print("unhandled"); break;\
4832 case activeState: tty->print("active"); break;\
4833 case inactiveState: tty->print("inactive"); break;\
4834 case handledState: tty->print("handled"); break;\
4835 default: ShouldNotReachHere(); \
4836 }
4837
4838 print_state(from); tty->print(" to "); print_state(to);
4839 tty->fill_to(23);
4840 interval->print();
4841
4842 #undef print_state
4843 }
4844 }
4845 #endif // ASSERT
4846
4847 // **** Implementation of LinearScanWalker **************************
4848
4849 LinearScanWalker::LinearScanWalker(LinearScan* allocator, Interval* unhandled_fixed_first, Interval* unhandled_any_first)
4850 : IntervalWalker(allocator, unhandled_fixed_first, unhandled_any_first)
4851 , _move_resolver(allocator)
4852 {
4853 for (int i = 0; i < LinearScan::nof_regs; i++) {
4854 _spill_intervals[i] = new IntervalList(2);
4855 }
4856 }
4857
4858
4859 inline void LinearScanWalker::init_use_lists(bool only_process_use_pos) {
4860 for (int i = _first_reg; i <= _last_reg; i++) {
4861 _use_pos[i] = max_jint;
4862
4863 if (!only_process_use_pos) {
4864 _block_pos[i] = max_jint;
4865 _spill_intervals[i]->clear();
4866 }
4867 }
4868 }
4869
4870 inline void LinearScanWalker::exclude_from_use(int reg) {
4871 assert(reg < LinearScan::nof_regs, "interval must have a register assigned (stack slots not allowed)");
4872 if (reg >= _first_reg && reg <= _last_reg) {
4873 _use_pos[reg] = 0;
4874 }
4875 }
4876 inline void LinearScanWalker::exclude_from_use(Interval* i) {
4877 assert(i->assigned_reg() != any_reg, "interval has no register assigned");
4878
4879 exclude_from_use(i->assigned_reg());
4880 exclude_from_use(i->assigned_regHi());
4881 }
4882
4883 inline void LinearScanWalker::set_use_pos(int reg, Interval* i, int use_pos, bool only_process_use_pos) {
4884 assert(use_pos != 0, "must use exclude_from_use to set use_pos to 0");
4885
4886 if (reg >= _first_reg && reg <= _last_reg) {
4887 if (_use_pos[reg] > use_pos) {
4888 _use_pos[reg] = use_pos;
4889 }
4890 if (!only_process_use_pos) {
4891 _spill_intervals[reg]->append(i);
4892 }
4893 }
4894 }
4895 inline void LinearScanWalker::set_use_pos(Interval* i, int use_pos, bool only_process_use_pos) {
4896 assert(i->assigned_reg() != any_reg, "interval has no register assigned");
4897 if (use_pos != -1) {
4898 set_use_pos(i->assigned_reg(), i, use_pos, only_process_use_pos);
4899 set_use_pos(i->assigned_regHi(), i, use_pos, only_process_use_pos);
4900 }
4901 }
4902
4903 inline void LinearScanWalker::set_block_pos(int reg, Interval* i, int block_pos) {
4904 if (reg >= _first_reg && reg <= _last_reg) {
4905 if (_block_pos[reg] > block_pos) {
4906 _block_pos[reg] = block_pos;
4907 }
4908 if (_use_pos[reg] > block_pos) {
4909 _use_pos[reg] = block_pos;
4910 }
4911 }
4912 }
4913 inline void LinearScanWalker::set_block_pos(Interval* i, int block_pos) {
4914 assert(i->assigned_reg() != any_reg, "interval has no register assigned");
4915 if (block_pos != -1) {
4916 set_block_pos(i->assigned_reg(), i, block_pos);
4917 set_block_pos(i->assigned_regHi(), i, block_pos);
4918 }
4919 }
4920
4921
4922 void LinearScanWalker::free_exclude_active_fixed() {
4923 Interval* list = active_first(fixedKind);
4924 while (list != Interval::end()) {
4925 assert(list->assigned_reg() < LinearScan::nof_regs, "active interval must have a register assigned");
4926 exclude_from_use(list);
4927 list = list->next();
4928 }
4929 }
4930
4931 void LinearScanWalker::free_exclude_active_any() {
4932 Interval* list = active_first(anyKind);
4933 while (list != Interval::end()) {
4934 exclude_from_use(list);
4935 list = list->next();
4936 }
4937 }
4938
4939 void LinearScanWalker::free_collect_inactive_fixed(Interval* cur) {
4940 Interval* list = inactive_first(fixedKind);
4941 while (list != Interval::end()) {
4942 if (cur->to() <= list->current_from()) {
4943 assert(list->current_intersects_at(cur) == -1, "must not intersect");
4944 set_use_pos(list, list->current_from(), true);
4945 } else {
4946 set_use_pos(list, list->current_intersects_at(cur), true);
4947 }
4948 list = list->next();
4949 }
4950 }
4951
4952 void LinearScanWalker::free_collect_inactive_any(Interval* cur) {
4953 Interval* list = inactive_first(anyKind);
4954 while (list != Interval::end()) {
4955 set_use_pos(list, list->current_intersects_at(cur), true);
4956 list = list->next();
4957 }
4958 }
4959
4960 void LinearScanWalker::spill_exclude_active_fixed() {
4961 Interval* list = active_first(fixedKind);
4962 while (list != Interval::end()) {
4963 exclude_from_use(list);
4964 list = list->next();
4965 }
4966 }
4967
4968 void LinearScanWalker::spill_block_inactive_fixed(Interval* cur) {
4969 Interval* list = inactive_first(fixedKind);
4970 while (list != Interval::end()) {
4971 if (cur->to() > list->current_from()) {
4972 set_block_pos(list, list->current_intersects_at(cur));
4973 } else {
4974 assert(list->current_intersects_at(cur) == -1, "invalid optimization: intervals intersect");
4975 }
4976
4977 list = list->next();
4978 }
4979 }
4980
4981 void LinearScanWalker::spill_collect_active_any() {
4982 Interval* list = active_first(anyKind);
4983 while (list != Interval::end()) {
4984 set_use_pos(list, MIN2(list->next_usage(loopEndMarker, _current_position), list->to()), false);
4985 list = list->next();
4986 }
4987 }
4988
4989 void LinearScanWalker::spill_collect_inactive_any(Interval* cur) {
4990 Interval* list = inactive_first(anyKind);
4991 while (list != Interval::end()) {
4992 if (list->current_intersects(cur)) {
4993 set_use_pos(list, MIN2(list->next_usage(loopEndMarker, _current_position), list->to()), false);
4994 }
4995 list = list->next();
4996 }
4997 }
4998
4999
5000 void LinearScanWalker::insert_move(int op_id, Interval* src_it, Interval* dst_it) {
5001 // output all moves here. When source and target are equal, the move is
5002 // optimized away later in assign_reg_nums
5003
5004 op_id = (op_id + 1) & ~1;
5005 BlockBegin* op_block = allocator()->block_of_op_with_id(op_id);
5006 assert(op_id > 0 && allocator()->block_of_op_with_id(op_id - 2) == op_block, "cannot insert move at block boundary");
5007
5008 // calculate index of instruction inside instruction list of current block
5009 // the minimal index (for a block with no spill moves) can be calculated because the
5010 // numbering of instructions is known.
5011 // When the block already contains spill moves, the index must be increased until the
5012 // correct index is reached.
5013 LIR_OpList* list = op_block->lir()->instructions_list();
5014 int index = (op_id - list->at(0)->id()) / 2;
5015 assert(list->at(index)->id() <= op_id, "error in calculation");
5016
5017 while (list->at(index)->id() != op_id) {
5018 index++;
5019 assert(0 <= index && index < list->length(), "index out of bounds");
5020 }
5021 assert(1 <= index && index < list->length(), "index out of bounds");
5022 assert(list->at(index)->id() == op_id, "error in calculation");
5023
5024 // insert new instruction before instruction at position index
5025 _move_resolver.move_insert_position(op_block->lir(), index - 1);
5026 _move_resolver.add_mapping(src_it, dst_it);
5027 }
5028
5029
5030 int LinearScanWalker::find_optimal_split_pos(BlockBegin* min_block, BlockBegin* max_block, int max_split_pos) {
5031 int from_block_nr = min_block->linear_scan_number();
5032 int to_block_nr = max_block->linear_scan_number();
5033
5034 assert(0 <= from_block_nr && from_block_nr < block_count(), "out of range");
5035 assert(0 <= to_block_nr && to_block_nr < block_count(), "out of range");
5036 assert(from_block_nr < to_block_nr, "must cross block boundary");
5037
5038 // Try to split at end of max_block. If this would be after
5039 // max_split_pos, then use the begin of max_block
5040 int optimal_split_pos = max_block->last_lir_instruction_id() + 2;
5041 if (optimal_split_pos > max_split_pos) {
5042 optimal_split_pos = max_block->first_lir_instruction_id();
5043 }
5044
5045 int min_loop_depth = max_block->loop_depth();
5046 for (int i = to_block_nr - 1; i >= from_block_nr; i--) {
5047 BlockBegin* cur = block_at(i);
5048
5049 if (cur->loop_depth() < min_loop_depth) {
5050 // block with lower loop-depth found -> split at the end of this block
5051 min_loop_depth = cur->loop_depth();
5052 optimal_split_pos = cur->last_lir_instruction_id() + 2;
5053 }
5054 }
5055 assert(optimal_split_pos > allocator()->max_lir_op_id() || allocator()->is_block_begin(optimal_split_pos), "algorithm must move split pos to block boundary");
5056
5057 return optimal_split_pos;
5058 }
5059
5060
5061 int LinearScanWalker::find_optimal_split_pos(Interval* it, int min_split_pos, int max_split_pos, bool do_loop_optimization) {
5062 int optimal_split_pos = -1;
5063 if (min_split_pos == max_split_pos) {
5064 // trivial case, no optimization of split position possible
5065 TRACE_LINEAR_SCAN(4, tty->print_cr(" min-pos and max-pos are equal, no optimization possible"));
5066 optimal_split_pos = min_split_pos;
5067
5068 } else {
5069 assert(min_split_pos < max_split_pos, "must be true then");
5070 assert(min_split_pos > 0, "cannot access min_split_pos - 1 otherwise");
5071
5072 // reason for using min_split_pos - 1: when the minimal split pos is exactly at the
5073 // beginning of a block, then min_split_pos is also a possible split position.
5074 // Use the block before as min_block, because then min_block->last_lir_instruction_id() + 2 == min_split_pos
5075 BlockBegin* min_block = allocator()->block_of_op_with_id(min_split_pos - 1);
5076
5077 // reason for using max_split_pos - 1: otherwise there would be an assertion failure
5078 // when an interval ends at the end of the last block of the method
5079 // (in this case, max_split_pos == allocator()->max_lir_op_id() + 2, and there is no
5080 // block at this op_id)
5081 BlockBegin* max_block = allocator()->block_of_op_with_id(max_split_pos - 1);
5082
5083 assert(min_block->linear_scan_number() <= max_block->linear_scan_number(), "invalid order");
5084 if (min_block == max_block) {
5085 // split position cannot be moved to block boundary, so split as late as possible
5086 TRACE_LINEAR_SCAN(4, tty->print_cr(" cannot move split pos to block boundary because min_pos and max_pos are in same block"));
5087 optimal_split_pos = max_split_pos;
5088
5089 } else if (it->has_hole_between(max_split_pos - 1, max_split_pos) && !allocator()->is_block_begin(max_split_pos)) {
5090 // Do not move split position if the interval has a hole before max_split_pos.
5091 // Intervals resulting from Phi-Functions have more than one definition (marked
5092 // as mustHaveRegister) with a hole before each definition. When the register is needed
5093 // for the second definition, an earlier reloading is unnecessary.
5094 TRACE_LINEAR_SCAN(4, tty->print_cr(" interval has hole just before max_split_pos, so splitting at max_split_pos"));
5095 optimal_split_pos = max_split_pos;
5096
5097 } else {
5098 // search optimal block boundary between min_split_pos and max_split_pos
5099 TRACE_LINEAR_SCAN(4, tty->print_cr(" moving split pos to optimal block boundary between block B%d and B%d", min_block->block_id(), max_block->block_id()));
5100
5101 if (do_loop_optimization) {
5102 // Loop optimization: if a loop-end marker is found between min- and max-position,
5103 // then split before this loop
5104 int loop_end_pos = it->next_usage_exact(loopEndMarker, min_block->last_lir_instruction_id() + 2);
5105 TRACE_LINEAR_SCAN(4, tty->print_cr(" loop optimization: loop end found at pos %d", loop_end_pos));
5106
5107 assert(loop_end_pos > min_split_pos, "invalid order");
5108 if (loop_end_pos < max_split_pos) {
5109 // loop-end marker found between min- and max-position
5110 // if it is not the end marker for the same loop as the min-position, then move
5111 // the max-position to this loop block.
5112 // Desired result: uses tagged as shouldHaveRegister inside a loop cause a reloading
5113 // of the interval (normally, only mustHaveRegister causes a reloading)
5114 BlockBegin* loop_block = allocator()->block_of_op_with_id(loop_end_pos);
5115
5116 TRACE_LINEAR_SCAN(4, tty->print_cr(" interval is used in loop that ends in block B%d, so trying to move max_block back from B%d to B%d", loop_block->block_id(), max_block->block_id(), loop_block->block_id()));
5117 assert(loop_block != min_block, "loop_block and min_block must be different because block boundary is needed between");
5118
5119 optimal_split_pos = find_optimal_split_pos(min_block, loop_block, loop_block->last_lir_instruction_id() + 2);
5120 if (optimal_split_pos == loop_block->last_lir_instruction_id() + 2) {
5121 optimal_split_pos = -1;
5122 TRACE_LINEAR_SCAN(4, tty->print_cr(" loop optimization not necessary"));
5123 } else {
5124 TRACE_LINEAR_SCAN(4, tty->print_cr(" loop optimization successful"));
5125 }
5126 }
5127 }
5128
5129 if (optimal_split_pos == -1) {
5130 // not calculated by loop optimization
5131 optimal_split_pos = find_optimal_split_pos(min_block, max_block, max_split_pos);
5132 }
5133 }
5134 }
5135 TRACE_LINEAR_SCAN(4, tty->print_cr(" optimal split position: %d", optimal_split_pos));
5136
5137 return optimal_split_pos;
5138 }
5139
5140
5141 /*
5142 split an interval at the optimal position between min_split_pos and
5143 max_split_pos in two parts:
5144 1) the left part has already a location assigned
5145 2) the right part is sorted into to the unhandled-list
5146 */
5147 void LinearScanWalker::split_before_usage(Interval* it, int min_split_pos, int max_split_pos) {
5148 TRACE_LINEAR_SCAN(2, tty->print ("----- splitting interval: "); it->print());
5149 TRACE_LINEAR_SCAN(2, tty->print_cr(" between %d and %d", min_split_pos, max_split_pos));
5150
5151 assert(it->from() < min_split_pos, "cannot split at start of interval");
5152 assert(current_position() < min_split_pos, "cannot split before current position");
5153 assert(min_split_pos <= max_split_pos, "invalid order");
5154 assert(max_split_pos <= it->to(), "cannot split after end of interval");
5155
5156 int optimal_split_pos = find_optimal_split_pos(it, min_split_pos, max_split_pos, true);
5157
5158 assert(min_split_pos <= optimal_split_pos && optimal_split_pos <= max_split_pos, "out of range");
5159 assert(optimal_split_pos <= it->to(), "cannot split after end of interval");
5160 assert(optimal_split_pos > it->from(), "cannot split at start of interval");
5161
5162 if (optimal_split_pos == it->to() && it->next_usage(mustHaveRegister, min_split_pos) == max_jint) {
5163 // the split position would be just before the end of the interval
5164 // -> no split at all necessary
5165 TRACE_LINEAR_SCAN(4, tty->print_cr(" no split necessary because optimal split position is at end of interval"));
5166 return;
5167 }
5168
5169 // must calculate this before the actual split is performed and before split position is moved to odd op_id
5170 bool move_necessary = !allocator()->is_block_begin(optimal_split_pos) && !it->has_hole_between(optimal_split_pos - 1, optimal_split_pos);
5171
5172 if (!allocator()->is_block_begin(optimal_split_pos)) {
5173 // move position before actual instruction (odd op_id)
5174 optimal_split_pos = (optimal_split_pos - 1) | 1;
5175 }
5176
5177 TRACE_LINEAR_SCAN(4, tty->print_cr(" splitting at position %d", optimal_split_pos));
5178 assert(allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 1), "split pos must be odd when not on block boundary");
5179 assert(!allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 0), "split pos must be even on block boundary");
5180
5181 Interval* split_part = it->split(optimal_split_pos);
5182
5183 allocator()->append_interval(split_part);
5184 allocator()->copy_register_flags(it, split_part);
5185 split_part->set_insert_move_when_activated(move_necessary);
5186 append_to_unhandled(unhandled_first_addr(anyKind), split_part);
5187
5188 TRACE_LINEAR_SCAN(2, tty->print_cr(" split interval in two parts (insert_move_when_activated: %d)", move_necessary));
5189 TRACE_LINEAR_SCAN(2, tty->print (" "); it->print());
5190 TRACE_LINEAR_SCAN(2, tty->print (" "); split_part->print());
5191 }
5192
5193 /*
5194 split an interval at the optimal position between min_split_pos and
5195 max_split_pos in two parts:
5196 1) the left part has already a location assigned
5197 2) the right part is always on the stack and therefore ignored in further processing
5198 */
5199 void LinearScanWalker::split_for_spilling(Interval* it) {
5200 // calculate allowed range of splitting position
5201 int max_split_pos = current_position();
5202 int min_split_pos = MAX2(it->previous_usage(shouldHaveRegister, max_split_pos) + 1, it->from());
5203
5204 TRACE_LINEAR_SCAN(2, tty->print ("----- splitting and spilling interval: "); it->print());
5205 TRACE_LINEAR_SCAN(2, tty->print_cr(" between %d and %d", min_split_pos, max_split_pos));
5206
5207 assert(it->state() == activeState, "why spill interval that is not active?");
5208 assert(it->from() <= min_split_pos, "cannot split before start of interval");
5209 assert(min_split_pos <= max_split_pos, "invalid order");
5210 assert(max_split_pos < it->to(), "cannot split at end end of interval");
5211 assert(current_position() < it->to(), "interval must not end before current position");
5212
5213 if (min_split_pos == it->from()) {
5214 // the whole interval is never used, so spill it entirely to memory
5215 TRACE_LINEAR_SCAN(2, tty->print_cr(" spilling entire interval because split pos is at beginning of interval"));
5216 assert(it->first_usage(shouldHaveRegister) > current_position(), "interval must not have use position before current_position");
5217
5218 allocator()->assign_spill_slot(it);
5219 allocator()->change_spill_state(it, min_split_pos);
5220
5221 // Also kick parent intervals out of register to memory when they have no use
5222 // position. This avoids short interval in register surrounded by intervals in
5223 // memory -> avoid useless moves from memory to register and back
5224 Interval* parent = it;
5225 while (parent != nullptr && parent->is_split_child()) {
5226 parent = parent->split_child_before_op_id(parent->from());
5227
5228 if (parent->assigned_reg() < LinearScan::nof_regs) {
5229 if (parent->first_usage(shouldHaveRegister) == max_jint) {
5230 // parent is never used, so kick it out of its assigned register
5231 TRACE_LINEAR_SCAN(4, tty->print_cr(" kicking out interval %d out of its register because it is never used", parent->reg_num()));
5232 allocator()->assign_spill_slot(parent);
5233 } else {
5234 // do not go further back because the register is actually used by the interval
5235 parent = nullptr;
5236 }
5237 }
5238 }
5239
5240 } else {
5241 // search optimal split pos, split interval and spill only the right hand part
5242 int optimal_split_pos = find_optimal_split_pos(it, min_split_pos, max_split_pos, false);
5243
5244 assert(min_split_pos <= optimal_split_pos && optimal_split_pos <= max_split_pos, "out of range");
5245 assert(optimal_split_pos < it->to(), "cannot split at end of interval");
5246 assert(optimal_split_pos >= it->from(), "cannot split before start of interval");
5247
5248 if (!allocator()->is_block_begin(optimal_split_pos)) {
5249 // move position before actual instruction (odd op_id)
5250 optimal_split_pos = (optimal_split_pos - 1) | 1;
5251 }
5252
5253 TRACE_LINEAR_SCAN(4, tty->print_cr(" splitting at position %d", optimal_split_pos));
5254 assert(allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 1), "split pos must be odd when not on block boundary");
5255 assert(!allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 0), "split pos must be even on block boundary");
5256
5257 Interval* spilled_part = it->split(optimal_split_pos);
5258 allocator()->append_interval(spilled_part);
5259 allocator()->assign_spill_slot(spilled_part);
5260 allocator()->change_spill_state(spilled_part, optimal_split_pos);
5261
5262 if (!allocator()->is_block_begin(optimal_split_pos)) {
5263 TRACE_LINEAR_SCAN(4, tty->print_cr(" inserting move from interval %d to %d", it->reg_num(), spilled_part->reg_num()));
5264 insert_move(optimal_split_pos, it, spilled_part);
5265 }
5266
5267 // the current_split_child is needed later when moves are inserted for reloading
5268 assert(spilled_part->current_split_child() == it, "overwriting wrong current_split_child");
5269 spilled_part->make_current_split_child();
5270
5271 TRACE_LINEAR_SCAN(2, tty->print_cr(" split interval in two parts"));
5272 TRACE_LINEAR_SCAN(2, tty->print (" "); it->print());
5273 TRACE_LINEAR_SCAN(2, tty->print (" "); spilled_part->print());
5274 }
5275 }
5276
5277
5278 void LinearScanWalker::split_stack_interval(Interval* it) {
5279 int min_split_pos = current_position() + 1;
5280 int max_split_pos = MIN2(it->first_usage(shouldHaveRegister), it->to());
5281
5282 split_before_usage(it, min_split_pos, max_split_pos);
5283 }
5284
5285 void LinearScanWalker::split_when_partial_register_available(Interval* it, int register_available_until) {
5286 int min_split_pos = MAX2(it->previous_usage(shouldHaveRegister, register_available_until), it->from() + 1);
5287 int max_split_pos = register_available_until;
5288
5289 split_before_usage(it, min_split_pos, max_split_pos);
5290 }
5291
5292 void LinearScanWalker::split_and_spill_interval(Interval* it) {
5293 assert(it->state() == activeState || it->state() == inactiveState, "other states not allowed");
5294
5295 int current_pos = current_position();
5296 if (it->state() == inactiveState) {
5297 // the interval is currently inactive, so no spill slot is needed for now.
5298 // when the split part is activated, the interval has a new chance to get a register,
5299 // so in the best case no stack slot is necessary
5300 assert(it->has_hole_between(current_pos - 1, current_pos + 1), "interval can not be inactive otherwise");
5301 split_before_usage(it, current_pos + 1, current_pos + 1);
5302
5303 } else {
5304 // search the position where the interval must have a register and split
5305 // at the optimal position before.
5306 // The new created part is added to the unhandled list and will get a register
5307 // when it is activated
5308 int min_split_pos = current_pos + 1;
5309 int max_split_pos = MIN2(it->next_usage(mustHaveRegister, min_split_pos), it->to());
5310
5311 split_before_usage(it, min_split_pos, max_split_pos);
5312
5313 assert(it->next_usage(mustHaveRegister, current_pos) == max_jint, "the remaining part is spilled to stack and therefore has no register");
5314 split_for_spilling(it);
5315 }
5316 }
5317
5318 int LinearScanWalker::find_free_reg(int reg_needed_until, int interval_to, int hint_reg, int ignore_reg, bool* need_split) {
5319 int min_full_reg = any_reg;
5320 int max_partial_reg = any_reg;
5321
5322 for (int i = _first_reg; i <= _last_reg; i++) {
5323 if (i == ignore_reg) {
5324 // this register must be ignored
5325
5326 } else if (_use_pos[i] >= interval_to) {
5327 // this register is free for the full interval
5328 if (min_full_reg == any_reg || i == hint_reg || (_use_pos[i] < _use_pos[min_full_reg] && min_full_reg != hint_reg)) {
5329 min_full_reg = i;
5330 }
5331 } else if (_use_pos[i] > reg_needed_until) {
5332 // this register is at least free until reg_needed_until
5333 if (max_partial_reg == any_reg || i == hint_reg || (_use_pos[i] > _use_pos[max_partial_reg] && max_partial_reg != hint_reg)) {
5334 max_partial_reg = i;
5335 }
5336 }
5337 }
5338
5339 if (min_full_reg != any_reg) {
5340 return min_full_reg;
5341 } else if (max_partial_reg != any_reg) {
5342 *need_split = true;
5343 return max_partial_reg;
5344 } else {
5345 return any_reg;
5346 }
5347 }
5348
5349 int LinearScanWalker::find_free_double_reg(int reg_needed_until, int interval_to, int hint_reg, bool* need_split) {
5350 assert((_last_reg - _first_reg + 1) % 2 == 0, "adjust algorithm");
5351
5352 int min_full_reg = any_reg;
5353 int max_partial_reg = any_reg;
5354
5355 for (int i = _first_reg; i < _last_reg; i+=2) {
5356 if (_use_pos[i] >= interval_to && _use_pos[i + 1] >= interval_to) {
5357 // this register is free for the full interval
5358 if (min_full_reg == any_reg || i == hint_reg || (_use_pos[i] < _use_pos[min_full_reg] && min_full_reg != hint_reg)) {
5359 min_full_reg = i;
5360 }
5361 } else if (_use_pos[i] > reg_needed_until && _use_pos[i + 1] > reg_needed_until) {
5362 // this register is at least free until reg_needed_until
5363 if (max_partial_reg == any_reg || i == hint_reg || (_use_pos[i] > _use_pos[max_partial_reg] && max_partial_reg != hint_reg)) {
5364 max_partial_reg = i;
5365 }
5366 }
5367 }
5368
5369 if (min_full_reg != any_reg) {
5370 return min_full_reg;
5371 } else if (max_partial_reg != any_reg) {
5372 *need_split = true;
5373 return max_partial_reg;
5374 } else {
5375 return any_reg;
5376 }
5377 }
5378
5379 bool LinearScanWalker::alloc_free_reg(Interval* cur) {
5380 TRACE_LINEAR_SCAN(2, tty->print("trying to find free register for "); cur->print());
5381
5382 init_use_lists(true);
5383 free_exclude_active_fixed();
5384 free_exclude_active_any();
5385 free_collect_inactive_fixed(cur);
5386 free_collect_inactive_any(cur);
5387 assert(unhandled_first(fixedKind) == Interval::end(), "must not have unhandled fixed intervals because all fixed intervals have a use at position 0");
5388
5389 // _use_pos contains the start of the next interval that has this register assigned
5390 // (either as a fixed register or a normal allocated register in the past)
5391 // only intervals overlapping with cur are processed, non-overlapping invervals can be ignored safely
5392 #ifdef ASSERT
5393 if (TraceLinearScanLevel >= 4) {
5394 tty->print_cr(" state of registers:");
5395 for (int i = _first_reg; i <= _last_reg; i++) {
5396 tty->print(" reg %d (", i);
5397 LinearScan::print_reg_num(i);
5398 tty->print_cr("): use_pos: %d", _use_pos[i]);
5399 }
5400 }
5401 #endif
5402
5403 int hint_reg, hint_regHi;
5404 Interval* register_hint = cur->register_hint();
5405 if (register_hint != nullptr) {
5406 hint_reg = register_hint->assigned_reg();
5407 hint_regHi = register_hint->assigned_regHi();
5408
5409 if (_num_phys_regs == 2 && allocator()->is_precolored_cpu_interval(register_hint)) {
5410 assert(hint_reg != any_reg && hint_regHi == any_reg, "must be for fixed intervals");
5411 hint_regHi = hint_reg + 1; // connect e.g. eax-edx
5412 }
5413 #ifdef ASSERT
5414 if (TraceLinearScanLevel >= 4) {
5415 tty->print(" hint registers %d (", hint_reg);
5416 LinearScan::print_reg_num(hint_reg);
5417 tty->print("), %d (", hint_regHi);
5418 LinearScan::print_reg_num(hint_regHi);
5419 tty->print(") from interval ");
5420 register_hint->print();
5421 }
5422 #endif
5423 } else {
5424 hint_reg = any_reg;
5425 hint_regHi = any_reg;
5426 }
5427 assert(hint_reg == any_reg || hint_reg != hint_regHi, "hint reg and regHi equal");
5428 assert(cur->assigned_reg() == any_reg && cur->assigned_regHi() == any_reg, "register already assigned to interval");
5429
5430 // the register must be free at least until this position
5431 int reg_needed_until = cur->from() + 1;
5432 int interval_to = cur->to();
5433
5434 bool need_split = false;
5435 int split_pos;
5436 int reg;
5437 int regHi = any_reg;
5438
5439 if (_adjacent_regs) {
5440 reg = find_free_double_reg(reg_needed_until, interval_to, hint_reg, &need_split);
5441 regHi = reg + 1;
5442 if (reg == any_reg) {
5443 return false;
5444 }
5445 split_pos = MIN2(_use_pos[reg], _use_pos[regHi]);
5446
5447 } else {
5448 reg = find_free_reg(reg_needed_until, interval_to, hint_reg, any_reg, &need_split);
5449 if (reg == any_reg) {
5450 return false;
5451 }
5452 split_pos = _use_pos[reg];
5453
5454 if (_num_phys_regs == 2) {
5455 regHi = find_free_reg(reg_needed_until, interval_to, hint_regHi, reg, &need_split);
5456
5457 if (_use_pos[reg] < interval_to && regHi == any_reg) {
5458 // do not split interval if only one register can be assigned until the split pos
5459 // (when one register is found for the whole interval, split&spill is only
5460 // performed for the hi register)
5461 return false;
5462
5463 } else if (regHi != any_reg) {
5464 split_pos = MIN2(split_pos, _use_pos[regHi]);
5465
5466 // sort register numbers to prevent e.g. a move from eax,ebx to ebx,eax
5467 if (reg > regHi) {
5468 int temp = reg;
5469 reg = regHi;
5470 regHi = temp;
5471 }
5472 }
5473 }
5474 }
5475
5476 cur->assign_reg(reg, regHi);
5477 #ifdef ASSERT
5478 if (TraceLinearScanLevel >= 2) {
5479 tty->print(" selected registers %d (", reg);
5480 LinearScan::print_reg_num(reg);
5481 tty->print("), %d (", regHi);
5482 LinearScan::print_reg_num(regHi);
5483 tty->print_cr(")");
5484 }
5485 #endif
5486 assert(split_pos > 0, "invalid split_pos");
5487 if (need_split) {
5488 // register not available for full interval, so split it
5489 split_when_partial_register_available(cur, split_pos);
5490 }
5491
5492 // only return true if interval is completely assigned
5493 return _num_phys_regs == 1 || regHi != any_reg;
5494 }
5495
5496
5497 int LinearScanWalker::find_locked_reg(int reg_needed_until, int interval_to, int ignore_reg, bool* need_split) {
5498 int max_reg = any_reg;
5499
5500 for (int i = _first_reg; i <= _last_reg; i++) {
5501 if (i == ignore_reg) {
5502 // this register must be ignored
5503
5504 } else if (_use_pos[i] > reg_needed_until) {
5505 if (max_reg == any_reg || _use_pos[i] > _use_pos[max_reg]) {
5506 max_reg = i;
5507 }
5508 }
5509 }
5510
5511 if (max_reg != any_reg && _block_pos[max_reg] <= interval_to) {
5512 *need_split = true;
5513 }
5514
5515 return max_reg;
5516 }
5517
5518 int LinearScanWalker::find_locked_double_reg(int reg_needed_until, int interval_to, bool* need_split) {
5519 assert((_last_reg - _first_reg + 1) % 2 == 0, "adjust algorithm");
5520
5521 int max_reg = any_reg;
5522
5523 for (int i = _first_reg; i < _last_reg; i+=2) {
5524 if (_use_pos[i] > reg_needed_until && _use_pos[i + 1] > reg_needed_until) {
5525 if (max_reg == any_reg || _use_pos[i] > _use_pos[max_reg]) {
5526 max_reg = i;
5527 }
5528 }
5529 }
5530
5531 if (max_reg != any_reg &&
5532 (_block_pos[max_reg] <= interval_to || _block_pos[max_reg + 1] <= interval_to)) {
5533 *need_split = true;
5534 }
5535
5536 return max_reg;
5537 }
5538
5539 void LinearScanWalker::split_and_spill_intersecting_intervals(int reg, int regHi) {
5540 assert(reg != any_reg, "no register assigned");
5541
5542 for (int i = 0; i < _spill_intervals[reg]->length(); i++) {
5543 Interval* it = _spill_intervals[reg]->at(i);
5544 remove_from_list(it);
5545 split_and_spill_interval(it);
5546 }
5547
5548 if (regHi != any_reg) {
5549 IntervalList* processed = _spill_intervals[reg];
5550 for (int i = 0; i < _spill_intervals[regHi]->length(); i++) {
5551 Interval* it = _spill_intervals[regHi]->at(i);
5552 if (processed->find(it) == -1) {
5553 remove_from_list(it);
5554 split_and_spill_interval(it);
5555 }
5556 }
5557 }
5558 }
5559
5560
5561 // Split an Interval and spill it to memory so that cur can be placed in a register
5562 void LinearScanWalker::alloc_locked_reg(Interval* cur) {
5563 TRACE_LINEAR_SCAN(2, tty->print("need to split and spill to get register for "); cur->print());
5564
5565 // collect current usage of registers
5566 init_use_lists(false);
5567 spill_exclude_active_fixed();
5568 assert(unhandled_first(fixedKind) == Interval::end(), "must not have unhandled fixed intervals because all fixed intervals have a use at position 0");
5569 spill_block_inactive_fixed(cur);
5570 spill_collect_active_any();
5571 spill_collect_inactive_any(cur);
5572
5573 #ifdef ASSERT
5574 if (TraceLinearScanLevel >= 4) {
5575 tty->print_cr(" state of registers:");
5576 for (int i = _first_reg; i <= _last_reg; i++) {
5577 tty->print(" reg %d(", i);
5578 LinearScan::print_reg_num(i);
5579 tty->print("): use_pos: %d, block_pos: %d, intervals: ", _use_pos[i], _block_pos[i]);
5580 for (int j = 0; j < _spill_intervals[i]->length(); j++) {
5581 tty->print("%d ", _spill_intervals[i]->at(j)->reg_num());
5582 }
5583 tty->cr();
5584 }
5585 }
5586 #endif
5587
5588 // the register must be free at least until this position
5589 int reg_needed_until = MIN2(cur->first_usage(mustHaveRegister), cur->from() + 1);
5590 int interval_to = cur->to();
5591 assert (reg_needed_until > 0 && reg_needed_until < max_jint, "interval has no use");
5592
5593 int split_pos = 0;
5594 int use_pos = 0;
5595 bool need_split = false;
5596 int reg, regHi;
5597
5598 if (_adjacent_regs) {
5599 reg = find_locked_double_reg(reg_needed_until, interval_to, &need_split);
5600 regHi = reg + 1;
5601
5602 if (reg != any_reg) {
5603 use_pos = MIN2(_use_pos[reg], _use_pos[regHi]);
5604 split_pos = MIN2(_block_pos[reg], _block_pos[regHi]);
5605 }
5606 } else {
5607 reg = find_locked_reg(reg_needed_until, interval_to, cur->assigned_reg(), &need_split);
5608 regHi = any_reg;
5609
5610 if (reg != any_reg) {
5611 use_pos = _use_pos[reg];
5612 split_pos = _block_pos[reg];
5613
5614 if (_num_phys_regs == 2) {
5615 if (cur->assigned_reg() != any_reg) {
5616 regHi = reg;
5617 reg = cur->assigned_reg();
5618 } else {
5619 regHi = find_locked_reg(reg_needed_until, interval_to, reg, &need_split);
5620 if (regHi != any_reg) {
5621 use_pos = MIN2(use_pos, _use_pos[regHi]);
5622 split_pos = MIN2(split_pos, _block_pos[regHi]);
5623 }
5624 }
5625
5626 if (regHi != any_reg && reg > regHi) {
5627 // sort register numbers to prevent e.g. a move from eax,ebx to ebx,eax
5628 int temp = reg;
5629 reg = regHi;
5630 regHi = temp;
5631 }
5632 }
5633 }
5634 }
5635
5636 if (reg == any_reg || (_num_phys_regs == 2 && regHi == any_reg) || use_pos <= cur->first_usage(mustHaveRegister)) {
5637 // the first use of cur is later than the spilling position -> spill cur
5638 TRACE_LINEAR_SCAN(4, tty->print_cr("able to spill current interval. first_usage(register): %d, use_pos: %d", cur->first_usage(mustHaveRegister), use_pos));
5639
5640 if (cur->first_usage(mustHaveRegister) <= cur->from() + 1) {
5641 assert(false, "cannot spill interval that is used in first instruction (possible reason: no register found)");
5642 // assign a reasonable register and do a bailout in product mode to avoid errors
5643 allocator()->assign_spill_slot(cur);
5644 BAILOUT("LinearScan: no register found");
5645 }
5646
5647 split_and_spill_interval(cur);
5648 } else {
5649 #ifdef ASSERT
5650 if (TraceLinearScanLevel >= 4) {
5651 tty->print("decided to use register %d (", reg);
5652 LinearScan::print_reg_num(reg);
5653 tty->print("), %d (", regHi);
5654 LinearScan::print_reg_num(regHi);
5655 tty->print_cr(")");
5656 }
5657 #endif
5658 assert(reg != any_reg && (_num_phys_regs == 1 || regHi != any_reg), "no register found");
5659 assert(split_pos > 0, "invalid split_pos");
5660 assert(need_split == false || split_pos > cur->from(), "splitting interval at from");
5661
5662 cur->assign_reg(reg, regHi);
5663 if (need_split) {
5664 // register not available for full interval, so split it
5665 split_when_partial_register_available(cur, split_pos);
5666 }
5667
5668 // perform splitting and spilling for all affected intervals
5669 split_and_spill_intersecting_intervals(reg, regHi);
5670 }
5671 }
5672
5673 bool LinearScanWalker::no_allocation_possible(Interval* cur) {
5674 #ifdef X86
5675 // fast calculation of intervals that can never get a register because the
5676 // the next instruction is a call that blocks all registers
5677 // Note: this does not work if callee-saved registers are available (e.g. on Sparc)
5678
5679 // check if this interval is the result of a split operation
5680 // (an interval got a register until this position)
5681 int pos = cur->from();
5682 if ((pos & 1) == 1) {
5683 // the current instruction is a call that blocks all registers
5684 if (pos < allocator()->max_lir_op_id() && allocator()->has_call(pos + 1)) {
5685 TRACE_LINEAR_SCAN(4, tty->print_cr(" free register cannot be available because all registers blocked by following call"));
5686
5687 // safety check that there is really no register available
5688 assert(alloc_free_reg(cur) == false, "found a register for this interval");
5689 return true;
5690 }
5691
5692 }
5693 #endif
5694 return false;
5695 }
5696
5697 void LinearScanWalker::init_vars_for_alloc(Interval* cur) {
5698 BasicType type = cur->type();
5699 _num_phys_regs = LinearScan::num_physical_regs(type);
5700 _adjacent_regs = LinearScan::requires_adjacent_regs(type);
5701
5702 if (pd_init_regs_for_alloc(cur)) {
5703 // the appropriate register range was selected.
5704 } else if (type == T_FLOAT || type == T_DOUBLE) {
5705 _first_reg = pd_first_fpu_reg;
5706 _last_reg = pd_last_fpu_reg;
5707 } else {
5708 _first_reg = pd_first_cpu_reg;
5709 _last_reg = FrameMap::last_cpu_reg();
5710 }
5711
5712 assert(0 <= _first_reg && _first_reg < LinearScan::nof_regs, "out of range");
5713 assert(0 <= _last_reg && _last_reg < LinearScan::nof_regs, "out of range");
5714 }
5715
5716
5717 bool LinearScanWalker::is_move(LIR_Op* op, Interval* from, Interval* to) {
5718 if (op->code() != lir_move) {
5719 return false;
5720 }
5721 assert(op->as_Op1() != nullptr, "move must be LIR_Op1");
5722
5723 LIR_Opr in = ((LIR_Op1*)op)->in_opr();
5724 LIR_Opr res = ((LIR_Op1*)op)->result_opr();
5725 return in->is_virtual() && res->is_virtual() && in->vreg_number() == from->reg_num() && res->vreg_number() == to->reg_num();
5726 }
5727
5728 // optimization (especially for phi functions of nested loops):
5729 // assign same spill slot to non-intersecting intervals
5730 void LinearScanWalker::combine_spilled_intervals(Interval* cur) {
5731 if (cur->is_split_child()) {
5732 // optimization is only suitable for split parents
5733 return;
5734 }
5735
5736 Interval* register_hint = cur->register_hint(false);
5737 if (register_hint == nullptr) {
5738 // cur is not the target of a move, otherwise register_hint would be set
5739 return;
5740 }
5741 assert(register_hint->is_split_parent(), "register hint must be split parent");
5742
5743 if (cur->spill_state() != noOptimization || register_hint->spill_state() != noOptimization) {
5744 // combining the stack slots for intervals where spill move optimization is applied
5745 // is not benefitial and would cause problems
5746 return;
5747 }
5748
5749 int begin_pos = cur->from();
5750 int end_pos = cur->to();
5751 if (end_pos > allocator()->max_lir_op_id() || (begin_pos & 1) != 0 || (end_pos & 1) != 0) {
5752 // safety check that lir_op_with_id is allowed
5753 return;
5754 }
5755
5756 if (!is_move(allocator()->lir_op_with_id(begin_pos), register_hint, cur) || !is_move(allocator()->lir_op_with_id(end_pos), cur, register_hint)) {
5757 // cur and register_hint are not connected with two moves
5758 return;
5759 }
5760
5761 Interval* begin_hint = register_hint->split_child_at_op_id(begin_pos, LIR_OpVisitState::inputMode);
5762 Interval* end_hint = register_hint->split_child_at_op_id(end_pos, LIR_OpVisitState::outputMode);
5763 if (begin_hint == end_hint || begin_hint->to() != begin_pos || end_hint->from() != end_pos) {
5764 // register_hint must be split, otherwise the re-writing of use positions does not work
5765 return;
5766 }
5767
5768 assert(begin_hint->assigned_reg() != any_reg, "must have register assigned");
5769 assert(end_hint->assigned_reg() == any_reg, "must not have register assigned");
5770 assert(cur->first_usage(mustHaveRegister) == begin_pos, "must have use position at begin of interval because of move");
5771 assert(end_hint->first_usage(mustHaveRegister) == end_pos, "must have use position at begin of interval because of move");
5772
5773 if (begin_hint->assigned_reg() < LinearScan::nof_regs) {
5774 // register_hint is not spilled at begin_pos, so it would not be benefitial to immediately spill cur
5775 return;
5776 }
5777 assert(register_hint->canonical_spill_slot() != -1, "must be set when part of interval was spilled");
5778 assert(!cur->intersects(register_hint), "cur should not intersect register_hint");
5779
5780 if (cur->intersects_any_children_of(register_hint)) {
5781 // Bail out if cur intersects any split children of register_hint, which have the same spill slot as their parent. An overlap of two intervals with
5782 // the same spill slot could result in a situation where both intervals are spilled at the same time to the same stack location which is not correct.
5783 return;
5784 }
5785
5786 // modify intervals such that cur gets the same stack slot as register_hint
5787 // delete use positions to prevent the intervals to get a register at beginning
5788 cur->set_canonical_spill_slot(register_hint->canonical_spill_slot());
5789 cur->remove_first_use_pos();
5790 end_hint->remove_first_use_pos();
5791 }
5792
5793
5794 // allocate a physical register or memory location to an interval
5795 bool LinearScanWalker::activate_current() {
5796 Interval* cur = current();
5797 bool result = true;
5798
5799 TRACE_LINEAR_SCAN(2, tty->print ("+++++ activating interval "); cur->print());
5800 TRACE_LINEAR_SCAN(4, tty->print_cr(" split_parent: %d, insert_move_when_activated: %d", cur->split_parent()->reg_num(), cur->insert_move_when_activated()));
5801
5802 if (cur->assigned_reg() >= LinearScan::nof_regs) {
5803 // activating an interval that has a stack slot assigned -> split it at first use position
5804 // used for method parameters
5805 TRACE_LINEAR_SCAN(4, tty->print_cr(" interval has spill slot assigned (method parameter) -> split it before first use"));
5806
5807 split_stack_interval(cur);
5808 result = false;
5809
5810 } else if (allocator()->gen()->is_vreg_flag_set(cur->reg_num(), LIRGenerator::must_start_in_memory)) {
5811 // activating an interval that must start in a stack slot, but may get a register later
5812 TRACE_LINEAR_SCAN(4, tty->print_cr(" interval must start in stack slot -> split it before first use"));
5813 assert(cur->assigned_reg() == any_reg && cur->assigned_regHi() == any_reg, "register already assigned");
5814
5815 allocator()->assign_spill_slot(cur);
5816 split_stack_interval(cur);
5817 result = false;
5818
5819 } else if (cur->assigned_reg() == any_reg) {
5820 // interval has not assigned register -> normal allocation
5821 // (this is the normal case for most intervals)
5822 TRACE_LINEAR_SCAN(4, tty->print_cr(" normal allocation of register"));
5823
5824 // assign same spill slot to non-intersecting intervals
5825 combine_spilled_intervals(cur);
5826
5827 init_vars_for_alloc(cur);
5828 if (no_allocation_possible(cur) || !alloc_free_reg(cur)) {
5829 // no empty register available.
5830 // split and spill another interval so that this interval gets a register
5831 alloc_locked_reg(cur);
5832 }
5833
5834 // spilled intervals need not be move to active-list
5835 if (cur->assigned_reg() >= LinearScan::nof_regs) {
5836 result = false;
5837 }
5838 }
5839
5840 // load spilled values that become active from stack slot to register
5841 if (cur->insert_move_when_activated()) {
5842 assert(cur->is_split_child(), "must be");
5843 assert(cur->current_split_child() != nullptr, "must be");
5844 assert(cur->current_split_child()->reg_num() != cur->reg_num(), "cannot insert move between same interval");
5845 TRACE_LINEAR_SCAN(4, tty->print_cr("Inserting move from interval %d to %d because insert_move_when_activated is set", cur->current_split_child()->reg_num(), cur->reg_num()));
5846
5847 insert_move(cur->from(), cur->current_split_child(), cur);
5848 }
5849 cur->make_current_split_child();
5850
5851 return result; // true = interval is moved to active list
5852 }
5853
5854
5855 // Implementation of EdgeMoveOptimizer
5856
5857 EdgeMoveOptimizer::EdgeMoveOptimizer() :
5858 _edge_instructions(4),
5859 _edge_instructions_idx(4)
5860 {
5861 }
5862
5863 void EdgeMoveOptimizer::optimize(BlockList* code) {
5864 EdgeMoveOptimizer optimizer = EdgeMoveOptimizer();
5865
5866 // ignore the first block in the list (index 0 is not processed)
5867 for (int i = code->length() - 1; i >= 1; i--) {
5868 BlockBegin* block = code->at(i);
5869
5870 if (block->number_of_preds() > 1 && !block->is_set(BlockBegin::exception_entry_flag)) {
5871 optimizer.optimize_moves_at_block_end(block);
5872 }
5873 if (block->number_of_sux() == 2) {
5874 optimizer.optimize_moves_at_block_begin(block);
5875 }
5876 }
5877 }
5878
5879
5880 // clear all internal data structures
5881 void EdgeMoveOptimizer::init_instructions() {
5882 _edge_instructions.clear();
5883 _edge_instructions_idx.clear();
5884 }
5885
5886 // append a lir-instruction-list and the index of the current operation in to the list
5887 void EdgeMoveOptimizer::append_instructions(LIR_OpList* instructions, int instructions_idx) {
5888 _edge_instructions.append(instructions);
5889 _edge_instructions_idx.append(instructions_idx);
5890 }
5891
5892 // return the current operation of the given edge (predecessor or successor)
5893 LIR_Op* EdgeMoveOptimizer::instruction_at(int edge) {
5894 LIR_OpList* instructions = _edge_instructions.at(edge);
5895 int idx = _edge_instructions_idx.at(edge);
5896
5897 if (idx < instructions->length()) {
5898 return instructions->at(idx);
5899 } else {
5900 return nullptr;
5901 }
5902 }
5903
5904 // removes the current operation of the given edge (predecessor or successor)
5905 void EdgeMoveOptimizer::remove_cur_instruction(int edge, bool decrement_index) {
5906 LIR_OpList* instructions = _edge_instructions.at(edge);
5907 int idx = _edge_instructions_idx.at(edge);
5908 instructions->remove_at(idx);
5909
5910 if (decrement_index) {
5911 _edge_instructions_idx.at_put(edge, idx - 1);
5912 }
5913 }
5914
5915
5916 bool EdgeMoveOptimizer::operations_different(LIR_Op* op1, LIR_Op* op2) {
5917 if (op1 == nullptr || op2 == nullptr) {
5918 // at least one block is already empty -> no optimization possible
5919 return true;
5920 }
5921
5922 if (op1->code() == lir_move && op2->code() == lir_move) {
5923 assert(op1->as_Op1() != nullptr, "move must be LIR_Op1");
5924 assert(op2->as_Op1() != nullptr, "move must be LIR_Op1");
5925 LIR_Op1* move1 = (LIR_Op1*)op1;
5926 LIR_Op1* move2 = (LIR_Op1*)op2;
5927 if (move1->info() == move2->info() && move1->in_opr() == move2->in_opr() && move1->result_opr() == move2->result_opr()) {
5928 // these moves are exactly equal and can be optimized
5929 return false;
5930 }
5931 }
5932
5933 // no optimization possible
5934 return true;
5935 }
5936
5937 void EdgeMoveOptimizer::optimize_moves_at_block_end(BlockBegin* block) {
5938 TRACE_LINEAR_SCAN(4, tty->print_cr("optimizing moves at end of block B%d", block->block_id()));
5939
5940 if (block->is_predecessor(block)) {
5941 // currently we can't handle this correctly.
5942 return;
5943 }
5944
5945 init_instructions();
5946 int num_preds = block->number_of_preds();
5947 assert(num_preds > 1, "do not call otherwise");
5948 assert(!block->is_set(BlockBegin::exception_entry_flag), "exception handlers not allowed");
5949
5950 // setup a list with the lir-instructions of all predecessors
5951 int i;
5952 for (i = 0; i < num_preds; i++) {
5953 BlockBegin* pred = block->pred_at(i);
5954 LIR_OpList* pred_instructions = pred->lir()->instructions_list();
5955
5956 if (pred->number_of_sux() != 1) {
5957 // this can happen with switch-statements where multiple edges are between
5958 // the same blocks.
5959 return;
5960 }
5961
5962 assert(pred->number_of_sux() == 1, "can handle only one successor");
5963 assert(pred->sux_at(0) == block, "invalid control flow");
5964 assert(pred_instructions->last()->code() == lir_branch, "block with successor must end with branch");
5965 assert(pred_instructions->last()->as_OpBranch() != nullptr, "branch must be LIR_OpBranch");
5966 assert(pred_instructions->last()->as_OpBranch()->cond() == lir_cond_always, "block must end with unconditional branch");
5967
5968 if (pred_instructions->last()->info() != nullptr) {
5969 // can not optimize instructions when debug info is needed
5970 return;
5971 }
5972
5973 // ignore the unconditional branch at the end of the block
5974 append_instructions(pred_instructions, pred_instructions->length() - 2);
5975 }
5976
5977
5978 // process lir-instructions while all predecessors end with the same instruction
5979 while (true) {
5980 LIR_Op* op = instruction_at(0);
5981 for (i = 1; i < num_preds; i++) {
5982 if (operations_different(op, instruction_at(i))) {
5983 // these instructions are different and cannot be optimized ->
5984 // no further optimization possible
5985 return;
5986 }
5987 }
5988
5989 TRACE_LINEAR_SCAN(4, tty->print("found instruction that is equal in all %d predecessors: ", num_preds); op->print());
5990
5991 // insert the instruction at the beginning of the current block
5992 block->lir()->insert_before(1, op);
5993
5994 // delete the instruction at the end of all predecessors
5995 for (i = 0; i < num_preds; i++) {
5996 remove_cur_instruction(i, true);
5997 }
5998 }
5999 }
6000
6001
6002 void EdgeMoveOptimizer::optimize_moves_at_block_begin(BlockBegin* block) {
6003 TRACE_LINEAR_SCAN(4, tty->print_cr("optimization moves at begin of block B%d", block->block_id()));
6004
6005 init_instructions();
6006 int num_sux = block->number_of_sux();
6007
6008 LIR_OpList* cur_instructions = block->lir()->instructions_list();
6009
6010 assert(num_sux == 2, "method should not be called otherwise");
6011 assert(cur_instructions->last()->code() == lir_branch, "block with successor must end with branch");
6012 assert(cur_instructions->last()->as_OpBranch() != nullptr, "branch must be LIR_OpBranch");
6013 assert(cur_instructions->last()->as_OpBranch()->cond() == lir_cond_always, "block must end with unconditional branch");
6014
6015 if (cur_instructions->last()->info() != nullptr) {
6016 // can no optimize instructions when debug info is needed
6017 return;
6018 }
6019
6020 LIR_Op* branch = cur_instructions->at(cur_instructions->length() - 2);
6021 if (branch->info() != nullptr || (branch->code() != lir_branch && branch->code() != lir_cond_float_branch)) {
6022 // not a valid case for optimization
6023 // currently, only blocks that end with two branches (conditional branch followed
6024 // by unconditional branch) are optimized
6025 return;
6026 }
6027
6028 // now it is guaranteed that the block ends with two branch instructions.
6029 // the instructions are inserted at the end of the block before these two branches
6030 int insert_idx = cur_instructions->length() - 2;
6031
6032 int i;
6033 #ifdef ASSERT
6034 for (i = insert_idx - 1; i >= 0; i--) {
6035 LIR_Op* op = cur_instructions->at(i);
6036 if ((op->code() == lir_branch || op->code() == lir_cond_float_branch) && ((LIR_OpBranch*)op)->block() != nullptr) {
6037 assert(false, "block with two successors can have only two branch instructions");
6038 }
6039 }
6040 #endif
6041
6042 // setup a list with the lir-instructions of all successors
6043 for (i = 0; i < num_sux; i++) {
6044 BlockBegin* sux = block->sux_at(i);
6045 LIR_OpList* sux_instructions = sux->lir()->instructions_list();
6046
6047 assert(sux_instructions->at(0)->code() == lir_label, "block must start with label");
6048
6049 if (sux->number_of_preds() != 1) {
6050 // this can happen with switch-statements where multiple edges are between
6051 // the same blocks.
6052 return;
6053 }
6054 assert(sux->pred_at(0) == block, "invalid control flow");
6055 assert(!sux->is_set(BlockBegin::exception_entry_flag), "exception handlers not allowed");
6056
6057 // ignore the label at the beginning of the block
6058 append_instructions(sux_instructions, 1);
6059 }
6060
6061 // process lir-instructions while all successors begin with the same instruction
6062 while (true) {
6063 LIR_Op* op = instruction_at(0);
6064 for (i = 1; i < num_sux; i++) {
6065 if (operations_different(op, instruction_at(i))) {
6066 // these instructions are different and cannot be optimized ->
6067 // no further optimization possible
6068 return;
6069 }
6070 }
6071
6072 TRACE_LINEAR_SCAN(4, tty->print("----- found instruction that is equal in all %d successors: ", num_sux); op->print());
6073
6074 // insert instruction at end of current block
6075 block->lir()->insert_before(insert_idx, op);
6076 insert_idx++;
6077
6078 // delete the instructions at the beginning of all successors
6079 for (i = 0; i < num_sux; i++) {
6080 remove_cur_instruction(i, false);
6081 }
6082 }
6083 }
6084
6085
6086 // Implementation of ControlFlowOptimizer
6087
6088 ControlFlowOptimizer::ControlFlowOptimizer() :
6089 _original_preds(4)
6090 {
6091 }
6092
6093 void ControlFlowOptimizer::optimize(BlockList* code) {
6094 ControlFlowOptimizer optimizer = ControlFlowOptimizer();
6095
6096 // push the OSR entry block to the end so that we're not jumping over it.
6097 BlockBegin* osr_entry = code->at(0)->end()->as_Base()->osr_entry();
6098 if (osr_entry) {
6099 int index = osr_entry->linear_scan_number();
6100 assert(code->at(index) == osr_entry, "wrong index");
6101 code->remove_at(index);
6102 code->append(osr_entry);
6103 }
6104
6105 optimizer.reorder_short_loops(code);
6106 optimizer.delete_empty_blocks(code);
6107 optimizer.delete_unnecessary_jumps(code);
6108 optimizer.delete_jumps_to_return(code);
6109 }
6110
6111 void ControlFlowOptimizer::reorder_short_loop(BlockList* code, BlockBegin* header_block, int header_idx) {
6112 int i = header_idx + 1;
6113 int max_end = MIN2(header_idx + ShortLoopSize, code->length());
6114 while (i < max_end && code->at(i)->loop_depth() >= header_block->loop_depth()) {
6115 i++;
6116 }
6117
6118 if (i == code->length() || code->at(i)->loop_depth() < header_block->loop_depth()) {
6119 int end_idx = i - 1;
6120 BlockBegin* end_block = code->at(end_idx);
6121
6122 if (end_block->number_of_sux() == 1 && end_block->sux_at(0) == header_block) {
6123 // short loop from header_idx to end_idx found -> reorder blocks such that
6124 // the header_block is the last block instead of the first block of the loop
6125 TRACE_LINEAR_SCAN(1, tty->print_cr("Reordering short loop: length %d, header B%d, end B%d",
6126 end_idx - header_idx + 1,
6127 header_block->block_id(), end_block->block_id()));
6128
6129 for (int j = header_idx; j < end_idx; j++) {
6130 code->at_put(j, code->at(j + 1));
6131 }
6132 code->at_put(end_idx, header_block);
6133
6134 // correct the flags so that any loop alignment occurs in the right place.
6135 assert(code->at(end_idx)->is_set(BlockBegin::backward_branch_target_flag), "must be backward branch target");
6136 code->at(end_idx)->clear(BlockBegin::backward_branch_target_flag);
6137 code->at(header_idx)->set(BlockBegin::backward_branch_target_flag);
6138 }
6139 }
6140 }
6141
6142 void ControlFlowOptimizer::reorder_short_loops(BlockList* code) {
6143 for (int i = code->length() - 1; i >= 0; i--) {
6144 BlockBegin* block = code->at(i);
6145
6146 if (block->is_set(BlockBegin::linear_scan_loop_header_flag)) {
6147 reorder_short_loop(code, block, i);
6148 }
6149 }
6150
6151 DEBUG_ONLY(verify(code));
6152 }
6153
6154 // only blocks with exactly one successor can be deleted. Such blocks
6155 // must always end with an unconditional branch to this successor
6156 bool ControlFlowOptimizer::can_delete_block(BlockBegin* block) {
6157 if (block->number_of_sux() != 1 || block->number_of_exception_handlers() != 0 || block->is_entry_block()) {
6158 return false;
6159 }
6160
6161 LIR_OpList* instructions = block->lir()->instructions_list();
6162
6163 assert(instructions->length() >= 2, "block must have label and branch");
6164 assert(instructions->at(0)->code() == lir_label, "first instruction must always be a label");
6165 assert(instructions->last()->as_OpBranch() != nullptr, "last instruction must always be a branch");
6166 assert(instructions->last()->as_OpBranch()->cond() == lir_cond_always, "branch must be unconditional");
6167 assert(instructions->last()->as_OpBranch()->block() == block->sux_at(0), "branch target must be the successor");
6168
6169 // block must have exactly one successor
6170
6171 if (instructions->length() == 2 && instructions->last()->info() == nullptr) {
6172 return true;
6173 }
6174 return false;
6175 }
6176
6177 // substitute branch targets in all branch-instructions of this blocks
6178 void ControlFlowOptimizer::substitute_branch_target(BlockBegin* block, BlockBegin* target_from, BlockBegin* target_to) {
6179 TRACE_LINEAR_SCAN(3, tty->print_cr("Deleting empty block: substituting from B%d to B%d inside B%d", target_from->block_id(), target_to->block_id(), block->block_id()));
6180
6181 LIR_OpList* instructions = block->lir()->instructions_list();
6182
6183 assert(instructions->at(0)->code() == lir_label, "first instruction must always be a label");
6184 for (int i = instructions->length() - 1; i >= 1; i--) {
6185 LIR_Op* op = instructions->at(i);
6186
6187 if (op->code() == lir_branch || op->code() == lir_cond_float_branch) {
6188 assert(op->as_OpBranch() != nullptr, "branch must be of type LIR_OpBranch");
6189 LIR_OpBranch* branch = (LIR_OpBranch*)op;
6190
6191 if (branch->block() == target_from) {
6192 branch->change_block(target_to);
6193 }
6194 if (branch->ublock() == target_from) {
6195 branch->change_ublock(target_to);
6196 }
6197 }
6198 }
6199 }
6200
6201 void ControlFlowOptimizer::delete_empty_blocks(BlockList* code) {
6202 int old_pos = 0;
6203 int new_pos = 0;
6204 int num_blocks = code->length();
6205
6206 while (old_pos < num_blocks) {
6207 BlockBegin* block = code->at(old_pos);
6208
6209 if (can_delete_block(block)) {
6210 BlockBegin* new_target = block->sux_at(0);
6211
6212 // propagate backward branch target flag for correct code alignment
6213 if (block->is_set(BlockBegin::backward_branch_target_flag)) {
6214 new_target->set(BlockBegin::backward_branch_target_flag);
6215 }
6216
6217 // collect a list with all predecessors that contains each predecessor only once
6218 // the predecessors of cur are changed during the substitution, so a copy of the
6219 // predecessor list is necessary
6220 int j;
6221 _original_preds.clear();
6222 for (j = block->number_of_preds() - 1; j >= 0; j--) {
6223 BlockBegin* pred = block->pred_at(j);
6224 if (_original_preds.find(pred) == -1) {
6225 _original_preds.append(pred);
6226 }
6227 }
6228
6229 for (j = _original_preds.length() - 1; j >= 0; j--) {
6230 BlockBegin* pred = _original_preds.at(j);
6231 substitute_branch_target(pred, block, new_target);
6232 pred->substitute_sux(block, new_target);
6233 }
6234 } else {
6235 // adjust position of this block in the block list if blocks before
6236 // have been deleted
6237 if (new_pos != old_pos) {
6238 code->at_put(new_pos, code->at(old_pos));
6239 }
6240 new_pos++;
6241 }
6242 old_pos++;
6243 }
6244 code->trunc_to(new_pos);
6245
6246 DEBUG_ONLY(verify(code));
6247 }
6248
6249 void ControlFlowOptimizer::delete_unnecessary_jumps(BlockList* code) {
6250 // skip the last block because there a branch is always necessary
6251 for (int i = code->length() - 2; i >= 0; i--) {
6252 BlockBegin* block = code->at(i);
6253 LIR_OpList* instructions = block->lir()->instructions_list();
6254
6255 LIR_Op* last_op = instructions->last();
6256 if (last_op->code() == lir_branch) {
6257 assert(last_op->as_OpBranch() != nullptr, "branch must be of type LIR_OpBranch");
6258 LIR_OpBranch* last_branch = (LIR_OpBranch*)last_op;
6259
6260 assert(last_branch->block() != nullptr, "last branch must always have a block as target");
6261 assert(last_branch->label() == last_branch->block()->label(), "must be equal");
6262
6263 if (last_branch->info() == nullptr) {
6264 if (last_branch->block() == code->at(i + 1)) {
6265
6266 TRACE_LINEAR_SCAN(3, tty->print_cr("Deleting unconditional branch at end of block B%d", block->block_id()));
6267
6268 // delete last branch instruction
6269 instructions->trunc_to(instructions->length() - 1);
6270
6271 } else {
6272 LIR_Op* prev_op = instructions->at(instructions->length() - 2);
6273 if (prev_op->code() == lir_branch || prev_op->code() == lir_cond_float_branch) {
6274 assert(prev_op->as_OpBranch() != nullptr, "branch must be of type LIR_OpBranch");
6275 LIR_OpBranch* prev_branch = (LIR_OpBranch*)prev_op;
6276
6277 if (prev_branch->stub() == nullptr) {
6278
6279 LIR_Op2* prev_cmp = nullptr;
6280 // There might be a cmove inserted for profiling which depends on the same
6281 // compare. If we change the condition of the respective compare, we have
6282 // to take care of this cmove as well.
6283 LIR_Op4* prev_cmove = nullptr;
6284
6285 for(int j = instructions->length() - 3; j >= 0 && prev_cmp == nullptr; j--) {
6286 prev_op = instructions->at(j);
6287 // check for the cmove
6288 if (prev_op->code() == lir_cmove) {
6289 assert(prev_op->as_Op4() != nullptr, "cmove must be of type LIR_Op4");
6290 prev_cmove = (LIR_Op4*)prev_op;
6291 assert(prev_branch->cond() == prev_cmove->condition(), "should be the same");
6292 }
6293 if (prev_op->code() == lir_cmp) {
6294 assert(prev_op->as_Op2() != nullptr, "branch must be of type LIR_Op2");
6295 prev_cmp = (LIR_Op2*)prev_op;
6296 assert(prev_branch->cond() == prev_cmp->condition(), "should be the same");
6297 }
6298 }
6299 // Guarantee because it is dereferenced below.
6300 guarantee(prev_cmp != nullptr, "should have found comp instruction for branch");
6301 if (prev_branch->block() == code->at(i + 1) && prev_branch->info() == nullptr) {
6302
6303 TRACE_LINEAR_SCAN(3, tty->print_cr("Negating conditional branch and deleting unconditional branch at end of block B%d", block->block_id()));
6304
6305 // eliminate a conditional branch to the immediate successor
6306 prev_branch->change_block(last_branch->block());
6307 prev_branch->negate_cond();
6308 prev_cmp->set_condition(prev_branch->cond());
6309 instructions->trunc_to(instructions->length() - 1);
6310 // if we do change the condition, we have to change the cmove as well
6311 if (prev_cmove != nullptr) {
6312 prev_cmove->set_condition(prev_branch->cond());
6313 LIR_Opr t = prev_cmove->in_opr1();
6314 prev_cmove->set_in_opr1(prev_cmove->in_opr2());
6315 prev_cmove->set_in_opr2(t);
6316 }
6317 }
6318 }
6319 }
6320 }
6321 }
6322 }
6323 }
6324
6325 DEBUG_ONLY(verify(code));
6326 }
6327
6328 void ControlFlowOptimizer::delete_jumps_to_return(BlockList* code) {
6329 #ifdef ASSERT
6330 ResourceBitMap return_converted(BlockBegin::number_of_blocks());
6331 #endif
6332
6333 for (int i = code->length() - 1; i >= 0; i--) {
6334 BlockBegin* block = code->at(i);
6335 LIR_OpList* cur_instructions = block->lir()->instructions_list();
6336 LIR_Op* cur_last_op = cur_instructions->last();
6337
6338 assert(cur_instructions->at(0)->code() == lir_label, "first instruction must always be a label");
6339 if (cur_instructions->length() == 2 && cur_last_op->code() == lir_return) {
6340 // the block contains only a label and a return
6341 // if a predecessor ends with an unconditional jump to this block, then the jump
6342 // can be replaced with a return instruction
6343 //
6344 // Note: the original block with only a return statement cannot be deleted completely
6345 // because the predecessors might have other (conditional) jumps to this block
6346 // -> this may lead to unnecessary return instructions in the final code
6347
6348 assert(cur_last_op->info() == nullptr, "return instructions do not have debug information");
6349 assert(block->number_of_sux() == 0 ||
6350 (return_converted.at(block->block_id()) && block->number_of_sux() == 1),
6351 "blocks that end with return must not have successors");
6352
6353 assert(cur_last_op->as_Op1() != nullptr, "return must be LIR_Op1");
6354 LIR_Opr return_opr = ((LIR_Op1*)cur_last_op)->in_opr();
6355
6356 for (int j = block->number_of_preds() - 1; j >= 0; j--) {
6357 BlockBegin* pred = block->pred_at(j);
6358 LIR_OpList* pred_instructions = pred->lir()->instructions_list();
6359 LIR_Op* pred_last_op = pred_instructions->last();
6360
6361 if (pred_last_op->code() == lir_branch) {
6362 assert(pred_last_op->as_OpBranch() != nullptr, "branch must be LIR_OpBranch");
6363 LIR_OpBranch* pred_last_branch = (LIR_OpBranch*)pred_last_op;
6364
6365 if (pred_last_branch->block() == block && pred_last_branch->cond() == lir_cond_always && pred_last_branch->info() == nullptr) {
6366 // replace the jump to a return with a direct return
6367 // Note: currently the edge between the blocks is not deleted
6368 pred_instructions->at_put(pred_instructions->length() - 1, new LIR_OpReturn(return_opr));
6369 #ifdef ASSERT
6370 return_converted.set_bit(pred->block_id());
6371 #endif
6372 }
6373 }
6374 }
6375 }
6376 }
6377 }
6378
6379
6380 #ifdef ASSERT
6381 void ControlFlowOptimizer::verify(BlockList* code) {
6382 for (int i = 0; i < code->length(); i++) {
6383 BlockBegin* block = code->at(i);
6384 LIR_OpList* instructions = block->lir()->instructions_list();
6385
6386 int j;
6387 for (j = 0; j < instructions->length(); j++) {
6388 LIR_OpBranch* op_branch = instructions->at(j)->as_OpBranch();
6389
6390 if (op_branch != nullptr) {
6391 assert(op_branch->block() == nullptr || code->find(op_branch->block()) != -1, "branch target not valid");
6392 assert(op_branch->ublock() == nullptr || code->find(op_branch->ublock()) != -1, "branch target not valid");
6393 }
6394 }
6395
6396 for (j = 0; j < block->number_of_sux() - 1; j++) {
6397 BlockBegin* sux = block->sux_at(j);
6398 assert(code->find(sux) != -1, "successor not valid");
6399 }
6400
6401 for (j = 0; j < block->number_of_preds() - 1; j++) {
6402 BlockBegin* pred = block->pred_at(j);
6403 assert(code->find(pred) != -1, "successor not valid");
6404 }
6405 }
6406 }
6407 #endif
6408
6409
6410 #ifndef PRODUCT
6411
6412 // Implementation of LinearStatistic
6413
6414 const char* LinearScanStatistic::counter_name(int counter_idx) {
6415 switch (counter_idx) {
6416 case counter_method: return "compiled methods";
6417 case counter_fpu_method: return "methods using fpu";
6418 case counter_loop_method: return "methods with loops";
6419 case counter_exception_method:return "methods with xhandler";
6420
6421 case counter_loop: return "loops";
6422 case counter_block: return "blocks";
6423 case counter_loop_block: return "blocks inside loop";
6424 case counter_exception_block: return "exception handler entries";
6425 case counter_interval: return "intervals";
6426 case counter_fixed_interval: return "fixed intervals";
6427 case counter_range: return "ranges";
6428 case counter_fixed_range: return "fixed ranges";
6429 case counter_use_pos: return "use positions";
6430 case counter_fixed_use_pos: return "fixed use positions";
6431 case counter_spill_slots: return "spill slots";
6432
6433 // counter for classes of lir instructions
6434 case counter_instruction: return "total instructions";
6435 case counter_label: return "labels";
6436 case counter_entry: return "method entries";
6437 case counter_return: return "method returns";
6438 case counter_call: return "method calls";
6439 case counter_move: return "moves";
6440 case counter_cmp: return "compare";
6441 case counter_cond_branch: return "conditional branches";
6442 case counter_uncond_branch: return "unconditional branches";
6443 case counter_stub_branch: return "branches to stub";
6444 case counter_alu: return "artithmetic + logic";
6445 case counter_alloc: return "allocations";
6446 case counter_sync: return "synchronisation";
6447 case counter_throw: return "throw";
6448 case counter_unwind: return "unwind";
6449 case counter_typecheck: return "type+null-checks";
6450 case counter_misc_inst: return "other instructions";
6451 case counter_other_inst: return "misc. instructions";
6452
6453 // counter for different types of moves
6454 case counter_move_total: return "total moves";
6455 case counter_move_reg_reg: return "register->register";
6456 case counter_move_reg_stack: return "register->stack";
6457 case counter_move_stack_reg: return "stack->register";
6458 case counter_move_stack_stack:return "stack->stack";
6459 case counter_move_reg_mem: return "register->memory";
6460 case counter_move_mem_reg: return "memory->register";
6461 case counter_move_const_any: return "constant->any";
6462
6463 case blank_line_1: return "";
6464 case blank_line_2: return "";
6465
6466 default: ShouldNotReachHere(); return "";
6467 }
6468 }
6469
6470 LinearScanStatistic::Counter LinearScanStatistic::base_counter(int counter_idx) {
6471 if (counter_idx == counter_fpu_method || counter_idx == counter_loop_method || counter_idx == counter_exception_method) {
6472 return counter_method;
6473 } else if (counter_idx == counter_loop_block || counter_idx == counter_exception_block) {
6474 return counter_block;
6475 } else if (counter_idx >= counter_instruction && counter_idx <= counter_other_inst) {
6476 return counter_instruction;
6477 } else if (counter_idx >= counter_move_total && counter_idx <= counter_move_const_any) {
6478 return counter_move_total;
6479 }
6480 return invalid_counter;
6481 }
6482
6483 LinearScanStatistic::LinearScanStatistic() {
6484 for (int i = 0; i < number_of_counters; i++) {
6485 _counters_sum[i] = 0;
6486 _counters_max[i] = -1;
6487 }
6488
6489 }
6490
6491 // add the method-local numbers to the total sum
6492 void LinearScanStatistic::sum_up(LinearScanStatistic &method_statistic) {
6493 for (int i = 0; i < number_of_counters; i++) {
6494 _counters_sum[i] += method_statistic._counters_sum[i];
6495 _counters_max[i] = MAX2(_counters_max[i], method_statistic._counters_sum[i]);
6496 }
6497 }
6498
6499 void LinearScanStatistic::print(const char* title) {
6500 if (CountLinearScan || TraceLinearScanLevel > 0) {
6501 tty->cr();
6502 tty->print_cr("***** LinearScan statistic - %s *****", title);
6503
6504 for (int i = 0; i < number_of_counters; i++) {
6505 if (_counters_sum[i] > 0 || _counters_max[i] >= 0) {
6506 tty->print("%25s: %8d", counter_name(i), _counters_sum[i]);
6507
6508 LinearScanStatistic::Counter cntr = base_counter(i);
6509 if (cntr != invalid_counter) {
6510 tty->print(" (%5.1f%%) ", _counters_sum[i] * 100.0 / _counters_sum[cntr]);
6511 } else {
6512 tty->print(" ");
6513 }
6514
6515 if (_counters_max[i] >= 0) {
6516 tty->print("%8d", _counters_max[i]);
6517 }
6518 }
6519 tty->cr();
6520 }
6521 }
6522 }
6523
6524 void LinearScanStatistic::collect(LinearScan* allocator) {
6525 inc_counter(counter_method);
6526 if (allocator->has_fpu_registers()) {
6527 inc_counter(counter_fpu_method);
6528 }
6529 if (allocator->num_loops() > 0) {
6530 inc_counter(counter_loop_method);
6531 }
6532 inc_counter(counter_loop, allocator->num_loops());
6533 inc_counter(counter_spill_slots, allocator->max_spills());
6534
6535 int i;
6536 for (i = 0; i < allocator->interval_count(); i++) {
6537 Interval* cur = allocator->interval_at(i);
6538
6539 if (cur != nullptr) {
6540 inc_counter(counter_interval);
6541 inc_counter(counter_use_pos, cur->num_use_positions());
6542 if (LinearScan::is_precolored_interval(cur)) {
6543 inc_counter(counter_fixed_interval);
6544 inc_counter(counter_fixed_use_pos, cur->num_use_positions());
6545 }
6546
6547 Range* range = cur->first();
6548 while (range != Range::end()) {
6549 inc_counter(counter_range);
6550 if (LinearScan::is_precolored_interval(cur)) {
6551 inc_counter(counter_fixed_range);
6552 }
6553 range = range->next();
6554 }
6555 }
6556 }
6557
6558 bool has_xhandlers = false;
6559 // Note: only count blocks that are in code-emit order
6560 for (i = 0; i < allocator->ir()->code()->length(); i++) {
6561 BlockBegin* cur = allocator->ir()->code()->at(i);
6562
6563 inc_counter(counter_block);
6564 if (cur->loop_depth() > 0) {
6565 inc_counter(counter_loop_block);
6566 }
6567 if (cur->is_set(BlockBegin::exception_entry_flag)) {
6568 inc_counter(counter_exception_block);
6569 has_xhandlers = true;
6570 }
6571
6572 LIR_OpList* instructions = cur->lir()->instructions_list();
6573 for (int j = 0; j < instructions->length(); j++) {
6574 LIR_Op* op = instructions->at(j);
6575
6576 inc_counter(counter_instruction);
6577
6578 switch (op->code()) {
6579 case lir_label: inc_counter(counter_label); break;
6580 case lir_std_entry:
6581 case lir_osr_entry: inc_counter(counter_entry); break;
6582 case lir_return: inc_counter(counter_return); break;
6583
6584 case lir_rtcall:
6585 case lir_static_call:
6586 case lir_optvirtual_call: inc_counter(counter_call); break;
6587
6588 case lir_move: {
6589 inc_counter(counter_move);
6590 inc_counter(counter_move_total);
6591
6592 LIR_Opr in = op->as_Op1()->in_opr();
6593 LIR_Opr res = op->as_Op1()->result_opr();
6594 if (in->is_register()) {
6595 if (res->is_register()) {
6596 inc_counter(counter_move_reg_reg);
6597 } else if (res->is_stack()) {
6598 inc_counter(counter_move_reg_stack);
6599 } else if (res->is_address()) {
6600 inc_counter(counter_move_reg_mem);
6601 } else {
6602 ShouldNotReachHere();
6603 }
6604 } else if (in->is_stack()) {
6605 if (res->is_register()) {
6606 inc_counter(counter_move_stack_reg);
6607 } else {
6608 inc_counter(counter_move_stack_stack);
6609 }
6610 } else if (in->is_address()) {
6611 assert(res->is_register(), "must be");
6612 inc_counter(counter_move_mem_reg);
6613 } else if (in->is_constant()) {
6614 inc_counter(counter_move_const_any);
6615 } else {
6616 ShouldNotReachHere();
6617 }
6618 break;
6619 }
6620
6621 case lir_cmp: inc_counter(counter_cmp); break;
6622
6623 case lir_branch:
6624 case lir_cond_float_branch: {
6625 LIR_OpBranch* branch = op->as_OpBranch();
6626 if (branch->block() == nullptr) {
6627 inc_counter(counter_stub_branch);
6628 } else if (branch->cond() == lir_cond_always) {
6629 inc_counter(counter_uncond_branch);
6630 } else {
6631 inc_counter(counter_cond_branch);
6632 }
6633 break;
6634 }
6635
6636 case lir_neg:
6637 case lir_add:
6638 case lir_sub:
6639 case lir_mul:
6640 case lir_div:
6641 case lir_rem:
6642 case lir_sqrt:
6643 case lir_abs:
6644 case lir_f2hf:
6645 case lir_hf2f:
6646 case lir_logic_and:
6647 case lir_logic_or:
6648 case lir_logic_xor:
6649 case lir_shl:
6650 case lir_shr:
6651 case lir_ushr: inc_counter(counter_alu); break;
6652
6653 case lir_alloc_object:
6654 case lir_alloc_array: inc_counter(counter_alloc); break;
6655
6656 case lir_monaddr:
6657 case lir_lock:
6658 case lir_unlock: inc_counter(counter_sync); break;
6659
6660 case lir_throw: inc_counter(counter_throw); break;
6661
6662 case lir_unwind: inc_counter(counter_unwind); break;
6663
6664 case lir_null_check:
6665 case lir_leal:
6666 case lir_instanceof:
6667 case lir_checkcast:
6668 case lir_store_check: inc_counter(counter_typecheck); break;
6669
6670 case lir_nop:
6671 case lir_push:
6672 case lir_pop:
6673 case lir_convert:
6674 case lir_cmove: inc_counter(counter_misc_inst); break;
6675
6676 default: inc_counter(counter_other_inst); break;
6677 }
6678 }
6679 }
6680
6681 if (has_xhandlers) {
6682 inc_counter(counter_exception_method);
6683 }
6684 }
6685
6686 void LinearScanStatistic::compute(LinearScan* allocator, LinearScanStatistic &global_statistic) {
6687 if (CountLinearScan || TraceLinearScanLevel > 0) {
6688
6689 LinearScanStatistic local_statistic = LinearScanStatistic();
6690
6691 local_statistic.collect(allocator);
6692 global_statistic.sum_up(local_statistic);
6693
6694 if (TraceLinearScanLevel > 2) {
6695 local_statistic.print("current local statistic");
6696 }
6697 }
6698 }
6699
6700
6701 // Implementation of LinearTimers
6702
6703 LinearScanTimers::LinearScanTimers() {
6704 for (int i = 0; i < number_of_timers; i++) {
6705 timer(i)->reset();
6706 }
6707 }
6708
6709 const char* LinearScanTimers::timer_name(int idx) {
6710 switch (idx) {
6711 case timer_do_nothing: return "Nothing (Time Check)";
6712 case timer_number_instructions: return "Number Instructions";
6713 case timer_compute_local_live_sets: return "Local Live Sets";
6714 case timer_compute_global_live_sets: return "Global Live Sets";
6715 case timer_build_intervals: return "Build Intervals";
6716 case timer_sort_intervals_before: return "Sort Intervals Before";
6717 case timer_allocate_registers: return "Allocate Registers";
6718 case timer_resolve_data_flow: return "Resolve Data Flow";
6719 case timer_sort_intervals_after: return "Sort Intervals After";
6720 case timer_eliminate_spill_moves: return "Spill optimization";
6721 case timer_assign_reg_num: return "Assign Reg Num";
6722 case timer_optimize_lir: return "Optimize LIR";
6723 default: ShouldNotReachHere(); return "";
6724 }
6725 }
6726
6727 void LinearScanTimers::print(double total_time) {
6728 if (TimeLinearScan) {
6729 // correction value: sum of dummy-timer that only measures the time that
6730 // is necessary to start and stop itself
6731 double c = timer(timer_do_nothing)->seconds();
6732
6733 for (int i = 0; i < number_of_timers; i++) {
6734 double t = timer(i)->seconds();
6735 tty->print_cr(" %25s: %6.3f s (%4.1f%%) corrected: %6.3f s (%4.1f%%)", timer_name(i), t, (t / total_time) * 100.0, t - c, (t - c) / (total_time - 2 * number_of_timers * c) * 100);
6736 }
6737 }
6738 }
6739
6740 #endif // #ifndef PRODUCT