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