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