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