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