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