src/share/vm/c1/c1_LinearScan.cpp

Mon, 24 Jan 2011 13:34:18 -0800

author
never
date
Mon, 24 Jan 2011 13:34:18 -0800
changeset 2488
e4fee0bdaa85
parent 2404
7223744c2784
child 2508
b92c45f2bc75
permissions
-rw-r--r--

7008809: should report the class in ArrayStoreExceptions from compiled code
Reviewed-by: iveresov, twisti

     1 /*
     2  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  *
    23  */
    25 #include "precompiled.hpp"
    26 #include "c1/c1_CFGPrinter.hpp"
    27 #include "c1/c1_CodeStubs.hpp"
    28 #include "c1/c1_Compilation.hpp"
    29 #include "c1/c1_FrameMap.hpp"
    30 #include "c1/c1_IR.hpp"
    31 #include "c1/c1_LIRGenerator.hpp"
    32 #include "c1/c1_LinearScan.hpp"
    33 #include "c1/c1_ValueStack.hpp"
    34 #include "utilities/bitMap.inline.hpp"
    35 #ifdef TARGET_ARCH_x86
    36 # include "vmreg_x86.inline.hpp"
    37 #endif
    38 #ifdef TARGET_ARCH_sparc
    39 # include "vmreg_sparc.inline.hpp"
    40 #endif
    41 #ifdef TARGET_ARCH_zero
    42 # include "vmreg_zero.inline.hpp"
    43 #endif
    46 #ifndef PRODUCT
    48   static LinearScanStatistic _stat_before_alloc;
    49   static LinearScanStatistic _stat_after_asign;
    50   static LinearScanStatistic _stat_final;
    52   static LinearScanTimers _total_timer;
    54   // helper macro for short definition of timer
    55   #define TIME_LINEAR_SCAN(timer_name)  TraceTime _block_timer("", _total_timer.timer(LinearScanTimers::timer_name), TimeLinearScan || TimeEachLinearScan, Verbose);
    57   // helper macro for short definition of trace-output inside code
    58   #define TRACE_LINEAR_SCAN(level, code)       \
    59     if (TraceLinearScanLevel >= level) {       \
    60       code;                                    \
    61     }
    63 #else
    65   #define TIME_LINEAR_SCAN(timer_name)
    66   #define TRACE_LINEAR_SCAN(level, code)
    68 #endif
    70 // Map BasicType to spill size in 32-bit words, matching VMReg's notion of words
    71 #ifdef _LP64
    72 static int type2spill_size[T_CONFLICT+1]={ -1, 0, 0, 0, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 0, 1, -1};
    73 #else
    74 static int type2spill_size[T_CONFLICT+1]={ -1, 0, 0, 0, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 0, 1, -1};
    75 #endif
    78 // Implementation of LinearScan
    80 LinearScan::LinearScan(IR* ir, LIRGenerator* gen, FrameMap* frame_map)
    81  : _compilation(ir->compilation())
    82  , _ir(ir)
    83  , _gen(gen)
    84  , _frame_map(frame_map)
    85  , _num_virtual_regs(gen->max_virtual_register_number())
    86  , _has_fpu_registers(false)
    87  , _num_calls(-1)
    88  , _max_spills(0)
    89  , _unused_spill_slot(-1)
    90  , _intervals(0)   // initialized later with correct length
    91  , _new_intervals_from_allocation(new IntervalList())
    92  , _sorted_intervals(NULL)
    93  , _needs_full_resort(false)
    94  , _lir_ops(0)     // initialized later with correct length
    95  , _block_of_op(0) // initialized later with correct length
    96  , _has_info(0)
    97  , _has_call(0)
    98  , _scope_value_cache(0) // initialized later with correct length
    99  , _interval_in_loop(0, 0) // initialized later with correct length
   100  , _cached_blocks(*ir->linear_scan_order())
   101 #ifdef X86
   102  , _fpu_stack_allocator(NULL)
   103 #endif
   104 {
   105   assert(this->ir() != NULL,          "check if valid");
   106   assert(this->compilation() != NULL, "check if valid");
   107   assert(this->gen() != NULL,         "check if valid");
   108   assert(this->frame_map() != NULL,   "check if valid");
   109 }
   112 // ********** functions for converting LIR-Operands to register numbers
   113 //
   114 // Emulate a flat register file comprising physical integer registers,
   115 // physical floating-point registers and virtual registers, in that order.
   116 // Virtual registers already have appropriate numbers, since V0 is
   117 // the number of physical registers.
   118 // Returns -1 for hi word if opr is a single word operand.
   119 //
   120 // Note: the inverse operation (calculating an operand for register numbers)
   121 //       is done in calc_operand_for_interval()
   123 int LinearScan::reg_num(LIR_Opr opr) {
   124   assert(opr->is_register(), "should not call this otherwise");
   126   if (opr->is_virtual_register()) {
   127     assert(opr->vreg_number() >= nof_regs, "found a virtual register with a fixed-register number");
   128     return opr->vreg_number();
   129   } else if (opr->is_single_cpu()) {
   130     return opr->cpu_regnr();
   131   } else if (opr->is_double_cpu()) {
   132     return opr->cpu_regnrLo();
   133 #ifdef X86
   134   } else if (opr->is_single_xmm()) {
   135     return opr->fpu_regnr() + pd_first_xmm_reg;
   136   } else if (opr->is_double_xmm()) {
   137     return opr->fpu_regnrLo() + pd_first_xmm_reg;
   138 #endif
   139   } else if (opr->is_single_fpu()) {
   140     return opr->fpu_regnr() + pd_first_fpu_reg;
   141   } else if (opr->is_double_fpu()) {
   142     return opr->fpu_regnrLo() + pd_first_fpu_reg;
   143   } else {
   144     ShouldNotReachHere();
   145     return -1;
   146   }
   147 }
   149 int LinearScan::reg_numHi(LIR_Opr opr) {
   150   assert(opr->is_register(), "should not call this otherwise");
   152   if (opr->is_virtual_register()) {
   153     return -1;
   154   } else if (opr->is_single_cpu()) {
   155     return -1;
   156   } else if (opr->is_double_cpu()) {
   157     return opr->cpu_regnrHi();
   158 #ifdef X86
   159   } else if (opr->is_single_xmm()) {
   160     return -1;
   161   } else if (opr->is_double_xmm()) {
   162     return -1;
   163 #endif
   164   } else if (opr->is_single_fpu()) {
   165     return -1;
   166   } else if (opr->is_double_fpu()) {
   167     return opr->fpu_regnrHi() + pd_first_fpu_reg;
   168   } else {
   169     ShouldNotReachHere();
   170     return -1;
   171   }
   172 }
   175 // ********** functions for classification of intervals
   177 bool LinearScan::is_precolored_interval(const Interval* i) {
   178   return i->reg_num() < LinearScan::nof_regs;
   179 }
   181 bool LinearScan::is_virtual_interval(const Interval* i) {
   182   return i->reg_num() >= LIR_OprDesc::vreg_base;
   183 }
   185 bool LinearScan::is_precolored_cpu_interval(const Interval* i) {
   186   return i->reg_num() < LinearScan::nof_cpu_regs;
   187 }
   189 bool LinearScan::is_virtual_cpu_interval(const Interval* i) {
   190 #if defined(__SOFTFP__) || defined(E500V2)
   191   return i->reg_num() >= LIR_OprDesc::vreg_base;
   192 #else
   193   return i->reg_num() >= LIR_OprDesc::vreg_base && (i->type() != T_FLOAT && i->type() != T_DOUBLE);
   194 #endif // __SOFTFP__ or E500V2
   195 }
   197 bool LinearScan::is_precolored_fpu_interval(const Interval* i) {
   198   return i->reg_num() >= LinearScan::nof_cpu_regs && i->reg_num() < LinearScan::nof_regs;
   199 }
   201 bool LinearScan::is_virtual_fpu_interval(const Interval* i) {
   202 #if defined(__SOFTFP__) || defined(E500V2)
   203   return false;
   204 #else
   205   return i->reg_num() >= LIR_OprDesc::vreg_base && (i->type() == T_FLOAT || i->type() == T_DOUBLE);
   206 #endif // __SOFTFP__ or E500V2
   207 }
   209 bool LinearScan::is_in_fpu_register(const Interval* i) {
   210   // fixed intervals not needed for FPU stack allocation
   211   return i->reg_num() >= nof_regs && pd_first_fpu_reg <= i->assigned_reg() && i->assigned_reg() <= pd_last_fpu_reg;
   212 }
   214 bool LinearScan::is_oop_interval(const Interval* i) {
   215   // fixed intervals never contain oops
   216   return i->reg_num() >= nof_regs && i->type() == T_OBJECT;
   217 }
   220 // ********** General helper functions
   222 // compute next unused stack index that can be used for spilling
   223 int LinearScan::allocate_spill_slot(bool double_word) {
   224   int spill_slot;
   225   if (double_word) {
   226     if ((_max_spills & 1) == 1) {
   227       // alignment of double-word values
   228       // the hole because of the alignment is filled with the next single-word value
   229       assert(_unused_spill_slot == -1, "wasting a spill slot");
   230       _unused_spill_slot = _max_spills;
   231       _max_spills++;
   232     }
   233     spill_slot = _max_spills;
   234     _max_spills += 2;
   236   } else if (_unused_spill_slot != -1) {
   237     // re-use hole that was the result of a previous double-word alignment
   238     spill_slot = _unused_spill_slot;
   239     _unused_spill_slot = -1;
   241   } else {
   242     spill_slot = _max_spills;
   243     _max_spills++;
   244   }
   246   int result = spill_slot + LinearScan::nof_regs + frame_map()->argcount();
   248   // the class OopMapValue uses only 11 bits for storing the name of the
   249   // oop location. So a stack slot bigger than 2^11 leads to an overflow
   250   // that is not reported in product builds. Prevent this by checking the
   251   // spill slot here (altough this value and the later used location name
   252   // are slightly different)
   253   if (result > 2000) {
   254     bailout("too many stack slots used");
   255   }
   257   return result;
   258 }
   260 void LinearScan::assign_spill_slot(Interval* it) {
   261   // assign the canonical spill slot of the parent (if a part of the interval
   262   // is already spilled) or allocate a new spill slot
   263   if (it->canonical_spill_slot() >= 0) {
   264     it->assign_reg(it->canonical_spill_slot());
   265   } else {
   266     int spill = allocate_spill_slot(type2spill_size[it->type()] == 2);
   267     it->set_canonical_spill_slot(spill);
   268     it->assign_reg(spill);
   269   }
   270 }
   272 void LinearScan::propagate_spill_slots() {
   273   if (!frame_map()->finalize_frame(max_spills())) {
   274     bailout("frame too large");
   275   }
   276 }
   278 // create a new interval with a predefined reg_num
   279 // (only used for parent intervals that are created during the building phase)
   280 Interval* LinearScan::create_interval(int reg_num) {
   281   assert(_intervals.at(reg_num) == NULL, "overwriting exisiting interval");
   283   Interval* interval = new Interval(reg_num);
   284   _intervals.at_put(reg_num, interval);
   286   // assign register number for precolored intervals
   287   if (reg_num < LIR_OprDesc::vreg_base) {
   288     interval->assign_reg(reg_num);
   289   }
   290   return interval;
   291 }
   293 // assign a new reg_num to the interval and append it to the list of intervals
   294 // (only used for child intervals that are created during register allocation)
   295 void LinearScan::append_interval(Interval* it) {
   296   it->set_reg_num(_intervals.length());
   297   _intervals.append(it);
   298   _new_intervals_from_allocation->append(it);
   299 }
   301 // copy the vreg-flags if an interval is split
   302 void LinearScan::copy_register_flags(Interval* from, Interval* to) {
   303   if (gen()->is_vreg_flag_set(from->reg_num(), LIRGenerator::byte_reg)) {
   304     gen()->set_vreg_flag(to->reg_num(), LIRGenerator::byte_reg);
   305   }
   306   if (gen()->is_vreg_flag_set(from->reg_num(), LIRGenerator::callee_saved)) {
   307     gen()->set_vreg_flag(to->reg_num(), LIRGenerator::callee_saved);
   308   }
   310   // Note: do not copy the must_start_in_memory flag because it is not necessary for child
   311   //       intervals (only the very beginning of the interval must be in memory)
   312 }
   315 // ********** spill move optimization
   316 // eliminate moves from register to stack if stack slot is known to be correct
   318 // called during building of intervals
   319 void LinearScan::change_spill_definition_pos(Interval* interval, int def_pos) {
   320   assert(interval->is_split_parent(), "can only be called for split parents");
   322   switch (interval->spill_state()) {
   323     case noDefinitionFound:
   324       assert(interval->spill_definition_pos() == -1, "must no be set before");
   325       interval->set_spill_definition_pos(def_pos);
   326       interval->set_spill_state(oneDefinitionFound);
   327       break;
   329     case oneDefinitionFound:
   330       assert(def_pos <= interval->spill_definition_pos(), "positions are processed in reverse order when intervals are created");
   331       if (def_pos < interval->spill_definition_pos() - 2) {
   332         // second definition found, so no spill optimization possible for this interval
   333         interval->set_spill_state(noOptimization);
   334       } else {
   335         // two consecutive definitions (because of two-operand LIR form)
   336         assert(block_of_op_with_id(def_pos) == block_of_op_with_id(interval->spill_definition_pos()), "block must be equal");
   337       }
   338       break;
   340     case noOptimization:
   341       // nothing to do
   342       break;
   344     default:
   345       assert(false, "other states not allowed at this time");
   346   }
   347 }
   349 // called during register allocation
   350 void LinearScan::change_spill_state(Interval* interval, int spill_pos) {
   351   switch (interval->spill_state()) {
   352     case oneDefinitionFound: {
   353       int def_loop_depth = block_of_op_with_id(interval->spill_definition_pos())->loop_depth();
   354       int spill_loop_depth = block_of_op_with_id(spill_pos)->loop_depth();
   356       if (def_loop_depth < spill_loop_depth) {
   357         // the loop depth of the spilling position is higher then the loop depth
   358         // at the definition of the interval -> move write to memory out of loop
   359         // by storing at definitin of the interval
   360         interval->set_spill_state(storeAtDefinition);
   361       } else {
   362         // the interval is currently spilled only once, so for now there is no
   363         // reason to store the interval at the definition
   364         interval->set_spill_state(oneMoveInserted);
   365       }
   366       break;
   367     }
   369     case oneMoveInserted: {
   370       // the interval is spilled more then once, so it is better to store it to
   371       // memory at the definition
   372       interval->set_spill_state(storeAtDefinition);
   373       break;
   374     }
   376     case storeAtDefinition:
   377     case startInMemory:
   378     case noOptimization:
   379     case noDefinitionFound:
   380       // nothing to do
   381       break;
   383     default:
   384       assert(false, "other states not allowed at this time");
   385   }
   386 }
   389 bool LinearScan::must_store_at_definition(const Interval* i) {
   390   return i->is_split_parent() && i->spill_state() == storeAtDefinition;
   391 }
   393 // called once before asignment of register numbers
   394 void LinearScan::eliminate_spill_moves() {
   395   TIME_LINEAR_SCAN(timer_eliminate_spill_moves);
   396   TRACE_LINEAR_SCAN(3, tty->print_cr("***** Eliminating unnecessary spill moves"));
   398   // collect all intervals that must be stored after their definion.
   399   // the list is sorted by Interval::spill_definition_pos
   400   Interval* interval;
   401   Interval* temp_list;
   402   create_unhandled_lists(&interval, &temp_list, must_store_at_definition, NULL);
   404 #ifdef ASSERT
   405   Interval* prev = NULL;
   406   Interval* temp = interval;
   407   while (temp != Interval::end()) {
   408     assert(temp->spill_definition_pos() > 0, "invalid spill definition pos");
   409     if (prev != NULL) {
   410       assert(temp->from() >= prev->from(), "intervals not sorted");
   411       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");
   412     }
   414     assert(temp->canonical_spill_slot() >= LinearScan::nof_regs, "interval has no spill slot assigned");
   415     assert(temp->spill_definition_pos() >= temp->from(), "invalid order");
   416     assert(temp->spill_definition_pos() <= temp->from() + 2, "only intervals defined once at their start-pos can be optimized");
   418     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()));
   420     temp = temp->next();
   421   }
   422 #endif
   424   LIR_InsertionBuffer insertion_buffer;
   425   int num_blocks = block_count();
   426   for (int i = 0; i < num_blocks; i++) {
   427     BlockBegin* block = block_at(i);
   428     LIR_OpList* instructions = block->lir()->instructions_list();
   429     int         num_inst = instructions->length();
   430     bool        has_new = false;
   432     // iterate all instructions of the block. skip the first because it is always a label
   433     for (int j = 1; j < num_inst; j++) {
   434       LIR_Op* op = instructions->at(j);
   435       int op_id = op->id();
   437       if (op_id == -1) {
   438         // remove move from register to stack if the stack slot is guaranteed to be correct.
   439         // only moves that have been inserted by LinearScan can be removed.
   440         assert(op->code() == lir_move, "only moves can have a op_id of -1");
   441         assert(op->as_Op1() != NULL, "move must be LIR_Op1");
   442         assert(op->as_Op1()->result_opr()->is_virtual(), "LinearScan inserts only moves to virtual registers");
   444         LIR_Op1* op1 = (LIR_Op1*)op;
   445         Interval* interval = interval_at(op1->result_opr()->vreg_number());
   447         if (interval->assigned_reg() >= LinearScan::nof_regs && interval->always_in_memory()) {
   448           // move target is a stack slot that is always correct, so eliminate instruction
   449           TRACE_LINEAR_SCAN(4, tty->print_cr("eliminating move from interval %d to %d", op1->in_opr()->vreg_number(), op1->result_opr()->vreg_number()));
   450           instructions->at_put(j, NULL); // NULL-instructions are deleted by assign_reg_num
   451         }
   453       } else {
   454         // insert move from register to stack just after the beginning of the interval
   455         assert(interval == Interval::end() || interval->spill_definition_pos() >= op_id, "invalid order");
   456         assert(interval == Interval::end() || (interval->is_split_parent() && interval->spill_state() == storeAtDefinition), "invalid interval");
   458         while (interval != Interval::end() && interval->spill_definition_pos() == op_id) {
   459           if (!has_new) {
   460             // prepare insertion buffer (appended when all instructions of the block are processed)
   461             insertion_buffer.init(block->lir());
   462             has_new = true;
   463           }
   465           LIR_Opr from_opr = operand_for_interval(interval);
   466           LIR_Opr to_opr = canonical_spill_opr(interval);
   467           assert(from_opr->is_fixed_cpu() || from_opr->is_fixed_fpu(), "from operand must be a register");
   468           assert(to_opr->is_stack(), "to operand must be a stack slot");
   470           insertion_buffer.move(j, from_opr, to_opr);
   471           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));
   473           interval = interval->next();
   474         }
   475       }
   476     } // end of instruction iteration
   478     if (has_new) {
   479       block->lir()->append(&insertion_buffer);
   480     }
   481   } // end of block iteration
   483   assert(interval == Interval::end(), "missed an interval");
   484 }
   487 // ********** Phase 1: number all instructions in all blocks
   488 // Compute depth-first and linear scan block orders, and number LIR_Op nodes for linear scan.
   490 void LinearScan::number_instructions() {
   491   {
   492     // dummy-timer to measure the cost of the timer itself
   493     // (this time is then subtracted from all other timers to get the real value)
   494     TIME_LINEAR_SCAN(timer_do_nothing);
   495   }
   496   TIME_LINEAR_SCAN(timer_number_instructions);
   498   // Assign IDs to LIR nodes and build a mapping, lir_ops, from ID to LIR_Op node.
   499   int num_blocks = block_count();
   500   int num_instructions = 0;
   501   int i;
   502   for (i = 0; i < num_blocks; i++) {
   503     num_instructions += block_at(i)->lir()->instructions_list()->length();
   504   }
   506   // initialize with correct length
   507   _lir_ops = LIR_OpArray(num_instructions);
   508   _block_of_op = BlockBeginArray(num_instructions);
   510   int op_id = 0;
   511   int idx = 0;
   513   for (i = 0; i < num_blocks; i++) {
   514     BlockBegin* block = block_at(i);
   515     block->set_first_lir_instruction_id(op_id);
   516     LIR_OpList* instructions = block->lir()->instructions_list();
   518     int num_inst = instructions->length();
   519     for (int j = 0; j < num_inst; j++) {
   520       LIR_Op* op = instructions->at(j);
   521       op->set_id(op_id);
   523       _lir_ops.at_put(idx, op);
   524       _block_of_op.at_put(idx, block);
   525       assert(lir_op_with_id(op_id) == op, "must match");
   527       idx++;
   528       op_id += 2; // numbering of lir_ops by two
   529     }
   530     block->set_last_lir_instruction_id(op_id - 2);
   531   }
   532   assert(idx == num_instructions, "must match");
   533   assert(idx * 2 == op_id, "must match");
   535   _has_call = BitMap(num_instructions); _has_call.clear();
   536   _has_info = BitMap(num_instructions); _has_info.clear();
   537 }
   540 // ********** Phase 2: compute local live sets separately for each block
   541 // (sets live_gen and live_kill for each block)
   543 void LinearScan::set_live_gen_kill(Value value, LIR_Op* op, BitMap& live_gen, BitMap& live_kill) {
   544   LIR_Opr opr = value->operand();
   545   Constant* con = value->as_Constant();
   547   // check some asumptions about debug information
   548   assert(!value->type()->is_illegal(), "if this local is used by the interpreter it shouldn't be of indeterminate type");
   549   assert(con == NULL || opr->is_virtual() || opr->is_constant() || opr->is_illegal(), "asumption: Constant instructions have only constant operands");
   550   assert(con != NULL || opr->is_virtual(), "asumption: non-Constant instructions have only virtual operands");
   552   if ((con == NULL || con->is_pinned()) && opr->is_register()) {
   553     assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
   554     int reg = opr->vreg_number();
   555     if (!live_kill.at(reg)) {
   556       live_gen.set_bit(reg);
   557       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));
   558     }
   559   }
   560 }
   563 void LinearScan::compute_local_live_sets() {
   564   TIME_LINEAR_SCAN(timer_compute_local_live_sets);
   566   int  num_blocks = block_count();
   567   int  live_size = live_set_size();
   568   bool local_has_fpu_registers = false;
   569   int  local_num_calls = 0;
   570   LIR_OpVisitState visitor;
   572   BitMap2D local_interval_in_loop = BitMap2D(_num_virtual_regs, num_loops());
   573   local_interval_in_loop.clear();
   575   // iterate all blocks
   576   for (int i = 0; i < num_blocks; i++) {
   577     BlockBegin* block = block_at(i);
   579     BitMap live_gen(live_size);  live_gen.clear();
   580     BitMap live_kill(live_size); live_kill.clear();
   582     if (block->is_set(BlockBegin::exception_entry_flag)) {
   583       // Phi functions at the begin of an exception handler are
   584       // implicitly defined (= killed) at the beginning of the block.
   585       for_each_phi_fun(block, phi,
   586         live_kill.set_bit(phi->operand()->vreg_number())
   587       );
   588     }
   590     LIR_OpList* instructions = block->lir()->instructions_list();
   591     int num_inst = instructions->length();
   593     // iterate all instructions of the block. skip the first because it is always a label
   594     assert(visitor.no_operands(instructions->at(0)), "first operation must always be a label");
   595     for (int j = 1; j < num_inst; j++) {
   596       LIR_Op* op = instructions->at(j);
   598       // visit operation to collect all operands
   599       visitor.visit(op);
   601       if (visitor.has_call()) {
   602         _has_call.set_bit(op->id() >> 1);
   603         local_num_calls++;
   604       }
   605       if (visitor.info_count() > 0) {
   606         _has_info.set_bit(op->id() >> 1);
   607       }
   609       // iterate input operands of instruction
   610       int k, n, reg;
   611       n = visitor.opr_count(LIR_OpVisitState::inputMode);
   612       for (k = 0; k < n; k++) {
   613         LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::inputMode, k);
   614         assert(opr->is_register(), "visitor should only return register operands");
   616         if (opr->is_virtual_register()) {
   617           assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
   618           reg = opr->vreg_number();
   619           if (!live_kill.at(reg)) {
   620             live_gen.set_bit(reg);
   621             TRACE_LINEAR_SCAN(4, tty->print_cr("  Setting live_gen for register %d at instruction %d", reg, op->id()));
   622           }
   623           if (block->loop_index() >= 0) {
   624             local_interval_in_loop.set_bit(reg, block->loop_index());
   625           }
   626           local_has_fpu_registers = local_has_fpu_registers || opr->is_virtual_fpu();
   627         }
   629 #ifdef ASSERT
   630         // fixed intervals are never live at block boundaries, so
   631         // they need not be processed in live sets.
   632         // this is checked by these assertions to be sure about it.
   633         // the entry block may have incoming values in registers, which is ok.
   634         if (!opr->is_virtual_register() && block != ir()->start()) {
   635           reg = reg_num(opr);
   636           if (is_processed_reg_num(reg)) {
   637             assert(live_kill.at(reg), "using fixed register that is not defined in this block");
   638           }
   639           reg = reg_numHi(opr);
   640           if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
   641             assert(live_kill.at(reg), "using fixed register that is not defined in this block");
   642           }
   643         }
   644 #endif
   645       }
   647       // Add uses of live locals from interpreter's point of view for proper debug information generation
   648       n = visitor.info_count();
   649       for (k = 0; k < n; k++) {
   650         CodeEmitInfo* info = visitor.info_at(k);
   651         ValueStack* stack = info->stack();
   652         for_each_state_value(stack, value,
   653           set_live_gen_kill(value, op, live_gen, live_kill)
   654         );
   655       }
   657       // iterate temp operands of instruction
   658       n = visitor.opr_count(LIR_OpVisitState::tempMode);
   659       for (k = 0; k < n; k++) {
   660         LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::tempMode, k);
   661         assert(opr->is_register(), "visitor should only return register operands");
   663         if (opr->is_virtual_register()) {
   664           assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
   665           reg = opr->vreg_number();
   666           live_kill.set_bit(reg);
   667           if (block->loop_index() >= 0) {
   668             local_interval_in_loop.set_bit(reg, block->loop_index());
   669           }
   670           local_has_fpu_registers = local_has_fpu_registers || opr->is_virtual_fpu();
   671         }
   673 #ifdef ASSERT
   674         // fixed intervals are never live at block boundaries, so
   675         // they need not be processed in live sets
   676         // process them only in debug mode so that this can be checked
   677         if (!opr->is_virtual_register()) {
   678           reg = reg_num(opr);
   679           if (is_processed_reg_num(reg)) {
   680             live_kill.set_bit(reg_num(opr));
   681           }
   682           reg = reg_numHi(opr);
   683           if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
   684             live_kill.set_bit(reg);
   685           }
   686         }
   687 #endif
   688       }
   690       // iterate output operands of instruction
   691       n = visitor.opr_count(LIR_OpVisitState::outputMode);
   692       for (k = 0; k < n; k++) {
   693         LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::outputMode, k);
   694         assert(opr->is_register(), "visitor should only return register operands");
   696         if (opr->is_virtual_register()) {
   697           assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
   698           reg = opr->vreg_number();
   699           live_kill.set_bit(reg);
   700           if (block->loop_index() >= 0) {
   701             local_interval_in_loop.set_bit(reg, block->loop_index());
   702           }
   703           local_has_fpu_registers = local_has_fpu_registers || opr->is_virtual_fpu();
   704         }
   706 #ifdef ASSERT
   707         // fixed intervals are never live at block boundaries, so
   708         // they need not be processed in live sets
   709         // process them only in debug mode so that this can be checked
   710         if (!opr->is_virtual_register()) {
   711           reg = reg_num(opr);
   712           if (is_processed_reg_num(reg)) {
   713             live_kill.set_bit(reg_num(opr));
   714           }
   715           reg = reg_numHi(opr);
   716           if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
   717             live_kill.set_bit(reg);
   718           }
   719         }
   720 #endif
   721       }
   722     } // end of instruction iteration
   724     block->set_live_gen (live_gen);
   725     block->set_live_kill(live_kill);
   726     block->set_live_in  (BitMap(live_size)); block->live_in().clear();
   727     block->set_live_out (BitMap(live_size)); block->live_out().clear();
   729     TRACE_LINEAR_SCAN(4, tty->print("live_gen  B%d ", block->block_id()); print_bitmap(block->live_gen()));
   730     TRACE_LINEAR_SCAN(4, tty->print("live_kill B%d ", block->block_id()); print_bitmap(block->live_kill()));
   731   } // end of block iteration
   733   // propagate local calculated information into LinearScan object
   734   _has_fpu_registers = local_has_fpu_registers;
   735   compilation()->set_has_fpu_code(local_has_fpu_registers);
   737   _num_calls = local_num_calls;
   738   _interval_in_loop = local_interval_in_loop;
   739 }
   742 // ********** Phase 3: perform a backward dataflow analysis to compute global live sets
   743 // (sets live_in and live_out for each block)
   745 void LinearScan::compute_global_live_sets() {
   746   TIME_LINEAR_SCAN(timer_compute_global_live_sets);
   748   int  num_blocks = block_count();
   749   bool change_occurred;
   750   bool change_occurred_in_block;
   751   int  iteration_count = 0;
   752   BitMap live_out(live_set_size()); live_out.clear(); // scratch set for calculations
   754   // Perform a backward dataflow analysis to compute live_out and live_in for each block.
   755   // The loop is executed until a fixpoint is reached (no changes in an iteration)
   756   // Exception handlers must be processed because not all live values are
   757   // present in the state array, e.g. because of global value numbering
   758   do {
   759     change_occurred = false;
   761     // iterate all blocks in reverse order
   762     for (int i = num_blocks - 1; i >= 0; i--) {
   763       BlockBegin* block = block_at(i);
   765       change_occurred_in_block = false;
   767       // live_out(block) is the union of live_in(sux), for successors sux of block
   768       int n = block->number_of_sux();
   769       int e = block->number_of_exception_handlers();
   770       if (n + e > 0) {
   771         // block has successors
   772         if (n > 0) {
   773           live_out.set_from(block->sux_at(0)->live_in());
   774           for (int j = 1; j < n; j++) {
   775             live_out.set_union(block->sux_at(j)->live_in());
   776           }
   777         } else {
   778           live_out.clear();
   779         }
   780         for (int j = 0; j < e; j++) {
   781           live_out.set_union(block->exception_handler_at(j)->live_in());
   782         }
   784         if (!block->live_out().is_same(live_out)) {
   785           // A change occurred.  Swap the old and new live out sets to avoid copying.
   786           BitMap temp = block->live_out();
   787           block->set_live_out(live_out);
   788           live_out = temp;
   790           change_occurred = true;
   791           change_occurred_in_block = true;
   792         }
   793       }
   795       if (iteration_count == 0 || change_occurred_in_block) {
   796         // live_in(block) is the union of live_gen(block) with (live_out(block) & !live_kill(block))
   797         // note: live_in has to be computed only in first iteration or if live_out has changed!
   798         BitMap live_in = block->live_in();
   799         live_in.set_from(block->live_out());
   800         live_in.set_difference(block->live_kill());
   801         live_in.set_union(block->live_gen());
   802       }
   804 #ifndef PRODUCT
   805       if (TraceLinearScanLevel >= 4) {
   806         char c = ' ';
   807         if (iteration_count == 0 || change_occurred_in_block) {
   808           c = '*';
   809         }
   810         tty->print("(%d) live_in%c  B%d ", iteration_count, c, block->block_id()); print_bitmap(block->live_in());
   811         tty->print("(%d) live_out%c B%d ", iteration_count, c, block->block_id()); print_bitmap(block->live_out());
   812       }
   813 #endif
   814     }
   815     iteration_count++;
   817     if (change_occurred && iteration_count > 50) {
   818       BAILOUT("too many iterations in compute_global_live_sets");
   819     }
   820   } while (change_occurred);
   823 #ifdef ASSERT
   824   // check that fixed intervals are not live at block boundaries
   825   // (live set must be empty at fixed intervals)
   826   for (int i = 0; i < num_blocks; i++) {
   827     BlockBegin* block = block_at(i);
   828     for (int j = 0; j < LIR_OprDesc::vreg_base; j++) {
   829       assert(block->live_in().at(j)  == false, "live_in  set of fixed register must be empty");
   830       assert(block->live_out().at(j) == false, "live_out set of fixed register must be empty");
   831       assert(block->live_gen().at(j) == false, "live_gen set of fixed register must be empty");
   832     }
   833   }
   834 #endif
   836   // check that the live_in set of the first block is empty
   837   BitMap live_in_args(ir()->start()->live_in().size());
   838   live_in_args.clear();
   839   if (!ir()->start()->live_in().is_same(live_in_args)) {
   840 #ifdef ASSERT
   841     tty->print_cr("Error: live_in set of first block must be empty (when this fails, virtual registers are used before they are defined)");
   842     tty->print_cr("affected registers:");
   843     print_bitmap(ir()->start()->live_in());
   845     // print some additional information to simplify debugging
   846     for (unsigned int i = 0; i < ir()->start()->live_in().size(); i++) {
   847       if (ir()->start()->live_in().at(i)) {
   848         Instruction* instr = gen()->instruction_for_vreg(i);
   849         tty->print_cr("* vreg %d (HIR instruction %c%d)", i, instr == NULL ? ' ' : instr->type()->tchar(), instr == NULL ? 0 : instr->id());
   851         for (int j = 0; j < num_blocks; j++) {
   852           BlockBegin* block = block_at(j);
   853           if (block->live_gen().at(i)) {
   854             tty->print_cr("  used in block B%d", block->block_id());
   855           }
   856           if (block->live_kill().at(i)) {
   857             tty->print_cr("  defined in block B%d", block->block_id());
   858           }
   859         }
   860       }
   861     }
   863 #endif
   864     // when this fails, virtual registers are used before they are defined.
   865     assert(false, "live_in set of first block must be empty");
   866     // bailout of if this occurs in product mode.
   867     bailout("live_in set of first block not empty");
   868   }
   869 }
   872 // ********** Phase 4: build intervals
   873 // (fills the list _intervals)
   875 void LinearScan::add_use(Value value, int from, int to, IntervalUseKind use_kind) {
   876   assert(!value->type()->is_illegal(), "if this value is used by the interpreter it shouldn't be of indeterminate type");
   877   LIR_Opr opr = value->operand();
   878   Constant* con = value->as_Constant();
   880   if ((con == NULL || con->is_pinned()) && opr->is_register()) {
   881     assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
   882     add_use(opr, from, to, use_kind);
   883   }
   884 }
   887 void LinearScan::add_def(LIR_Opr opr, int def_pos, IntervalUseKind use_kind) {
   888   TRACE_LINEAR_SCAN(2, tty->print(" def "); opr->print(tty); tty->print_cr(" def_pos %d (%d)", def_pos, use_kind));
   889   assert(opr->is_register(), "should not be called otherwise");
   891   if (opr->is_virtual_register()) {
   892     assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
   893     add_def(opr->vreg_number(), def_pos, use_kind, opr->type_register());
   895   } else {
   896     int reg = reg_num(opr);
   897     if (is_processed_reg_num(reg)) {
   898       add_def(reg, def_pos, use_kind, opr->type_register());
   899     }
   900     reg = reg_numHi(opr);
   901     if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
   902       add_def(reg, def_pos, use_kind, opr->type_register());
   903     }
   904   }
   905 }
   907 void LinearScan::add_use(LIR_Opr opr, int from, int to, IntervalUseKind use_kind) {
   908   TRACE_LINEAR_SCAN(2, tty->print(" use "); opr->print(tty); tty->print_cr(" from %d to %d (%d)", from, to, use_kind));
   909   assert(opr->is_register(), "should not be called otherwise");
   911   if (opr->is_virtual_register()) {
   912     assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
   913     add_use(opr->vreg_number(), from, to, use_kind, opr->type_register());
   915   } else {
   916     int reg = reg_num(opr);
   917     if (is_processed_reg_num(reg)) {
   918       add_use(reg, from, to, use_kind, opr->type_register());
   919     }
   920     reg = reg_numHi(opr);
   921     if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
   922       add_use(reg, from, to, use_kind, opr->type_register());
   923     }
   924   }
   925 }
   927 void LinearScan::add_temp(LIR_Opr opr, int temp_pos, IntervalUseKind use_kind) {
   928   TRACE_LINEAR_SCAN(2, tty->print(" temp "); opr->print(tty); tty->print_cr(" temp_pos %d (%d)", temp_pos, use_kind));
   929   assert(opr->is_register(), "should not be called otherwise");
   931   if (opr->is_virtual_register()) {
   932     assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
   933     add_temp(opr->vreg_number(), temp_pos, use_kind, opr->type_register());
   935   } else {
   936     int reg = reg_num(opr);
   937     if (is_processed_reg_num(reg)) {
   938       add_temp(reg, temp_pos, use_kind, opr->type_register());
   939     }
   940     reg = reg_numHi(opr);
   941     if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
   942       add_temp(reg, temp_pos, use_kind, opr->type_register());
   943     }
   944   }
   945 }
   948 void LinearScan::add_def(int reg_num, int def_pos, IntervalUseKind use_kind, BasicType type) {
   949   Interval* interval = interval_at(reg_num);
   950   if (interval != NULL) {
   951     assert(interval->reg_num() == reg_num, "wrong interval");
   953     if (type != T_ILLEGAL) {
   954       interval->set_type(type);
   955     }
   957     Range* r = interval->first();
   958     if (r->from() <= def_pos) {
   959       // Update the starting point (when a range is first created for a use, its
   960       // start is the beginning of the current block until a def is encountered.)
   961       r->set_from(def_pos);
   962       interval->add_use_pos(def_pos, use_kind);
   964     } else {
   965       // Dead value - make vacuous interval
   966       // also add use_kind for dead intervals
   967       interval->add_range(def_pos, def_pos + 1);
   968       interval->add_use_pos(def_pos, use_kind);
   969       TRACE_LINEAR_SCAN(2, tty->print_cr("Warning: def of reg %d at %d occurs without use", reg_num, def_pos));
   970     }
   972   } else {
   973     // Dead value - make vacuous interval
   974     // also add use_kind for dead intervals
   975     interval = create_interval(reg_num);
   976     if (type != T_ILLEGAL) {
   977       interval->set_type(type);
   978     }
   980     interval->add_range(def_pos, def_pos + 1);
   981     interval->add_use_pos(def_pos, use_kind);
   982     TRACE_LINEAR_SCAN(2, tty->print_cr("Warning: dead value %d at %d in live intervals", reg_num, def_pos));
   983   }
   985   change_spill_definition_pos(interval, def_pos);
   986   if (use_kind == noUse && interval->spill_state() <= startInMemory) {
   987         // detection of method-parameters and roundfp-results
   988         // TODO: move this directly to position where use-kind is computed
   989     interval->set_spill_state(startInMemory);
   990   }
   991 }
   993 void LinearScan::add_use(int reg_num, int from, int to, IntervalUseKind use_kind, BasicType type) {
   994   Interval* interval = interval_at(reg_num);
   995   if (interval == NULL) {
   996     interval = create_interval(reg_num);
   997   }
   998   assert(interval->reg_num() == reg_num, "wrong interval");
  1000   if (type != T_ILLEGAL) {
  1001     interval->set_type(type);
  1004   interval->add_range(from, to);
  1005   interval->add_use_pos(to, use_kind);
  1008 void LinearScan::add_temp(int reg_num, int temp_pos, IntervalUseKind use_kind, BasicType type) {
  1009   Interval* interval = interval_at(reg_num);
  1010   if (interval == NULL) {
  1011     interval = create_interval(reg_num);
  1013   assert(interval->reg_num() == reg_num, "wrong interval");
  1015   if (type != T_ILLEGAL) {
  1016     interval->set_type(type);
  1019   interval->add_range(temp_pos, temp_pos + 1);
  1020   interval->add_use_pos(temp_pos, use_kind);
  1024 // the results of this functions are used for optimizing spilling and reloading
  1025 // if the functions return shouldHaveRegister and the interval is spilled,
  1026 // it is not reloaded to a register.
  1027 IntervalUseKind LinearScan::use_kind_of_output_operand(LIR_Op* op, LIR_Opr opr) {
  1028   if (op->code() == lir_move) {
  1029     assert(op->as_Op1() != NULL, "lir_move must be LIR_Op1");
  1030     LIR_Op1* move = (LIR_Op1*)op;
  1031     LIR_Opr res = move->result_opr();
  1032     bool result_in_memory = res->is_virtual() && gen()->is_vreg_flag_set(res->vreg_number(), LIRGenerator::must_start_in_memory);
  1034     if (result_in_memory) {
  1035       // Begin of an interval with must_start_in_memory set.
  1036       // This interval will always get a stack slot first, so return noUse.
  1037       return noUse;
  1039     } else if (move->in_opr()->is_stack()) {
  1040       // method argument (condition must be equal to handle_method_arguments)
  1041       return noUse;
  1043     } else if (move->in_opr()->is_register() && move->result_opr()->is_register()) {
  1044       // Move from register to register
  1045       if (block_of_op_with_id(op->id())->is_set(BlockBegin::osr_entry_flag)) {
  1046         // special handling of phi-function moves inside osr-entry blocks
  1047         // input operand must have a register instead of output operand (leads to better register allocation)
  1048         return shouldHaveRegister;
  1053   if (opr->is_virtual() &&
  1054       gen()->is_vreg_flag_set(opr->vreg_number(), LIRGenerator::must_start_in_memory)) {
  1055     // result is a stack-slot, so prevent immediate reloading
  1056     return noUse;
  1059   // all other operands require a register
  1060   return mustHaveRegister;
  1063 IntervalUseKind LinearScan::use_kind_of_input_operand(LIR_Op* op, LIR_Opr opr) {
  1064   if (op->code() == lir_move) {
  1065     assert(op->as_Op1() != NULL, "lir_move must be LIR_Op1");
  1066     LIR_Op1* move = (LIR_Op1*)op;
  1067     LIR_Opr res = move->result_opr();
  1068     bool result_in_memory = res->is_virtual() && gen()->is_vreg_flag_set(res->vreg_number(), LIRGenerator::must_start_in_memory);
  1070     if (result_in_memory) {
  1071       // Move to an interval with must_start_in_memory set.
  1072       // To avoid moves from stack to stack (not allowed) force the input operand to a register
  1073       return mustHaveRegister;
  1075     } else if (move->in_opr()->is_register() && move->result_opr()->is_register()) {
  1076       // Move from register to register
  1077       if (block_of_op_with_id(op->id())->is_set(BlockBegin::osr_entry_flag)) {
  1078         // special handling of phi-function moves inside osr-entry blocks
  1079         // input operand must have a register instead of output operand (leads to better register allocation)
  1080         return mustHaveRegister;
  1083       // The input operand is not forced to a register (moves from stack to register are allowed),
  1084       // but it is faster if the input operand is in a register
  1085       return shouldHaveRegister;
  1090 #ifdef X86
  1091   if (op->code() == lir_cmove) {
  1092     // conditional moves can handle stack operands
  1093     assert(op->result_opr()->is_register(), "result must always be in a register");
  1094     return shouldHaveRegister;
  1097   // optimizations for second input operand of arithmehtic operations on Intel
  1098   // this operand is allowed to be on the stack in some cases
  1099   BasicType opr_type = opr->type_register();
  1100   if (opr_type == T_FLOAT || opr_type == T_DOUBLE) {
  1101     if ((UseSSE == 1 && opr_type == T_FLOAT) || UseSSE >= 2) {
  1102       // SSE float instruction (T_DOUBLE only supported with SSE2)
  1103       switch (op->code()) {
  1104         case lir_cmp:
  1105         case lir_add:
  1106         case lir_sub:
  1107         case lir_mul:
  1108         case lir_div:
  1110           assert(op->as_Op2() != NULL, "must be LIR_Op2");
  1111           LIR_Op2* op2 = (LIR_Op2*)op;
  1112           if (op2->in_opr1() != op2->in_opr2() && op2->in_opr2() == opr) {
  1113             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");
  1114             return shouldHaveRegister;
  1118     } else {
  1119       // FPU stack float instruction
  1120       switch (op->code()) {
  1121         case lir_add:
  1122         case lir_sub:
  1123         case lir_mul:
  1124         case lir_div:
  1126           assert(op->as_Op2() != NULL, "must be LIR_Op2");
  1127           LIR_Op2* op2 = (LIR_Op2*)op;
  1128           if (op2->in_opr1() != op2->in_opr2() && op2->in_opr2() == opr) {
  1129             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");
  1130             return shouldHaveRegister;
  1136   } else if (opr_type != T_LONG) {
  1137     // integer instruction (note: long operands must always be in register)
  1138     switch (op->code()) {
  1139       case lir_cmp:
  1140       case lir_add:
  1141       case lir_sub:
  1142       case lir_logic_and:
  1143       case lir_logic_or:
  1144       case lir_logic_xor:
  1146         assert(op->as_Op2() != NULL, "must be LIR_Op2");
  1147         LIR_Op2* op2 = (LIR_Op2*)op;
  1148         if (op2->in_opr1() != op2->in_opr2() && op2->in_opr2() == opr) {
  1149           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");
  1150           return shouldHaveRegister;
  1155 #endif // X86
  1157   // all other operands require a register
  1158   return mustHaveRegister;
  1162 void LinearScan::handle_method_arguments(LIR_Op* op) {
  1163   // special handling for method arguments (moves from stack to virtual register):
  1164   // the interval gets no register assigned, but the stack slot.
  1165   // it is split before the first use by the register allocator.
  1167   if (op->code() == lir_move) {
  1168     assert(op->as_Op1() != NULL, "must be LIR_Op1");
  1169     LIR_Op1* move = (LIR_Op1*)op;
  1171     if (move->in_opr()->is_stack()) {
  1172 #ifdef ASSERT
  1173       int arg_size = compilation()->method()->arg_size();
  1174       LIR_Opr o = move->in_opr();
  1175       if (o->is_single_stack()) {
  1176         assert(o->single_stack_ix() >= 0 && o->single_stack_ix() < arg_size, "out of range");
  1177       } else if (o->is_double_stack()) {
  1178         assert(o->double_stack_ix() >= 0 && o->double_stack_ix() < arg_size, "out of range");
  1179       } else {
  1180         ShouldNotReachHere();
  1183       assert(move->id() > 0, "invalid id");
  1184       assert(block_of_op_with_id(move->id())->number_of_preds() == 0, "move from stack must be in first block");
  1185       assert(move->result_opr()->is_virtual(), "result of move must be a virtual register");
  1187       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())));
  1188 #endif
  1190       Interval* interval = interval_at(reg_num(move->result_opr()));
  1192       int stack_slot = LinearScan::nof_regs + (move->in_opr()->is_single_stack() ? move->in_opr()->single_stack_ix() : move->in_opr()->double_stack_ix());
  1193       interval->set_canonical_spill_slot(stack_slot);
  1194       interval->assign_reg(stack_slot);
  1199 void LinearScan::handle_doubleword_moves(LIR_Op* op) {
  1200   // special handling for doubleword move from memory to register:
  1201   // in this case the registers of the input address and the result
  1202   // registers must not overlap -> add a temp range for the input registers
  1203   if (op->code() == lir_move) {
  1204     assert(op->as_Op1() != NULL, "must be LIR_Op1");
  1205     LIR_Op1* move = (LIR_Op1*)op;
  1207     if (move->result_opr()->is_double_cpu() && move->in_opr()->is_pointer()) {
  1208       LIR_Address* address = move->in_opr()->as_address_ptr();
  1209       if (address != NULL) {
  1210         if (address->base()->is_valid()) {
  1211           add_temp(address->base(), op->id(), noUse);
  1213         if (address->index()->is_valid()) {
  1214           add_temp(address->index(), op->id(), noUse);
  1221 void LinearScan::add_register_hints(LIR_Op* op) {
  1222   switch (op->code()) {
  1223     case lir_move:      // fall through
  1224     case lir_convert: {
  1225       assert(op->as_Op1() != NULL, "lir_move, lir_convert must be LIR_Op1");
  1226       LIR_Op1* move = (LIR_Op1*)op;
  1228       LIR_Opr move_from = move->in_opr();
  1229       LIR_Opr move_to = move->result_opr();
  1231       if (move_to->is_register() && move_from->is_register()) {
  1232         Interval* from = interval_at(reg_num(move_from));
  1233         Interval* to = interval_at(reg_num(move_to));
  1234         if (from != NULL && to != NULL) {
  1235           to->set_register_hint(from);
  1236           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()));
  1239       break;
  1241     case lir_cmove: {
  1242       assert(op->as_Op2() != NULL, "lir_cmove must be LIR_Op2");
  1243       LIR_Op2* cmove = (LIR_Op2*)op;
  1245       LIR_Opr move_from = cmove->in_opr1();
  1246       LIR_Opr move_to = cmove->result_opr();
  1248       if (move_to->is_register() && move_from->is_register()) {
  1249         Interval* from = interval_at(reg_num(move_from));
  1250         Interval* to = interval_at(reg_num(move_to));
  1251         if (from != NULL && to != NULL) {
  1252           to->set_register_hint(from);
  1253           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()));
  1256       break;
  1262 void LinearScan::build_intervals() {
  1263   TIME_LINEAR_SCAN(timer_build_intervals);
  1265   // initialize interval list with expected number of intervals
  1266   // (32 is added to have some space for split children without having to resize the list)
  1267   _intervals = IntervalList(num_virtual_regs() + 32);
  1268   // initialize all slots that are used by build_intervals
  1269   _intervals.at_put_grow(num_virtual_regs() - 1, NULL, NULL);
  1271   // create a list with all caller-save registers (cpu, fpu, xmm)
  1272   // when an instruction is a call, a temp range is created for all these registers
  1273   int num_caller_save_registers = 0;
  1274   int caller_save_registers[LinearScan::nof_regs];
  1276   int i;
  1277   for (i = 0; i < FrameMap::nof_caller_save_cpu_regs(); i++) {
  1278     LIR_Opr opr = FrameMap::caller_save_cpu_reg_at(i);
  1279     assert(opr->is_valid() && opr->is_register(), "FrameMap should not return invalid operands");
  1280     assert(reg_numHi(opr) == -1, "missing addition of range for hi-register");
  1281     caller_save_registers[num_caller_save_registers++] = reg_num(opr);
  1284   // temp ranges for fpu registers are only created when the method has
  1285   // virtual fpu operands. Otherwise no allocation for fpu registers is
  1286   // perfomed and so the temp ranges would be useless
  1287   if (has_fpu_registers()) {
  1288 #ifdef X86
  1289     if (UseSSE < 2) {
  1290 #endif
  1291       for (i = 0; i < FrameMap::nof_caller_save_fpu_regs; i++) {
  1292         LIR_Opr opr = FrameMap::caller_save_fpu_reg_at(i);
  1293         assert(opr->is_valid() && opr->is_register(), "FrameMap should not return invalid operands");
  1294         assert(reg_numHi(opr) == -1, "missing addition of range for hi-register");
  1295         caller_save_registers[num_caller_save_registers++] = reg_num(opr);
  1297 #ifdef X86
  1299     if (UseSSE > 0) {
  1300       for (i = 0; i < FrameMap::nof_caller_save_xmm_regs; i++) {
  1301         LIR_Opr opr = FrameMap::caller_save_xmm_reg_at(i);
  1302         assert(opr->is_valid() && opr->is_register(), "FrameMap should not return invalid operands");
  1303         assert(reg_numHi(opr) == -1, "missing addition of range for hi-register");
  1304         caller_save_registers[num_caller_save_registers++] = reg_num(opr);
  1307 #endif
  1309   assert(num_caller_save_registers <= LinearScan::nof_regs, "out of bounds");
  1312   LIR_OpVisitState visitor;
  1314   // iterate all blocks in reverse order
  1315   for (i = block_count() - 1; i >= 0; i--) {
  1316     BlockBegin* block = block_at(i);
  1317     LIR_OpList* instructions = block->lir()->instructions_list();
  1318     int         block_from =   block->first_lir_instruction_id();
  1319     int         block_to =     block->last_lir_instruction_id();
  1321     assert(block_from == instructions->at(0)->id(), "must be");
  1322     assert(block_to   == instructions->at(instructions->length() - 1)->id(), "must be");
  1324     // Update intervals for registers live at the end of this block;
  1325     BitMap live = block->live_out();
  1326     int size = (int)live.size();
  1327     for (int number = (int)live.get_next_one_offset(0, size); number < size; number = (int)live.get_next_one_offset(number + 1, size)) {
  1328       assert(live.at(number), "should not stop here otherwise");
  1329       assert(number >= LIR_OprDesc::vreg_base, "fixed intervals must not be live on block bounds");
  1330       TRACE_LINEAR_SCAN(2, tty->print_cr("live in %d to %d", number, block_to + 2));
  1332       add_use(number, block_from, block_to + 2, noUse, T_ILLEGAL);
  1334       // add special use positions for loop-end blocks when the
  1335       // interval is used anywhere inside this loop.  It's possible
  1336       // that the block was part of a non-natural loop, so it might
  1337       // have an invalid loop index.
  1338       if (block->is_set(BlockBegin::linear_scan_loop_end_flag) &&
  1339           block->loop_index() != -1 &&
  1340           is_interval_in_loop(number, block->loop_index())) {
  1341         interval_at(number)->add_use_pos(block_to + 1, loopEndMarker);
  1345     // iterate all instructions of the block in reverse order.
  1346     // skip the first instruction because it is always a label
  1347     // definitions of intervals are processed before uses
  1348     assert(visitor.no_operands(instructions->at(0)), "first operation must always be a label");
  1349     for (int j = instructions->length() - 1; j >= 1; j--) {
  1350       LIR_Op* op = instructions->at(j);
  1351       int op_id = op->id();
  1353       // visit operation to collect all operands
  1354       visitor.visit(op);
  1356       // add a temp range for each register if operation destroys caller-save registers
  1357       if (visitor.has_call()) {
  1358         for (int k = 0; k < num_caller_save_registers; k++) {
  1359           add_temp(caller_save_registers[k], op_id, noUse, T_ILLEGAL);
  1361         TRACE_LINEAR_SCAN(4, tty->print_cr("operation destroys all caller-save registers"));
  1364       // Add any platform dependent temps
  1365       pd_add_temps(op);
  1367       // visit definitions (output and temp operands)
  1368       int k, n;
  1369       n = visitor.opr_count(LIR_OpVisitState::outputMode);
  1370       for (k = 0; k < n; k++) {
  1371         LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::outputMode, k);
  1372         assert(opr->is_register(), "visitor should only return register operands");
  1373         add_def(opr, op_id, use_kind_of_output_operand(op, opr));
  1376       n = visitor.opr_count(LIR_OpVisitState::tempMode);
  1377       for (k = 0; k < n; k++) {
  1378         LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::tempMode, k);
  1379         assert(opr->is_register(), "visitor should only return register operands");
  1380         add_temp(opr, op_id, mustHaveRegister);
  1383       // visit uses (input operands)
  1384       n = visitor.opr_count(LIR_OpVisitState::inputMode);
  1385       for (k = 0; k < n; k++) {
  1386         LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::inputMode, k);
  1387         assert(opr->is_register(), "visitor should only return register operands");
  1388         add_use(opr, block_from, op_id, use_kind_of_input_operand(op, opr));
  1391       // Add uses of live locals from interpreter's point of view for proper
  1392       // debug information generation
  1393       // Treat these operands as temp values (if the life range is extended
  1394       // to a call site, the value would be in a register at the call otherwise)
  1395       n = visitor.info_count();
  1396       for (k = 0; k < n; k++) {
  1397         CodeEmitInfo* info = visitor.info_at(k);
  1398         ValueStack* stack = info->stack();
  1399         for_each_state_value(stack, value,
  1400           add_use(value, block_from, op_id + 1, noUse);
  1401         );
  1404       // special steps for some instructions (especially moves)
  1405       handle_method_arguments(op);
  1406       handle_doubleword_moves(op);
  1407       add_register_hints(op);
  1409     } // end of instruction iteration
  1410   } // end of block iteration
  1413   // add the range [0, 1[ to all fixed intervals
  1414   // -> the register allocator need not handle unhandled fixed intervals
  1415   for (int n = 0; n < LinearScan::nof_regs; n++) {
  1416     Interval* interval = interval_at(n);
  1417     if (interval != NULL) {
  1418       interval->add_range(0, 1);
  1424 // ********** Phase 5: actual register allocation
  1426 int LinearScan::interval_cmp(Interval** a, Interval** b) {
  1427   if (*a != NULL) {
  1428     if (*b != NULL) {
  1429       return (*a)->from() - (*b)->from();
  1430     } else {
  1431       return -1;
  1433   } else {
  1434     if (*b != NULL) {
  1435       return 1;
  1436     } else {
  1437       return 0;
  1442 #ifndef PRODUCT
  1443 bool LinearScan::is_sorted(IntervalArray* intervals) {
  1444   int from = -1;
  1445   int i, j;
  1446   for (i = 0; i < intervals->length(); i ++) {
  1447     Interval* it = intervals->at(i);
  1448     if (it != NULL) {
  1449       if (from > it->from()) {
  1450         assert(false, "");
  1451         return false;
  1453       from = it->from();
  1457   // check in both directions if sorted list and unsorted list contain same intervals
  1458   for (i = 0; i < interval_count(); i++) {
  1459     if (interval_at(i) != NULL) {
  1460       int num_found = 0;
  1461       for (j = 0; j < intervals->length(); j++) {
  1462         if (interval_at(i) == intervals->at(j)) {
  1463           num_found++;
  1466       assert(num_found == 1, "lists do not contain same intervals");
  1469   for (j = 0; j < intervals->length(); j++) {
  1470     int num_found = 0;
  1471     for (i = 0; i < interval_count(); i++) {
  1472       if (interval_at(i) == intervals->at(j)) {
  1473         num_found++;
  1476     assert(num_found == 1, "lists do not contain same intervals");
  1479   return true;
  1481 #endif
  1483 void LinearScan::add_to_list(Interval** first, Interval** prev, Interval* interval) {
  1484   if (*prev != NULL) {
  1485     (*prev)->set_next(interval);
  1486   } else {
  1487     *first = interval;
  1489   *prev = interval;
  1492 void LinearScan::create_unhandled_lists(Interval** list1, Interval** list2, bool (is_list1)(const Interval* i), bool (is_list2)(const Interval* i)) {
  1493   assert(is_sorted(_sorted_intervals), "interval list is not sorted");
  1495   *list1 = *list2 = Interval::end();
  1497   Interval* list1_prev = NULL;
  1498   Interval* list2_prev = NULL;
  1499   Interval* v;
  1501   const int n = _sorted_intervals->length();
  1502   for (int i = 0; i < n; i++) {
  1503     v = _sorted_intervals->at(i);
  1504     if (v == NULL) continue;
  1506     if (is_list1(v)) {
  1507       add_to_list(list1, &list1_prev, v);
  1508     } else if (is_list2 == NULL || is_list2(v)) {
  1509       add_to_list(list2, &list2_prev, v);
  1513   if (list1_prev != NULL) list1_prev->set_next(Interval::end());
  1514   if (list2_prev != NULL) list2_prev->set_next(Interval::end());
  1516   assert(list1_prev == NULL || list1_prev->next() == Interval::end(), "linear list ends not with sentinel");
  1517   assert(list2_prev == NULL || list2_prev->next() == Interval::end(), "linear list ends not with sentinel");
  1521 void LinearScan::sort_intervals_before_allocation() {
  1522   TIME_LINEAR_SCAN(timer_sort_intervals_before);
  1524   if (_needs_full_resort) {
  1525     // There is no known reason why this should occur but just in case...
  1526     assert(false, "should never occur");
  1527     // Re-sort existing interval list because an Interval::from() has changed
  1528     _sorted_intervals->sort(interval_cmp);
  1529     _needs_full_resort = false;
  1532   IntervalList* unsorted_list = &_intervals;
  1533   int unsorted_len = unsorted_list->length();
  1534   int sorted_len = 0;
  1535   int unsorted_idx;
  1536   int sorted_idx = 0;
  1537   int sorted_from_max = -1;
  1539   // calc number of items for sorted list (sorted list must not contain NULL values)
  1540   for (unsorted_idx = 0; unsorted_idx < unsorted_len; unsorted_idx++) {
  1541     if (unsorted_list->at(unsorted_idx) != NULL) {
  1542       sorted_len++;
  1545   IntervalArray* sorted_list = new IntervalArray(sorted_len);
  1547   // special sorting algorithm: the original interval-list is almost sorted,
  1548   // only some intervals are swapped. So this is much faster than a complete QuickSort
  1549   for (unsorted_idx = 0; unsorted_idx < unsorted_len; unsorted_idx++) {
  1550     Interval* cur_interval = unsorted_list->at(unsorted_idx);
  1552     if (cur_interval != NULL) {
  1553       int cur_from = cur_interval->from();
  1555       if (sorted_from_max <= cur_from) {
  1556         sorted_list->at_put(sorted_idx++, cur_interval);
  1557         sorted_from_max = cur_interval->from();
  1558       } else {
  1559         // the asumption that the intervals are already sorted failed,
  1560         // so this interval must be sorted in manually
  1561         int j;
  1562         for (j = sorted_idx - 1; j >= 0 && cur_from < sorted_list->at(j)->from(); j--) {
  1563           sorted_list->at_put(j + 1, sorted_list->at(j));
  1565         sorted_list->at_put(j + 1, cur_interval);
  1566         sorted_idx++;
  1570   _sorted_intervals = sorted_list;
  1571   assert(is_sorted(_sorted_intervals), "intervals unsorted");
  1574 void LinearScan::sort_intervals_after_allocation() {
  1575   TIME_LINEAR_SCAN(timer_sort_intervals_after);
  1577   if (_needs_full_resort) {
  1578     // Re-sort existing interval list because an Interval::from() has changed
  1579     _sorted_intervals->sort(interval_cmp);
  1580     _needs_full_resort = false;
  1583   IntervalArray* old_list      = _sorted_intervals;
  1584   IntervalList*  new_list      = _new_intervals_from_allocation;
  1585   int old_len = old_list->length();
  1586   int new_len = new_list->length();
  1588   if (new_len == 0) {
  1589     // no intervals have been added during allocation, so sorted list is already up to date
  1590     assert(is_sorted(_sorted_intervals), "intervals unsorted");
  1591     return;
  1594   // conventional sort-algorithm for new intervals
  1595   new_list->sort(interval_cmp);
  1597   // merge old and new list (both already sorted) into one combined list
  1598   IntervalArray* combined_list = new IntervalArray(old_len + new_len);
  1599   int old_idx = 0;
  1600   int new_idx = 0;
  1602   while (old_idx + new_idx < old_len + new_len) {
  1603     if (new_idx >= new_len || (old_idx < old_len && old_list->at(old_idx)->from() <= new_list->at(new_idx)->from())) {
  1604       combined_list->at_put(old_idx + new_idx, old_list->at(old_idx));
  1605       old_idx++;
  1606     } else {
  1607       combined_list->at_put(old_idx + new_idx, new_list->at(new_idx));
  1608       new_idx++;
  1612   _sorted_intervals = combined_list;
  1613   assert(is_sorted(_sorted_intervals), "intervals unsorted");
  1617 void LinearScan::allocate_registers() {
  1618   TIME_LINEAR_SCAN(timer_allocate_registers);
  1620   Interval* precolored_cpu_intervals, *not_precolored_cpu_intervals;
  1621   Interval* precolored_fpu_intervals, *not_precolored_fpu_intervals;
  1623   create_unhandled_lists(&precolored_cpu_intervals, &not_precolored_cpu_intervals, is_precolored_cpu_interval, is_virtual_cpu_interval);
  1624   if (has_fpu_registers()) {
  1625     create_unhandled_lists(&precolored_fpu_intervals, &not_precolored_fpu_intervals, is_precolored_fpu_interval, is_virtual_fpu_interval);
  1626 #ifdef ASSERT
  1627   } else {
  1628     // fpu register allocation is omitted because no virtual fpu registers are present
  1629     // just check this again...
  1630     create_unhandled_lists(&precolored_fpu_intervals, &not_precolored_fpu_intervals, is_precolored_fpu_interval, is_virtual_fpu_interval);
  1631     assert(not_precolored_fpu_intervals == Interval::end(), "missed an uncolored fpu interval");
  1632 #endif
  1635   // allocate cpu registers
  1636   LinearScanWalker cpu_lsw(this, precolored_cpu_intervals, not_precolored_cpu_intervals);
  1637   cpu_lsw.walk();
  1638   cpu_lsw.finish_allocation();
  1640   if (has_fpu_registers()) {
  1641     // allocate fpu registers
  1642     LinearScanWalker fpu_lsw(this, precolored_fpu_intervals, not_precolored_fpu_intervals);
  1643     fpu_lsw.walk();
  1644     fpu_lsw.finish_allocation();
  1649 // ********** Phase 6: resolve data flow
  1650 // (insert moves at edges between blocks if intervals have been split)
  1652 // wrapper for Interval::split_child_at_op_id that performs a bailout in product mode
  1653 // instead of returning NULL
  1654 Interval* LinearScan::split_child_at_op_id(Interval* interval, int op_id, LIR_OpVisitState::OprMode mode) {
  1655   Interval* result = interval->split_child_at_op_id(op_id, mode);
  1656   if (result != NULL) {
  1657     return result;
  1660   assert(false, "must find an interval, but do a clean bailout in product mode");
  1661   result = new Interval(LIR_OprDesc::vreg_base);
  1662   result->assign_reg(0);
  1663   result->set_type(T_INT);
  1664   BAILOUT_("LinearScan: interval is NULL", result);
  1668 Interval* LinearScan::interval_at_block_begin(BlockBegin* block, int reg_num) {
  1669   assert(LinearScan::nof_regs <= reg_num && reg_num < num_virtual_regs(), "register number out of bounds");
  1670   assert(interval_at(reg_num) != NULL, "no interval found");
  1672   return split_child_at_op_id(interval_at(reg_num), block->first_lir_instruction_id(), LIR_OpVisitState::outputMode);
  1675 Interval* LinearScan::interval_at_block_end(BlockBegin* block, int reg_num) {
  1676   assert(LinearScan::nof_regs <= reg_num && reg_num < num_virtual_regs(), "register number out of bounds");
  1677   assert(interval_at(reg_num) != NULL, "no interval found");
  1679   return split_child_at_op_id(interval_at(reg_num), block->last_lir_instruction_id() + 1, LIR_OpVisitState::outputMode);
  1682 Interval* LinearScan::interval_at_op_id(int reg_num, int op_id) {
  1683   assert(LinearScan::nof_regs <= reg_num && reg_num < num_virtual_regs(), "register number out of bounds");
  1684   assert(interval_at(reg_num) != NULL, "no interval found");
  1686   return split_child_at_op_id(interval_at(reg_num), op_id, LIR_OpVisitState::inputMode);
  1690 void LinearScan::resolve_collect_mappings(BlockBegin* from_block, BlockBegin* to_block, MoveResolver &move_resolver) {
  1691   DEBUG_ONLY(move_resolver.check_empty());
  1693   const int num_regs = num_virtual_regs();
  1694   const int size = live_set_size();
  1695   const BitMap live_at_edge = to_block->live_in();
  1697   // visit all registers where the live_at_edge bit is set
  1698   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)) {
  1699     assert(r < num_regs, "live information set for not exisiting interval");
  1700     assert(from_block->live_out().at(r) && to_block->live_in().at(r), "interval not live at this edge");
  1702     Interval* from_interval = interval_at_block_end(from_block, r);
  1703     Interval* to_interval = interval_at_block_begin(to_block, r);
  1705     if (from_interval != to_interval && (from_interval->assigned_reg() != to_interval->assigned_reg() || from_interval->assigned_regHi() != to_interval->assigned_regHi())) {
  1706       // need to insert move instruction
  1707       move_resolver.add_mapping(from_interval, to_interval);
  1713 void LinearScan::resolve_find_insert_pos(BlockBegin* from_block, BlockBegin* to_block, MoveResolver &move_resolver) {
  1714   if (from_block->number_of_sux() <= 1) {
  1715     TRACE_LINEAR_SCAN(4, tty->print_cr("inserting moves at end of from_block B%d", from_block->block_id()));
  1717     LIR_OpList* instructions = from_block->lir()->instructions_list();
  1718     LIR_OpBranch* branch = instructions->last()->as_OpBranch();
  1719     if (branch != NULL) {
  1720       // insert moves before branch
  1721       assert(branch->cond() == lir_cond_always, "block does not end with an unconditional jump");
  1722       move_resolver.set_insert_position(from_block->lir(), instructions->length() - 2);
  1723     } else {
  1724       move_resolver.set_insert_position(from_block->lir(), instructions->length() - 1);
  1727   } else {
  1728     TRACE_LINEAR_SCAN(4, tty->print_cr("inserting moves at beginning of to_block B%d", to_block->block_id()));
  1729 #ifdef ASSERT
  1730     assert(from_block->lir()->instructions_list()->at(0)->as_OpLabel() != NULL, "block does not start with a label");
  1732     // because the number of predecessor edges matches the number of
  1733     // successor edges, blocks which are reached by switch statements
  1734     // may have be more than one predecessor but it will be guaranteed
  1735     // that all predecessors will be the same.
  1736     for (int i = 0; i < to_block->number_of_preds(); i++) {
  1737       assert(from_block == to_block->pred_at(i), "all critical edges must be broken");
  1739 #endif
  1741     move_resolver.set_insert_position(to_block->lir(), 0);
  1746 // insert necessary moves (spilling or reloading) at edges between blocks if interval has been split
  1747 void LinearScan::resolve_data_flow() {
  1748   TIME_LINEAR_SCAN(timer_resolve_data_flow);
  1750   int num_blocks = block_count();
  1751   MoveResolver move_resolver(this);
  1752   BitMap block_completed(num_blocks);  block_completed.clear();
  1753   BitMap already_resolved(num_blocks); already_resolved.clear();
  1755   int i;
  1756   for (i = 0; i < num_blocks; i++) {
  1757     BlockBegin* block = block_at(i);
  1759     // check if block has only one predecessor and only one successor
  1760     if (block->number_of_preds() == 1 && block->number_of_sux() == 1 && block->number_of_exception_handlers() == 0) {
  1761       LIR_OpList* instructions = block->lir()->instructions_list();
  1762       assert(instructions->at(0)->code() == lir_label, "block must start with label");
  1763       assert(instructions->last()->code() == lir_branch, "block with successors must end with branch");
  1764       assert(instructions->last()->as_OpBranch()->cond() == lir_cond_always, "block with successor must end with unconditional branch");
  1766       // check if block is empty (only label and branch)
  1767       if (instructions->length() == 2) {
  1768         BlockBegin* pred = block->pred_at(0);
  1769         BlockBegin* sux = block->sux_at(0);
  1771         // prevent optimization of two consecutive blocks
  1772         if (!block_completed.at(pred->linear_scan_number()) && !block_completed.at(sux->linear_scan_number())) {
  1773           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()));
  1774           block_completed.set_bit(block->linear_scan_number());
  1776           // directly resolve between pred and sux (without looking at the empty block between)
  1777           resolve_collect_mappings(pred, sux, move_resolver);
  1778           if (move_resolver.has_mappings()) {
  1779             move_resolver.set_insert_position(block->lir(), 0);
  1780             move_resolver.resolve_and_append_moves();
  1788   for (i = 0; i < num_blocks; i++) {
  1789     if (!block_completed.at(i)) {
  1790       BlockBegin* from_block = block_at(i);
  1791       already_resolved.set_from(block_completed);
  1793       int num_sux = from_block->number_of_sux();
  1794       for (int s = 0; s < num_sux; s++) {
  1795         BlockBegin* to_block = from_block->sux_at(s);
  1797         // check for duplicate edges between the same blocks (can happen with switch blocks)
  1798         if (!already_resolved.at(to_block->linear_scan_number())) {
  1799           TRACE_LINEAR_SCAN(3, tty->print_cr("**** processing edge between B%d and B%d", from_block->block_id(), to_block->block_id()));
  1800           already_resolved.set_bit(to_block->linear_scan_number());
  1802           // collect all intervals that have been split between from_block and to_block
  1803           resolve_collect_mappings(from_block, to_block, move_resolver);
  1804           if (move_resolver.has_mappings()) {
  1805             resolve_find_insert_pos(from_block, to_block, move_resolver);
  1806             move_resolver.resolve_and_append_moves();
  1815 void LinearScan::resolve_exception_entry(BlockBegin* block, int reg_num, MoveResolver &move_resolver) {
  1816   if (interval_at(reg_num) == NULL) {
  1817     // if a phi function is never used, no interval is created -> ignore this
  1818     return;
  1821   Interval* interval = interval_at_block_begin(block, reg_num);
  1822   int reg = interval->assigned_reg();
  1823   int regHi = interval->assigned_regHi();
  1825   if ((reg < nof_regs && interval->always_in_memory()) ||
  1826       (use_fpu_stack_allocation() && reg >= pd_first_fpu_reg && reg <= pd_last_fpu_reg)) {
  1827     // the interval is split to get a short range that is located on the stack
  1828     // in the following two cases:
  1829     // * the interval started in memory (e.g. method parameter), but is currently in a register
  1830     //   this is an optimization for exception handling that reduces the number of moves that
  1831     //   are necessary for resolving the states when an exception uses this exception handler
  1832     // * the interval would be on the fpu stack at the begin of the exception handler
  1833     //   this is not allowed because of the complicated fpu stack handling on Intel
  1835     // range that will be spilled to memory
  1836     int from_op_id = block->first_lir_instruction_id();
  1837     int to_op_id = from_op_id + 1;  // short live range of length 1
  1838     assert(interval->from() <= from_op_id && interval->to() >= to_op_id,
  1839            "no split allowed between exception entry and first instruction");
  1841     if (interval->from() != from_op_id) {
  1842       // the part before from_op_id is unchanged
  1843       interval = interval->split(from_op_id);
  1844       interval->assign_reg(reg, regHi);
  1845       append_interval(interval);
  1846     } else {
  1847       _needs_full_resort = true;
  1849     assert(interval->from() == from_op_id, "must be true now");
  1851     Interval* spilled_part = interval;
  1852     if (interval->to() != to_op_id) {
  1853       // the part after to_op_id is unchanged
  1854       spilled_part = interval->split_from_start(to_op_id);
  1855       append_interval(spilled_part);
  1856       move_resolver.add_mapping(spilled_part, interval);
  1858     assign_spill_slot(spilled_part);
  1860     assert(spilled_part->from() == from_op_id && spilled_part->to() == to_op_id, "just checking");
  1864 void LinearScan::resolve_exception_entry(BlockBegin* block, MoveResolver &move_resolver) {
  1865   assert(block->is_set(BlockBegin::exception_entry_flag), "should not call otherwise");
  1866   DEBUG_ONLY(move_resolver.check_empty());
  1868   // visit all registers where the live_in bit is set
  1869   int size = live_set_size();
  1870   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)) {
  1871     resolve_exception_entry(block, r, move_resolver);
  1874   // the live_in bits are not set for phi functions of the xhandler entry, so iterate them separately
  1875   for_each_phi_fun(block, phi,
  1876     resolve_exception_entry(block, phi->operand()->vreg_number(), move_resolver)
  1877   );
  1879   if (move_resolver.has_mappings()) {
  1880     // insert moves after first instruction
  1881     move_resolver.set_insert_position(block->lir(), 1);
  1882     move_resolver.resolve_and_append_moves();
  1887 void LinearScan::resolve_exception_edge(XHandler* handler, int throwing_op_id, int reg_num, Phi* phi, MoveResolver &move_resolver) {
  1888   if (interval_at(reg_num) == NULL) {
  1889     // if a phi function is never used, no interval is created -> ignore this
  1890     return;
  1893   // the computation of to_interval is equal to resolve_collect_mappings,
  1894   // but from_interval is more complicated because of phi functions
  1895   BlockBegin* to_block = handler->entry_block();
  1896   Interval* to_interval = interval_at_block_begin(to_block, reg_num);
  1898   if (phi != NULL) {
  1899     // phi function of the exception entry block
  1900     // no moves are created for this phi function in the LIR_Generator, so the
  1901     // interval at the throwing instruction must be searched using the operands
  1902     // of the phi function
  1903     Value from_value = phi->operand_at(handler->phi_operand());
  1905     // with phi functions it can happen that the same from_value is used in
  1906     // multiple mappings, so notify move-resolver that this is allowed
  1907     move_resolver.set_multiple_reads_allowed();
  1909     Constant* con = from_value->as_Constant();
  1910     if (con != NULL && !con->is_pinned()) {
  1911       // unpinned constants may have no register, so add mapping from constant to interval
  1912       move_resolver.add_mapping(LIR_OprFact::value_type(con->type()), to_interval);
  1913     } else {
  1914       // search split child at the throwing op_id
  1915       Interval* from_interval = interval_at_op_id(from_value->operand()->vreg_number(), throwing_op_id);
  1916       move_resolver.add_mapping(from_interval, to_interval);
  1919   } else {
  1920     // no phi function, so use reg_num also for from_interval
  1921     // search split child at the throwing op_id
  1922     Interval* from_interval = interval_at_op_id(reg_num, throwing_op_id);
  1923     if (from_interval != to_interval) {
  1924       // optimization to reduce number of moves: when to_interval is on stack and
  1925       // the stack slot is known to be always correct, then no move is necessary
  1926       if (!from_interval->always_in_memory() || from_interval->canonical_spill_slot() != to_interval->assigned_reg()) {
  1927         move_resolver.add_mapping(from_interval, to_interval);
  1933 void LinearScan::resolve_exception_edge(XHandler* handler, int throwing_op_id, MoveResolver &move_resolver) {
  1934   TRACE_LINEAR_SCAN(4, tty->print_cr("resolving exception handler B%d: throwing_op_id=%d", handler->entry_block()->block_id(), throwing_op_id));
  1936   DEBUG_ONLY(move_resolver.check_empty());
  1937   assert(handler->lir_op_id() == -1, "already processed this xhandler");
  1938   DEBUG_ONLY(handler->set_lir_op_id(throwing_op_id));
  1939   assert(handler->entry_code() == NULL, "code already present");
  1941   // visit all registers where the live_in bit is set
  1942   BlockBegin* block = handler->entry_block();
  1943   int size = live_set_size();
  1944   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)) {
  1945     resolve_exception_edge(handler, throwing_op_id, r, NULL, move_resolver);
  1948   // the live_in bits are not set for phi functions of the xhandler entry, so iterate them separately
  1949   for_each_phi_fun(block, phi,
  1950     resolve_exception_edge(handler, throwing_op_id, phi->operand()->vreg_number(), phi, move_resolver)
  1951   );
  1953   if (move_resolver.has_mappings()) {
  1954     LIR_List* entry_code = new LIR_List(compilation());
  1955     move_resolver.set_insert_position(entry_code, 0);
  1956     move_resolver.resolve_and_append_moves();
  1958     entry_code->jump(handler->entry_block());
  1959     handler->set_entry_code(entry_code);
  1964 void LinearScan::resolve_exception_handlers() {
  1965   MoveResolver move_resolver(this);
  1966   LIR_OpVisitState visitor;
  1967   int num_blocks = block_count();
  1969   int i;
  1970   for (i = 0; i < num_blocks; i++) {
  1971     BlockBegin* block = block_at(i);
  1972     if (block->is_set(BlockBegin::exception_entry_flag)) {
  1973       resolve_exception_entry(block, move_resolver);
  1977   for (i = 0; i < num_blocks; i++) {
  1978     BlockBegin* block = block_at(i);
  1979     LIR_List* ops = block->lir();
  1980     int num_ops = ops->length();
  1982     // iterate all instructions of the block. skip the first because it is always a label
  1983     assert(visitor.no_operands(ops->at(0)), "first operation must always be a label");
  1984     for (int j = 1; j < num_ops; j++) {
  1985       LIR_Op* op = ops->at(j);
  1986       int op_id = op->id();
  1988       if (op_id != -1 && has_info(op_id)) {
  1989         // visit operation to collect all operands
  1990         visitor.visit(op);
  1991         assert(visitor.info_count() > 0, "should not visit otherwise");
  1993         XHandlers* xhandlers = visitor.all_xhandler();
  1994         int n = xhandlers->length();
  1995         for (int k = 0; k < n; k++) {
  1996           resolve_exception_edge(xhandlers->handler_at(k), op_id, move_resolver);
  1999 #ifdef ASSERT
  2000       } else {
  2001         visitor.visit(op);
  2002         assert(visitor.all_xhandler()->length() == 0, "missed exception handler");
  2003 #endif
  2010 // ********** Phase 7: assign register numbers back to LIR
  2011 // (includes computation of debug information and oop maps)
  2013 VMReg LinearScan::vm_reg_for_interval(Interval* interval) {
  2014   VMReg reg = interval->cached_vm_reg();
  2015   if (!reg->is_valid() ) {
  2016     reg = vm_reg_for_operand(operand_for_interval(interval));
  2017     interval->set_cached_vm_reg(reg);
  2019   assert(reg == vm_reg_for_operand(operand_for_interval(interval)), "wrong cached value");
  2020   return reg;
  2023 VMReg LinearScan::vm_reg_for_operand(LIR_Opr opr) {
  2024   assert(opr->is_oop(), "currently only implemented for oop operands");
  2025   return frame_map()->regname(opr);
  2029 LIR_Opr LinearScan::operand_for_interval(Interval* interval) {
  2030   LIR_Opr opr = interval->cached_opr();
  2031   if (opr->is_illegal()) {
  2032     opr = calc_operand_for_interval(interval);
  2033     interval->set_cached_opr(opr);
  2036   assert(opr == calc_operand_for_interval(interval), "wrong cached value");
  2037   return opr;
  2040 LIR_Opr LinearScan::calc_operand_for_interval(const Interval* interval) {
  2041   int assigned_reg = interval->assigned_reg();
  2042   BasicType type = interval->type();
  2044   if (assigned_reg >= nof_regs) {
  2045     // stack slot
  2046     assert(interval->assigned_regHi() == any_reg, "must not have hi register");
  2047     return LIR_OprFact::stack(assigned_reg - nof_regs, type);
  2049   } else {
  2050     // register
  2051     switch (type) {
  2052       case T_OBJECT: {
  2053         assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");
  2054         assert(interval->assigned_regHi() == any_reg, "must not have hi register");
  2055         return LIR_OprFact::single_cpu_oop(assigned_reg);
  2058       case T_ADDRESS: {
  2059         assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");
  2060         assert(interval->assigned_regHi() == any_reg, "must not have hi register");
  2061         return LIR_OprFact::single_cpu_address(assigned_reg);
  2064 #ifdef __SOFTFP__
  2065       case T_FLOAT:  // fall through
  2066 #endif // __SOFTFP__
  2067       case T_INT: {
  2068         assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");
  2069         assert(interval->assigned_regHi() == any_reg, "must not have hi register");
  2070         return LIR_OprFact::single_cpu(assigned_reg);
  2073 #ifdef __SOFTFP__
  2074       case T_DOUBLE:  // fall through
  2075 #endif // __SOFTFP__
  2076       case T_LONG: {
  2077         int assigned_regHi = interval->assigned_regHi();
  2078         assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");
  2079         assert(num_physical_regs(T_LONG) == 1 ||
  2080                (assigned_regHi >= pd_first_cpu_reg && assigned_regHi <= pd_last_cpu_reg), "no cpu register");
  2082         assert(assigned_reg != assigned_regHi, "invalid allocation");
  2083         assert(num_physical_regs(T_LONG) == 1 || assigned_reg < assigned_regHi,
  2084                "register numbers must be sorted (ensure that e.g. a move from eax,ebx to ebx,eax can not occur)");
  2085         assert((assigned_regHi != any_reg) ^ (num_physical_regs(T_LONG) == 1), "must be match");
  2086         if (requires_adjacent_regs(T_LONG)) {
  2087           assert(assigned_reg % 2 == 0 && assigned_reg + 1 == assigned_regHi, "must be sequential and even");
  2090 #ifdef _LP64
  2091         return LIR_OprFact::double_cpu(assigned_reg, assigned_reg);
  2092 #else
  2093 #if defined(SPARC) || defined(PPC)
  2094         return LIR_OprFact::double_cpu(assigned_regHi, assigned_reg);
  2095 #else
  2096         return LIR_OprFact::double_cpu(assigned_reg, assigned_regHi);
  2097 #endif // SPARC
  2098 #endif // LP64
  2101 #ifndef __SOFTFP__
  2102       case T_FLOAT: {
  2103 #ifdef X86
  2104         if (UseSSE >= 1) {
  2105           assert(assigned_reg >= pd_first_xmm_reg && assigned_reg <= pd_last_xmm_reg, "no xmm register");
  2106           assert(interval->assigned_regHi() == any_reg, "must not have hi register");
  2107           return LIR_OprFact::single_xmm(assigned_reg - pd_first_xmm_reg);
  2109 #endif
  2111         assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");
  2112         assert(interval->assigned_regHi() == any_reg, "must not have hi register");
  2113         return LIR_OprFact::single_fpu(assigned_reg - pd_first_fpu_reg);
  2116       case T_DOUBLE: {
  2117 #ifdef X86
  2118         if (UseSSE >= 2) {
  2119           assert(assigned_reg >= pd_first_xmm_reg && assigned_reg <= pd_last_xmm_reg, "no xmm register");
  2120           assert(interval->assigned_regHi() == any_reg, "must not have hi register (double xmm values are stored in one register)");
  2121           return LIR_OprFact::double_xmm(assigned_reg - pd_first_xmm_reg);
  2123 #endif
  2125 #ifdef SPARC
  2126         assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");
  2127         assert(interval->assigned_regHi() >= pd_first_fpu_reg && interval->assigned_regHi() <= pd_last_fpu_reg, "no fpu register");
  2128         assert(assigned_reg % 2 == 0 && assigned_reg + 1 == interval->assigned_regHi(), "must be sequential and even");
  2129         LIR_Opr result = LIR_OprFact::double_fpu(interval->assigned_regHi() - pd_first_fpu_reg, assigned_reg - pd_first_fpu_reg);
  2130 #elif defined(ARM)
  2131         assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");
  2132         assert(interval->assigned_regHi() >= pd_first_fpu_reg && interval->assigned_regHi() <= pd_last_fpu_reg, "no fpu register");
  2133         assert(assigned_reg % 2 == 0 && assigned_reg + 1 == interval->assigned_regHi(), "must be sequential and even");
  2134         LIR_Opr result = LIR_OprFact::double_fpu(assigned_reg - pd_first_fpu_reg, interval->assigned_regHi() - pd_first_fpu_reg);
  2135 #else
  2136         assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");
  2137         assert(interval->assigned_regHi() == any_reg, "must not have hi register (double fpu values are stored in one register on Intel)");
  2138         LIR_Opr result = LIR_OprFact::double_fpu(assigned_reg - pd_first_fpu_reg);
  2139 #endif
  2140         return result;
  2142 #endif // __SOFTFP__
  2144       default: {
  2145         ShouldNotReachHere();
  2146         return LIR_OprFact::illegalOpr;
  2152 LIR_Opr LinearScan::canonical_spill_opr(Interval* interval) {
  2153   assert(interval->canonical_spill_slot() >= nof_regs, "canonical spill slot not set");
  2154   return LIR_OprFact::stack(interval->canonical_spill_slot() - nof_regs, interval->type());
  2157 LIR_Opr LinearScan::color_lir_opr(LIR_Opr opr, int op_id, LIR_OpVisitState::OprMode mode) {
  2158   assert(opr->is_virtual(), "should not call this otherwise");
  2160   Interval* interval = interval_at(opr->vreg_number());
  2161   assert(interval != NULL, "interval must exist");
  2163   if (op_id != -1) {
  2164 #ifdef ASSERT
  2165     BlockBegin* block = block_of_op_with_id(op_id);
  2166     if (block->number_of_sux() <= 1 && op_id == block->last_lir_instruction_id()) {
  2167       // check if spill moves could have been appended at the end of this block, but
  2168       // before the branch instruction. So the split child information for this branch would
  2169       // be incorrect.
  2170       LIR_OpBranch* branch = block->lir()->instructions_list()->last()->as_OpBranch();
  2171       if (branch != NULL) {
  2172         if (block->live_out().at(opr->vreg_number())) {
  2173           assert(branch->cond() == lir_cond_always, "block does not end with an unconditional jump");
  2174           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)");
  2178 #endif
  2180     // operands are not changed when an interval is split during allocation,
  2181     // so search the right interval here
  2182     interval = split_child_at_op_id(interval, op_id, mode);
  2185   LIR_Opr res = operand_for_interval(interval);
  2187 #ifdef X86
  2188   // new semantic for is_last_use: not only set on definite end of interval,
  2189   // but also before hole
  2190   // This may still miss some cases (e.g. for dead values), but it is not necessary that the
  2191   // last use information is completely correct
  2192   // information is only needed for fpu stack allocation
  2193   if (res->is_fpu_register()) {
  2194     if (opr->is_last_use() || op_id == interval->to() || (op_id != -1 && interval->has_hole_between(op_id, op_id + 1))) {
  2195       assert(op_id == -1 || !is_block_begin(op_id), "holes at begin of block may also result from control flow");
  2196       res = res->make_last_use();
  2199 #endif
  2201   assert(!gen()->is_vreg_flag_set(opr->vreg_number(), LIRGenerator::callee_saved) || !FrameMap::is_caller_save_register(res), "bad allocation");
  2203   return res;
  2207 #ifdef ASSERT
  2208 // some methods used to check correctness of debug information
  2210 void assert_no_register_values(GrowableArray<ScopeValue*>* values) {
  2211   if (values == NULL) {
  2212     return;
  2215   for (int i = 0; i < values->length(); i++) {
  2216     ScopeValue* value = values->at(i);
  2218     if (value->is_location()) {
  2219       Location location = ((LocationValue*)value)->location();
  2220       assert(location.where() == Location::on_stack, "value is in register");
  2225 void assert_no_register_values(GrowableArray<MonitorValue*>* values) {
  2226   if (values == NULL) {
  2227     return;
  2230   for (int i = 0; i < values->length(); i++) {
  2231     MonitorValue* value = values->at(i);
  2233     if (value->owner()->is_location()) {
  2234       Location location = ((LocationValue*)value->owner())->location();
  2235       assert(location.where() == Location::on_stack, "owner is in register");
  2237     assert(value->basic_lock().where() == Location::on_stack, "basic_lock is in register");
  2241 void assert_equal(Location l1, Location l2) {
  2242   assert(l1.where() == l2.where() && l1.type() == l2.type() && l1.offset() == l2.offset(), "");
  2245 void assert_equal(ScopeValue* v1, ScopeValue* v2) {
  2246   if (v1->is_location()) {
  2247     assert(v2->is_location(), "");
  2248     assert_equal(((LocationValue*)v1)->location(), ((LocationValue*)v2)->location());
  2249   } else if (v1->is_constant_int()) {
  2250     assert(v2->is_constant_int(), "");
  2251     assert(((ConstantIntValue*)v1)->value() == ((ConstantIntValue*)v2)->value(), "");
  2252   } else if (v1->is_constant_double()) {
  2253     assert(v2->is_constant_double(), "");
  2254     assert(((ConstantDoubleValue*)v1)->value() == ((ConstantDoubleValue*)v2)->value(), "");
  2255   } else if (v1->is_constant_long()) {
  2256     assert(v2->is_constant_long(), "");
  2257     assert(((ConstantLongValue*)v1)->value() == ((ConstantLongValue*)v2)->value(), "");
  2258   } else if (v1->is_constant_oop()) {
  2259     assert(v2->is_constant_oop(), "");
  2260     assert(((ConstantOopWriteValue*)v1)->value() == ((ConstantOopWriteValue*)v2)->value(), "");
  2261   } else {
  2262     ShouldNotReachHere();
  2266 void assert_equal(MonitorValue* m1, MonitorValue* m2) {
  2267   assert_equal(m1->owner(), m2->owner());
  2268   assert_equal(m1->basic_lock(), m2->basic_lock());
  2271 void assert_equal(IRScopeDebugInfo* d1, IRScopeDebugInfo* d2) {
  2272   assert(d1->scope() == d2->scope(), "not equal");
  2273   assert(d1->bci() == d2->bci(), "not equal");
  2275   if (d1->locals() != NULL) {
  2276     assert(d1->locals() != NULL && d2->locals() != NULL, "not equal");
  2277     assert(d1->locals()->length() == d2->locals()->length(), "not equal");
  2278     for (int i = 0; i < d1->locals()->length(); i++) {
  2279       assert_equal(d1->locals()->at(i), d2->locals()->at(i));
  2281   } else {
  2282     assert(d1->locals() == NULL && d2->locals() == NULL, "not equal");
  2285   if (d1->expressions() != NULL) {
  2286     assert(d1->expressions() != NULL && d2->expressions() != NULL, "not equal");
  2287     assert(d1->expressions()->length() == d2->expressions()->length(), "not equal");
  2288     for (int i = 0; i < d1->expressions()->length(); i++) {
  2289       assert_equal(d1->expressions()->at(i), d2->expressions()->at(i));
  2291   } else {
  2292     assert(d1->expressions() == NULL && d2->expressions() == NULL, "not equal");
  2295   if (d1->monitors() != NULL) {
  2296     assert(d1->monitors() != NULL && d2->monitors() != NULL, "not equal");
  2297     assert(d1->monitors()->length() == d2->monitors()->length(), "not equal");
  2298     for (int i = 0; i < d1->monitors()->length(); i++) {
  2299       assert_equal(d1->monitors()->at(i), d2->monitors()->at(i));
  2301   } else {
  2302     assert(d1->monitors() == NULL && d2->monitors() == NULL, "not equal");
  2305   if (d1->caller() != NULL) {
  2306     assert(d1->caller() != NULL && d2->caller() != NULL, "not equal");
  2307     assert_equal(d1->caller(), d2->caller());
  2308   } else {
  2309     assert(d1->caller() == NULL && d2->caller() == NULL, "not equal");
  2313 void check_stack_depth(CodeEmitInfo* info, int stack_end) {
  2314   if (info->stack()->bci() != SynchronizationEntryBCI && !info->scope()->method()->is_native()) {
  2315     Bytecodes::Code code = info->scope()->method()->java_code_at_bci(info->stack()->bci());
  2316     switch (code) {
  2317       case Bytecodes::_ifnull    : // fall through
  2318       case Bytecodes::_ifnonnull : // fall through
  2319       case Bytecodes::_ifeq      : // fall through
  2320       case Bytecodes::_ifne      : // fall through
  2321       case Bytecodes::_iflt      : // fall through
  2322       case Bytecodes::_ifge      : // fall through
  2323       case Bytecodes::_ifgt      : // fall through
  2324       case Bytecodes::_ifle      : // fall through
  2325       case Bytecodes::_if_icmpeq : // fall through
  2326       case Bytecodes::_if_icmpne : // fall through
  2327       case Bytecodes::_if_icmplt : // fall through
  2328       case Bytecodes::_if_icmpge : // fall through
  2329       case Bytecodes::_if_icmpgt : // fall through
  2330       case Bytecodes::_if_icmple : // fall through
  2331       case Bytecodes::_if_acmpeq : // fall through
  2332       case Bytecodes::_if_acmpne :
  2333         assert(stack_end >= -Bytecodes::depth(code), "must have non-empty expression stack at if bytecode");
  2334         break;
  2339 #endif // ASSERT
  2342 IntervalWalker* LinearScan::init_compute_oop_maps() {
  2343   // setup lists of potential oops for walking
  2344   Interval* oop_intervals;
  2345   Interval* non_oop_intervals;
  2347   create_unhandled_lists(&oop_intervals, &non_oop_intervals, is_oop_interval, NULL);
  2349   // intervals that have no oops inside need not to be processed
  2350   // to ensure a walking until the last instruction id, add a dummy interval
  2351   // with a high operation id
  2352   non_oop_intervals = new Interval(any_reg);
  2353   non_oop_intervals->add_range(max_jint - 2, max_jint - 1);
  2355   return new IntervalWalker(this, oop_intervals, non_oop_intervals);
  2359 OopMap* LinearScan::compute_oop_map(IntervalWalker* iw, LIR_Op* op, CodeEmitInfo* info, bool is_call_site) {
  2360   TRACE_LINEAR_SCAN(3, tty->print_cr("creating oop map at op_id %d", op->id()));
  2362   // walk before the current operation -> intervals that start at
  2363   // the operation (= output operands of the operation) are not
  2364   // included in the oop map
  2365   iw->walk_before(op->id());
  2367   int frame_size = frame_map()->framesize();
  2368   int arg_count = frame_map()->oop_map_arg_count();
  2369   OopMap* map = new OopMap(frame_size, arg_count);
  2371   // Check if this is a patch site.
  2372   bool is_patch_info = false;
  2373   if (op->code() == lir_move) {
  2374     assert(!is_call_site, "move must not be a call site");
  2375     assert(op->as_Op1() != NULL, "move must be LIR_Op1");
  2376     LIR_Op1* move = (LIR_Op1*)op;
  2378     is_patch_info = move->patch_code() != lir_patch_none;
  2381   // Iterate through active intervals
  2382   for (Interval* interval = iw->active_first(fixedKind); interval != Interval::end(); interval = interval->next()) {
  2383     int assigned_reg = interval->assigned_reg();
  2385     assert(interval->current_from() <= op->id() && op->id() <= interval->current_to(), "interval should not be active otherwise");
  2386     assert(interval->assigned_regHi() == any_reg, "oop must be single word");
  2387     assert(interval->reg_num() >= LIR_OprDesc::vreg_base, "fixed interval found");
  2389     // Check if this range covers the instruction. Intervals that
  2390     // start or end at the current operation are not included in the
  2391     // oop map, except in the case of patching moves.  For patching
  2392     // moves, any intervals which end at this instruction are included
  2393     // in the oop map since we may safepoint while doing the patch
  2394     // before we've consumed the inputs.
  2395     if (is_patch_info || op->id() < interval->current_to()) {
  2397       // caller-save registers must not be included into oop-maps at calls
  2398       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");
  2400       VMReg name = vm_reg_for_interval(interval);
  2401       map->set_oop(name);
  2403       // Spill optimization: when the stack value is guaranteed to be always correct,
  2404       // then it must be added to the oop map even if the interval is currently in a register
  2405       if (interval->always_in_memory() &&
  2406           op->id() > interval->spill_definition_pos() &&
  2407           interval->assigned_reg() != interval->canonical_spill_slot()) {
  2408         assert(interval->spill_definition_pos() > 0, "position not set correctly");
  2409         assert(interval->canonical_spill_slot() >= LinearScan::nof_regs, "no spill slot assigned");
  2410         assert(interval->assigned_reg() < LinearScan::nof_regs, "interval is on stack, so stack slot is registered twice");
  2412         map->set_oop(frame_map()->slot_regname(interval->canonical_spill_slot() - LinearScan::nof_regs));
  2417   // add oops from lock stack
  2418   assert(info->stack() != NULL, "CodeEmitInfo must always have a stack");
  2419   int locks_count = info->stack()->total_locks_size();
  2420   for (int i = 0; i < locks_count; i++) {
  2421     map->set_oop(frame_map()->monitor_object_regname(i));
  2424   return map;
  2428 void LinearScan::compute_oop_map(IntervalWalker* iw, const LIR_OpVisitState &visitor, LIR_Op* op) {
  2429   assert(visitor.info_count() > 0, "no oop map needed");
  2431   // compute oop_map only for first CodeEmitInfo
  2432   // because it is (in most cases) equal for all other infos of the same operation
  2433   CodeEmitInfo* first_info = visitor.info_at(0);
  2434   OopMap* first_oop_map = compute_oop_map(iw, op, first_info, visitor.has_call());
  2436   for (int i = 0; i < visitor.info_count(); i++) {
  2437     CodeEmitInfo* info = visitor.info_at(i);
  2438     OopMap* oop_map = first_oop_map;
  2440     if (info->stack()->locks_size() != first_info->stack()->locks_size()) {
  2441       // this info has a different number of locks then the precomputed oop map
  2442       // (possible for lock and unlock instructions) -> compute oop map with
  2443       // correct lock information
  2444       oop_map = compute_oop_map(iw, op, info, visitor.has_call());
  2447     if (info->_oop_map == NULL) {
  2448       info->_oop_map = oop_map;
  2449     } else {
  2450       // a CodeEmitInfo can not be shared between different LIR-instructions
  2451       // because interval splitting can occur anywhere between two instructions
  2452       // and so the oop maps must be different
  2453       // -> check if the already set oop_map is exactly the one calculated for this operation
  2454       assert(info->_oop_map == oop_map, "same CodeEmitInfo used for multiple LIR instructions");
  2460 // frequently used constants
  2461 ConstantOopWriteValue LinearScan::_oop_null_scope_value = ConstantOopWriteValue(NULL);
  2462 ConstantIntValue      LinearScan::_int_m1_scope_value = ConstantIntValue(-1);
  2463 ConstantIntValue      LinearScan::_int_0_scope_value =  ConstantIntValue(0);
  2464 ConstantIntValue      LinearScan::_int_1_scope_value =  ConstantIntValue(1);
  2465 ConstantIntValue      LinearScan::_int_2_scope_value =  ConstantIntValue(2);
  2466 LocationValue         _illegal_value = LocationValue(Location());
  2468 void LinearScan::init_compute_debug_info() {
  2469   // cache for frequently used scope values
  2470   // (cpu registers and stack slots)
  2471   _scope_value_cache = ScopeValueArray((LinearScan::nof_cpu_regs + frame_map()->argcount() + max_spills()) * 2, NULL);
  2474 MonitorValue* LinearScan::location_for_monitor_index(int monitor_index) {
  2475   Location loc;
  2476   if (!frame_map()->location_for_monitor_object(monitor_index, &loc)) {
  2477     bailout("too large frame");
  2479   ScopeValue* object_scope_value = new LocationValue(loc);
  2481   if (!frame_map()->location_for_monitor_lock(monitor_index, &loc)) {
  2482     bailout("too large frame");
  2484   return new MonitorValue(object_scope_value, loc);
  2487 LocationValue* LinearScan::location_for_name(int name, Location::Type loc_type) {
  2488   Location loc;
  2489   if (!frame_map()->locations_for_slot(name, loc_type, &loc)) {
  2490     bailout("too large frame");
  2492   return new LocationValue(loc);
  2496 int LinearScan::append_scope_value_for_constant(LIR_Opr opr, GrowableArray<ScopeValue*>* scope_values) {
  2497   assert(opr->is_constant(), "should not be called otherwise");
  2499   LIR_Const* c = opr->as_constant_ptr();
  2500   BasicType t = c->type();
  2501   switch (t) {
  2502     case T_OBJECT: {
  2503       jobject value = c->as_jobject();
  2504       if (value == NULL) {
  2505         scope_values->append(&_oop_null_scope_value);
  2506       } else {
  2507         scope_values->append(new ConstantOopWriteValue(c->as_jobject()));
  2509       return 1;
  2512     case T_INT: // fall through
  2513     case T_FLOAT: {
  2514       int value = c->as_jint_bits();
  2515       switch (value) {
  2516         case -1: scope_values->append(&_int_m1_scope_value); break;
  2517         case 0:  scope_values->append(&_int_0_scope_value); break;
  2518         case 1:  scope_values->append(&_int_1_scope_value); break;
  2519         case 2:  scope_values->append(&_int_2_scope_value); break;
  2520         default: scope_values->append(new ConstantIntValue(c->as_jint_bits())); break;
  2522       return 1;
  2525     case T_LONG: // fall through
  2526     case T_DOUBLE: {
  2527 #ifdef _LP64
  2528       scope_values->append(&_int_0_scope_value);
  2529       scope_values->append(new ConstantLongValue(c->as_jlong_bits()));
  2530 #else
  2531       if (hi_word_offset_in_bytes > lo_word_offset_in_bytes) {
  2532         scope_values->append(new ConstantIntValue(c->as_jint_hi_bits()));
  2533         scope_values->append(new ConstantIntValue(c->as_jint_lo_bits()));
  2534       } else {
  2535         scope_values->append(new ConstantIntValue(c->as_jint_lo_bits()));
  2536         scope_values->append(new ConstantIntValue(c->as_jint_hi_bits()));
  2538 #endif
  2539       return 2;
  2542     case T_ADDRESS: {
  2543 #ifdef _LP64
  2544       scope_values->append(new ConstantLongValue(c->as_jint()));
  2545 #else
  2546       scope_values->append(new ConstantIntValue(c->as_jint()));
  2547 #endif
  2548       return 1;
  2551     default:
  2552       ShouldNotReachHere();
  2553       return -1;
  2557 int LinearScan::append_scope_value_for_operand(LIR_Opr opr, GrowableArray<ScopeValue*>* scope_values) {
  2558   if (opr->is_single_stack()) {
  2559     int stack_idx = opr->single_stack_ix();
  2560     bool is_oop = opr->is_oop_register();
  2561     int cache_idx = (stack_idx + LinearScan::nof_cpu_regs) * 2 + (is_oop ? 1 : 0);
  2563     ScopeValue* sv = _scope_value_cache.at(cache_idx);
  2564     if (sv == NULL) {
  2565       Location::Type loc_type = is_oop ? Location::oop : Location::normal;
  2566       sv = location_for_name(stack_idx, loc_type);
  2567       _scope_value_cache.at_put(cache_idx, sv);
  2570     // check if cached value is correct
  2571     DEBUG_ONLY(assert_equal(sv, location_for_name(stack_idx, is_oop ? Location::oop : Location::normal)));
  2573     scope_values->append(sv);
  2574     return 1;
  2576   } else if (opr->is_single_cpu()) {
  2577     bool is_oop = opr->is_oop_register();
  2578     int cache_idx = opr->cpu_regnr() * 2 + (is_oop ? 1 : 0);
  2579     Location::Type int_loc_type = NOT_LP64(Location::normal) LP64_ONLY(Location::int_in_long);
  2581     ScopeValue* sv = _scope_value_cache.at(cache_idx);
  2582     if (sv == NULL) {
  2583       Location::Type loc_type = is_oop ? Location::oop : int_loc_type;
  2584       VMReg rname = frame_map()->regname(opr);
  2585       sv = new LocationValue(Location::new_reg_loc(loc_type, rname));
  2586       _scope_value_cache.at_put(cache_idx, sv);
  2589     // check if cached value is correct
  2590     DEBUG_ONLY(assert_equal(sv, new LocationValue(Location::new_reg_loc(is_oop ? Location::oop : int_loc_type, frame_map()->regname(opr)))));
  2592     scope_values->append(sv);
  2593     return 1;
  2595 #ifdef X86
  2596   } else if (opr->is_single_xmm()) {
  2597     VMReg rname = opr->as_xmm_float_reg()->as_VMReg();
  2598     LocationValue* sv = new LocationValue(Location::new_reg_loc(Location::normal, rname));
  2600     scope_values->append(sv);
  2601     return 1;
  2602 #endif
  2604   } else if (opr->is_single_fpu()) {
  2605 #ifdef X86
  2606     // the exact location of fpu stack values is only known
  2607     // during fpu stack allocation, so the stack allocator object
  2608     // must be present
  2609     assert(use_fpu_stack_allocation(), "should not have float stack values without fpu stack allocation (all floats must be SSE2)");
  2610     assert(_fpu_stack_allocator != NULL, "must be present");
  2611     opr = _fpu_stack_allocator->to_fpu_stack(opr);
  2612 #endif
  2614     Location::Type loc_type = float_saved_as_double ? Location::float_in_dbl : Location::normal;
  2615     VMReg rname = frame_map()->fpu_regname(opr->fpu_regnr());
  2616     LocationValue* sv = new LocationValue(Location::new_reg_loc(loc_type, rname));
  2618     scope_values->append(sv);
  2619     return 1;
  2621   } else {
  2622     // double-size operands
  2624     ScopeValue* first;
  2625     ScopeValue* second;
  2627     if (opr->is_double_stack()) {
  2628 #ifdef _LP64
  2629       Location loc1;
  2630       Location::Type loc_type = opr->type() == T_LONG ? Location::lng : Location::dbl;
  2631       if (!frame_map()->locations_for_slot(opr->double_stack_ix(), loc_type, &loc1, NULL)) {
  2632         bailout("too large frame");
  2634       // Does this reverse on x86 vs. sparc?
  2635       first =  new LocationValue(loc1);
  2636       second = &_int_0_scope_value;
  2637 #else
  2638       Location loc1, loc2;
  2639       if (!frame_map()->locations_for_slot(opr->double_stack_ix(), Location::normal, &loc1, &loc2)) {
  2640         bailout("too large frame");
  2642       first =  new LocationValue(loc1);
  2643       second = new LocationValue(loc2);
  2644 #endif // _LP64
  2646     } else if (opr->is_double_cpu()) {
  2647 #ifdef _LP64
  2648       VMReg rname_first = opr->as_register_lo()->as_VMReg();
  2649       first = new LocationValue(Location::new_reg_loc(Location::lng, rname_first));
  2650       second = &_int_0_scope_value;
  2651 #else
  2652       VMReg rname_first = opr->as_register_lo()->as_VMReg();
  2653       VMReg rname_second = opr->as_register_hi()->as_VMReg();
  2655       if (hi_word_offset_in_bytes < lo_word_offset_in_bytes) {
  2656         // lo/hi and swapped relative to first and second, so swap them
  2657         VMReg tmp = rname_first;
  2658         rname_first = rname_second;
  2659         rname_second = tmp;
  2662       first = new LocationValue(Location::new_reg_loc(Location::normal, rname_first));
  2663       second = new LocationValue(Location::new_reg_loc(Location::normal, rname_second));
  2664 #endif //_LP64
  2667 #ifdef X86
  2668     } else if (opr->is_double_xmm()) {
  2669       assert(opr->fpu_regnrLo() == opr->fpu_regnrHi(), "assumed in calculation");
  2670       VMReg rname_first  = opr->as_xmm_double_reg()->as_VMReg();
  2671 #  ifdef _LP64
  2672       first = new LocationValue(Location::new_reg_loc(Location::dbl, rname_first));
  2673       second = &_int_0_scope_value;
  2674 #  else
  2675       first = new LocationValue(Location::new_reg_loc(Location::normal, rname_first));
  2676       // %%% This is probably a waste but we'll keep things as they were for now
  2677       if (true) {
  2678         VMReg rname_second = rname_first->next();
  2679         second = new LocationValue(Location::new_reg_loc(Location::normal, rname_second));
  2681 #  endif
  2682 #endif
  2684     } else if (opr->is_double_fpu()) {
  2685       // On SPARC, fpu_regnrLo/fpu_regnrHi represents the two halves of
  2686       // the double as float registers in the native ordering. On X86,
  2687       // fpu_regnrLo is a FPU stack slot whose VMReg represents
  2688       // the low-order word of the double and fpu_regnrLo + 1 is the
  2689       // name for the other half.  *first and *second must represent the
  2690       // least and most significant words, respectively.
  2692 #ifdef X86
  2693       // the exact location of fpu stack values is only known
  2694       // during fpu stack allocation, so the stack allocator object
  2695       // must be present
  2696       assert(use_fpu_stack_allocation(), "should not have float stack values without fpu stack allocation (all floats must be SSE2)");
  2697       assert(_fpu_stack_allocator != NULL, "must be present");
  2698       opr = _fpu_stack_allocator->to_fpu_stack(opr);
  2700       assert(opr->fpu_regnrLo() == opr->fpu_regnrHi(), "assumed in calculation (only fpu_regnrHi is used)");
  2701 #endif
  2702 #ifdef SPARC
  2703       assert(opr->fpu_regnrLo() == opr->fpu_regnrHi() + 1, "assumed in calculation (only fpu_regnrHi is used)");
  2704 #endif
  2705 #ifdef ARM
  2706       assert(opr->fpu_regnrHi() == opr->fpu_regnrLo() + 1, "assumed in calculation (only fpu_regnrLo is used)");
  2707 #endif
  2708 #ifdef PPC
  2709       assert(opr->fpu_regnrLo() == opr->fpu_regnrHi(), "assumed in calculation (only fpu_regnrHi is used)");
  2710 #endif
  2712       VMReg rname_first = frame_map()->fpu_regname(opr->fpu_regnrHi());
  2713 #ifdef _LP64
  2714       first = new LocationValue(Location::new_reg_loc(Location::dbl, rname_first));
  2715       second = &_int_0_scope_value;
  2716 #else
  2717       first = new LocationValue(Location::new_reg_loc(Location::normal, rname_first));
  2718       // %%% This is probably a waste but we'll keep things as they were for now
  2719       if (true) {
  2720         VMReg rname_second = rname_first->next();
  2721         second = new LocationValue(Location::new_reg_loc(Location::normal, rname_second));
  2723 #endif
  2725     } else {
  2726       ShouldNotReachHere();
  2727       first = NULL;
  2728       second = NULL;
  2731     assert(first != NULL && second != NULL, "must be set");
  2732     // The convention the interpreter uses is that the second local
  2733     // holds the first raw word of the native double representation.
  2734     // This is actually reasonable, since locals and stack arrays
  2735     // grow downwards in all implementations.
  2736     // (If, on some machine, the interpreter's Java locals or stack
  2737     // were to grow upwards, the embedded doubles would be word-swapped.)
  2738     scope_values->append(second);
  2739     scope_values->append(first);
  2740     return 2;
  2745 int LinearScan::append_scope_value(int op_id, Value value, GrowableArray<ScopeValue*>* scope_values) {
  2746   if (value != NULL) {
  2747     LIR_Opr opr = value->operand();
  2748     Constant* con = value->as_Constant();
  2750     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)");
  2751     assert(con != NULL || opr->is_virtual(), "asumption: non-Constant instructions have only virtual operands");
  2753     if (con != NULL && !con->is_pinned() && !opr->is_constant()) {
  2754       // Unpinned constants may have a virtual operand for a part of the lifetime
  2755       // or may be illegal when it was optimized away,
  2756       // so always use a constant operand
  2757       opr = LIR_OprFact::value_type(con->type());
  2759     assert(opr->is_virtual() || opr->is_constant(), "other cases not allowed here");
  2761     if (opr->is_virtual()) {
  2762       LIR_OpVisitState::OprMode mode = LIR_OpVisitState::inputMode;
  2764       BlockBegin* block = block_of_op_with_id(op_id);
  2765       if (block->number_of_sux() == 1 && op_id == block->last_lir_instruction_id()) {
  2766         // generating debug information for the last instruction of a block.
  2767         // if this instruction is a branch, spill moves are inserted before this branch
  2768         // and so the wrong operand would be returned (spill moves at block boundaries are not
  2769         // considered in the live ranges of intervals)
  2770         // Solution: use the first op_id of the branch target block instead.
  2771         if (block->lir()->instructions_list()->last()->as_OpBranch() != NULL) {
  2772           if (block->live_out().at(opr->vreg_number())) {
  2773             op_id = block->sux_at(0)->first_lir_instruction_id();
  2774             mode = LIR_OpVisitState::outputMode;
  2779       // Get current location of operand
  2780       // The operand must be live because debug information is considered when building the intervals
  2781       // if the interval is not live, color_lir_opr will cause an assertion failure
  2782       opr = color_lir_opr(opr, op_id, mode);
  2783       assert(!has_call(op_id) || opr->is_stack() || !is_caller_save(reg_num(opr)), "can not have caller-save register operands at calls");
  2785       // Append to ScopeValue array
  2786       return append_scope_value_for_operand(opr, scope_values);
  2788     } else {
  2789       assert(value->as_Constant() != NULL, "all other instructions have only virtual operands");
  2790       assert(opr->is_constant(), "operand must be constant");
  2792       return append_scope_value_for_constant(opr, scope_values);
  2794   } else {
  2795     // append a dummy value because real value not needed
  2796     scope_values->append(&_illegal_value);
  2797     return 1;
  2802 IRScopeDebugInfo* LinearScan::compute_debug_info_for_scope(int op_id, IRScope* cur_scope, ValueStack* cur_state, ValueStack* innermost_state) {
  2803   IRScopeDebugInfo* caller_debug_info = NULL;
  2805   ValueStack* caller_state = cur_state->caller_state();
  2806   if (caller_state != NULL) {
  2807     // process recursively to compute outermost scope first
  2808     caller_debug_info = compute_debug_info_for_scope(op_id, cur_scope->caller(), caller_state, innermost_state);
  2811   // initialize these to null.
  2812   // If we don't need deopt info or there are no locals, expressions or monitors,
  2813   // then these get recorded as no information and avoids the allocation of 0 length arrays.
  2814   GrowableArray<ScopeValue*>*   locals      = NULL;
  2815   GrowableArray<ScopeValue*>*   expressions = NULL;
  2816   GrowableArray<MonitorValue*>* monitors    = NULL;
  2818   // describe local variable values
  2819   int nof_locals = cur_state->locals_size();
  2820   if (nof_locals > 0) {
  2821     locals = new GrowableArray<ScopeValue*>(nof_locals);
  2823     int pos = 0;
  2824     while (pos < nof_locals) {
  2825       assert(pos < cur_state->locals_size(), "why not?");
  2827       Value local = cur_state->local_at(pos);
  2828       pos += append_scope_value(op_id, local, locals);
  2830       assert(locals->length() == pos, "must match");
  2832     assert(locals->length() == cur_scope->method()->max_locals(), "wrong number of locals");
  2833     assert(locals->length() == cur_state->locals_size(), "wrong number of locals");
  2834   } else if (cur_scope->method()->max_locals() > 0) {
  2835     assert(cur_state->kind() == ValueStack::EmptyExceptionState, "should be");
  2836     nof_locals = cur_scope->method()->max_locals();
  2837     locals = new GrowableArray<ScopeValue*>(nof_locals);
  2838     for(int i = 0; i < nof_locals; i++) {
  2839       locals->append(&_illegal_value);
  2843   // describe expression stack
  2844   int nof_stack = cur_state->stack_size();
  2845   if (nof_stack > 0) {
  2846     expressions = new GrowableArray<ScopeValue*>(nof_stack);
  2848     int pos = 0;
  2849     while (pos < nof_stack) {
  2850       Value expression = cur_state->stack_at_inc(pos);
  2851       append_scope_value(op_id, expression, expressions);
  2853       assert(expressions->length() == pos, "must match");
  2855     assert(expressions->length() == cur_state->stack_size(), "wrong number of stack entries");
  2858   // describe monitors
  2859   int nof_locks = cur_state->locks_size();
  2860   if (nof_locks > 0) {
  2861     int lock_offset = cur_state->caller_state() != NULL ? cur_state->caller_state()->total_locks_size() : 0;
  2862     monitors = new GrowableArray<MonitorValue*>(nof_locks);
  2863     for (int i = 0; i < nof_locks; i++) {
  2864       monitors->append(location_for_monitor_index(lock_offset + i));
  2868   return new IRScopeDebugInfo(cur_scope, cur_state->bci(), locals, expressions, monitors, caller_debug_info);
  2872 void LinearScan::compute_debug_info(CodeEmitInfo* info, int op_id) {
  2873   TRACE_LINEAR_SCAN(3, tty->print_cr("creating debug information at op_id %d", op_id));
  2875   IRScope* innermost_scope = info->scope();
  2876   ValueStack* innermost_state = info->stack();
  2878   assert(innermost_scope != NULL && innermost_state != NULL, "why is it missing?");
  2880   DEBUG_ONLY(check_stack_depth(info, innermost_state->stack_size()));
  2882   if (info->_scope_debug_info == NULL) {
  2883     // compute debug information
  2884     info->_scope_debug_info = compute_debug_info_for_scope(op_id, innermost_scope, innermost_state, innermost_state);
  2885   } else {
  2886     // debug information already set. Check that it is correct from the current point of view
  2887     DEBUG_ONLY(assert_equal(info->_scope_debug_info, compute_debug_info_for_scope(op_id, innermost_scope, innermost_state, innermost_state)));
  2892 void LinearScan::assign_reg_num(LIR_OpList* instructions, IntervalWalker* iw) {
  2893   LIR_OpVisitState visitor;
  2894   int num_inst = instructions->length();
  2895   bool has_dead = false;
  2897   for (int j = 0; j < num_inst; j++) {
  2898     LIR_Op* op = instructions->at(j);
  2899     if (op == NULL) {  // this can happen when spill-moves are removed in eliminate_spill_moves
  2900       has_dead = true;
  2901       continue;
  2903     int op_id = op->id();
  2905     // visit instruction to get list of operands
  2906     visitor.visit(op);
  2908     // iterate all modes of the visitor and process all virtual operands
  2909     for_each_visitor_mode(mode) {
  2910       int n = visitor.opr_count(mode);
  2911       for (int k = 0; k < n; k++) {
  2912         LIR_Opr opr = visitor.opr_at(mode, k);
  2913         if (opr->is_virtual_register()) {
  2914           visitor.set_opr_at(mode, k, color_lir_opr(opr, op_id, mode));
  2919     if (visitor.info_count() > 0) {
  2920       // exception handling
  2921       if (compilation()->has_exception_handlers()) {
  2922         XHandlers* xhandlers = visitor.all_xhandler();
  2923         int n = xhandlers->length();
  2924         for (int k = 0; k < n; k++) {
  2925           XHandler* handler = xhandlers->handler_at(k);
  2926           if (handler->entry_code() != NULL) {
  2927             assign_reg_num(handler->entry_code()->instructions_list(), NULL);
  2930       } else {
  2931         assert(visitor.all_xhandler()->length() == 0, "missed exception handler");
  2934       // compute oop map
  2935       assert(iw != NULL, "needed for compute_oop_map");
  2936       compute_oop_map(iw, visitor, op);
  2938       // compute debug information
  2939       if (!use_fpu_stack_allocation()) {
  2940         // compute debug information if fpu stack allocation is not needed.
  2941         // when fpu stack allocation is needed, the debug information can not
  2942         // be computed here because the exact location of fpu operands is not known
  2943         // -> debug information is created inside the fpu stack allocator
  2944         int n = visitor.info_count();
  2945         for (int k = 0; k < n; k++) {
  2946           compute_debug_info(visitor.info_at(k), op_id);
  2951 #ifdef ASSERT
  2952     // make sure we haven't made the op invalid.
  2953     op->verify();
  2954 #endif
  2956     // remove useless moves
  2957     if (op->code() == lir_move) {
  2958       assert(op->as_Op1() != NULL, "move must be LIR_Op1");
  2959       LIR_Op1* move = (LIR_Op1*)op;
  2960       LIR_Opr src = move->in_opr();
  2961       LIR_Opr dst = move->result_opr();
  2962       if (dst == src ||
  2963           !dst->is_pointer() && !src->is_pointer() &&
  2964           src->is_same_register(dst)) {
  2965         instructions->at_put(j, NULL);
  2966         has_dead = true;
  2971   if (has_dead) {
  2972     // iterate all instructions of the block and remove all null-values.
  2973     int insert_point = 0;
  2974     for (int j = 0; j < num_inst; j++) {
  2975       LIR_Op* op = instructions->at(j);
  2976       if (op != NULL) {
  2977         if (insert_point != j) {
  2978           instructions->at_put(insert_point, op);
  2980         insert_point++;
  2983     instructions->truncate(insert_point);
  2987 void LinearScan::assign_reg_num() {
  2988   TIME_LINEAR_SCAN(timer_assign_reg_num);
  2990   init_compute_debug_info();
  2991   IntervalWalker* iw = init_compute_oop_maps();
  2993   int num_blocks = block_count();
  2994   for (int i = 0; i < num_blocks; i++) {
  2995     BlockBegin* block = block_at(i);
  2996     assign_reg_num(block->lir()->instructions_list(), iw);
  3001 void LinearScan::do_linear_scan() {
  3002   NOT_PRODUCT(_total_timer.begin_method());
  3004   number_instructions();
  3006   NOT_PRODUCT(print_lir(1, "Before Register Allocation"));
  3008   compute_local_live_sets();
  3009   compute_global_live_sets();
  3010   CHECK_BAILOUT();
  3012   build_intervals();
  3013   CHECK_BAILOUT();
  3014   sort_intervals_before_allocation();
  3016   NOT_PRODUCT(print_intervals("Before Register Allocation"));
  3017   NOT_PRODUCT(LinearScanStatistic::compute(this, _stat_before_alloc));
  3019   allocate_registers();
  3020   CHECK_BAILOUT();
  3022   resolve_data_flow();
  3023   if (compilation()->has_exception_handlers()) {
  3024     resolve_exception_handlers();
  3026   // fill in number of spill slots into frame_map
  3027   propagate_spill_slots();
  3028   CHECK_BAILOUT();
  3030   NOT_PRODUCT(print_intervals("After Register Allocation"));
  3031   NOT_PRODUCT(print_lir(2, "LIR after register allocation:"));
  3033   sort_intervals_after_allocation();
  3035   DEBUG_ONLY(verify());
  3037   eliminate_spill_moves();
  3038   assign_reg_num();
  3039   CHECK_BAILOUT();
  3041   NOT_PRODUCT(print_lir(2, "LIR after assignment of register numbers:"));
  3042   NOT_PRODUCT(LinearScanStatistic::compute(this, _stat_after_asign));
  3044   { TIME_LINEAR_SCAN(timer_allocate_fpu_stack);
  3046     if (use_fpu_stack_allocation()) {
  3047       allocate_fpu_stack(); // Only has effect on Intel
  3048       NOT_PRODUCT(print_lir(2, "LIR after FPU stack allocation:"));
  3052   { TIME_LINEAR_SCAN(timer_optimize_lir);
  3054     EdgeMoveOptimizer::optimize(ir()->code());
  3055     ControlFlowOptimizer::optimize(ir()->code());
  3056     // check that cfg is still correct after optimizations
  3057     ir()->verify();
  3060   NOT_PRODUCT(print_lir(1, "Before Code Generation", false));
  3061   NOT_PRODUCT(LinearScanStatistic::compute(this, _stat_final));
  3062   NOT_PRODUCT(_total_timer.end_method(this));
  3066 // ********** Printing functions
  3068 #ifndef PRODUCT
  3070 void LinearScan::print_timers(double total) {
  3071   _total_timer.print(total);
  3074 void LinearScan::print_statistics() {
  3075   _stat_before_alloc.print("before allocation");
  3076   _stat_after_asign.print("after assignment of register");
  3077   _stat_final.print("after optimization");
  3080 void LinearScan::print_bitmap(BitMap& b) {
  3081   for (unsigned int i = 0; i < b.size(); i++) {
  3082     if (b.at(i)) tty->print("%d ", i);
  3084   tty->cr();
  3087 void LinearScan::print_intervals(const char* label) {
  3088   if (TraceLinearScanLevel >= 1) {
  3089     int i;
  3090     tty->cr();
  3091     tty->print_cr("%s", label);
  3093     for (i = 0; i < interval_count(); i++) {
  3094       Interval* interval = interval_at(i);
  3095       if (interval != NULL) {
  3096         interval->print();
  3100     tty->cr();
  3101     tty->print_cr("--- Basic Blocks ---");
  3102     for (i = 0; i < block_count(); i++) {
  3103       BlockBegin* block = block_at(i);
  3104       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());
  3106     tty->cr();
  3107     tty->cr();
  3110   if (PrintCFGToFile) {
  3111     CFGPrinter::print_intervals(&_intervals, label);
  3115 void LinearScan::print_lir(int level, const char* label, bool hir_valid) {
  3116   if (TraceLinearScanLevel >= level) {
  3117     tty->cr();
  3118     tty->print_cr("%s", label);
  3119     print_LIR(ir()->linear_scan_order());
  3120     tty->cr();
  3123   if (level == 1 && PrintCFGToFile) {
  3124     CFGPrinter::print_cfg(ir()->linear_scan_order(), label, hir_valid, true);
  3128 #endif //PRODUCT
  3131 // ********** verification functions for allocation
  3132 // (check that all intervals have a correct register and that no registers are overwritten)
  3133 #ifdef ASSERT
  3135 void LinearScan::verify() {
  3136   TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying intervals ******************************************"));
  3137   verify_intervals();
  3139   TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying that no oops are in fixed intervals ****************"));
  3140   verify_no_oops_in_fixed_intervals();
  3142   TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying that unpinned constants are not alive across block boundaries"));
  3143   verify_constants();
  3145   TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying register allocation ********************************"));
  3146   verify_registers();
  3148   TRACE_LINEAR_SCAN(2, tty->print_cr("********* no errors found **********************************************"));
  3151 void LinearScan::verify_intervals() {
  3152   int len = interval_count();
  3153   bool has_error = false;
  3155   for (int i = 0; i < len; i++) {
  3156     Interval* i1 = interval_at(i);
  3157     if (i1 == NULL) continue;
  3159     i1->check_split_children();
  3161     if (i1->reg_num() != i) {
  3162       tty->print_cr("Interval %d is on position %d in list", i1->reg_num(), i); i1->print(); tty->cr();
  3163       has_error = true;
  3166     if (i1->reg_num() >= LIR_OprDesc::vreg_base && i1->type() == T_ILLEGAL) {
  3167       tty->print_cr("Interval %d has no type assigned", i1->reg_num()); i1->print(); tty->cr();
  3168       has_error = true;
  3171     if (i1->assigned_reg() == any_reg) {
  3172       tty->print_cr("Interval %d has no register assigned", i1->reg_num()); i1->print(); tty->cr();
  3173       has_error = true;
  3176     if (i1->assigned_reg() == i1->assigned_regHi()) {
  3177       tty->print_cr("Interval %d: low and high register equal", i1->reg_num()); i1->print(); tty->cr();
  3178       has_error = true;
  3181     if (!is_processed_reg_num(i1->assigned_reg())) {
  3182       tty->print_cr("Can not have an Interval for an ignored register"); i1->print(); tty->cr();
  3183       has_error = true;
  3186     if (i1->first() == Range::end()) {
  3187       tty->print_cr("Interval %d has no Range", i1->reg_num()); i1->print(); tty->cr();
  3188       has_error = true;
  3191     for (Range* r = i1->first(); r != Range::end(); r = r->next()) {
  3192       if (r->from() >= r->to()) {
  3193         tty->print_cr("Interval %d has zero length range", i1->reg_num()); i1->print(); tty->cr();
  3194         has_error = true;
  3198     for (int j = i + 1; j < len; j++) {
  3199       Interval* i2 = interval_at(j);
  3200       if (i2 == NULL) continue;
  3202       // special intervals that are created in MoveResolver
  3203       // -> ignore them because the range information has no meaning there
  3204       if (i1->from() == 1 && i1->to() == 2) continue;
  3205       if (i2->from() == 1 && i2->to() == 2) continue;
  3207       int r1 = i1->assigned_reg();
  3208       int r1Hi = i1->assigned_regHi();
  3209       int r2 = i2->assigned_reg();
  3210       int r2Hi = i2->assigned_regHi();
  3211       if (i1->intersects(i2) && (r1 == r2 || r1 == r2Hi || (r1Hi != any_reg && (r1Hi == r2 || r1Hi == r2Hi)))) {
  3212         tty->print_cr("Intervals %d and %d overlap and have the same register assigned", i1->reg_num(), i2->reg_num());
  3213         i1->print(); tty->cr();
  3214         i2->print(); tty->cr();
  3215         has_error = true;
  3220   assert(has_error == false, "register allocation invalid");
  3224 void LinearScan::verify_no_oops_in_fixed_intervals() {
  3225   Interval* fixed_intervals;
  3226   Interval* other_intervals;
  3227   create_unhandled_lists(&fixed_intervals, &other_intervals, is_precolored_cpu_interval, NULL);
  3229   // to ensure a walking until the last instruction id, add a dummy interval
  3230   // with a high operation id
  3231   other_intervals = new Interval(any_reg);
  3232   other_intervals->add_range(max_jint - 2, max_jint - 1);
  3233   IntervalWalker* iw = new IntervalWalker(this, fixed_intervals, other_intervals);
  3235   LIR_OpVisitState visitor;
  3236   for (int i = 0; i < block_count(); i++) {
  3237     BlockBegin* block = block_at(i);
  3239     LIR_OpList* instructions = block->lir()->instructions_list();
  3241     for (int j = 0; j < instructions->length(); j++) {
  3242       LIR_Op* op = instructions->at(j);
  3243       int op_id = op->id();
  3245       visitor.visit(op);
  3247       if (visitor.info_count() > 0) {
  3248         iw->walk_before(op->id());
  3249         bool check_live = true;
  3250         if (op->code() == lir_move) {
  3251           LIR_Op1* move = (LIR_Op1*)op;
  3252           check_live = (move->patch_code() == lir_patch_none);
  3254         LIR_OpBranch* branch = op->as_OpBranch();
  3255         if (branch != NULL && branch->stub() != NULL && branch->stub()->is_exception_throw_stub()) {
  3256           // Don't bother checking the stub in this case since the
  3257           // exception stub will never return to normal control flow.
  3258           check_live = false;
  3261         // Make sure none of the fixed registers is live across an
  3262         // oopmap since we can't handle that correctly.
  3263         if (check_live) {
  3264           for (Interval* interval = iw->active_first(fixedKind);
  3265                interval != Interval::end();
  3266                interval = interval->next()) {
  3267             if (interval->current_to() > op->id() + 1) {
  3268               // This interval is live out of this op so make sure
  3269               // that this interval represents some value that's
  3270               // referenced by this op either as an input or output.
  3271               bool ok = false;
  3272               for_each_visitor_mode(mode) {
  3273                 int n = visitor.opr_count(mode);
  3274                 for (int k = 0; k < n; k++) {
  3275                   LIR_Opr opr = visitor.opr_at(mode, k);
  3276                   if (opr->is_fixed_cpu()) {
  3277                     if (interval_at(reg_num(opr)) == interval) {
  3278                       ok = true;
  3279                       break;
  3281                     int hi = reg_numHi(opr);
  3282                     if (hi != -1 && interval_at(hi) == interval) {
  3283                       ok = true;
  3284                       break;
  3289               assert(ok, "fixed intervals should never be live across an oopmap point");
  3295       // oop-maps at calls do not contain registers, so check is not needed
  3296       if (!visitor.has_call()) {
  3298         for_each_visitor_mode(mode) {
  3299           int n = visitor.opr_count(mode);
  3300           for (int k = 0; k < n; k++) {
  3301             LIR_Opr opr = visitor.opr_at(mode, k);
  3303             if (opr->is_fixed_cpu() && opr->is_oop()) {
  3304               // operand is a non-virtual cpu register and contains an oop
  3305               TRACE_LINEAR_SCAN(4, op->print_on(tty); tty->print("checking operand "); opr->print(); tty->cr());
  3307               Interval* interval = interval_at(reg_num(opr));
  3308               assert(interval != NULL, "no interval");
  3310               if (mode == LIR_OpVisitState::inputMode) {
  3311                 if (interval->to() >= op_id + 1) {
  3312                   assert(interval->to() < op_id + 2 ||
  3313                          interval->has_hole_between(op_id, op_id + 2),
  3314                          "oop input operand live after instruction");
  3316               } else if (mode == LIR_OpVisitState::outputMode) {
  3317                 if (interval->from() <= op_id - 1) {
  3318                   assert(interval->has_hole_between(op_id - 1, op_id),
  3319                          "oop input operand live after instruction");
  3331 void LinearScan::verify_constants() {
  3332   int num_regs = num_virtual_regs();
  3333   int size = live_set_size();
  3334   int num_blocks = block_count();
  3336   for (int i = 0; i < num_blocks; i++) {
  3337     BlockBegin* block = block_at(i);
  3338     BitMap live_at_edge = block->live_in();
  3340     // visit all registers where the live_at_edge bit is set
  3341     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)) {
  3342       TRACE_LINEAR_SCAN(4, tty->print("checking interval %d of block B%d", r, block->block_id()));
  3344       Value value = gen()->instruction_for_vreg(r);
  3346       assert(value != NULL, "all intervals live across block boundaries must have Value");
  3347       assert(value->operand()->is_register() && value->operand()->is_virtual(), "value must have virtual operand");
  3348       assert(value->operand()->vreg_number() == r, "register number must match");
  3349       // TKR assert(value->as_Constant() == NULL || value->is_pinned(), "only pinned constants can be alive accross block boundaries");
  3355 class RegisterVerifier: public StackObj {
  3356  private:
  3357   LinearScan*   _allocator;
  3358   BlockList     _work_list;      // all blocks that must be processed
  3359   IntervalsList _saved_states;   // saved information of previous check
  3361   // simplified access to methods of LinearScan
  3362   Compilation*  compilation() const              { return _allocator->compilation(); }
  3363   Interval*     interval_at(int reg_num) const   { return _allocator->interval_at(reg_num); }
  3364   int           reg_num(LIR_Opr opr) const       { return _allocator->reg_num(opr); }
  3366   // currently, only registers are processed
  3367   int           state_size()                     { return LinearScan::nof_regs; }
  3369   // accessors
  3370   IntervalList* state_for_block(BlockBegin* block) { return _saved_states.at(block->block_id()); }
  3371   void          set_state_for_block(BlockBegin* block, IntervalList* saved_state) { _saved_states.at_put(block->block_id(), saved_state); }
  3372   void          add_to_work_list(BlockBegin* block) { if (!_work_list.contains(block)) _work_list.append(block); }
  3374   // helper functions
  3375   IntervalList* copy(IntervalList* input_state);
  3376   void          state_put(IntervalList* input_state, int reg, Interval* interval);
  3377   bool          check_state(IntervalList* input_state, int reg, Interval* interval);
  3379   void process_block(BlockBegin* block);
  3380   void process_xhandler(XHandler* xhandler, IntervalList* input_state);
  3381   void process_successor(BlockBegin* block, IntervalList* input_state);
  3382   void process_operations(LIR_List* ops, IntervalList* input_state);
  3384  public:
  3385   RegisterVerifier(LinearScan* allocator)
  3386     : _allocator(allocator)
  3387     , _work_list(16)
  3388     , _saved_states(BlockBegin::number_of_blocks(), NULL)
  3389   { }
  3391   void verify(BlockBegin* start);
  3392 };
  3395 // entry function from LinearScan that starts the verification
  3396 void LinearScan::verify_registers() {
  3397   RegisterVerifier verifier(this);
  3398   verifier.verify(block_at(0));
  3402 void RegisterVerifier::verify(BlockBegin* start) {
  3403   // setup input registers (method arguments) for first block
  3404   IntervalList* input_state = new IntervalList(state_size(), NULL);
  3405   CallingConvention* args = compilation()->frame_map()->incoming_arguments();
  3406   for (int n = 0; n < args->length(); n++) {
  3407     LIR_Opr opr = args->at(n);
  3408     if (opr->is_register()) {
  3409       Interval* interval = interval_at(reg_num(opr));
  3411       if (interval->assigned_reg() < state_size()) {
  3412         input_state->at_put(interval->assigned_reg(), interval);
  3414       if (interval->assigned_regHi() != LinearScan::any_reg && interval->assigned_regHi() < state_size()) {
  3415         input_state->at_put(interval->assigned_regHi(), interval);
  3420   set_state_for_block(start, input_state);
  3421   add_to_work_list(start);
  3423   // main loop for verification
  3424   do {
  3425     BlockBegin* block = _work_list.at(0);
  3426     _work_list.remove_at(0);
  3428     process_block(block);
  3429   } while (!_work_list.is_empty());
  3432 void RegisterVerifier::process_block(BlockBegin* block) {
  3433   TRACE_LINEAR_SCAN(2, tty->cr(); tty->print_cr("process_block B%d", block->block_id()));
  3435   // must copy state because it is modified
  3436   IntervalList* input_state = copy(state_for_block(block));
  3438   if (TraceLinearScanLevel >= 4) {
  3439     tty->print_cr("Input-State of intervals:");
  3440     tty->print("    ");
  3441     for (int i = 0; i < state_size(); i++) {
  3442       if (input_state->at(i) != NULL) {
  3443         tty->print(" %4d", input_state->at(i)->reg_num());
  3444       } else {
  3445         tty->print("   __");
  3448     tty->cr();
  3449     tty->cr();
  3452   // process all operations of the block
  3453   process_operations(block->lir(), input_state);
  3455   // iterate all successors
  3456   for (int i = 0; i < block->number_of_sux(); i++) {
  3457     process_successor(block->sux_at(i), input_state);
  3461 void RegisterVerifier::process_xhandler(XHandler* xhandler, IntervalList* input_state) {
  3462   TRACE_LINEAR_SCAN(2, tty->print_cr("process_xhandler B%d", xhandler->entry_block()->block_id()));
  3464   // must copy state because it is modified
  3465   input_state = copy(input_state);
  3467   if (xhandler->entry_code() != NULL) {
  3468     process_operations(xhandler->entry_code(), input_state);
  3470   process_successor(xhandler->entry_block(), input_state);
  3473 void RegisterVerifier::process_successor(BlockBegin* block, IntervalList* input_state) {
  3474   IntervalList* saved_state = state_for_block(block);
  3476   if (saved_state != NULL) {
  3477     // this block was already processed before.
  3478     // check if new input_state is consistent with saved_state
  3480     bool saved_state_correct = true;
  3481     for (int i = 0; i < state_size(); i++) {
  3482       if (input_state->at(i) != saved_state->at(i)) {
  3483         // current input_state and previous saved_state assume a different
  3484         // interval in this register -> assume that this register is invalid
  3485         if (saved_state->at(i) != NULL) {
  3486           // invalidate old calculation only if it assumed that
  3487           // register was valid. when the register was already invalid,
  3488           // then the old calculation was correct.
  3489           saved_state_correct = false;
  3490           saved_state->at_put(i, NULL);
  3492           TRACE_LINEAR_SCAN(4, tty->print_cr("process_successor B%d: invalidating slot %d", block->block_id(), i));
  3497     if (saved_state_correct) {
  3498       // already processed block with correct input_state
  3499       TRACE_LINEAR_SCAN(2, tty->print_cr("process_successor B%d: previous visit already correct", block->block_id()));
  3500     } else {
  3501       // must re-visit this block
  3502       TRACE_LINEAR_SCAN(2, tty->print_cr("process_successor B%d: must re-visit because input state changed", block->block_id()));
  3503       add_to_work_list(block);
  3506   } else {
  3507     // block was not processed before, so set initial input_state
  3508     TRACE_LINEAR_SCAN(2, tty->print_cr("process_successor B%d: initial visit", block->block_id()));
  3510     set_state_for_block(block, copy(input_state));
  3511     add_to_work_list(block);
  3516 IntervalList* RegisterVerifier::copy(IntervalList* input_state) {
  3517   IntervalList* copy_state = new IntervalList(input_state->length());
  3518   copy_state->push_all(input_state);
  3519   return copy_state;
  3522 void RegisterVerifier::state_put(IntervalList* input_state, int reg, Interval* interval) {
  3523   if (reg != LinearScan::any_reg && reg < state_size()) {
  3524     if (interval != NULL) {
  3525       TRACE_LINEAR_SCAN(4, tty->print_cr("        reg[%d] = %d", reg, interval->reg_num()));
  3526     } else if (input_state->at(reg) != NULL) {
  3527       TRACE_LINEAR_SCAN(4, tty->print_cr("        reg[%d] = NULL", reg));
  3530     input_state->at_put(reg, interval);
  3534 bool RegisterVerifier::check_state(IntervalList* input_state, int reg, Interval* interval) {
  3535   if (reg != LinearScan::any_reg && reg < state_size()) {
  3536     if (input_state->at(reg) != interval) {
  3537       tty->print_cr("!! Error in register allocation: register %d does not contain interval %d", reg, interval->reg_num());
  3538       return true;
  3541   return false;
  3544 void RegisterVerifier::process_operations(LIR_List* ops, IntervalList* input_state) {
  3545   // visit all instructions of the block
  3546   LIR_OpVisitState visitor;
  3547   bool has_error = false;
  3549   for (int i = 0; i < ops->length(); i++) {
  3550     LIR_Op* op = ops->at(i);
  3551     visitor.visit(op);
  3553     TRACE_LINEAR_SCAN(4, op->print_on(tty));
  3555     // check if input operands are correct
  3556     int j;
  3557     int n = visitor.opr_count(LIR_OpVisitState::inputMode);
  3558     for (j = 0; j < n; j++) {
  3559       LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::inputMode, j);
  3560       if (opr->is_register() && LinearScan::is_processed_reg_num(reg_num(opr))) {
  3561         Interval* interval = interval_at(reg_num(opr));
  3562         if (op->id() != -1) {
  3563           interval = interval->split_child_at_op_id(op->id(), LIR_OpVisitState::inputMode);
  3566         has_error |= check_state(input_state, interval->assigned_reg(),   interval->split_parent());
  3567         has_error |= check_state(input_state, interval->assigned_regHi(), interval->split_parent());
  3569         // When an operand is marked with is_last_use, then the fpu stack allocator
  3570         // removes the register from the fpu stack -> the register contains no value
  3571         if (opr->is_last_use()) {
  3572           state_put(input_state, interval->assigned_reg(),   NULL);
  3573           state_put(input_state, interval->assigned_regHi(), NULL);
  3578     // invalidate all caller save registers at calls
  3579     if (visitor.has_call()) {
  3580       for (j = 0; j < FrameMap::nof_caller_save_cpu_regs(); j++) {
  3581         state_put(input_state, reg_num(FrameMap::caller_save_cpu_reg_at(j)), NULL);
  3583       for (j = 0; j < FrameMap::nof_caller_save_fpu_regs; j++) {
  3584         state_put(input_state, reg_num(FrameMap::caller_save_fpu_reg_at(j)), NULL);
  3587 #ifdef X86
  3588       for (j = 0; j < FrameMap::nof_caller_save_xmm_regs; j++) {
  3589         state_put(input_state, reg_num(FrameMap::caller_save_xmm_reg_at(j)), NULL);
  3591 #endif
  3594     // process xhandler before output and temp operands
  3595     XHandlers* xhandlers = visitor.all_xhandler();
  3596     n = xhandlers->length();
  3597     for (int k = 0; k < n; k++) {
  3598       process_xhandler(xhandlers->handler_at(k), input_state);
  3601     // set temp operands (some operations use temp operands also as output operands, so can't set them NULL)
  3602     n = visitor.opr_count(LIR_OpVisitState::tempMode);
  3603     for (j = 0; j < n; j++) {
  3604       LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::tempMode, j);
  3605       if (opr->is_register() && LinearScan::is_processed_reg_num(reg_num(opr))) {
  3606         Interval* interval = interval_at(reg_num(opr));
  3607         if (op->id() != -1) {
  3608           interval = interval->split_child_at_op_id(op->id(), LIR_OpVisitState::tempMode);
  3611         state_put(input_state, interval->assigned_reg(),   interval->split_parent());
  3612         state_put(input_state, interval->assigned_regHi(), interval->split_parent());
  3616     // set output operands
  3617     n = visitor.opr_count(LIR_OpVisitState::outputMode);
  3618     for (j = 0; j < n; j++) {
  3619       LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::outputMode, j);
  3620       if (opr->is_register() && LinearScan::is_processed_reg_num(reg_num(opr))) {
  3621         Interval* interval = interval_at(reg_num(opr));
  3622         if (op->id() != -1) {
  3623           interval = interval->split_child_at_op_id(op->id(), LIR_OpVisitState::outputMode);
  3626         state_put(input_state, interval->assigned_reg(),   interval->split_parent());
  3627         state_put(input_state, interval->assigned_regHi(), interval->split_parent());
  3631   assert(has_error == false, "Error in register allocation");
  3634 #endif // ASSERT
  3638 // **** Implementation of MoveResolver ******************************
  3640 MoveResolver::MoveResolver(LinearScan* allocator) :
  3641   _allocator(allocator),
  3642   _multiple_reads_allowed(false),
  3643   _mapping_from(8),
  3644   _mapping_from_opr(8),
  3645   _mapping_to(8),
  3646   _insert_list(NULL),
  3647   _insert_idx(-1),
  3648   _insertion_buffer()
  3650   for (int i = 0; i < LinearScan::nof_regs; i++) {
  3651     _register_blocked[i] = 0;
  3653   DEBUG_ONLY(check_empty());
  3657 #ifdef ASSERT
  3659 void MoveResolver::check_empty() {
  3660   assert(_mapping_from.length() == 0 && _mapping_from_opr.length() == 0 && _mapping_to.length() == 0, "list must be empty before and after processing");
  3661   for (int i = 0; i < LinearScan::nof_regs; i++) {
  3662     assert(register_blocked(i) == 0, "register map must be empty before and after processing");
  3664   assert(_multiple_reads_allowed == false, "must have default value");
  3667 void MoveResolver::verify_before_resolve() {
  3668   assert(_mapping_from.length() == _mapping_from_opr.length(), "length must be equal");
  3669   assert(_mapping_from.length() == _mapping_to.length(), "length must be equal");
  3670   assert(_insert_list != NULL && _insert_idx != -1, "insert position not set");
  3672   int i, j;
  3673   if (!_multiple_reads_allowed) {
  3674     for (i = 0; i < _mapping_from.length(); i++) {
  3675       for (j = i + 1; j < _mapping_from.length(); j++) {
  3676         assert(_mapping_from.at(i) == NULL || _mapping_from.at(i) != _mapping_from.at(j), "cannot read from same interval twice");
  3681   for (i = 0; i < _mapping_to.length(); i++) {
  3682     for (j = i + 1; j < _mapping_to.length(); j++) {
  3683       assert(_mapping_to.at(i) != _mapping_to.at(j), "cannot write to same interval twice");
  3688   BitMap used_regs(LinearScan::nof_regs + allocator()->frame_map()->argcount() + allocator()->max_spills());
  3689   used_regs.clear();
  3690   if (!_multiple_reads_allowed) {
  3691     for (i = 0; i < _mapping_from.length(); i++) {
  3692       Interval* it = _mapping_from.at(i);
  3693       if (it != NULL) {
  3694         assert(!used_regs.at(it->assigned_reg()), "cannot read from same register twice");
  3695         used_regs.set_bit(it->assigned_reg());
  3697         if (it->assigned_regHi() != LinearScan::any_reg) {
  3698           assert(!used_regs.at(it->assigned_regHi()), "cannot read from same register twice");
  3699           used_regs.set_bit(it->assigned_regHi());
  3705   used_regs.clear();
  3706   for (i = 0; i < _mapping_to.length(); i++) {
  3707     Interval* it = _mapping_to.at(i);
  3708     assert(!used_regs.at(it->assigned_reg()), "cannot write to same register twice");
  3709     used_regs.set_bit(it->assigned_reg());
  3711     if (it->assigned_regHi() != LinearScan::any_reg) {
  3712       assert(!used_regs.at(it->assigned_regHi()), "cannot write to same register twice");
  3713       used_regs.set_bit(it->assigned_regHi());
  3717   used_regs.clear();
  3718   for (i = 0; i < _mapping_from.length(); i++) {
  3719     Interval* it = _mapping_from.at(i);
  3720     if (it != NULL && it->assigned_reg() >= LinearScan::nof_regs) {
  3721       used_regs.set_bit(it->assigned_reg());
  3724   for (i = 0; i < _mapping_to.length(); i++) {
  3725     Interval* it = _mapping_to.at(i);
  3726     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");
  3730 #endif // ASSERT
  3733 // mark assigned_reg and assigned_regHi of the interval as blocked
  3734 void MoveResolver::block_registers(Interval* it) {
  3735   int reg = it->assigned_reg();
  3736   if (reg < LinearScan::nof_regs) {
  3737     assert(_multiple_reads_allowed || register_blocked(reg) == 0, "register already marked as used");
  3738     set_register_blocked(reg, 1);
  3740   reg = it->assigned_regHi();
  3741   if (reg != LinearScan::any_reg && reg < LinearScan::nof_regs) {
  3742     assert(_multiple_reads_allowed || register_blocked(reg) == 0, "register already marked as used");
  3743     set_register_blocked(reg, 1);
  3747 // mark assigned_reg and assigned_regHi of the interval as unblocked
  3748 void MoveResolver::unblock_registers(Interval* it) {
  3749   int reg = it->assigned_reg();
  3750   if (reg < LinearScan::nof_regs) {
  3751     assert(register_blocked(reg) > 0, "register already marked as unused");
  3752     set_register_blocked(reg, -1);
  3754   reg = it->assigned_regHi();
  3755   if (reg != LinearScan::any_reg && reg < LinearScan::nof_regs) {
  3756     assert(register_blocked(reg) > 0, "register already marked as unused");
  3757     set_register_blocked(reg, -1);
  3761 // check if assigned_reg and assigned_regHi of the to-interval are not blocked (or only blocked by from)
  3762 bool MoveResolver::save_to_process_move(Interval* from, Interval* to) {
  3763   int from_reg = -1;
  3764   int from_regHi = -1;
  3765   if (from != NULL) {
  3766     from_reg = from->assigned_reg();
  3767     from_regHi = from->assigned_regHi();
  3770   int reg = to->assigned_reg();
  3771   if (reg < LinearScan::nof_regs) {
  3772     if (register_blocked(reg) > 1 || (register_blocked(reg) == 1 && reg != from_reg && reg != from_regHi)) {
  3773       return false;
  3776   reg = to->assigned_regHi();
  3777   if (reg != LinearScan::any_reg && reg < LinearScan::nof_regs) {
  3778     if (register_blocked(reg) > 1 || (register_blocked(reg) == 1 && reg != from_reg && reg != from_regHi)) {
  3779       return false;
  3783   return true;
  3787 void MoveResolver::create_insertion_buffer(LIR_List* list) {
  3788   assert(!_insertion_buffer.initialized(), "overwriting existing buffer");
  3789   _insertion_buffer.init(list);
  3792 void MoveResolver::append_insertion_buffer() {
  3793   if (_insertion_buffer.initialized()) {
  3794     _insertion_buffer.lir_list()->append(&_insertion_buffer);
  3796   assert(!_insertion_buffer.initialized(), "must be uninitialized now");
  3798   _insert_list = NULL;
  3799   _insert_idx = -1;
  3802 void MoveResolver::insert_move(Interval* from_interval, Interval* to_interval) {
  3803   assert(from_interval->reg_num() != to_interval->reg_num(), "from and to interval equal");
  3804   assert(from_interval->type() == to_interval->type(), "move between different types");
  3805   assert(_insert_list != NULL && _insert_idx != -1, "must setup insert position first");
  3806   assert(_insertion_buffer.lir_list() == _insert_list, "wrong insertion buffer");
  3808   LIR_Opr from_opr = LIR_OprFact::virtual_register(from_interval->reg_num(), from_interval->type());
  3809   LIR_Opr to_opr = LIR_OprFact::virtual_register(to_interval->reg_num(), to_interval->type());
  3811   if (!_multiple_reads_allowed) {
  3812     // the last_use flag is an optimization for FPU stack allocation. When the same
  3813     // input interval is used in more than one move, then it is too difficult to determine
  3814     // if this move is really the last use.
  3815     from_opr = from_opr->make_last_use();
  3817   _insertion_buffer.move(_insert_idx, from_opr, to_opr);
  3819   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()));
  3822 void MoveResolver::insert_move(LIR_Opr from_opr, Interval* to_interval) {
  3823   assert(from_opr->type() == to_interval->type(), "move between different types");
  3824   assert(_insert_list != NULL && _insert_idx != -1, "must setup insert position first");
  3825   assert(_insertion_buffer.lir_list() == _insert_list, "wrong insertion buffer");
  3827   LIR_Opr to_opr = LIR_OprFact::virtual_register(to_interval->reg_num(), to_interval->type());
  3828   _insertion_buffer.move(_insert_idx, from_opr, to_opr);
  3830   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()));
  3834 void MoveResolver::resolve_mappings() {
  3835   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));
  3836   DEBUG_ONLY(verify_before_resolve());
  3838   // Block all registers that are used as input operands of a move.
  3839   // When a register is blocked, no move to this register is emitted.
  3840   // This is necessary for detecting cycles in moves.
  3841   int i;
  3842   for (i = _mapping_from.length() - 1; i >= 0; i--) {
  3843     Interval* from_interval = _mapping_from.at(i);
  3844     if (from_interval != NULL) {
  3845       block_registers(from_interval);
  3849   int spill_candidate = -1;
  3850   while (_mapping_from.length() > 0) {
  3851     bool processed_interval = false;
  3853     for (i = _mapping_from.length() - 1; i >= 0; i--) {
  3854       Interval* from_interval = _mapping_from.at(i);
  3855       Interval* to_interval = _mapping_to.at(i);
  3857       if (save_to_process_move(from_interval, to_interval)) {
  3858         // this inverval can be processed because target is free
  3859         if (from_interval != NULL) {
  3860           insert_move(from_interval, to_interval);
  3861           unblock_registers(from_interval);
  3862         } else {
  3863           insert_move(_mapping_from_opr.at(i), to_interval);
  3865         _mapping_from.remove_at(i);
  3866         _mapping_from_opr.remove_at(i);
  3867         _mapping_to.remove_at(i);
  3869         processed_interval = true;
  3870       } else if (from_interval != NULL && from_interval->assigned_reg() < LinearScan::nof_regs) {
  3871         // this interval cannot be processed now because target is not free
  3872         // it starts in a register, so it is a possible candidate for spilling
  3873         spill_candidate = i;
  3877     if (!processed_interval) {
  3878       // no move could be processed because there is a cycle in the move list
  3879       // (e.g. r1 -> r2, r2 -> r1), so one interval must be spilled to memory
  3880       assert(spill_candidate != -1, "no interval in register for spilling found");
  3882       // create a new spill interval and assign a stack slot to it
  3883       Interval* from_interval = _mapping_from.at(spill_candidate);
  3884       Interval* spill_interval = new Interval(-1);
  3885       spill_interval->set_type(from_interval->type());
  3887       // add a dummy range because real position is difficult to calculate
  3888       // Note: this range is a special case when the integrity of the allocation is checked
  3889       spill_interval->add_range(1, 2);
  3891       //       do not allocate a new spill slot for temporary interval, but
  3892       //       use spill slot assigned to from_interval. Otherwise moves from
  3893       //       one stack slot to another can happen (not allowed by LIR_Assembler
  3894       int spill_slot = from_interval->canonical_spill_slot();
  3895       if (spill_slot < 0) {
  3896         spill_slot = allocator()->allocate_spill_slot(type2spill_size[spill_interval->type()] == 2);
  3897         from_interval->set_canonical_spill_slot(spill_slot);
  3899       spill_interval->assign_reg(spill_slot);
  3900       allocator()->append_interval(spill_interval);
  3902       TRACE_LINEAR_SCAN(4, tty->print_cr("created new Interval %d for spilling", spill_interval->reg_num()));
  3904       // insert a move from register to stack and update the mapping
  3905       insert_move(from_interval, spill_interval);
  3906       _mapping_from.at_put(spill_candidate, spill_interval);
  3907       unblock_registers(from_interval);
  3911   // reset to default value
  3912   _multiple_reads_allowed = false;
  3914   // check that all intervals have been processed
  3915   DEBUG_ONLY(check_empty());
  3919 void MoveResolver::set_insert_position(LIR_List* insert_list, int insert_idx) {
  3920   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));
  3921   assert(_insert_list == NULL && _insert_idx == -1, "use move_insert_position instead of set_insert_position when data already set");
  3923   create_insertion_buffer(insert_list);
  3924   _insert_list = insert_list;
  3925   _insert_idx = insert_idx;
  3928 void MoveResolver::move_insert_position(LIR_List* insert_list, int insert_idx) {
  3929   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));
  3931   if (_insert_list != NULL && (insert_list != _insert_list || insert_idx != _insert_idx)) {
  3932     // insert position changed -> resolve current mappings
  3933     resolve_mappings();
  3936   if (insert_list != _insert_list) {
  3937     // block changed -> append insertion_buffer because it is
  3938     // bound to a specific block and create a new insertion_buffer
  3939     append_insertion_buffer();
  3940     create_insertion_buffer(insert_list);
  3943   _insert_list = insert_list;
  3944   _insert_idx = insert_idx;
  3947 void MoveResolver::add_mapping(Interval* from_interval, Interval* to_interval) {
  3948   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()));
  3950   _mapping_from.append(from_interval);
  3951   _mapping_from_opr.append(LIR_OprFact::illegalOpr);
  3952   _mapping_to.append(to_interval);
  3956 void MoveResolver::add_mapping(LIR_Opr from_opr, Interval* to_interval) {
  3957   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()));
  3958   assert(from_opr->is_constant(), "only for constants");
  3960   _mapping_from.append(NULL);
  3961   _mapping_from_opr.append(from_opr);
  3962   _mapping_to.append(to_interval);
  3965 void MoveResolver::resolve_and_append_moves() {
  3966   if (has_mappings()) {
  3967     resolve_mappings();
  3969   append_insertion_buffer();
  3974 // **** Implementation of Range *************************************
  3976 Range::Range(int from, int to, Range* next) :
  3977   _from(from),
  3978   _to(to),
  3979   _next(next)
  3983 // initialize sentinel
  3984 Range* Range::_end = NULL;
  3985 void Range::initialize(Arena* arena) {
  3986   _end = new (arena) Range(max_jint, max_jint, NULL);
  3989 int Range::intersects_at(Range* r2) const {
  3990   const Range* r1 = this;
  3992   assert(r1 != NULL && r2 != NULL, "null ranges not allowed");
  3993   assert(r1 != _end && r2 != _end, "empty ranges not allowed");
  3995   do {
  3996     if (r1->from() < r2->from()) {
  3997       if (r1->to() <= r2->from()) {
  3998         r1 = r1->next(); if (r1 == _end) return -1;
  3999       } else {
  4000         return r2->from();
  4002     } else if (r2->from() < r1->from()) {
  4003       if (r2->to() <= r1->from()) {
  4004         r2 = r2->next(); if (r2 == _end) return -1;
  4005       } else {
  4006         return r1->from();
  4008     } else { // r1->from() == r2->from()
  4009       if (r1->from() == r1->to()) {
  4010         r1 = r1->next(); if (r1 == _end) return -1;
  4011       } else if (r2->from() == r2->to()) {
  4012         r2 = r2->next(); if (r2 == _end) return -1;
  4013       } else {
  4014         return r1->from();
  4017   } while (true);
  4020 #ifndef PRODUCT
  4021 void Range::print(outputStream* out) const {
  4022   out->print("[%d, %d[ ", _from, _to);
  4024 #endif
  4028 // **** Implementation of Interval **********************************
  4030 // initialize sentinel
  4031 Interval* Interval::_end = NULL;
  4032 void Interval::initialize(Arena* arena) {
  4033   Range::initialize(arena);
  4034   _end = new (arena) Interval(-1);
  4037 Interval::Interval(int reg_num) :
  4038   _reg_num(reg_num),
  4039   _type(T_ILLEGAL),
  4040   _first(Range::end()),
  4041   _use_pos_and_kinds(12),
  4042   _current(Range::end()),
  4043   _next(_end),
  4044   _state(invalidState),
  4045   _assigned_reg(LinearScan::any_reg),
  4046   _assigned_regHi(LinearScan::any_reg),
  4047   _cached_to(-1),
  4048   _cached_opr(LIR_OprFact::illegalOpr),
  4049   _cached_vm_reg(VMRegImpl::Bad()),
  4050   _split_children(0),
  4051   _canonical_spill_slot(-1),
  4052   _insert_move_when_activated(false),
  4053   _register_hint(NULL),
  4054   _spill_state(noDefinitionFound),
  4055   _spill_definition_pos(-1)
  4057   _split_parent = this;
  4058   _current_split_child = this;
  4061 int Interval::calc_to() {
  4062   assert(_first != Range::end(), "interval has no range");
  4064   Range* r = _first;
  4065   while (r->next() != Range::end()) {
  4066     r = r->next();
  4068   return r->to();
  4072 #ifdef ASSERT
  4073 // consistency check of split-children
  4074 void Interval::check_split_children() {
  4075   if (_split_children.length() > 0) {
  4076     assert(is_split_parent(), "only split parents can have children");
  4078     for (int i = 0; i < _split_children.length(); i++) {
  4079       Interval* i1 = _split_children.at(i);
  4081       assert(i1->split_parent() == this, "not a split child of this interval");
  4082       assert(i1->type() == type(), "must be equal for all split children");
  4083       assert(i1->canonical_spill_slot() == canonical_spill_slot(), "must be equal for all split children");
  4085       for (int j = i + 1; j < _split_children.length(); j++) {
  4086         Interval* i2 = _split_children.at(j);
  4088         assert(i1->reg_num() != i2->reg_num(), "same register number");
  4090         if (i1->from() < i2->from()) {
  4091           assert(i1->to() <= i2->from() && i1->to() < i2->to(), "intervals overlapping");
  4092         } else {
  4093           assert(i2->from() < i1->from(), "intervals start at same op_id");
  4094           assert(i2->to() <= i1->from() && i2->to() < i1->to(), "intervals overlapping");
  4100 #endif // ASSERT
  4102 Interval* Interval::register_hint(bool search_split_child) const {
  4103   if (!search_split_child) {
  4104     return _register_hint;
  4107   if (_register_hint != NULL) {
  4108     assert(_register_hint->is_split_parent(), "ony split parents are valid hint registers");
  4110     if (_register_hint->assigned_reg() >= 0 && _register_hint->assigned_reg() < LinearScan::nof_regs) {
  4111       return _register_hint;
  4113     } else if (_register_hint->_split_children.length() > 0) {
  4114       // search the first split child that has a register assigned
  4115       int len = _register_hint->_split_children.length();
  4116       for (int i = 0; i < len; i++) {
  4117         Interval* cur = _register_hint->_split_children.at(i);
  4119         if (cur->assigned_reg() >= 0 && cur->assigned_reg() < LinearScan::nof_regs) {
  4120           return cur;
  4126   // no hint interval found that has a register assigned
  4127   return NULL;
  4131 Interval* Interval::split_child_at_op_id(int op_id, LIR_OpVisitState::OprMode mode) {
  4132   assert(is_split_parent(), "can only be called for split parents");
  4133   assert(op_id >= 0, "invalid op_id (method can not be called for spill moves)");
  4135   Interval* result;
  4136   if (_split_children.length() == 0) {
  4137     result = this;
  4138   } else {
  4139     result = NULL;
  4140     int len = _split_children.length();
  4142     // in outputMode, the end of the interval (op_id == cur->to()) is not valid
  4143     int to_offset = (mode == LIR_OpVisitState::outputMode ? 0 : 1);
  4145     int i;
  4146     for (i = 0; i < len; i++) {
  4147       Interval* cur = _split_children.at(i);
  4148       if (cur->from() <= op_id && op_id < cur->to() + to_offset) {
  4149         if (i > 0) {
  4150           // exchange current split child to start of list (faster access for next call)
  4151           _split_children.at_put(i, _split_children.at(0));
  4152           _split_children.at_put(0, cur);
  4155         // interval found
  4156         result = cur;
  4157         break;
  4161 #ifdef ASSERT
  4162     for (i = 0; i < len; i++) {
  4163       Interval* tmp = _split_children.at(i);
  4164       if (tmp != result && tmp->from() <= op_id && op_id < tmp->to() + to_offset) {
  4165         tty->print_cr("two valid result intervals found for op_id %d: %d and %d", op_id, result->reg_num(), tmp->reg_num());
  4166         result->print();
  4167         tmp->print();
  4168         assert(false, "two valid result intervals found");
  4171 #endif
  4174   assert(result != NULL, "no matching interval found");
  4175   assert(result->covers(op_id, mode), "op_id not covered by interval");
  4177   return result;
  4181 // returns the last split child that ends before the given op_id
  4182 Interval* Interval::split_child_before_op_id(int op_id) {
  4183   assert(op_id >= 0, "invalid op_id");
  4185   Interval* parent = split_parent();
  4186   Interval* result = NULL;
  4188   int len = parent->_split_children.length();
  4189   assert(len > 0, "no split children available");
  4191   for (int i = len - 1; i >= 0; i--) {
  4192     Interval* cur = parent->_split_children.at(i);
  4193     if (cur->to() <= op_id && (result == NULL || result->to() < cur->to())) {
  4194       result = cur;
  4198   assert(result != NULL, "no split child found");
  4199   return result;
  4203 // checks if op_id is covered by any split child
  4204 bool Interval::split_child_covers(int op_id, LIR_OpVisitState::OprMode mode) {
  4205   assert(is_split_parent(), "can only be called for split parents");
  4206   assert(op_id >= 0, "invalid op_id (method can not be called for spill moves)");
  4208   if (_split_children.length() == 0) {
  4209     // simple case if interval was not split
  4210     return covers(op_id, mode);
  4212   } else {
  4213     // extended case: check all split children
  4214     int len = _split_children.length();
  4215     for (int i = 0; i < len; i++) {
  4216       Interval* cur = _split_children.at(i);
  4217       if (cur->covers(op_id, mode)) {
  4218         return true;
  4221     return false;
  4226 // Note: use positions are sorted descending -> first use has highest index
  4227 int Interval::first_usage(IntervalUseKind min_use_kind) const {
  4228   assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");
  4230   for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {
  4231     if (_use_pos_and_kinds.at(i + 1) >= min_use_kind) {
  4232       return _use_pos_and_kinds.at(i);
  4235   return max_jint;
  4238 int Interval::next_usage(IntervalUseKind min_use_kind, int from) const {
  4239   assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");
  4241   for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {
  4242     if (_use_pos_and_kinds.at(i) >= from && _use_pos_and_kinds.at(i + 1) >= min_use_kind) {
  4243       return _use_pos_and_kinds.at(i);
  4246   return max_jint;
  4249 int Interval::next_usage_exact(IntervalUseKind exact_use_kind, int from) const {
  4250   assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");
  4252   for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {
  4253     if (_use_pos_and_kinds.at(i) >= from && _use_pos_and_kinds.at(i + 1) == exact_use_kind) {
  4254       return _use_pos_and_kinds.at(i);
  4257   return max_jint;
  4260 int Interval::previous_usage(IntervalUseKind min_use_kind, int from) const {
  4261   assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");
  4263   int prev = 0;
  4264   for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {
  4265     if (_use_pos_and_kinds.at(i) > from) {
  4266       return prev;
  4268     if (_use_pos_and_kinds.at(i + 1) >= min_use_kind) {
  4269       prev = _use_pos_and_kinds.at(i);
  4272   return prev;
  4275 void Interval::add_use_pos(int pos, IntervalUseKind use_kind) {
  4276   assert(covers(pos, LIR_OpVisitState::inputMode), "use position not covered by live range");
  4278   // do not add use positions for precolored intervals because
  4279   // they are never used
  4280   if (use_kind != noUse && reg_num() >= LIR_OprDesc::vreg_base) {
  4281 #ifdef ASSERT
  4282     assert(_use_pos_and_kinds.length() % 2 == 0, "must be");
  4283     for (int i = 0; i < _use_pos_and_kinds.length(); i += 2) {
  4284       assert(pos <= _use_pos_and_kinds.at(i), "already added a use-position with lower position");
  4285       assert(_use_pos_and_kinds.at(i + 1) >= firstValidKind && _use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");
  4286       if (i > 0) {
  4287         assert(_use_pos_and_kinds.at(i) < _use_pos_and_kinds.at(i - 2), "not sorted descending");
  4290 #endif
  4292     // Note: add_use is called in descending order, so list gets sorted
  4293     //       automatically by just appending new use positions
  4294     int len = _use_pos_and_kinds.length();
  4295     if (len == 0 || _use_pos_and_kinds.at(len - 2) > pos) {
  4296       _use_pos_and_kinds.append(pos);
  4297       _use_pos_and_kinds.append(use_kind);
  4298     } else if (_use_pos_and_kinds.at(len - 1) < use_kind) {
  4299       assert(_use_pos_and_kinds.at(len - 2) == pos, "list not sorted correctly");
  4300       _use_pos_and_kinds.at_put(len - 1, use_kind);
  4305 void Interval::add_range(int from, int to) {
  4306   assert(from < to, "invalid range");
  4307   assert(first() == Range::end() || to < first()->next()->from(), "not inserting at begin of interval");
  4308   assert(from <= first()->to(), "not inserting at begin of interval");
  4310   if (first()->from() <= to) {
  4311     // join intersecting ranges
  4312     first()->set_from(MIN2(from, first()->from()));
  4313     first()->set_to  (MAX2(to,   first()->to()));
  4314   } else {
  4315     // insert new range
  4316     _first = new Range(from, to, first());
  4320 Interval* Interval::new_split_child() {
  4321   // allocate new interval
  4322   Interval* result = new Interval(-1);
  4323   result->set_type(type());
  4325   Interval* parent = split_parent();
  4326   result->_split_parent = parent;
  4327   result->set_register_hint(parent);
  4329   // insert new interval in children-list of parent
  4330   if (parent->_split_children.length() == 0) {
  4331     assert(is_split_parent(), "list must be initialized at first split");
  4333     parent->_split_children = IntervalList(4);
  4334     parent->_split_children.append(this);
  4336   parent->_split_children.append(result);
  4338   return result;
  4341 // split this interval at the specified position and return
  4342 // the remainder as a new interval.
  4343 //
  4344 // when an interval is split, a bi-directional link is established between the original interval
  4345 // (the split parent) and the intervals that are split off this interval (the split children)
  4346 // When a split child is split again, the new created interval is also a direct child
  4347 // of the original parent (there is no tree of split children stored, but a flat list)
  4348 // All split children are spilled to the same stack slot (stored in _canonical_spill_slot)
  4349 //
  4350 // Note: The new interval has no valid reg_num
  4351 Interval* Interval::split(int split_pos) {
  4352   assert(LinearScan::is_virtual_interval(this), "cannot split fixed intervals");
  4354   // allocate new interval
  4355   Interval* result = new_split_child();
  4357   // split the ranges
  4358   Range* prev = NULL;
  4359   Range* cur = _first;
  4360   while (cur != Range::end() && cur->to() <= split_pos) {
  4361     prev = cur;
  4362     cur = cur->next();
  4364   assert(cur != Range::end(), "split interval after end of last range");
  4366   if (cur->from() < split_pos) {
  4367     result->_first = new Range(split_pos, cur->to(), cur->next());
  4368     cur->set_to(split_pos);
  4369     cur->set_next(Range::end());
  4371   } else {
  4372     assert(prev != NULL, "split before start of first range");
  4373     result->_first = cur;
  4374     prev->set_next(Range::end());
  4376   result->_current = result->_first;
  4377   _cached_to = -1; // clear cached value
  4379   // split list of use positions
  4380   int total_len = _use_pos_and_kinds.length();
  4381   int start_idx = total_len - 2;
  4382   while (start_idx >= 0 && _use_pos_and_kinds.at(start_idx) < split_pos) {
  4383     start_idx -= 2;
  4386   intStack new_use_pos_and_kinds(total_len - start_idx);
  4387   int i;
  4388   for (i = start_idx + 2; i < total_len; i++) {
  4389     new_use_pos_and_kinds.append(_use_pos_and_kinds.at(i));
  4392   _use_pos_and_kinds.truncate(start_idx + 2);
  4393   result->_use_pos_and_kinds = _use_pos_and_kinds;
  4394   _use_pos_and_kinds = new_use_pos_and_kinds;
  4396 #ifdef ASSERT
  4397   assert(_use_pos_and_kinds.length() % 2 == 0, "must have use kind for each use pos");
  4398   assert(result->_use_pos_and_kinds.length() % 2 == 0, "must have use kind for each use pos");
  4399   assert(_use_pos_and_kinds.length() + result->_use_pos_and_kinds.length() == total_len, "missed some entries");
  4401   for (i = 0; i < _use_pos_and_kinds.length(); i += 2) {
  4402     assert(_use_pos_and_kinds.at(i) < split_pos, "must be");
  4403     assert(_use_pos_and_kinds.at(i + 1) >= firstValidKind && _use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");
  4405   for (i = 0; i < result->_use_pos_and_kinds.length(); i += 2) {
  4406     assert(result->_use_pos_and_kinds.at(i) >= split_pos, "must be");
  4407     assert(result->_use_pos_and_kinds.at(i + 1) >= firstValidKind && result->_use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");
  4409 #endif
  4411   return result;
  4414 // split this interval at the specified position and return
  4415 // the head as a new interval (the original interval is the tail)
  4416 //
  4417 // Currently, only the first range can be split, and the new interval
  4418 // must not have split positions
  4419 Interval* Interval::split_from_start(int split_pos) {
  4420   assert(LinearScan::is_virtual_interval(this), "cannot split fixed intervals");
  4421   assert(split_pos > from() && split_pos < to(), "can only split inside interval");
  4422   assert(split_pos > _first->from() && split_pos <= _first->to(), "can only split inside first range");
  4423   assert(first_usage(noUse) > split_pos, "can not split when use positions are present");
  4425   // allocate new interval
  4426   Interval* result = new_split_child();
  4428   // the new created interval has only one range (checked by assertion above),
  4429   // so the splitting of the ranges is very simple
  4430   result->add_range(_first->from(), split_pos);
  4432   if (split_pos == _first->to()) {
  4433     assert(_first->next() != Range::end(), "must not be at end");
  4434     _first = _first->next();
  4435   } else {
  4436     _first->set_from(split_pos);
  4439   return result;
  4443 // returns true if the op_id is inside the interval
  4444 bool Interval::covers(int op_id, LIR_OpVisitState::OprMode mode) const {
  4445   Range* cur  = _first;
  4447   while (cur != Range::end() && cur->to() < op_id) {
  4448     cur = cur->next();
  4450   if (cur != Range::end()) {
  4451     assert(cur->to() != cur->next()->from(), "ranges not separated");
  4453     if (mode == LIR_OpVisitState::outputMode) {
  4454       return cur->from() <= op_id && op_id < cur->to();
  4455     } else {
  4456       return cur->from() <= op_id && op_id <= cur->to();
  4459   return false;
  4462 // returns true if the interval has any hole between hole_from and hole_to
  4463 // (even if the hole has only the length 1)
  4464 bool Interval::has_hole_between(int hole_from, int hole_to) {
  4465   assert(hole_from < hole_to, "check");
  4466   assert(from() <= hole_from && hole_to <= to(), "index out of interval");
  4468   Range* cur  = _first;
  4469   while (cur != Range::end()) {
  4470     assert(cur->to() < cur->next()->from(), "no space between ranges");
  4472     // hole-range starts before this range -> hole
  4473     if (hole_from < cur->from()) {
  4474       return true;
  4476     // hole-range completely inside this range -> no hole
  4477     } else if (hole_to <= cur->to()) {
  4478       return false;
  4480     // overlapping of hole-range with this range -> hole
  4481     } else if (hole_from <= cur->to()) {
  4482       return true;
  4485     cur = cur->next();
  4488   return false;
  4492 #ifndef PRODUCT
  4493 void Interval::print(outputStream* out) const {
  4494   const char* SpillState2Name[] = { "no definition", "no spill store", "one spill store", "store at definition", "start in memory", "no optimization" };
  4495   const char* UseKind2Name[] = { "N", "L", "S", "M" };
  4497   const char* type_name;
  4498   LIR_Opr opr = LIR_OprFact::illegal();
  4499   if (reg_num() < LIR_OprDesc::vreg_base) {
  4500     type_name = "fixed";
  4501     // need a temporary operand for fixed intervals because type() cannot be called
  4502     if (assigned_reg() >= pd_first_cpu_reg && assigned_reg() <= pd_last_cpu_reg) {
  4503       opr = LIR_OprFact::single_cpu(assigned_reg());
  4504     } else if (assigned_reg() >= pd_first_fpu_reg && assigned_reg() <= pd_last_fpu_reg) {
  4505       opr = LIR_OprFact::single_fpu(assigned_reg() - pd_first_fpu_reg);
  4506 #ifdef X86
  4507     } else if (assigned_reg() >= pd_first_xmm_reg && assigned_reg() <= pd_last_xmm_reg) {
  4508       opr = LIR_OprFact::single_xmm(assigned_reg() - pd_first_xmm_reg);
  4509 #endif
  4510     } else {
  4511       ShouldNotReachHere();
  4513   } else {
  4514     type_name = type2name(type());
  4515     if (assigned_reg() != -1 &&
  4516         (LinearScan::num_physical_regs(type()) == 1 || assigned_regHi() != -1)) {
  4517       opr = LinearScan::calc_operand_for_interval(this);
  4521   out->print("%d %s ", reg_num(), type_name);
  4522   if (opr->is_valid()) {
  4523     out->print("\"");
  4524     opr->print(out);
  4525     out->print("\" ");
  4527   out->print("%d %d ", split_parent()->reg_num(), (register_hint(false) != NULL ? register_hint(false)->reg_num() : -1));
  4529   // print ranges
  4530   Range* cur = _first;
  4531   while (cur != Range::end()) {
  4532     cur->print(out);
  4533     cur = cur->next();
  4534     assert(cur != NULL, "range list not closed with range sentinel");
  4537   // print use positions
  4538   int prev = 0;
  4539   assert(_use_pos_and_kinds.length() % 2 == 0, "must be");
  4540   for (int i =_use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {
  4541     assert(_use_pos_and_kinds.at(i + 1) >= firstValidKind && _use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");
  4542     assert(prev < _use_pos_and_kinds.at(i), "use positions not sorted");
  4544     out->print("%d %s ", _use_pos_and_kinds.at(i), UseKind2Name[_use_pos_and_kinds.at(i + 1)]);
  4545     prev = _use_pos_and_kinds.at(i);
  4548   out->print(" \"%s\"", SpillState2Name[spill_state()]);
  4549   out->cr();
  4551 #endif
  4555 // **** Implementation of IntervalWalker ****************************
  4557 IntervalWalker::IntervalWalker(LinearScan* allocator, Interval* unhandled_fixed_first, Interval* unhandled_any_first)
  4558  : _compilation(allocator->compilation())
  4559  , _allocator(allocator)
  4561   _unhandled_first[fixedKind] = unhandled_fixed_first;
  4562   _unhandled_first[anyKind]   = unhandled_any_first;
  4563   _active_first[fixedKind]    = Interval::end();
  4564   _inactive_first[fixedKind]  = Interval::end();
  4565   _active_first[anyKind]      = Interval::end();
  4566   _inactive_first[anyKind]    = Interval::end();
  4567   _current_position = -1;
  4568   _current = NULL;
  4569   next_interval();
  4573 // append interval at top of list
  4574 void IntervalWalker::append_unsorted(Interval** list, Interval* interval) {
  4575   interval->set_next(*list); *list = interval;
  4579 // append interval in order of current range from()
  4580 void IntervalWalker::append_sorted(Interval** list, Interval* interval) {
  4581   Interval* prev = NULL;
  4582   Interval* cur  = *list;
  4583   while (cur->current_from() < interval->current_from()) {
  4584     prev = cur; cur = cur->next();
  4586   if (prev == NULL) {
  4587     *list = interval;
  4588   } else {
  4589     prev->set_next(interval);
  4591   interval->set_next(cur);
  4594 void IntervalWalker::append_to_unhandled(Interval** list, Interval* interval) {
  4595   assert(interval->from() >= current()->current_from(), "cannot append new interval before current walk position");
  4597   Interval* prev = NULL;
  4598   Interval* cur  = *list;
  4599   while (cur->from() < interval->from() || (cur->from() == interval->from() && cur->first_usage(noUse) < interval->first_usage(noUse))) {
  4600     prev = cur; cur = cur->next();
  4602   if (prev == NULL) {
  4603     *list = interval;
  4604   } else {
  4605     prev->set_next(interval);
  4607   interval->set_next(cur);
  4611 inline bool IntervalWalker::remove_from_list(Interval** list, Interval* i) {
  4612   while (*list != Interval::end() && *list != i) {
  4613     list = (*list)->next_addr();
  4615   if (*list != Interval::end()) {
  4616     assert(*list == i, "check");
  4617     *list = (*list)->next();
  4618     return true;
  4619   } else {
  4620     return false;
  4624 void IntervalWalker::remove_from_list(Interval* i) {
  4625   bool deleted;
  4627   if (i->state() == activeState) {
  4628     deleted = remove_from_list(active_first_addr(anyKind), i);
  4629   } else {
  4630     assert(i->state() == inactiveState, "invalid state");
  4631     deleted = remove_from_list(inactive_first_addr(anyKind), i);
  4634   assert(deleted, "interval has not been found in list");
  4638 void IntervalWalker::walk_to(IntervalState state, int from) {
  4639   assert (state == activeState || state == inactiveState, "wrong state");
  4640   for_each_interval_kind(kind) {
  4641     Interval** prev = state == activeState ? active_first_addr(kind) : inactive_first_addr(kind);
  4642     Interval* next   = *prev;
  4643     while (next->current_from() <= from) {
  4644       Interval* cur = next;
  4645       next = cur->next();
  4647       bool range_has_changed = false;
  4648       while (cur->current_to() <= from) {
  4649         cur->next_range();
  4650         range_has_changed = true;
  4653       // also handle move from inactive list to active list
  4654       range_has_changed = range_has_changed || (state == inactiveState && cur->current_from() <= from);
  4656       if (range_has_changed) {
  4657         // remove cur from list
  4658         *prev = next;
  4659         if (cur->current_at_end()) {
  4660           // move to handled state (not maintained as a list)
  4661           cur->set_state(handledState);
  4662           interval_moved(cur, kind, state, handledState);
  4663         } else if (cur->current_from() <= from){
  4664           // sort into active list
  4665           append_sorted(active_first_addr(kind), cur);
  4666           cur->set_state(activeState);
  4667           if (*prev == cur) {
  4668             assert(state == activeState, "check");
  4669             prev = cur->next_addr();
  4671           interval_moved(cur, kind, state, activeState);
  4672         } else {
  4673           // sort into inactive list
  4674           append_sorted(inactive_first_addr(kind), cur);
  4675           cur->set_state(inactiveState);
  4676           if (*prev == cur) {
  4677             assert(state == inactiveState, "check");
  4678             prev = cur->next_addr();
  4680           interval_moved(cur, kind, state, inactiveState);
  4682       } else {
  4683         prev = cur->next_addr();
  4684         continue;
  4691 void IntervalWalker::next_interval() {
  4692   IntervalKind kind;
  4693   Interval* any   = _unhandled_first[anyKind];
  4694   Interval* fixed = _unhandled_first[fixedKind];
  4696   if (any != Interval::end()) {
  4697     // intervals may start at same position -> prefer fixed interval
  4698     kind = fixed != Interval::end() && fixed->from() <= any->from() ? fixedKind : anyKind;
  4700     assert (kind == fixedKind && fixed->from() <= any->from() ||
  4701             kind == anyKind   && any->from() <= fixed->from(), "wrong interval!!!");
  4702     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");
  4704   } else if (fixed != Interval::end()) {
  4705     kind = fixedKind;
  4706   } else {
  4707     _current = NULL; return;
  4709   _current_kind = kind;
  4710   _current = _unhandled_first[kind];
  4711   _unhandled_first[kind] = _current->next();
  4712   _current->set_next(Interval::end());
  4713   _current->rewind_range();
  4717 void IntervalWalker::walk_to(int lir_op_id) {
  4718   assert(_current_position <= lir_op_id, "can not walk backwards");
  4719   while (current() != NULL) {
  4720     bool is_active = current()->from() <= lir_op_id;
  4721     int id = is_active ? current()->from() : lir_op_id;
  4723     TRACE_LINEAR_SCAN(2, if (_current_position < id) { tty->cr(); tty->print_cr("walk_to(%d) **************************************************************", id); })
  4725     // set _current_position prior to call of walk_to
  4726     _current_position = id;
  4728     // call walk_to even if _current_position == id
  4729     walk_to(activeState, id);
  4730     walk_to(inactiveState, id);
  4732     if (is_active) {
  4733       current()->set_state(activeState);
  4734       if (activate_current()) {
  4735         append_sorted(active_first_addr(current_kind()), current());
  4736         interval_moved(current(), current_kind(), unhandledState, activeState);
  4739       next_interval();
  4740     } else {
  4741       return;
  4746 void IntervalWalker::interval_moved(Interval* interval, IntervalKind kind, IntervalState from, IntervalState to) {
  4747 #ifndef PRODUCT
  4748   if (TraceLinearScanLevel >= 4) {
  4749     #define print_state(state) \
  4750     switch(state) {\
  4751       case unhandledState: tty->print("unhandled"); break;\
  4752       case activeState: tty->print("active"); break;\
  4753       case inactiveState: tty->print("inactive"); break;\
  4754       case handledState: tty->print("handled"); break;\
  4755       default: ShouldNotReachHere(); \
  4758     print_state(from); tty->print(" to "); print_state(to);
  4759     tty->fill_to(23);
  4760     interval->print();
  4762     #undef print_state
  4764 #endif
  4769 // **** Implementation of LinearScanWalker **************************
  4771 LinearScanWalker::LinearScanWalker(LinearScan* allocator, Interval* unhandled_fixed_first, Interval* unhandled_any_first)
  4772   : IntervalWalker(allocator, unhandled_fixed_first, unhandled_any_first)
  4773   , _move_resolver(allocator)
  4775   for (int i = 0; i < LinearScan::nof_regs; i++) {
  4776     _spill_intervals[i] = new IntervalList(2);
  4781 inline void LinearScanWalker::init_use_lists(bool only_process_use_pos) {
  4782   for (int i = _first_reg; i <= _last_reg; i++) {
  4783     _use_pos[i] = max_jint;
  4785     if (!only_process_use_pos) {
  4786       _block_pos[i] = max_jint;
  4787       _spill_intervals[i]->clear();
  4792 inline void LinearScanWalker::exclude_from_use(int reg) {
  4793   assert(reg < LinearScan::nof_regs, "interval must have a register assigned (stack slots not allowed)");
  4794   if (reg >= _first_reg && reg <= _last_reg) {
  4795     _use_pos[reg] = 0;
  4798 inline void LinearScanWalker::exclude_from_use(Interval* i) {
  4799   assert(i->assigned_reg() != any_reg, "interval has no register assigned");
  4801   exclude_from_use(i->assigned_reg());
  4802   exclude_from_use(i->assigned_regHi());
  4805 inline void LinearScanWalker::set_use_pos(int reg, Interval* i, int use_pos, bool only_process_use_pos) {
  4806   assert(use_pos != 0, "must use exclude_from_use to set use_pos to 0");
  4808   if (reg >= _first_reg && reg <= _last_reg) {
  4809     if (_use_pos[reg] > use_pos) {
  4810       _use_pos[reg] = use_pos;
  4812     if (!only_process_use_pos) {
  4813       _spill_intervals[reg]->append(i);
  4817 inline void LinearScanWalker::set_use_pos(Interval* i, int use_pos, bool only_process_use_pos) {
  4818   assert(i->assigned_reg() != any_reg, "interval has no register assigned");
  4819   if (use_pos != -1) {
  4820     set_use_pos(i->assigned_reg(), i, use_pos, only_process_use_pos);
  4821     set_use_pos(i->assigned_regHi(), i, use_pos, only_process_use_pos);
  4825 inline void LinearScanWalker::set_block_pos(int reg, Interval* i, int block_pos) {
  4826   if (reg >= _first_reg && reg <= _last_reg) {
  4827     if (_block_pos[reg] > block_pos) {
  4828       _block_pos[reg] = block_pos;
  4830     if (_use_pos[reg] > block_pos) {
  4831       _use_pos[reg] = block_pos;
  4835 inline void LinearScanWalker::set_block_pos(Interval* i, int block_pos) {
  4836   assert(i->assigned_reg() != any_reg, "interval has no register assigned");
  4837   if (block_pos != -1) {
  4838     set_block_pos(i->assigned_reg(), i, block_pos);
  4839     set_block_pos(i->assigned_regHi(), i, block_pos);
  4844 void LinearScanWalker::free_exclude_active_fixed() {
  4845   Interval* list = active_first(fixedKind);
  4846   while (list != Interval::end()) {
  4847     assert(list->assigned_reg() < LinearScan::nof_regs, "active interval must have a register assigned");
  4848     exclude_from_use(list);
  4849     list = list->next();
  4853 void LinearScanWalker::free_exclude_active_any() {
  4854   Interval* list = active_first(anyKind);
  4855   while (list != Interval::end()) {
  4856     exclude_from_use(list);
  4857     list = list->next();
  4861 void LinearScanWalker::free_collect_inactive_fixed(Interval* cur) {
  4862   Interval* list = inactive_first(fixedKind);
  4863   while (list != Interval::end()) {
  4864     if (cur->to() <= list->current_from()) {
  4865       assert(list->current_intersects_at(cur) == -1, "must not intersect");
  4866       set_use_pos(list, list->current_from(), true);
  4867     } else {
  4868       set_use_pos(list, list->current_intersects_at(cur), true);
  4870     list = list->next();
  4874 void LinearScanWalker::free_collect_inactive_any(Interval* cur) {
  4875   Interval* list = inactive_first(anyKind);
  4876   while (list != Interval::end()) {
  4877     set_use_pos(list, list->current_intersects_at(cur), true);
  4878     list = list->next();
  4882 void LinearScanWalker::free_collect_unhandled(IntervalKind kind, Interval* cur) {
  4883   Interval* list = unhandled_first(kind);
  4884   while (list != Interval::end()) {
  4885     set_use_pos(list, list->intersects_at(cur), true);
  4886     if (kind == fixedKind && cur->to() <= list->from()) {
  4887       set_use_pos(list, list->from(), true);
  4889     list = list->next();
  4893 void LinearScanWalker::spill_exclude_active_fixed() {
  4894   Interval* list = active_first(fixedKind);
  4895   while (list != Interval::end()) {
  4896     exclude_from_use(list);
  4897     list = list->next();
  4901 void LinearScanWalker::spill_block_unhandled_fixed(Interval* cur) {
  4902   Interval* list = unhandled_first(fixedKind);
  4903   while (list != Interval::end()) {
  4904     set_block_pos(list, list->intersects_at(cur));
  4905     list = list->next();
  4909 void LinearScanWalker::spill_block_inactive_fixed(Interval* cur) {
  4910   Interval* list = inactive_first(fixedKind);
  4911   while (list != Interval::end()) {
  4912     if (cur->to() > list->current_from()) {
  4913       set_block_pos(list, list->current_intersects_at(cur));
  4914     } else {
  4915       assert(list->current_intersects_at(cur) == -1, "invalid optimization: intervals intersect");
  4918     list = list->next();
  4922 void LinearScanWalker::spill_collect_active_any() {
  4923   Interval* list = active_first(anyKind);
  4924   while (list != Interval::end()) {
  4925     set_use_pos(list, MIN2(list->next_usage(loopEndMarker, _current_position), list->to()), false);
  4926     list = list->next();
  4930 void LinearScanWalker::spill_collect_inactive_any(Interval* cur) {
  4931   Interval* list = inactive_first(anyKind);
  4932   while (list != Interval::end()) {
  4933     if (list->current_intersects(cur)) {
  4934       set_use_pos(list, MIN2(list->next_usage(loopEndMarker, _current_position), list->to()), false);
  4936     list = list->next();
  4941 void LinearScanWalker::insert_move(int op_id, Interval* src_it, Interval* dst_it) {
  4942   // output all moves here. When source and target are equal, the move is
  4943   // optimized away later in assign_reg_nums
  4945   op_id = (op_id + 1) & ~1;
  4946   BlockBegin* op_block = allocator()->block_of_op_with_id(op_id);
  4947   assert(op_id > 0 && allocator()->block_of_op_with_id(op_id - 2) == op_block, "cannot insert move at block boundary");
  4949   // calculate index of instruction inside instruction list of current block
  4950   // the minimal index (for a block with no spill moves) can be calculated because the
  4951   // numbering of instructions is known.
  4952   // When the block already contains spill moves, the index must be increased until the
  4953   // correct index is reached.
  4954   LIR_OpList* list = op_block->lir()->instructions_list();
  4955   int index = (op_id - list->at(0)->id()) / 2;
  4956   assert(list->at(index)->id() <= op_id, "error in calculation");
  4958   while (list->at(index)->id() != op_id) {
  4959     index++;
  4960     assert(0 <= index && index < list->length(), "index out of bounds");
  4962   assert(1 <= index && index < list->length(), "index out of bounds");
  4963   assert(list->at(index)->id() == op_id, "error in calculation");
  4965   // insert new instruction before instruction at position index
  4966   _move_resolver.move_insert_position(op_block->lir(), index - 1);
  4967   _move_resolver.add_mapping(src_it, dst_it);
  4971 int LinearScanWalker::find_optimal_split_pos(BlockBegin* min_block, BlockBegin* max_block, int max_split_pos) {
  4972   int from_block_nr = min_block->linear_scan_number();
  4973   int to_block_nr = max_block->linear_scan_number();
  4975   assert(0 <= from_block_nr && from_block_nr < block_count(), "out of range");
  4976   assert(0 <= to_block_nr && to_block_nr < block_count(), "out of range");
  4977   assert(from_block_nr < to_block_nr, "must cross block boundary");
  4979   // Try to split at end of max_block. If this would be after
  4980   // max_split_pos, then use the begin of max_block
  4981   int optimal_split_pos = max_block->last_lir_instruction_id() + 2;
  4982   if (optimal_split_pos > max_split_pos) {
  4983     optimal_split_pos = max_block->first_lir_instruction_id();
  4986   int min_loop_depth = max_block->loop_depth();
  4987   for (int i = to_block_nr - 1; i >= from_block_nr; i--) {
  4988     BlockBegin* cur = block_at(i);
  4990     if (cur->loop_depth() < min_loop_depth) {
  4991       // block with lower loop-depth found -> split at the end of this block
  4992       min_loop_depth = cur->loop_depth();
  4993       optimal_split_pos = cur->last_lir_instruction_id() + 2;
  4996   assert(optimal_split_pos > allocator()->max_lir_op_id() || allocator()->is_block_begin(optimal_split_pos), "algorithm must move split pos to block boundary");
  4998   return optimal_split_pos;
  5002 int LinearScanWalker::find_optimal_split_pos(Interval* it, int min_split_pos, int max_split_pos, bool do_loop_optimization) {
  5003   int optimal_split_pos = -1;
  5004   if (min_split_pos == max_split_pos) {
  5005     // trivial case, no optimization of split position possible
  5006     TRACE_LINEAR_SCAN(4, tty->print_cr("      min-pos and max-pos are equal, no optimization possible"));
  5007     optimal_split_pos = min_split_pos;
  5009   } else {
  5010     assert(min_split_pos < max_split_pos, "must be true then");
  5011     assert(min_split_pos > 0, "cannot access min_split_pos - 1 otherwise");
  5013     // reason for using min_split_pos - 1: when the minimal split pos is exactly at the
  5014     // beginning of a block, then min_split_pos is also a possible split position.
  5015     // Use the block before as min_block, because then min_block->last_lir_instruction_id() + 2 == min_split_pos
  5016     BlockBegin* min_block = allocator()->block_of_op_with_id(min_split_pos - 1);
  5018     // reason for using max_split_pos - 1: otherwise there would be an assertion failure
  5019     // when an interval ends at the end of the last block of the method
  5020     // (in this case, max_split_pos == allocator()->max_lir_op_id() + 2, and there is no
  5021     // block at this op_id)
  5022     BlockBegin* max_block = allocator()->block_of_op_with_id(max_split_pos - 1);
  5024     assert(min_block->linear_scan_number() <= max_block->linear_scan_number(), "invalid order");
  5025     if (min_block == max_block) {
  5026       // split position cannot be moved to block boundary, so split as late as possible
  5027       TRACE_LINEAR_SCAN(4, tty->print_cr("      cannot move split pos to block boundary because min_pos and max_pos are in same block"));
  5028       optimal_split_pos = max_split_pos;
  5030     } else if (it->has_hole_between(max_split_pos - 1, max_split_pos) && !allocator()->is_block_begin(max_split_pos)) {
  5031       // Do not move split position if the interval has a hole before max_split_pos.
  5032       // Intervals resulting from Phi-Functions have more than one definition (marked
  5033       // as mustHaveRegister) with a hole before each definition. When the register is needed
  5034       // for the second definition, an earlier reloading is unnecessary.
  5035       TRACE_LINEAR_SCAN(4, tty->print_cr("      interval has hole just before max_split_pos, so splitting at max_split_pos"));
  5036       optimal_split_pos = max_split_pos;
  5038     } else {
  5039       // seach optimal block boundary between min_split_pos and max_split_pos
  5040       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()));
  5042       if (do_loop_optimization) {
  5043         // Loop optimization: if a loop-end marker is found between min- and max-position,
  5044         // then split before this loop
  5045         int loop_end_pos = it->next_usage_exact(loopEndMarker, min_block->last_lir_instruction_id() + 2);
  5046         TRACE_LINEAR_SCAN(4, tty->print_cr("      loop optimization: loop end found at pos %d", loop_end_pos));
  5048         assert(loop_end_pos > min_split_pos, "invalid order");
  5049         if (loop_end_pos < max_split_pos) {
  5050           // loop-end marker found between min- and max-position
  5051           // if it is not the end marker for the same loop as the min-position, then move
  5052           // the max-position to this loop block.
  5053           // Desired result: uses tagged as shouldHaveRegister inside a loop cause a reloading
  5054           // of the interval (normally, only mustHaveRegister causes a reloading)
  5055           BlockBegin* loop_block = allocator()->block_of_op_with_id(loop_end_pos);
  5057           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()));
  5058           assert(loop_block != min_block, "loop_block and min_block must be different because block boundary is needed between");
  5060           optimal_split_pos = find_optimal_split_pos(min_block, loop_block, loop_block->last_lir_instruction_id() + 2);
  5061           if (optimal_split_pos == loop_block->last_lir_instruction_id() + 2) {
  5062             optimal_split_pos = -1;
  5063             TRACE_LINEAR_SCAN(4, tty->print_cr("      loop optimization not necessary"));
  5064           } else {
  5065             TRACE_LINEAR_SCAN(4, tty->print_cr("      loop optimization successful"));
  5070       if (optimal_split_pos == -1) {
  5071         // not calculated by loop optimization
  5072         optimal_split_pos = find_optimal_split_pos(min_block, max_block, max_split_pos);
  5076   TRACE_LINEAR_SCAN(4, tty->print_cr("      optimal split position: %d", optimal_split_pos));
  5078   return optimal_split_pos;
  5082 /*
  5083   split an interval at the optimal position between min_split_pos and
  5084   max_split_pos in two parts:
  5085   1) the left part has already a location assigned
  5086   2) the right part is sorted into to the unhandled-list
  5087 */
  5088 void LinearScanWalker::split_before_usage(Interval* it, int min_split_pos, int max_split_pos) {
  5089   TRACE_LINEAR_SCAN(2, tty->print   ("----- splitting interval: "); it->print());
  5090   TRACE_LINEAR_SCAN(2, tty->print_cr("      between %d and %d", min_split_pos, max_split_pos));
  5092   assert(it->from() < min_split_pos,         "cannot split at start of interval");
  5093   assert(current_position() < min_split_pos, "cannot split before current position");
  5094   assert(min_split_pos <= max_split_pos,     "invalid order");
  5095   assert(max_split_pos <= it->to(),          "cannot split after end of interval");
  5097   int optimal_split_pos = find_optimal_split_pos(it, min_split_pos, max_split_pos, true);
  5099   assert(min_split_pos <= optimal_split_pos && optimal_split_pos <= max_split_pos, "out of range");
  5100   assert(optimal_split_pos <= it->to(),  "cannot split after end of interval");
  5101   assert(optimal_split_pos > it->from(), "cannot split at start of interval");
  5103   if (optimal_split_pos == it->to() && it->next_usage(mustHaveRegister, min_split_pos) == max_jint) {
  5104     // the split position would be just before the end of the interval
  5105     // -> no split at all necessary
  5106     TRACE_LINEAR_SCAN(4, tty->print_cr("      no split necessary because optimal split position is at end of interval"));
  5107     return;
  5110   // must calculate this before the actual split is performed and before split position is moved to odd op_id
  5111   bool move_necessary = !allocator()->is_block_begin(optimal_split_pos) && !it->has_hole_between(optimal_split_pos - 1, optimal_split_pos);
  5113   if (!allocator()->is_block_begin(optimal_split_pos)) {
  5114     // move position before actual instruction (odd op_id)
  5115     optimal_split_pos = (optimal_split_pos - 1) | 1;
  5118   TRACE_LINEAR_SCAN(4, tty->print_cr("      splitting at position %d", optimal_split_pos));
  5119   assert(allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 1), "split pos must be odd when not on block boundary");
  5120   assert(!allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 0), "split pos must be even on block boundary");
  5122   Interval* split_part = it->split(optimal_split_pos);
  5124   allocator()->append_interval(split_part);
  5125   allocator()->copy_register_flags(it, split_part);
  5126   split_part->set_insert_move_when_activated(move_necessary);
  5127   append_to_unhandled(unhandled_first_addr(anyKind), split_part);
  5129   TRACE_LINEAR_SCAN(2, tty->print_cr("      split interval in two parts (insert_move_when_activated: %d)", move_necessary));
  5130   TRACE_LINEAR_SCAN(2, tty->print   ("      "); it->print());
  5131   TRACE_LINEAR_SCAN(2, tty->print   ("      "); split_part->print());
  5134 /*
  5135   split an interval at the optimal position between min_split_pos and
  5136   max_split_pos in two parts:
  5137   1) the left part has already a location assigned
  5138   2) the right part is always on the stack and therefore ignored in further processing
  5139 */
  5140 void LinearScanWalker::split_for_spilling(Interval* it) {
  5141   // calculate allowed range of splitting position
  5142   int max_split_pos = current_position();
  5143   int min_split_pos = MAX2(it->previous_usage(shouldHaveRegister, max_split_pos) + 1, it->from());
  5145   TRACE_LINEAR_SCAN(2, tty->print   ("----- splitting and spilling interval: "); it->print());
  5146   TRACE_LINEAR_SCAN(2, tty->print_cr("      between %d and %d", min_split_pos, max_split_pos));
  5148   assert(it->state() == activeState,     "why spill interval that is not active?");
  5149   assert(it->from() <= min_split_pos,    "cannot split before start of interval");
  5150   assert(min_split_pos <= max_split_pos, "invalid order");
  5151   assert(max_split_pos < it->to(),       "cannot split at end end of interval");
  5152   assert(current_position() < it->to(),  "interval must not end before current position");
  5154   if (min_split_pos == it->from()) {
  5155     // the whole interval is never used, so spill it entirely to memory
  5156     TRACE_LINEAR_SCAN(2, tty->print_cr("      spilling entire interval because split pos is at beginning of interval"));
  5157     assert(it->first_usage(shouldHaveRegister) > current_position(), "interval must not have use position before current_position");
  5159     allocator()->assign_spill_slot(it);
  5160     allocator()->change_spill_state(it, min_split_pos);
  5162     // Also kick parent intervals out of register to memory when they have no use
  5163     // position. This avoids short interval in register surrounded by intervals in
  5164     // memory -> avoid useless moves from memory to register and back
  5165     Interval* parent = it;
  5166     while (parent != NULL && parent->is_split_child()) {
  5167       parent = parent->split_child_before_op_id(parent->from());
  5169       if (parent->assigned_reg() < LinearScan::nof_regs) {
  5170         if (parent->first_usage(shouldHaveRegister) == max_jint) {
  5171           // parent is never used, so kick it out of its assigned register
  5172           TRACE_LINEAR_SCAN(4, tty->print_cr("      kicking out interval %d out of its register because it is never used", parent->reg_num()));
  5173           allocator()->assign_spill_slot(parent);
  5174         } else {
  5175           // do not go further back because the register is actually used by the interval
  5176           parent = NULL;
  5181   } else {
  5182     // search optimal split pos, split interval and spill only the right hand part
  5183     int optimal_split_pos = find_optimal_split_pos(it, min_split_pos, max_split_pos, false);
  5185     assert(min_split_pos <= optimal_split_pos && optimal_split_pos <= max_split_pos, "out of range");
  5186     assert(optimal_split_pos < it->to(), "cannot split at end of interval");
  5187     assert(optimal_split_pos >= it->from(), "cannot split before start of interval");
  5189     if (!allocator()->is_block_begin(optimal_split_pos)) {
  5190       // move position before actual instruction (odd op_id)
  5191       optimal_split_pos = (optimal_split_pos - 1) | 1;
  5194     TRACE_LINEAR_SCAN(4, tty->print_cr("      splitting at position %d", optimal_split_pos));
  5195     assert(allocator()->is_block_begin(optimal_split_pos)  || (optimal_split_pos % 2 == 1), "split pos must be odd when not on block boundary");
  5196     assert(!allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 0), "split pos must be even on block boundary");
  5198     Interval* spilled_part = it->split(optimal_split_pos);
  5199     allocator()->append_interval(spilled_part);
  5200     allocator()->assign_spill_slot(spilled_part);
  5201     allocator()->change_spill_state(spilled_part, optimal_split_pos);
  5203     if (!allocator()->is_block_begin(optimal_split_pos)) {
  5204       TRACE_LINEAR_SCAN(4, tty->print_cr("      inserting move from interval %d to %d", it->reg_num(), spilled_part->reg_num()));
  5205       insert_move(optimal_split_pos, it, spilled_part);
  5208     // the current_split_child is needed later when moves are inserted for reloading
  5209     assert(spilled_part->current_split_child() == it, "overwriting wrong current_split_child");
  5210     spilled_part->make_current_split_child();
  5212     TRACE_LINEAR_SCAN(2, tty->print_cr("      split interval in two parts"));
  5213     TRACE_LINEAR_SCAN(2, tty->print   ("      "); it->print());
  5214     TRACE_LINEAR_SCAN(2, tty->print   ("      "); spilled_part->print());
  5219 void LinearScanWalker::split_stack_interval(Interval* it) {
  5220   int min_split_pos = current_position() + 1;
  5221   int max_split_pos = MIN2(it->first_usage(shouldHaveRegister), it->to());
  5223   split_before_usage(it, min_split_pos, max_split_pos);
  5226 void LinearScanWalker::split_when_partial_register_available(Interval* it, int register_available_until) {
  5227   int min_split_pos = MAX2(it->previous_usage(shouldHaveRegister, register_available_until), it->from() + 1);
  5228   int max_split_pos = register_available_until;
  5230   split_before_usage(it, min_split_pos, max_split_pos);
  5233 void LinearScanWalker::split_and_spill_interval(Interval* it) {
  5234   assert(it->state() == activeState || it->state() == inactiveState, "other states not allowed");
  5236   int current_pos = current_position();
  5237   if (it->state() == inactiveState) {
  5238     // the interval is currently inactive, so no spill slot is needed for now.
  5239     // when the split part is activated, the interval has a new chance to get a register,
  5240     // so in the best case no stack slot is necessary
  5241     assert(it->has_hole_between(current_pos - 1, current_pos + 1), "interval can not be inactive otherwise");
  5242     split_before_usage(it, current_pos + 1, current_pos + 1);
  5244   } else {
  5245     // search the position where the interval must have a register and split
  5246     // at the optimal position before.
  5247     // The new created part is added to the unhandled list and will get a register
  5248     // when it is activated
  5249     int min_split_pos = current_pos + 1;
  5250     int max_split_pos = MIN2(it->next_usage(mustHaveRegister, min_split_pos), it->to());
  5252     split_before_usage(it, min_split_pos, max_split_pos);
  5254     assert(it->next_usage(mustHaveRegister, current_pos) == max_jint, "the remaining part is spilled to stack and therefore has no register");
  5255     split_for_spilling(it);
  5260 int LinearScanWalker::find_free_reg(int reg_needed_until, int interval_to, int hint_reg, int ignore_reg, bool* need_split) {
  5261   int min_full_reg = any_reg;
  5262   int max_partial_reg = any_reg;
  5264   for (int i = _first_reg; i <= _last_reg; i++) {
  5265     if (i == ignore_reg) {
  5266       // this register must be ignored
  5268     } else if (_use_pos[i] >= interval_to) {
  5269       // this register is free for the full interval
  5270       if (min_full_reg == any_reg || i == hint_reg || (_use_pos[i] < _use_pos[min_full_reg] && min_full_reg != hint_reg)) {
  5271         min_full_reg = i;
  5273     } else if (_use_pos[i] > reg_needed_until) {
  5274       // this register is at least free until reg_needed_until
  5275       if (max_partial_reg == any_reg || i == hint_reg || (_use_pos[i] > _use_pos[max_partial_reg] && max_partial_reg != hint_reg)) {
  5276         max_partial_reg = i;
  5281   if (min_full_reg != any_reg) {
  5282     return min_full_reg;
  5283   } else if (max_partial_reg != any_reg) {
  5284     *need_split = true;
  5285     return max_partial_reg;
  5286   } else {
  5287     return any_reg;
  5291 int LinearScanWalker::find_free_double_reg(int reg_needed_until, int interval_to, int hint_reg, bool* need_split) {
  5292   assert((_last_reg - _first_reg + 1) % 2 == 0, "adjust algorithm");
  5294   int min_full_reg = any_reg;
  5295   int max_partial_reg = any_reg;
  5297   for (int i = _first_reg; i < _last_reg; i+=2) {
  5298     if (_use_pos[i] >= interval_to && _use_pos[i + 1] >= interval_to) {
  5299       // this register is free for the full interval
  5300       if (min_full_reg == any_reg || i == hint_reg || (_use_pos[i] < _use_pos[min_full_reg] && min_full_reg != hint_reg)) {
  5301         min_full_reg = i;
  5303     } else if (_use_pos[i] > reg_needed_until && _use_pos[i + 1] > reg_needed_until) {
  5304       // this register is at least free until reg_needed_until
  5305       if (max_partial_reg == any_reg || i == hint_reg || (_use_pos[i] > _use_pos[max_partial_reg] && max_partial_reg != hint_reg)) {
  5306         max_partial_reg = i;
  5311   if (min_full_reg != any_reg) {
  5312     return min_full_reg;
  5313   } else if (max_partial_reg != any_reg) {
  5314     *need_split = true;
  5315     return max_partial_reg;
  5316   } else {
  5317     return any_reg;
  5322 bool LinearScanWalker::alloc_free_reg(Interval* cur) {
  5323   TRACE_LINEAR_SCAN(2, tty->print("trying to find free register for "); cur->print());
  5325   init_use_lists(true);
  5326   free_exclude_active_fixed();
  5327   free_exclude_active_any();
  5328   free_collect_inactive_fixed(cur);
  5329   free_collect_inactive_any(cur);
  5330 //  free_collect_unhandled(fixedKind, cur);
  5331   assert(unhandled_first(fixedKind) == Interval::end(), "must not have unhandled fixed intervals because all fixed intervals have a use at position 0");
  5333   // _use_pos contains the start of the next interval that has this register assigned
  5334   // (either as a fixed register or a normal allocated register in the past)
  5335   // only intervals overlapping with cur are processed, non-overlapping invervals can be ignored safely
  5336   TRACE_LINEAR_SCAN(4, tty->print_cr("      state of registers:"));
  5337   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]));
  5339   int hint_reg, hint_regHi;
  5340   Interval* register_hint = cur->register_hint();
  5341   if (register_hint != NULL) {
  5342     hint_reg = register_hint->assigned_reg();
  5343     hint_regHi = register_hint->assigned_regHi();
  5345     if (allocator()->is_precolored_cpu_interval(register_hint)) {
  5346       assert(hint_reg != any_reg && hint_regHi == any_reg, "must be for fixed intervals");
  5347       hint_regHi = hint_reg + 1;  // connect e.g. eax-edx
  5349     TRACE_LINEAR_SCAN(4, tty->print("      hint registers %d, %d from interval ", hint_reg, hint_regHi); register_hint->print());
  5351   } else {
  5352     hint_reg = any_reg;
  5353     hint_regHi = any_reg;
  5355   assert(hint_reg == any_reg || hint_reg != hint_regHi, "hint reg and regHi equal");
  5356   assert(cur->assigned_reg() == any_reg && cur->assigned_regHi() == any_reg, "register already assigned to interval");
  5358   // the register must be free at least until this position
  5359   int reg_needed_until = cur->from() + 1;
  5360   int interval_to = cur->to();
  5362   bool need_split = false;
  5363   int split_pos = -1;
  5364   int reg = any_reg;
  5365   int regHi = any_reg;
  5367   if (_adjacent_regs) {
  5368     reg = find_free_double_reg(reg_needed_until, interval_to, hint_reg, &need_split);
  5369     regHi = reg + 1;
  5370     if (reg == any_reg) {
  5371       return false;
  5373     split_pos = MIN2(_use_pos[reg], _use_pos[regHi]);
  5375   } else {
  5376     reg = find_free_reg(reg_needed_until, interval_to, hint_reg, any_reg, &need_split);
  5377     if (reg == any_reg) {
  5378       return false;
  5380     split_pos = _use_pos[reg];
  5382     if (_num_phys_regs == 2) {
  5383       regHi = find_free_reg(reg_needed_until, interval_to, hint_regHi, reg, &need_split);
  5385       if (_use_pos[reg] < interval_to && regHi == any_reg) {
  5386         // do not split interval if only one register can be assigned until the split pos
  5387         // (when one register is found for the whole interval, split&spill is only
  5388         // performed for the hi register)
  5389         return false;
  5391       } else if (regHi != any_reg) {
  5392         split_pos = MIN2(split_pos, _use_pos[regHi]);
  5394         // sort register numbers to prevent e.g. a move from eax,ebx to ebx,eax
  5395         if (reg > regHi) {
  5396           int temp = reg;
  5397           reg = regHi;
  5398           regHi = temp;
  5404   cur->assign_reg(reg, regHi);
  5405   TRACE_LINEAR_SCAN(2, tty->print_cr("selected register %d, %d", reg, regHi));
  5407   assert(split_pos > 0, "invalid split_pos");
  5408   if (need_split) {
  5409     // register not available for full interval, so split it
  5410     split_when_partial_register_available(cur, split_pos);
  5413   // only return true if interval is completely assigned
  5414   return _num_phys_regs == 1 || regHi != any_reg;
  5418 int LinearScanWalker::find_locked_reg(int reg_needed_until, int interval_to, int hint_reg, int ignore_reg, bool* need_split) {
  5419   int max_reg = any_reg;
  5421   for (int i = _first_reg; i <= _last_reg; i++) {
  5422     if (i == ignore_reg) {
  5423       // this register must be ignored
  5425     } else if (_use_pos[i] > reg_needed_until) {
  5426       if (max_reg == any_reg || i == hint_reg || (_use_pos[i] > _use_pos[max_reg] && max_reg != hint_reg)) {
  5427         max_reg = i;
  5432   if (max_reg != any_reg && _block_pos[max_reg] <= interval_to) {
  5433     *need_split = true;
  5436   return max_reg;
  5439 int LinearScanWalker::find_locked_double_reg(int reg_needed_until, int interval_to, int hint_reg, bool* need_split) {
  5440   assert((_last_reg - _first_reg + 1) % 2 == 0, "adjust algorithm");
  5442   int max_reg = any_reg;
  5444   for (int i = _first_reg; i < _last_reg; i+=2) {
  5445     if (_use_pos[i] > reg_needed_until && _use_pos[i + 1] > reg_needed_until) {
  5446       if (max_reg == any_reg || _use_pos[i] > _use_pos[max_reg]) {
  5447         max_reg = i;
  5452   if (_block_pos[max_reg] <= interval_to || _block_pos[max_reg + 1] <= interval_to) {
  5453     *need_split = true;
  5456   return max_reg;
  5459 void LinearScanWalker::split_and_spill_intersecting_intervals(int reg, int regHi) {
  5460   assert(reg != any_reg, "no register assigned");
  5462   for (int i = 0; i < _spill_intervals[reg]->length(); i++) {
  5463     Interval* it = _spill_intervals[reg]->at(i);
  5464     remove_from_list(it);
  5465     split_and_spill_interval(it);
  5468   if (regHi != any_reg) {
  5469     IntervalList* processed = _spill_intervals[reg];
  5470     for (int i = 0; i < _spill_intervals[regHi]->length(); i++) {
  5471       Interval* it = _spill_intervals[regHi]->at(i);
  5472       if (processed->index_of(it) == -1) {
  5473         remove_from_list(it);
  5474         split_and_spill_interval(it);
  5481 // Split an Interval and spill it to memory so that cur can be placed in a register
  5482 void LinearScanWalker::alloc_locked_reg(Interval* cur) {
  5483   TRACE_LINEAR_SCAN(2, tty->print("need to split and spill to get register for "); cur->print());
  5485   // collect current usage of registers
  5486   init_use_lists(false);
  5487   spill_exclude_active_fixed();
  5488 //  spill_block_unhandled_fixed(cur);
  5489   assert(unhandled_first(fixedKind) == Interval::end(), "must not have unhandled fixed intervals because all fixed intervals have a use at position 0");
  5490   spill_block_inactive_fixed(cur);
  5491   spill_collect_active_any();
  5492   spill_collect_inactive_any(cur);
  5494 #ifndef PRODUCT
  5495   if (TraceLinearScanLevel >= 4) {
  5496     tty->print_cr("      state of registers:");
  5497     for (int i = _first_reg; i <= _last_reg; i++) {
  5498       tty->print("      reg %d: use_pos: %d, block_pos: %d, intervals: ", i, _use_pos[i], _block_pos[i]);
  5499       for (int j = 0; j < _spill_intervals[i]->length(); j++) {
  5500         tty->print("%d ", _spill_intervals[i]->at(j)->reg_num());
  5502       tty->cr();
  5505 #endif
  5507   // the register must be free at least until this position
  5508   int reg_needed_until = MIN2(cur->first_usage(mustHaveRegister), cur->from() + 1);
  5509   int interval_to = cur->to();
  5510   assert (reg_needed_until > 0 && reg_needed_until < max_jint, "interval has no use");
  5512   int split_pos = 0;
  5513   int use_pos = 0;
  5514   bool need_split = false;
  5515   int reg, regHi;
  5517   if (_adjacent_regs) {
  5518     reg = find_locked_double_reg(reg_needed_until, interval_to, any_reg, &need_split);
  5519     regHi = reg + 1;
  5521     if (reg != any_reg) {
  5522       use_pos = MIN2(_use_pos[reg], _use_pos[regHi]);
  5523       split_pos = MIN2(_block_pos[reg], _block_pos[regHi]);
  5525   } else {
  5526     reg = find_locked_reg(reg_needed_until, interval_to, any_reg, cur->assigned_reg(), &need_split);
  5527     regHi = any_reg;
  5529     if (reg != any_reg) {
  5530       use_pos = _use_pos[reg];
  5531       split_pos = _block_pos[reg];
  5533       if (_num_phys_regs == 2) {
  5534         if (cur->assigned_reg() != any_reg) {
  5535           regHi = reg;
  5536           reg = cur->assigned_reg();
  5537         } else {
  5538           regHi = find_locked_reg(reg_needed_until, interval_to, any_reg, reg, &need_split);
  5539           if (regHi != any_reg) {
  5540             use_pos = MIN2(use_pos, _use_pos[regHi]);
  5541             split_pos = MIN2(split_pos, _block_pos[regHi]);
  5545         if (regHi != any_reg && reg > regHi) {
  5546           // sort register numbers to prevent e.g. a move from eax,ebx to ebx,eax
  5547           int temp = reg;
  5548           reg = regHi;
  5549           regHi = temp;
  5555   if (reg == any_reg || (_num_phys_regs == 2 && regHi == any_reg) || use_pos <= cur->first_usage(mustHaveRegister)) {
  5556     // the first use of cur is later than the spilling position -> spill cur
  5557     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));
  5559     if (cur->first_usage(mustHaveRegister) <= cur->from() + 1) {
  5560       assert(false, "cannot spill interval that is used in first instruction (possible reason: no register found)");
  5561       // assign a reasonable register and do a bailout in product mode to avoid errors
  5562       allocator()->assign_spill_slot(cur);
  5563       BAILOUT("LinearScan: no register found");
  5566     split_and_spill_interval(cur);
  5567   } else {
  5568     TRACE_LINEAR_SCAN(4, tty->print_cr("decided to use register %d, %d", reg, regHi));
  5569     assert(reg != any_reg && (_num_phys_regs == 1 || regHi != any_reg), "no register found");
  5570     assert(split_pos > 0, "invalid split_pos");
  5571     assert(need_split == false || split_pos > cur->from(), "splitting interval at from");
  5573     cur->assign_reg(reg, regHi);
  5574     if (need_split) {
  5575       // register not available for full interval, so split it
  5576       split_when_partial_register_available(cur, split_pos);
  5579     // perform splitting and spilling for all affected intervalls
  5580     split_and_spill_intersecting_intervals(reg, regHi);
  5584 bool LinearScanWalker::no_allocation_possible(Interval* cur) {
  5585 #ifdef X86
  5586   // fast calculation of intervals that can never get a register because the
  5587   // the next instruction is a call that blocks all registers
  5588   // Note: this does not work if callee-saved registers are available (e.g. on Sparc)
  5590   // check if this interval is the result of a split operation
  5591   // (an interval got a register until this position)
  5592   int pos = cur->from();
  5593   if ((pos & 1) == 1) {
  5594     // the current instruction is a call that blocks all registers
  5595     if (pos < allocator()->max_lir_op_id() && allocator()->has_call(pos + 1)) {
  5596       TRACE_LINEAR_SCAN(4, tty->print_cr("      free register cannot be available because all registers blocked by following call"));
  5598       // safety check that there is really no register available
  5599       assert(alloc_free_reg(cur) == false, "found a register for this interval");
  5600       return true;
  5604 #endif
  5605   return false;
  5608 void LinearScanWalker::init_vars_for_alloc(Interval* cur) {
  5609   BasicType type = cur->type();
  5610   _num_phys_regs = LinearScan::num_physical_regs(type);
  5611   _adjacent_regs = LinearScan::requires_adjacent_regs(type);
  5613   if (pd_init_regs_for_alloc(cur)) {
  5614     // the appropriate register range was selected.
  5615   } else if (type == T_FLOAT || type == T_DOUBLE) {
  5616     _first_reg = pd_first_fpu_reg;
  5617     _last_reg = pd_last_fpu_reg;
  5618   } else {
  5619     _first_reg = pd_first_cpu_reg;
  5620     _last_reg = FrameMap::last_cpu_reg();
  5623   assert(0 <= _first_reg && _first_reg < LinearScan::nof_regs, "out of range");
  5624   assert(0 <= _last_reg && _last_reg < LinearScan::nof_regs, "out of range");
  5628 bool LinearScanWalker::is_move(LIR_Op* op, Interval* from, Interval* to) {
  5629   if (op->code() != lir_move) {
  5630     return false;
  5632   assert(op->as_Op1() != NULL, "move must be LIR_Op1");
  5634   LIR_Opr in = ((LIR_Op1*)op)->in_opr();
  5635   LIR_Opr res = ((LIR_Op1*)op)->result_opr();
  5636   return in->is_virtual() && res->is_virtual() && in->vreg_number() == from->reg_num() && res->vreg_number() == to->reg_num();
  5639 // optimization (especially for phi functions of nested loops):
  5640 // assign same spill slot to non-intersecting intervals
  5641 void LinearScanWalker::combine_spilled_intervals(Interval* cur) {
  5642   if (cur->is_split_child()) {
  5643     // optimization is only suitable for split parents
  5644     return;
  5647   Interval* register_hint = cur->register_hint(false);
  5648   if (register_hint == NULL) {
  5649     // cur is not the target of a move, otherwise register_hint would be set
  5650     return;
  5652   assert(register_hint->is_split_parent(), "register hint must be split parent");
  5654   if (cur->spill_state() != noOptimization || register_hint->spill_state() != noOptimization) {
  5655     // combining the stack slots for intervals where spill move optimization is applied
  5656     // is not benefitial and would cause problems
  5657     return;
  5660   int begin_pos = cur->from();
  5661   int end_pos = cur->to();
  5662   if (end_pos > allocator()->max_lir_op_id() || (begin_pos & 1) != 0 || (end_pos & 1) != 0) {
  5663     // safety check that lir_op_with_id is allowed
  5664     return;
  5667   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)) {
  5668     // cur and register_hint are not connected with two moves
  5669     return;
  5672   Interval* begin_hint = register_hint->split_child_at_op_id(begin_pos, LIR_OpVisitState::inputMode);
  5673   Interval* end_hint = register_hint->split_child_at_op_id(end_pos, LIR_OpVisitState::outputMode);
  5674   if (begin_hint == end_hint || begin_hint->to() != begin_pos || end_hint->from() != end_pos) {
  5675     // register_hint must be split, otherwise the re-writing of use positions does not work
  5676     return;
  5679   assert(begin_hint->assigned_reg() != any_reg, "must have register assigned");
  5680   assert(end_hint->assigned_reg() == any_reg, "must not have register assigned");
  5681   assert(cur->first_usage(mustHaveRegister) == begin_pos, "must have use position at begin of interval because of move");
  5682   assert(end_hint->first_usage(mustHaveRegister) == end_pos, "must have use position at begin of interval because of move");
  5684   if (begin_hint->assigned_reg() < LinearScan::nof_regs) {
  5685     // register_hint is not spilled at begin_pos, so it would not be benefitial to immediately spill cur
  5686     return;
  5688   assert(register_hint->canonical_spill_slot() != -1, "must be set when part of interval was spilled");
  5690   // modify intervals such that cur gets the same stack slot as register_hint
  5691   // delete use positions to prevent the intervals to get a register at beginning
  5692   cur->set_canonical_spill_slot(register_hint->canonical_spill_slot());
  5693   cur->remove_first_use_pos();
  5694   end_hint->remove_first_use_pos();
  5698 // allocate a physical register or memory location to an interval
  5699 bool LinearScanWalker::activate_current() {
  5700   Interval* cur = current();
  5701   bool result = true;
  5703   TRACE_LINEAR_SCAN(2, tty->print   ("+++++ activating interval "); cur->print());
  5704   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()));
  5706   if (cur->assigned_reg() >= LinearScan::nof_regs) {
  5707     // activating an interval that has a stack slot assigned -> split it at first use position
  5708     // used for method parameters
  5709     TRACE_LINEAR_SCAN(4, tty->print_cr("      interval has spill slot assigned (method parameter) -> split it before first use"));
  5711     split_stack_interval(cur);
  5712     result = false;
  5714   } else if (allocator()->gen()->is_vreg_flag_set(cur->reg_num(), LIRGenerator::must_start_in_memory)) {
  5715     // activating an interval that must start in a stack slot, but may get a register later
  5716     // used for lir_roundfp: rounding is done by store to stack and reload later
  5717     TRACE_LINEAR_SCAN(4, tty->print_cr("      interval must start in stack slot -> split it before first use"));
  5718     assert(cur->assigned_reg() == any_reg && cur->assigned_regHi() == any_reg, "register already assigned");
  5720     allocator()->assign_spill_slot(cur);
  5721     split_stack_interval(cur);
  5722     result = false;
  5724   } else if (cur->assigned_reg() == any_reg) {
  5725     // interval has not assigned register -> normal allocation
  5726     // (this is the normal case for most intervals)
  5727     TRACE_LINEAR_SCAN(4, tty->print_cr("      normal allocation of register"));
  5729     // assign same spill slot to non-intersecting intervals
  5730     combine_spilled_intervals(cur);
  5732     init_vars_for_alloc(cur);
  5733     if (no_allocation_possible(cur) || !alloc_free_reg(cur)) {
  5734       // no empty register available.
  5735       // split and spill another interval so that this interval gets a register
  5736       alloc_locked_reg(cur);
  5739     // spilled intervals need not be move to active-list
  5740     if (cur->assigned_reg() >= LinearScan::nof_regs) {
  5741       result = false;
  5745   // load spilled values that become active from stack slot to register
  5746   if (cur->insert_move_when_activated()) {
  5747     assert(cur->is_split_child(), "must be");
  5748     assert(cur->current_split_child() != NULL, "must be");
  5749     assert(cur->current_split_child()->reg_num() != cur->reg_num(), "cannot insert move between same interval");
  5750     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()));
  5752     insert_move(cur->from(), cur->current_split_child(), cur);
  5754   cur->make_current_split_child();
  5756   return result; // true = interval is moved to active list
  5760 // Implementation of EdgeMoveOptimizer
  5762 EdgeMoveOptimizer::EdgeMoveOptimizer() :
  5763   _edge_instructions(4),
  5764   _edge_instructions_idx(4)
  5768 void EdgeMoveOptimizer::optimize(BlockList* code) {
  5769   EdgeMoveOptimizer optimizer = EdgeMoveOptimizer();
  5771   // ignore the first block in the list (index 0 is not processed)
  5772   for (int i = code->length() - 1; i >= 1; i--) {
  5773     BlockBegin* block = code->at(i);
  5775     if (block->number_of_preds() > 1 && !block->is_set(BlockBegin::exception_entry_flag)) {
  5776       optimizer.optimize_moves_at_block_end(block);
  5778     if (block->number_of_sux() == 2) {
  5779       optimizer.optimize_moves_at_block_begin(block);
  5785 // clear all internal data structures
  5786 void EdgeMoveOptimizer::init_instructions() {
  5787   _edge_instructions.clear();
  5788   _edge_instructions_idx.clear();
  5791 // append a lir-instruction-list and the index of the current operation in to the list
  5792 void EdgeMoveOptimizer::append_instructions(LIR_OpList* instructions, int instructions_idx) {
  5793   _edge_instructions.append(instructions);
  5794   _edge_instructions_idx.append(instructions_idx);
  5797 // return the current operation of the given edge (predecessor or successor)
  5798 LIR_Op* EdgeMoveOptimizer::instruction_at(int edge) {
  5799   LIR_OpList* instructions = _edge_instructions.at(edge);
  5800   int idx = _edge_instructions_idx.at(edge);
  5802   if (idx < instructions->length()) {
  5803     return instructions->at(idx);
  5804   } else {
  5805     return NULL;
  5809 // removes the current operation of the given edge (predecessor or successor)
  5810 void EdgeMoveOptimizer::remove_cur_instruction(int edge, bool decrement_index) {
  5811   LIR_OpList* instructions = _edge_instructions.at(edge);
  5812   int idx = _edge_instructions_idx.at(edge);
  5813   instructions->remove_at(idx);
  5815   if (decrement_index) {
  5816     _edge_instructions_idx.at_put(edge, idx - 1);
  5821 bool EdgeMoveOptimizer::operations_different(LIR_Op* op1, LIR_Op* op2) {
  5822   if (op1 == NULL || op2 == NULL) {
  5823     // at least one block is already empty -> no optimization possible
  5824     return true;
  5827   if (op1->code() == lir_move && op2->code() == lir_move) {
  5828     assert(op1->as_Op1() != NULL, "move must be LIR_Op1");
  5829     assert(op2->as_Op1() != NULL, "move must be LIR_Op1");
  5830     LIR_Op1* move1 = (LIR_Op1*)op1;
  5831     LIR_Op1* move2 = (LIR_Op1*)op2;
  5832     if (move1->info() == move2->info() && move1->in_opr() == move2->in_opr() && move1->result_opr() == move2->result_opr()) {
  5833       // these moves are exactly equal and can be optimized
  5834       return false;
  5837   } else if (op1->code() == lir_fxch && op2->code() == lir_fxch) {
  5838     assert(op1->as_Op1() != NULL, "fxch must be LIR_Op1");
  5839     assert(op2->as_Op1() != NULL, "fxch must be LIR_Op1");
  5840     LIR_Op1* fxch1 = (LIR_Op1*)op1;
  5841     LIR_Op1* fxch2 = (LIR_Op1*)op2;
  5842     if (fxch1->in_opr()->as_jint() == fxch2->in_opr()->as_jint()) {
  5843       // equal FPU stack operations can be optimized
  5844       return false;
  5847   } else if (op1->code() == lir_fpop_raw && op2->code() == lir_fpop_raw) {
  5848     // equal FPU stack operations can be optimized
  5849     return false;
  5852   // no optimization possible
  5853   return true;
  5856 void EdgeMoveOptimizer::optimize_moves_at_block_end(BlockBegin* block) {
  5857   TRACE_LINEAR_SCAN(4, tty->print_cr("optimizing moves at end of block B%d", block->block_id()));
  5859   if (block->is_predecessor(block)) {
  5860     // currently we can't handle this correctly.
  5861     return;
  5864   init_instructions();
  5865   int num_preds = block->number_of_preds();
  5866   assert(num_preds > 1, "do not call otherwise");
  5867   assert(!block->is_set(BlockBegin::exception_entry_flag), "exception handlers not allowed");
  5869   // setup a list with the lir-instructions of all predecessors
  5870   int i;
  5871   for (i = 0; i < num_preds; i++) {
  5872     BlockBegin* pred = block->pred_at(i);
  5873     LIR_OpList* pred_instructions = pred->lir()->instructions_list();
  5875     if (pred->number_of_sux() != 1) {
  5876       // this can happen with switch-statements where multiple edges are between
  5877       // the same blocks.
  5878       return;
  5881     assert(pred->number_of_sux() == 1, "can handle only one successor");
  5882     assert(pred->sux_at(0) == block, "invalid control flow");
  5883     assert(pred_instructions->last()->code() == lir_branch, "block with successor must end with branch");
  5884     assert(pred_instructions->last()->as_OpBranch() != NULL, "branch must be LIR_OpBranch");
  5885     assert(pred_instructions->last()->as_OpBranch()->cond() == lir_cond_always, "block must end with unconditional branch");
  5887     if (pred_instructions->last()->info() != NULL) {
  5888       // can not optimize instructions when debug info is needed
  5889       return;
  5892     // ignore the unconditional branch at the end of the block
  5893     append_instructions(pred_instructions, pred_instructions->length() - 2);
  5897   // process lir-instructions while all predecessors end with the same instruction
  5898   while (true) {
  5899     LIR_Op* op = instruction_at(0);
  5900     for (i = 1; i < num_preds; i++) {
  5901       if (operations_different(op, instruction_at(i))) {
  5902         // these instructions are different and cannot be optimized ->
  5903         // no further optimization possible
  5904         return;
  5908     TRACE_LINEAR_SCAN(4, tty->print("found instruction that is equal in all %d predecessors: ", num_preds); op->print());
  5910     // insert the instruction at the beginning of the current block
  5911     block->lir()->insert_before(1, op);
  5913     // delete the instruction at the end of all predecessors
  5914     for (i = 0; i < num_preds; i++) {
  5915       remove_cur_instruction(i, true);
  5921 void EdgeMoveOptimizer::optimize_moves_at_block_begin(BlockBegin* block) {
  5922   TRACE_LINEAR_SCAN(4, tty->print_cr("optimization moves at begin of block B%d", block->block_id()));
  5924   init_instructions();
  5925   int num_sux = block->number_of_sux();
  5927   LIR_OpList* cur_instructions = block->lir()->instructions_list();
  5929   assert(num_sux == 2, "method should not be called otherwise");
  5930   assert(cur_instructions->last()->code() == lir_branch, "block with successor must end with branch");
  5931   assert(cur_instructions->last()->as_OpBranch() != NULL, "branch must be LIR_OpBranch");
  5932   assert(cur_instructions->last()->as_OpBranch()->cond() == lir_cond_always, "block must end with unconditional branch");
  5934   if (cur_instructions->last()->info() != NULL) {
  5935     // can no optimize instructions when debug info is needed
  5936     return;
  5939   LIR_Op* branch = cur_instructions->at(cur_instructions->length() - 2);
  5940   if (branch->info() != NULL || (branch->code() != lir_branch && branch->code() != lir_cond_float_branch)) {
  5941     // not a valid case for optimization
  5942     // currently, only blocks that end with two branches (conditional branch followed
  5943     // by unconditional branch) are optimized
  5944     return;
  5947   // now it is guaranteed that the block ends with two branch instructions.
  5948   // the instructions are inserted at the end of the block before these two branches
  5949   int insert_idx = cur_instructions->length() - 2;
  5951   int i;
  5952 #ifdef ASSERT
  5953   for (i = insert_idx - 1; i >= 0; i--) {
  5954     LIR_Op* op = cur_instructions->at(i);
  5955     if ((op->code() == lir_branch || op->code() == lir_cond_float_branch) && ((LIR_OpBranch*)op)->block() != NULL) {
  5956       assert(false, "block with two successors can have only two branch instructions");
  5959 #endif
  5961   // setup a list with the lir-instructions of all successors
  5962   for (i = 0; i < num_sux; i++) {
  5963     BlockBegin* sux = block->sux_at(i);
  5964     LIR_OpList* sux_instructions = sux->lir()->instructions_list();
  5966     assert(sux_instructions->at(0)->code() == lir_label, "block must start with label");
  5968     if (sux->number_of_preds() != 1) {
  5969       // this can happen with switch-statements where multiple edges are between
  5970       // the same blocks.
  5971       return;
  5973     assert(sux->pred_at(0) == block, "invalid control flow");
  5974     assert(!sux->is_set(BlockBegin::exception_entry_flag), "exception handlers not allowed");
  5976     // ignore the label at the beginning of the block
  5977     append_instructions(sux_instructions, 1);
  5980   // process lir-instructions while all successors begin with the same instruction
  5981   while (true) {
  5982     LIR_Op* op = instruction_at(0);
  5983     for (i = 1; i < num_sux; i++) {
  5984       if (operations_different(op, instruction_at(i))) {
  5985         // these instructions are different and cannot be optimized ->
  5986         // no further optimization possible
  5987         return;
  5991     TRACE_LINEAR_SCAN(4, tty->print("----- found instruction that is equal in all %d successors: ", num_sux); op->print());
  5993     // insert instruction at end of current block
  5994     block->lir()->insert_before(insert_idx, op);
  5995     insert_idx++;
  5997     // delete the instructions at the beginning of all successors
  5998     for (i = 0; i < num_sux; i++) {
  5999       remove_cur_instruction(i, false);
  6005 // Implementation of ControlFlowOptimizer
  6007 ControlFlowOptimizer::ControlFlowOptimizer() :
  6008   _original_preds(4)
  6012 void ControlFlowOptimizer::optimize(BlockList* code) {
  6013   ControlFlowOptimizer optimizer = ControlFlowOptimizer();
  6015   // push the OSR entry block to the end so that we're not jumping over it.
  6016   BlockBegin* osr_entry = code->at(0)->end()->as_Base()->osr_entry();
  6017   if (osr_entry) {
  6018     int index = osr_entry->linear_scan_number();
  6019     assert(code->at(index) == osr_entry, "wrong index");
  6020     code->remove_at(index);
  6021     code->append(osr_entry);
  6024   optimizer.reorder_short_loops(code);
  6025   optimizer.delete_empty_blocks(code);
  6026   optimizer.delete_unnecessary_jumps(code);
  6027   optimizer.delete_jumps_to_return(code);
  6030 void ControlFlowOptimizer::reorder_short_loop(BlockList* code, BlockBegin* header_block, int header_idx) {
  6031   int i = header_idx + 1;
  6032   int max_end = MIN2(header_idx + ShortLoopSize, code->length());
  6033   while (i < max_end && code->at(i)->loop_depth() >= header_block->loop_depth()) {
  6034     i++;
  6037   if (i == code->length() || code->at(i)->loop_depth() < header_block->loop_depth()) {
  6038     int end_idx = i - 1;
  6039     BlockBegin* end_block = code->at(end_idx);
  6041     if (end_block->number_of_sux() == 1 && end_block->sux_at(0) == header_block) {
  6042       // short loop from header_idx to end_idx found -> reorder blocks such that
  6043       // the header_block is the last block instead of the first block of the loop
  6044       TRACE_LINEAR_SCAN(1, tty->print_cr("Reordering short loop: length %d, header B%d, end B%d",
  6045                                          end_idx - header_idx + 1,
  6046                                          header_block->block_id(), end_block->block_id()));
  6048       for (int j = header_idx; j < end_idx; j++) {
  6049         code->at_put(j, code->at(j + 1));
  6051       code->at_put(end_idx, header_block);
  6053       // correct the flags so that any loop alignment occurs in the right place.
  6054       assert(code->at(end_idx)->is_set(BlockBegin::backward_branch_target_flag), "must be backward branch target");
  6055       code->at(end_idx)->clear(BlockBegin::backward_branch_target_flag);
  6056       code->at(header_idx)->set(BlockBegin::backward_branch_target_flag);
  6061 void ControlFlowOptimizer::reorder_short_loops(BlockList* code) {
  6062   for (int i = code->length() - 1; i >= 0; i--) {
  6063     BlockBegin* block = code->at(i);
  6065     if (block->is_set(BlockBegin::linear_scan_loop_header_flag)) {
  6066       reorder_short_loop(code, block, i);
  6070   DEBUG_ONLY(verify(code));
  6073 // only blocks with exactly one successor can be deleted. Such blocks
  6074 // must always end with an unconditional branch to this successor
  6075 bool ControlFlowOptimizer::can_delete_block(BlockBegin* block) {
  6076   if (block->number_of_sux() != 1 || block->number_of_exception_handlers() != 0 || block->is_entry_block()) {
  6077     return false;
  6080   LIR_OpList* instructions = block->lir()->instructions_list();
  6082   assert(instructions->length() >= 2, "block must have label and branch");
  6083   assert(instructions->at(0)->code() == lir_label, "first instruction must always be a label");
  6084   assert(instructions->last()->as_OpBranch() != NULL, "last instrcution must always be a branch");
  6085   assert(instructions->last()->as_OpBranch()->cond() == lir_cond_always, "branch must be unconditional");
  6086   assert(instructions->last()->as_OpBranch()->block() == block->sux_at(0), "branch target must be the successor");
  6088   // block must have exactly one successor
  6090   if (instructions->length() == 2 && instructions->last()->info() == NULL) {
  6091     return true;
  6093   return false;
  6096 // substitute branch targets in all branch-instructions of this blocks
  6097 void ControlFlowOptimizer::substitute_branch_target(BlockBegin* block, BlockBegin* target_from, BlockBegin* target_to) {
  6098   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()));
  6100   LIR_OpList* instructions = block->lir()->instructions_list();
  6102   assert(instructions->at(0)->code() == lir_label, "first instruction must always be a label");
  6103   for (int i = instructions->length() - 1; i >= 1; i--) {
  6104     LIR_Op* op = instructions->at(i);
  6106     if (op->code() == lir_branch || op->code() == lir_cond_float_branch) {
  6107       assert(op->as_OpBranch() != NULL, "branch must be of type LIR_OpBranch");
  6108       LIR_OpBranch* branch = (LIR_OpBranch*)op;
  6110       if (branch->block() == target_from) {
  6111         branch->change_block(target_to);
  6113       if (branch->ublock() == target_from) {
  6114         branch->change_ublock(target_to);
  6120 void ControlFlowOptimizer::delete_empty_blocks(BlockList* code) {
  6121   int old_pos = 0;
  6122   int new_pos = 0;
  6123   int num_blocks = code->length();
  6125   while (old_pos < num_blocks) {
  6126     BlockBegin* block = code->at(old_pos);
  6128     if (can_delete_block(block)) {
  6129       BlockBegin* new_target = block->sux_at(0);
  6131       // propagate backward branch target flag for correct code alignment
  6132       if (block->is_set(BlockBegin::backward_branch_target_flag)) {
  6133         new_target->set(BlockBegin::backward_branch_target_flag);
  6136       // collect a list with all predecessors that contains each predecessor only once
  6137       // the predecessors of cur are changed during the substitution, so a copy of the
  6138       // predecessor list is necessary
  6139       int j;
  6140       _original_preds.clear();
  6141       for (j = block->number_of_preds() - 1; j >= 0; j--) {
  6142         BlockBegin* pred = block->pred_at(j);
  6143         if (_original_preds.index_of(pred) == -1) {
  6144           _original_preds.append(pred);
  6148       for (j = _original_preds.length() - 1; j >= 0; j--) {
  6149         BlockBegin* pred = _original_preds.at(j);
  6150         substitute_branch_target(pred, block, new_target);
  6151         pred->substitute_sux(block, new_target);
  6153     } else {
  6154       // adjust position of this block in the block list if blocks before
  6155       // have been deleted
  6156       if (new_pos != old_pos) {
  6157         code->at_put(new_pos, code->at(old_pos));
  6159       new_pos++;
  6161     old_pos++;
  6163   code->truncate(new_pos);
  6165   DEBUG_ONLY(verify(code));
  6168 void ControlFlowOptimizer::delete_unnecessary_jumps(BlockList* code) {
  6169   // skip the last block because there a branch is always necessary
  6170   for (int i = code->length() - 2; i >= 0; i--) {
  6171     BlockBegin* block = code->at(i);
  6172     LIR_OpList* instructions = block->lir()->instructions_list();
  6174     LIR_Op* last_op = instructions->last();
  6175     if (last_op->code() == lir_branch) {
  6176       assert(last_op->as_OpBranch() != NULL, "branch must be of type LIR_OpBranch");
  6177       LIR_OpBranch* last_branch = (LIR_OpBranch*)last_op;
  6179       assert(last_branch->block() != NULL, "last branch must always have a block as target");
  6180       assert(last_branch->label() == last_branch->block()->label(), "must be equal");
  6182       if (last_branch->info() == NULL) {
  6183         if (last_branch->block() == code->at(i + 1)) {
  6185           TRACE_LINEAR_SCAN(3, tty->print_cr("Deleting unconditional branch at end of block B%d", block->block_id()));
  6187           // delete last branch instruction
  6188           instructions->truncate(instructions->length() - 1);
  6190         } else {
  6191           LIR_Op* prev_op = instructions->at(instructions->length() - 2);
  6192           if (prev_op->code() == lir_branch || prev_op->code() == lir_cond_float_branch) {
  6193             assert(prev_op->as_OpBranch() != NULL, "branch must be of type LIR_OpBranch");
  6194             LIR_OpBranch* prev_branch = (LIR_OpBranch*)prev_op;
  6196             LIR_Op2* prev_cmp = NULL;
  6198             for(int j = instructions->length() - 3; j >= 0 && prev_cmp == NULL; j--) {
  6199               prev_op = instructions->at(j);
  6200               if(prev_op->code() == lir_cmp) {
  6201                 assert(prev_op->as_Op2() != NULL, "branch must be of type LIR_Op2");
  6202                 prev_cmp = (LIR_Op2*)prev_op;
  6203                 assert(prev_branch->cond() == prev_cmp->condition(), "should be the same");
  6206             assert(prev_cmp != NULL, "should have found comp instruction for branch");
  6207             if (prev_branch->block() == code->at(i + 1) && prev_branch->info() == NULL) {
  6209               TRACE_LINEAR_SCAN(3, tty->print_cr("Negating conditional branch and deleting unconditional branch at end of block B%d", block->block_id()));
  6211               // eliminate a conditional branch to the immediate successor
  6212               prev_branch->change_block(last_branch->block());
  6213               prev_branch->negate_cond();
  6214               prev_cmp->set_condition(prev_branch->cond());
  6215               instructions->truncate(instructions->length() - 1);
  6223   DEBUG_ONLY(verify(code));
  6226 void ControlFlowOptimizer::delete_jumps_to_return(BlockList* code) {
  6227 #ifdef ASSERT
  6228   BitMap return_converted(BlockBegin::number_of_blocks());
  6229   return_converted.clear();
  6230 #endif
  6232   for (int i = code->length() - 1; i >= 0; i--) {
  6233     BlockBegin* block = code->at(i);
  6234     LIR_OpList* cur_instructions = block->lir()->instructions_list();
  6235     LIR_Op*     cur_last_op = cur_instructions->last();
  6237     assert(cur_instructions->at(0)->code() == lir_label, "first instruction must always be a label");
  6238     if (cur_instructions->length() == 2 && cur_last_op->code() == lir_return) {
  6239       // the block contains only a label and a return
  6240       // if a predecessor ends with an unconditional jump to this block, then the jump
  6241       // can be replaced with a return instruction
  6242       //
  6243       // Note: the original block with only a return statement cannot be deleted completely
  6244       //       because the predecessors might have other (conditional) jumps to this block
  6245       //       -> this may lead to unnecesary return instructions in the final code
  6247       assert(cur_last_op->info() == NULL, "return instructions do not have debug information");
  6248       assert(block->number_of_sux() == 0 ||
  6249              (return_converted.at(block->block_id()) && block->number_of_sux() == 1),
  6250              "blocks that end with return must not have successors");
  6252       assert(cur_last_op->as_Op1() != NULL, "return must be LIR_Op1");
  6253       LIR_Opr return_opr = ((LIR_Op1*)cur_last_op)->in_opr();
  6255       for (int j = block->number_of_preds() - 1; j >= 0; j--) {
  6256         BlockBegin* pred = block->pred_at(j);
  6257         LIR_OpList* pred_instructions = pred->lir()->instructions_list();
  6258         LIR_Op*     pred_last_op = pred_instructions->last();
  6260         if (pred_last_op->code() == lir_branch) {
  6261           assert(pred_last_op->as_OpBranch() != NULL, "branch must be LIR_OpBranch");
  6262           LIR_OpBranch* pred_last_branch = (LIR_OpBranch*)pred_last_op;
  6264           if (pred_last_branch->block() == block && pred_last_branch->cond() == lir_cond_always && pred_last_branch->info() == NULL) {
  6265             // replace the jump to a return with a direct return
  6266             // Note: currently the edge between the blocks is not deleted
  6267             pred_instructions->at_put(pred_instructions->length() - 1, new LIR_Op1(lir_return, return_opr));
  6268 #ifdef ASSERT
  6269             return_converted.set_bit(pred->block_id());
  6270 #endif
  6279 #ifdef ASSERT
  6280 void ControlFlowOptimizer::verify(BlockList* code) {
  6281   for (int i = 0; i < code->length(); i++) {
  6282     BlockBegin* block = code->at(i);
  6283     LIR_OpList* instructions = block->lir()->instructions_list();
  6285     int j;
  6286     for (j = 0; j < instructions->length(); j++) {
  6287       LIR_OpBranch* op_branch = instructions->at(j)->as_OpBranch();
  6289       if (op_branch != NULL) {
  6290         assert(op_branch->block() == NULL || code->index_of(op_branch->block()) != -1, "branch target not valid");
  6291         assert(op_branch->ublock() == NULL || code->index_of(op_branch->ublock()) != -1, "branch target not valid");
  6295     for (j = 0; j < block->number_of_sux() - 1; j++) {
  6296       BlockBegin* sux = block->sux_at(j);
  6297       assert(code->index_of(sux) != -1, "successor not valid");
  6300     for (j = 0; j < block->number_of_preds() - 1; j++) {
  6301       BlockBegin* pred = block->pred_at(j);
  6302       assert(code->index_of(pred) != -1, "successor not valid");
  6306 #endif
  6309 #ifndef PRODUCT
  6311 // Implementation of LinearStatistic
  6313 const char* LinearScanStatistic::counter_name(int counter_idx) {
  6314   switch (counter_idx) {
  6315     case counter_method:          return "compiled methods";
  6316     case counter_fpu_method:      return "methods using fpu";
  6317     case counter_loop_method:     return "methods with loops";
  6318     case counter_exception_method:return "methods with xhandler";
  6320     case counter_loop:            return "loops";
  6321     case counter_block:           return "blocks";
  6322     case counter_loop_block:      return "blocks inside loop";
  6323     case counter_exception_block: return "exception handler entries";
  6324     case counter_interval:        return "intervals";
  6325     case counter_fixed_interval:  return "fixed intervals";
  6326     case counter_range:           return "ranges";
  6327     case counter_fixed_range:     return "fixed ranges";
  6328     case counter_use_pos:         return "use positions";
  6329     case counter_fixed_use_pos:   return "fixed use positions";
  6330     case counter_spill_slots:     return "spill slots";
  6332     // counter for classes of lir instructions
  6333     case counter_instruction:     return "total instructions";
  6334     case counter_label:           return "labels";
  6335     case counter_entry:           return "method entries";
  6336     case counter_return:          return "method returns";
  6337     case counter_call:            return "method calls";
  6338     case counter_move:            return "moves";
  6339     case counter_cmp:             return "compare";
  6340     case counter_cond_branch:     return "conditional branches";
  6341     case counter_uncond_branch:   return "unconditional branches";
  6342     case counter_stub_branch:     return "branches to stub";
  6343     case counter_alu:             return "artithmetic + logic";
  6344     case counter_alloc:           return "allocations";
  6345     case counter_sync:            return "synchronisation";
  6346     case counter_throw:           return "throw";
  6347     case counter_unwind:          return "unwind";
  6348     case counter_typecheck:       return "type+null-checks";
  6349     case counter_fpu_stack:       return "fpu-stack";
  6350     case counter_misc_inst:       return "other instructions";
  6351     case counter_other_inst:      return "misc. instructions";
  6353     // counter for different types of moves
  6354     case counter_move_total:      return "total moves";
  6355     case counter_move_reg_reg:    return "register->register";
  6356     case counter_move_reg_stack:  return "register->stack";
  6357     case counter_move_stack_reg:  return "stack->register";
  6358     case counter_move_stack_stack:return "stack->stack";
  6359     case counter_move_reg_mem:    return "register->memory";
  6360     case counter_move_mem_reg:    return "memory->register";
  6361     case counter_move_const_any:  return "constant->any";
  6363     case blank_line_1:            return "";
  6364     case blank_line_2:            return "";
  6366     default: ShouldNotReachHere(); return "";
  6370 LinearScanStatistic::Counter LinearScanStatistic::base_counter(int counter_idx) {
  6371   if (counter_idx == counter_fpu_method || counter_idx == counter_loop_method || counter_idx == counter_exception_method) {
  6372     return counter_method;
  6373   } else if (counter_idx == counter_loop_block || counter_idx == counter_exception_block) {
  6374     return counter_block;
  6375   } else if (counter_idx >= counter_instruction && counter_idx <= counter_other_inst) {
  6376     return counter_instruction;
  6377   } else if (counter_idx >= counter_move_total && counter_idx <= counter_move_const_any) {
  6378     return counter_move_total;
  6380   return invalid_counter;
  6383 LinearScanStatistic::LinearScanStatistic() {
  6384   for (int i = 0; i < number_of_counters; i++) {
  6385     _counters_sum[i] = 0;
  6386     _counters_max[i] = -1;
  6391 // add the method-local numbers to the total sum
  6392 void LinearScanStatistic::sum_up(LinearScanStatistic &method_statistic) {
  6393   for (int i = 0; i < number_of_counters; i++) {
  6394     _counters_sum[i] += method_statistic._counters_sum[i];
  6395     _counters_max[i] = MAX2(_counters_max[i], method_statistic._counters_sum[i]);
  6399 void LinearScanStatistic::print(const char* title) {
  6400   if (CountLinearScan || TraceLinearScanLevel > 0) {
  6401     tty->cr();
  6402     tty->print_cr("***** LinearScan statistic - %s *****", title);
  6404     for (int i = 0; i < number_of_counters; i++) {
  6405       if (_counters_sum[i] > 0 || _counters_max[i] >= 0) {
  6406         tty->print("%25s: %8d", counter_name(i), _counters_sum[i]);
  6408         if (base_counter(i) != invalid_counter) {
  6409           tty->print("  (%5.1f%%) ", _counters_sum[i] * 100.0 / _counters_sum[base_counter(i)]);
  6410         } else {
  6411           tty->print("           ");
  6414         if (_counters_max[i] >= 0) {
  6415           tty->print("%8d", _counters_max[i]);
  6418       tty->cr();
  6423 void LinearScanStatistic::collect(LinearScan* allocator) {
  6424   inc_counter(counter_method);
  6425   if (allocator->has_fpu_registers()) {
  6426     inc_counter(counter_fpu_method);
  6428   if (allocator->num_loops() > 0) {
  6429     inc_counter(counter_loop_method);
  6431   inc_counter(counter_loop, allocator->num_loops());
  6432   inc_counter(counter_spill_slots, allocator->max_spills());
  6434   int i;
  6435   for (i = 0; i < allocator->interval_count(); i++) {
  6436     Interval* cur = allocator->interval_at(i);
  6438     if (cur != NULL) {
  6439       inc_counter(counter_interval);
  6440       inc_counter(counter_use_pos, cur->num_use_positions());
  6441       if (LinearScan::is_precolored_interval(cur)) {
  6442         inc_counter(counter_fixed_interval);
  6443         inc_counter(counter_fixed_use_pos, cur->num_use_positions());
  6446       Range* range = cur->first();
  6447       while (range != Range::end()) {
  6448         inc_counter(counter_range);
  6449         if (LinearScan::is_precolored_interval(cur)) {
  6450           inc_counter(counter_fixed_range);
  6452         range = range->next();
  6457   bool has_xhandlers = false;
  6458   // Note: only count blocks that are in code-emit order
  6459   for (i = 0; i < allocator->ir()->code()->length(); i++) {
  6460     BlockBegin* cur = allocator->ir()->code()->at(i);
  6462     inc_counter(counter_block);
  6463     if (cur->loop_depth() > 0) {
  6464       inc_counter(counter_loop_block);
  6466     if (cur->is_set(BlockBegin::exception_entry_flag)) {
  6467       inc_counter(counter_exception_block);
  6468       has_xhandlers = true;
  6471     LIR_OpList* instructions = cur->lir()->instructions_list();
  6472     for (int j = 0; j < instructions->length(); j++) {
  6473       LIR_Op* op = instructions->at(j);
  6475       inc_counter(counter_instruction);
  6477       switch (op->code()) {
  6478         case lir_label:           inc_counter(counter_label); break;
  6479         case lir_std_entry:
  6480         case lir_osr_entry:       inc_counter(counter_entry); break;
  6481         case lir_return:          inc_counter(counter_return); break;
  6483         case lir_rtcall:
  6484         case lir_static_call:
  6485         case lir_optvirtual_call:
  6486         case lir_virtual_call:    inc_counter(counter_call); break;
  6488         case lir_move: {
  6489           inc_counter(counter_move);
  6490           inc_counter(counter_move_total);
  6492           LIR_Opr in = op->as_Op1()->in_opr();
  6493           LIR_Opr res = op->as_Op1()->result_opr();
  6494           if (in->is_register()) {
  6495             if (res->is_register()) {
  6496               inc_counter(counter_move_reg_reg);
  6497             } else if (res->is_stack()) {
  6498               inc_counter(counter_move_reg_stack);
  6499             } else if (res->is_address()) {
  6500               inc_counter(counter_move_reg_mem);
  6501             } else {
  6502               ShouldNotReachHere();
  6504           } else if (in->is_stack()) {
  6505             if (res->is_register()) {
  6506               inc_counter(counter_move_stack_reg);
  6507             } else {
  6508               inc_counter(counter_move_stack_stack);
  6510           } else if (in->is_address()) {
  6511             assert(res->is_register(), "must be");
  6512             inc_counter(counter_move_mem_reg);
  6513           } else if (in->is_constant()) {
  6514             inc_counter(counter_move_const_any);
  6515           } else {
  6516             ShouldNotReachHere();
  6518           break;
  6521         case lir_cmp:             inc_counter(counter_cmp); break;
  6523         case lir_branch:
  6524         case lir_cond_float_branch: {
  6525           LIR_OpBranch* branch = op->as_OpBranch();
  6526           if (branch->block() == NULL) {
  6527             inc_counter(counter_stub_branch);
  6528           } else if (branch->cond() == lir_cond_always) {
  6529             inc_counter(counter_uncond_branch);
  6530           } else {
  6531             inc_counter(counter_cond_branch);
  6533           break;
  6536         case lir_neg:
  6537         case lir_add:
  6538         case lir_sub:
  6539         case lir_mul:
  6540         case lir_mul_strictfp:
  6541         case lir_div:
  6542         case lir_div_strictfp:
  6543         case lir_rem:
  6544         case lir_sqrt:
  6545         case lir_sin:
  6546         case lir_cos:
  6547         case lir_abs:
  6548         case lir_log10:
  6549         case lir_log:
  6550         case lir_logic_and:
  6551         case lir_logic_or:
  6552         case lir_logic_xor:
  6553         case lir_shl:
  6554         case lir_shr:
  6555         case lir_ushr:            inc_counter(counter_alu); break;
  6557         case lir_alloc_object:
  6558         case lir_alloc_array:     inc_counter(counter_alloc); break;
  6560         case lir_monaddr:
  6561         case lir_lock:
  6562         case lir_unlock:          inc_counter(counter_sync); break;
  6564         case lir_throw:           inc_counter(counter_throw); break;
  6566         case lir_unwind:          inc_counter(counter_unwind); break;
  6568         case lir_null_check:
  6569         case lir_leal:
  6570         case lir_instanceof:
  6571         case lir_checkcast:
  6572         case lir_store_check:     inc_counter(counter_typecheck); break;
  6574         case lir_fpop_raw:
  6575         case lir_fxch:
  6576         case lir_fld:             inc_counter(counter_fpu_stack); break;
  6578         case lir_nop:
  6579         case lir_push:
  6580         case lir_pop:
  6581         case lir_convert:
  6582         case lir_roundfp:
  6583         case lir_cmove:           inc_counter(counter_misc_inst); break;
  6585         default:                  inc_counter(counter_other_inst); break;
  6590   if (has_xhandlers) {
  6591     inc_counter(counter_exception_method);
  6595 void LinearScanStatistic::compute(LinearScan* allocator, LinearScanStatistic &global_statistic) {
  6596   if (CountLinearScan || TraceLinearScanLevel > 0) {
  6598     LinearScanStatistic local_statistic = LinearScanStatistic();
  6600     local_statistic.collect(allocator);
  6601     global_statistic.sum_up(local_statistic);
  6603     if (TraceLinearScanLevel > 2) {
  6604       local_statistic.print("current local statistic");
  6610 // Implementation of LinearTimers
  6612 LinearScanTimers::LinearScanTimers() {
  6613   for (int i = 0; i < number_of_timers; i++) {
  6614     timer(i)->reset();
  6618 const char* LinearScanTimers::timer_name(int idx) {
  6619   switch (idx) {
  6620     case timer_do_nothing:               return "Nothing (Time Check)";
  6621     case timer_number_instructions:      return "Number Instructions";
  6622     case timer_compute_local_live_sets:  return "Local Live Sets";
  6623     case timer_compute_global_live_sets: return "Global Live Sets";
  6624     case timer_build_intervals:          return "Build Intervals";
  6625     case timer_sort_intervals_before:    return "Sort Intervals Before";
  6626     case timer_allocate_registers:       return "Allocate Registers";
  6627     case timer_resolve_data_flow:        return "Resolve Data Flow";
  6628     case timer_sort_intervals_after:     return "Sort Intervals After";
  6629     case timer_eliminate_spill_moves:    return "Spill optimization";
  6630     case timer_assign_reg_num:           return "Assign Reg Num";
  6631     case timer_allocate_fpu_stack:       return "Allocate FPU Stack";
  6632     case timer_optimize_lir:             return "Optimize LIR";
  6633     default: ShouldNotReachHere();       return "";
  6637 void LinearScanTimers::begin_method() {
  6638   if (TimeEachLinearScan) {
  6639     // reset all timers to measure only current method
  6640     for (int i = 0; i < number_of_timers; i++) {
  6641       timer(i)->reset();
  6646 void LinearScanTimers::end_method(LinearScan* allocator) {
  6647   if (TimeEachLinearScan) {
  6649     double c = timer(timer_do_nothing)->seconds();
  6650     double total = 0;
  6651     for (int i = 1; i < number_of_timers; i++) {
  6652       total += timer(i)->seconds() - c;
  6655     if (total >= 0.0005) {
  6656       // print all information in one line for automatic processing
  6657       tty->print("@"); allocator->compilation()->method()->print_name();
  6659       tty->print("@ %d ", allocator->compilation()->method()->code_size());
  6660       tty->print("@ %d ", allocator->block_at(allocator->block_count() - 1)->last_lir_instruction_id() / 2);
  6661       tty->print("@ %d ", allocator->block_count());
  6662       tty->print("@ %d ", allocator->num_virtual_regs());
  6663       tty->print("@ %d ", allocator->interval_count());
  6664       tty->print("@ %d ", allocator->_num_calls);
  6665       tty->print("@ %d ", allocator->num_loops());
  6667       tty->print("@ %6.6f ", total);
  6668       for (int i = 1; i < number_of_timers; i++) {
  6669         tty->print("@ %4.1f ", ((timer(i)->seconds() - c) / total) * 100);
  6671       tty->cr();
  6676 void LinearScanTimers::print(double total_time) {
  6677   if (TimeLinearScan) {
  6678     // correction value: sum of dummy-timer that only measures the time that
  6679     // is necesary to start and stop itself
  6680     double c = timer(timer_do_nothing)->seconds();
  6682     for (int i = 0; i < number_of_timers; i++) {
  6683       double t = timer(i)->seconds();
  6684       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);
  6689 #endif // #ifndef PRODUCT

mercurial