Path: blob/master/src/hotspot/share/c1/c1_LinearScan.cpp
40931 views
/*1* Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "c1/c1_CFGPrinter.hpp"26#include "c1/c1_CodeStubs.hpp"27#include "c1/c1_Compilation.hpp"28#include "c1/c1_FrameMap.hpp"29#include "c1/c1_IR.hpp"30#include "c1/c1_LIRGenerator.hpp"31#include "c1/c1_LinearScan.hpp"32#include "c1/c1_ValueStack.hpp"33#include "code/vmreg.inline.hpp"34#include "runtime/timerTrace.hpp"35#include "utilities/bitMap.inline.hpp"3637#ifndef PRODUCT3839static LinearScanStatistic _stat_before_alloc;40static LinearScanStatistic _stat_after_asign;41static LinearScanStatistic _stat_final;4243static LinearScanTimers _total_timer;4445// helper macro for short definition of timer46#define TIME_LINEAR_SCAN(timer_name) TraceTime _block_timer("", _total_timer.timer(LinearScanTimers::timer_name), TimeLinearScan || TimeEachLinearScan, Verbose);4748#else49#define TIME_LINEAR_SCAN(timer_name)50#endif5152#ifdef ASSERT5354// helper macro for short definition of trace-output inside code55#define TRACE_LINEAR_SCAN(level, code) \56if (TraceLinearScanLevel >= level) { \57code; \58}59#else60#define TRACE_LINEAR_SCAN(level, code)61#endif6263// Map BasicType to spill size in 32-bit words, matching VMReg's notion of words64#ifdef _LP6465static int type2spill_size[T_CONFLICT+1]={ -1, 0, 0, 0, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 0, 2, 1, 2, 1, -1};66#else67static int type2spill_size[T_CONFLICT+1]={ -1, 0, 0, 0, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 0, 1, -1, 1, 1, -1};68#endif697071// Implementation of LinearScan7273LinearScan::LinearScan(IR* ir, LIRGenerator* gen, FrameMap* frame_map)74: _compilation(ir->compilation())75, _ir(ir)76, _gen(gen)77, _frame_map(frame_map)78, _cached_blocks(*ir->linear_scan_order())79, _num_virtual_regs(gen->max_virtual_register_number())80, _has_fpu_registers(false)81, _num_calls(-1)82, _max_spills(0)83, _unused_spill_slot(-1)84, _intervals(0) // initialized later with correct length85, _new_intervals_from_allocation(NULL)86, _sorted_intervals(NULL)87, _needs_full_resort(false)88, _lir_ops(0) // initialized later with correct length89, _block_of_op(0) // initialized later with correct length90, _has_info(0)91, _has_call(0)92, _interval_in_loop(0) // initialized later with correct length93, _scope_value_cache(0) // initialized later with correct length94#ifdef IA3295, _fpu_stack_allocator(NULL)96#endif97{98assert(this->ir() != NULL, "check if valid");99assert(this->compilation() != NULL, "check if valid");100assert(this->gen() != NULL, "check if valid");101assert(this->frame_map() != NULL, "check if valid");102}103104105// ********** functions for converting LIR-Operands to register numbers106//107// Emulate a flat register file comprising physical integer registers,108// physical floating-point registers and virtual registers, in that order.109// Virtual registers already have appropriate numbers, since V0 is110// the number of physical registers.111// Returns -1 for hi word if opr is a single word operand.112//113// Note: the inverse operation (calculating an operand for register numbers)114// is done in calc_operand_for_interval()115116int LinearScan::reg_num(LIR_Opr opr) {117assert(opr->is_register(), "should not call this otherwise");118119if (opr->is_virtual_register()) {120assert(opr->vreg_number() >= nof_regs, "found a virtual register with a fixed-register number");121return opr->vreg_number();122} else if (opr->is_single_cpu()) {123return opr->cpu_regnr();124} else if (opr->is_double_cpu()) {125return opr->cpu_regnrLo();126#ifdef X86127} else if (opr->is_single_xmm()) {128return opr->fpu_regnr() + pd_first_xmm_reg;129} else if (opr->is_double_xmm()) {130return opr->fpu_regnrLo() + pd_first_xmm_reg;131#endif132} else if (opr->is_single_fpu()) {133return opr->fpu_regnr() + pd_first_fpu_reg;134} else if (opr->is_double_fpu()) {135return opr->fpu_regnrLo() + pd_first_fpu_reg;136} else {137ShouldNotReachHere();138return -1;139}140}141142int LinearScan::reg_numHi(LIR_Opr opr) {143assert(opr->is_register(), "should not call this otherwise");144145if (opr->is_virtual_register()) {146return -1;147} else if (opr->is_single_cpu()) {148return -1;149} else if (opr->is_double_cpu()) {150return opr->cpu_regnrHi();151#ifdef X86152} else if (opr->is_single_xmm()) {153return -1;154} else if (opr->is_double_xmm()) {155return -1;156#endif157} else if (opr->is_single_fpu()) {158return -1;159} else if (opr->is_double_fpu()) {160return opr->fpu_regnrHi() + pd_first_fpu_reg;161} else {162ShouldNotReachHere();163return -1;164}165}166167168// ********** functions for classification of intervals169170bool LinearScan::is_precolored_interval(const Interval* i) {171return i->reg_num() < LinearScan::nof_regs;172}173174bool LinearScan::is_virtual_interval(const Interval* i) {175return i->reg_num() >= LIR_OprDesc::vreg_base;176}177178bool LinearScan::is_precolored_cpu_interval(const Interval* i) {179return i->reg_num() < LinearScan::nof_cpu_regs;180}181182bool LinearScan::is_virtual_cpu_interval(const Interval* i) {183#if defined(__SOFTFP__) || defined(E500V2)184return i->reg_num() >= LIR_OprDesc::vreg_base;185#else186return i->reg_num() >= LIR_OprDesc::vreg_base && (i->type() != T_FLOAT && i->type() != T_DOUBLE);187#endif // __SOFTFP__ or E500V2188}189190bool LinearScan::is_precolored_fpu_interval(const Interval* i) {191return i->reg_num() >= LinearScan::nof_cpu_regs && i->reg_num() < LinearScan::nof_regs;192}193194bool LinearScan::is_virtual_fpu_interval(const Interval* i) {195#if defined(__SOFTFP__) || defined(E500V2)196return false;197#else198return i->reg_num() >= LIR_OprDesc::vreg_base && (i->type() == T_FLOAT || i->type() == T_DOUBLE);199#endif // __SOFTFP__ or E500V2200}201202bool LinearScan::is_in_fpu_register(const Interval* i) {203// fixed intervals not needed for FPU stack allocation204return i->reg_num() >= nof_regs && pd_first_fpu_reg <= i->assigned_reg() && i->assigned_reg() <= pd_last_fpu_reg;205}206207bool LinearScan::is_oop_interval(const Interval* i) {208// fixed intervals never contain oops209return i->reg_num() >= nof_regs && i->type() == T_OBJECT;210}211212213// ********** General helper functions214215// compute next unused stack index that can be used for spilling216int LinearScan::allocate_spill_slot(bool double_word) {217int spill_slot;218if (double_word) {219if ((_max_spills & 1) == 1) {220// alignment of double-word values221// the hole because of the alignment is filled with the next single-word value222assert(_unused_spill_slot == -1, "wasting a spill slot");223_unused_spill_slot = _max_spills;224_max_spills++;225}226spill_slot = _max_spills;227_max_spills += 2;228229} else if (_unused_spill_slot != -1) {230// re-use hole that was the result of a previous double-word alignment231spill_slot = _unused_spill_slot;232_unused_spill_slot = -1;233234} else {235spill_slot = _max_spills;236_max_spills++;237}238239int result = spill_slot + LinearScan::nof_regs + frame_map()->argcount();240241// if too many slots used, bailout compilation.242if (result > 2000) {243bailout("too many stack slots used");244}245246return result;247}248249void LinearScan::assign_spill_slot(Interval* it) {250// assign the canonical spill slot of the parent (if a part of the interval251// is already spilled) or allocate a new spill slot252if (it->canonical_spill_slot() >= 0) {253it->assign_reg(it->canonical_spill_slot());254} else {255int spill = allocate_spill_slot(type2spill_size[it->type()] == 2);256it->set_canonical_spill_slot(spill);257it->assign_reg(spill);258}259}260261void LinearScan::propagate_spill_slots() {262if (!frame_map()->finalize_frame(max_spills())) {263bailout("frame too large");264}265}266267// create a new interval with a predefined reg_num268// (only used for parent intervals that are created during the building phase)269Interval* LinearScan::create_interval(int reg_num) {270assert(_intervals.at(reg_num) == NULL, "overwriting exisiting interval");271272Interval* interval = new Interval(reg_num);273_intervals.at_put(reg_num, interval);274275// assign register number for precolored intervals276if (reg_num < LIR_OprDesc::vreg_base) {277interval->assign_reg(reg_num);278}279return interval;280}281282// assign a new reg_num to the interval and append it to the list of intervals283// (only used for child intervals that are created during register allocation)284void LinearScan::append_interval(Interval* it) {285it->set_reg_num(_intervals.length());286_intervals.append(it);287IntervalList* new_intervals = _new_intervals_from_allocation;288if (new_intervals == NULL) {289new_intervals = _new_intervals_from_allocation = new IntervalList();290}291new_intervals->append(it);292}293294// copy the vreg-flags if an interval is split295void LinearScan::copy_register_flags(Interval* from, Interval* to) {296if (gen()->is_vreg_flag_set(from->reg_num(), LIRGenerator::byte_reg)) {297gen()->set_vreg_flag(to->reg_num(), LIRGenerator::byte_reg);298}299if (gen()->is_vreg_flag_set(from->reg_num(), LIRGenerator::callee_saved)) {300gen()->set_vreg_flag(to->reg_num(), LIRGenerator::callee_saved);301}302303// Note: do not copy the must_start_in_memory flag because it is not necessary for child304// intervals (only the very beginning of the interval must be in memory)305}306307308// ********** spill move optimization309// eliminate moves from register to stack if stack slot is known to be correct310311// called during building of intervals312void LinearScan::change_spill_definition_pos(Interval* interval, int def_pos) {313assert(interval->is_split_parent(), "can only be called for split parents");314315switch (interval->spill_state()) {316case noDefinitionFound:317assert(interval->spill_definition_pos() == -1, "must no be set before");318interval->set_spill_definition_pos(def_pos);319interval->set_spill_state(oneDefinitionFound);320break;321322case oneDefinitionFound:323assert(def_pos <= interval->spill_definition_pos(), "positions are processed in reverse order when intervals are created");324if (def_pos < interval->spill_definition_pos() - 2) {325// second definition found, so no spill optimization possible for this interval326interval->set_spill_state(noOptimization);327} else {328// two consecutive definitions (because of two-operand LIR form)329assert(block_of_op_with_id(def_pos) == block_of_op_with_id(interval->spill_definition_pos()), "block must be equal");330}331break;332333case noOptimization:334// nothing to do335break;336337default:338assert(false, "other states not allowed at this time");339}340}341342// called during register allocation343void LinearScan::change_spill_state(Interval* interval, int spill_pos) {344switch (interval->spill_state()) {345case oneDefinitionFound: {346int def_loop_depth = block_of_op_with_id(interval->spill_definition_pos())->loop_depth();347int spill_loop_depth = block_of_op_with_id(spill_pos)->loop_depth();348349if (def_loop_depth < spill_loop_depth) {350// the loop depth of the spilling position is higher then the loop depth351// at the definition of the interval -> move write to memory out of loop352// by storing at definitin of the interval353interval->set_spill_state(storeAtDefinition);354} else {355// the interval is currently spilled only once, so for now there is no356// reason to store the interval at the definition357interval->set_spill_state(oneMoveInserted);358}359break;360}361362case oneMoveInserted: {363// the interval is spilled more then once, so it is better to store it to364// memory at the definition365interval->set_spill_state(storeAtDefinition);366break;367}368369case storeAtDefinition:370case startInMemory:371case noOptimization:372case noDefinitionFound:373// nothing to do374break;375376default:377assert(false, "other states not allowed at this time");378}379}380381382bool LinearScan::must_store_at_definition(const Interval* i) {383return i->is_split_parent() && i->spill_state() == storeAtDefinition;384}385386// called once before asignment of register numbers387void LinearScan::eliminate_spill_moves() {388TIME_LINEAR_SCAN(timer_eliminate_spill_moves);389TRACE_LINEAR_SCAN(3, tty->print_cr("***** Eliminating unnecessary spill moves"));390391// collect all intervals that must be stored after their definion.392// the list is sorted by Interval::spill_definition_pos393Interval* interval;394Interval* temp_list;395create_unhandled_lists(&interval, &temp_list, must_store_at_definition, NULL);396397#ifdef ASSERT398Interval* prev = NULL;399Interval* temp = interval;400while (temp != Interval::end()) {401assert(temp->spill_definition_pos() > 0, "invalid spill definition pos");402if (prev != NULL) {403assert(temp->from() >= prev->from(), "intervals not sorted");404assert(temp->spill_definition_pos() >= prev->spill_definition_pos(), "when intervals are sorted by from, then they must also be sorted by spill_definition_pos");405}406407assert(temp->canonical_spill_slot() >= LinearScan::nof_regs, "interval has no spill slot assigned");408assert(temp->spill_definition_pos() >= temp->from(), "invalid order");409assert(temp->spill_definition_pos() <= temp->from() + 2, "only intervals defined once at their start-pos can be optimized");410411TRACE_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()));412413temp = temp->next();414}415#endif416417LIR_InsertionBuffer insertion_buffer;418int num_blocks = block_count();419for (int i = 0; i < num_blocks; i++) {420BlockBegin* block = block_at(i);421LIR_OpList* instructions = block->lir()->instructions_list();422int num_inst = instructions->length();423bool has_new = false;424425// iterate all instructions of the block. skip the first because it is always a label426for (int j = 1; j < num_inst; j++) {427LIR_Op* op = instructions->at(j);428int op_id = op->id();429430if (op_id == -1) {431// remove move from register to stack if the stack slot is guaranteed to be correct.432// only moves that have been inserted by LinearScan can be removed.433assert(op->code() == lir_move, "only moves can have a op_id of -1");434assert(op->as_Op1() != NULL, "move must be LIR_Op1");435assert(op->as_Op1()->result_opr()->is_virtual(), "LinearScan inserts only moves to virtual registers");436437LIR_Op1* op1 = (LIR_Op1*)op;438Interval* interval = interval_at(op1->result_opr()->vreg_number());439440if (interval->assigned_reg() >= LinearScan::nof_regs && interval->always_in_memory()) {441// move target is a stack slot that is always correct, so eliminate instruction442TRACE_LINEAR_SCAN(4, tty->print_cr("eliminating move from interval %d to %d", op1->in_opr()->vreg_number(), op1->result_opr()->vreg_number()));443instructions->at_put(j, NULL); // NULL-instructions are deleted by assign_reg_num444}445446} else {447// insert move from register to stack just after the beginning of the interval448assert(interval == Interval::end() || interval->spill_definition_pos() >= op_id, "invalid order");449assert(interval == Interval::end() || (interval->is_split_parent() && interval->spill_state() == storeAtDefinition), "invalid interval");450451while (interval != Interval::end() && interval->spill_definition_pos() == op_id) {452if (!has_new) {453// prepare insertion buffer (appended when all instructions of the block are processed)454insertion_buffer.init(block->lir());455has_new = true;456}457458LIR_Opr from_opr = operand_for_interval(interval);459LIR_Opr to_opr = canonical_spill_opr(interval);460assert(from_opr->is_fixed_cpu() || from_opr->is_fixed_fpu(), "from operand must be a register");461assert(to_opr->is_stack(), "to operand must be a stack slot");462463insertion_buffer.move(j, from_opr, to_opr);464TRACE_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));465466interval = interval->next();467}468}469} // end of instruction iteration470471if (has_new) {472block->lir()->append(&insertion_buffer);473}474} // end of block iteration475476assert(interval == Interval::end(), "missed an interval");477}478479480// ********** Phase 1: number all instructions in all blocks481// Compute depth-first and linear scan block orders, and number LIR_Op nodes for linear scan.482483void LinearScan::number_instructions() {484{485// dummy-timer to measure the cost of the timer itself486// (this time is then subtracted from all other timers to get the real value)487TIME_LINEAR_SCAN(timer_do_nothing);488}489TIME_LINEAR_SCAN(timer_number_instructions);490491// Assign IDs to LIR nodes and build a mapping, lir_ops, from ID to LIR_Op node.492int num_blocks = block_count();493int num_instructions = 0;494int i;495for (i = 0; i < num_blocks; i++) {496num_instructions += block_at(i)->lir()->instructions_list()->length();497}498499// initialize with correct length500_lir_ops = LIR_OpArray(num_instructions, num_instructions, NULL);501_block_of_op = BlockBeginArray(num_instructions, num_instructions, NULL);502503int op_id = 0;504int idx = 0;505506for (i = 0; i < num_blocks; i++) {507BlockBegin* block = block_at(i);508block->set_first_lir_instruction_id(op_id);509LIR_OpList* instructions = block->lir()->instructions_list();510511int num_inst = instructions->length();512for (int j = 0; j < num_inst; j++) {513LIR_Op* op = instructions->at(j);514op->set_id(op_id);515516_lir_ops.at_put(idx, op);517_block_of_op.at_put(idx, block);518assert(lir_op_with_id(op_id) == op, "must match");519520idx++;521op_id += 2; // numbering of lir_ops by two522}523block->set_last_lir_instruction_id(op_id - 2);524}525assert(idx == num_instructions, "must match");526assert(idx * 2 == op_id, "must match");527528_has_call.initialize(num_instructions);529_has_info.initialize(num_instructions);530}531532533// ********** Phase 2: compute local live sets separately for each block534// (sets live_gen and live_kill for each block)535536void LinearScan::set_live_gen_kill(Value value, LIR_Op* op, BitMap& live_gen, BitMap& live_kill) {537LIR_Opr opr = value->operand();538Constant* con = value->as_Constant();539540// check some asumptions about debug information541assert(!value->type()->is_illegal(), "if this local is used by the interpreter it shouldn't be of indeterminate type");542assert(con == NULL || opr->is_virtual() || opr->is_constant() || opr->is_illegal(), "asumption: Constant instructions have only constant operands");543assert(con != NULL || opr->is_virtual(), "asumption: non-Constant instructions have only virtual operands");544545if ((con == NULL || con->is_pinned()) && opr->is_register()) {546assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");547int reg = opr->vreg_number();548if (!live_kill.at(reg)) {549live_gen.set_bit(reg);550TRACE_LINEAR_SCAN(4, tty->print_cr(" Setting live_gen for value %c%d, LIR op_id %d, register number %d", value->type()->tchar(), value->id(), op->id(), reg));551}552}553}554555556void LinearScan::compute_local_live_sets() {557TIME_LINEAR_SCAN(timer_compute_local_live_sets);558559int num_blocks = block_count();560int live_size = live_set_size();561bool local_has_fpu_registers = false;562int local_num_calls = 0;563LIR_OpVisitState visitor;564565BitMap2D local_interval_in_loop = BitMap2D(_num_virtual_regs, num_loops());566567// iterate all blocks568for (int i = 0; i < num_blocks; i++) {569BlockBegin* block = block_at(i);570571ResourceBitMap live_gen(live_size);572ResourceBitMap live_kill(live_size);573574if (block->is_set(BlockBegin::exception_entry_flag)) {575// Phi functions at the begin of an exception handler are576// implicitly defined (= killed) at the beginning of the block.577for_each_phi_fun(block, phi,578if (!phi->is_illegal()) { live_kill.set_bit(phi->operand()->vreg_number()); }579);580}581582LIR_OpList* instructions = block->lir()->instructions_list();583int num_inst = instructions->length();584585// iterate all instructions of the block. skip the first because it is always a label586assert(visitor.no_operands(instructions->at(0)), "first operation must always be a label");587for (int j = 1; j < num_inst; j++) {588LIR_Op* op = instructions->at(j);589590// visit operation to collect all operands591visitor.visit(op);592593if (visitor.has_call()) {594_has_call.set_bit(op->id() >> 1);595local_num_calls++;596}597if (visitor.info_count() > 0) {598_has_info.set_bit(op->id() >> 1);599}600601// iterate input operands of instruction602int k, n, reg;603n = visitor.opr_count(LIR_OpVisitState::inputMode);604for (k = 0; k < n; k++) {605LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::inputMode, k);606assert(opr->is_register(), "visitor should only return register operands");607608if (opr->is_virtual_register()) {609assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");610reg = opr->vreg_number();611if (!live_kill.at(reg)) {612live_gen.set_bit(reg);613TRACE_LINEAR_SCAN(4, tty->print_cr(" Setting live_gen for register %d at instruction %d", reg, op->id()));614}615if (block->loop_index() >= 0) {616local_interval_in_loop.set_bit(reg, block->loop_index());617}618local_has_fpu_registers = local_has_fpu_registers || opr->is_virtual_fpu();619}620621#ifdef ASSERT622// fixed intervals are never live at block boundaries, so623// they need not be processed in live sets.624// this is checked by these assertions to be sure about it.625// the entry block may have incoming values in registers, which is ok.626if (!opr->is_virtual_register() && block != ir()->start()) {627reg = reg_num(opr);628if (is_processed_reg_num(reg)) {629assert(live_kill.at(reg), "using fixed register that is not defined in this block");630}631reg = reg_numHi(opr);632if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {633assert(live_kill.at(reg), "using fixed register that is not defined in this block");634}635}636#endif637}638639// Add uses of live locals from interpreter's point of view for proper debug information generation640n = visitor.info_count();641for (k = 0; k < n; k++) {642CodeEmitInfo* info = visitor.info_at(k);643ValueStack* stack = info->stack();644for_each_state_value(stack, value,645set_live_gen_kill(value, op, live_gen, live_kill)646);647}648649// iterate temp operands of instruction650n = visitor.opr_count(LIR_OpVisitState::tempMode);651for (k = 0; k < n; k++) {652LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::tempMode, k);653assert(opr->is_register(), "visitor should only return register operands");654655if (opr->is_virtual_register()) {656assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");657reg = opr->vreg_number();658live_kill.set_bit(reg);659if (block->loop_index() >= 0) {660local_interval_in_loop.set_bit(reg, block->loop_index());661}662local_has_fpu_registers = local_has_fpu_registers || opr->is_virtual_fpu();663}664665#ifdef ASSERT666// fixed intervals are never live at block boundaries, so667// they need not be processed in live sets668// process them only in debug mode so that this can be checked669if (!opr->is_virtual_register()) {670reg = reg_num(opr);671if (is_processed_reg_num(reg)) {672live_kill.set_bit(reg_num(opr));673}674reg = reg_numHi(opr);675if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {676live_kill.set_bit(reg);677}678}679#endif680}681682// iterate output operands of instruction683n = visitor.opr_count(LIR_OpVisitState::outputMode);684for (k = 0; k < n; k++) {685LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::outputMode, k);686assert(opr->is_register(), "visitor should only return register operands");687688if (opr->is_virtual_register()) {689assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");690reg = opr->vreg_number();691live_kill.set_bit(reg);692if (block->loop_index() >= 0) {693local_interval_in_loop.set_bit(reg, block->loop_index());694}695local_has_fpu_registers = local_has_fpu_registers || opr->is_virtual_fpu();696}697698#ifdef ASSERT699// fixed intervals are never live at block boundaries, so700// they need not be processed in live sets701// process them only in debug mode so that this can be checked702if (!opr->is_virtual_register()) {703reg = reg_num(opr);704if (is_processed_reg_num(reg)) {705live_kill.set_bit(reg_num(opr));706}707reg = reg_numHi(opr);708if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {709live_kill.set_bit(reg);710}711}712#endif713}714} // end of instruction iteration715716block->set_live_gen (live_gen);717block->set_live_kill(live_kill);718block->set_live_in (ResourceBitMap(live_size));719block->set_live_out (ResourceBitMap(live_size));720721TRACE_LINEAR_SCAN(4, tty->print("live_gen B%d ", block->block_id()); print_bitmap(block->live_gen()));722TRACE_LINEAR_SCAN(4, tty->print("live_kill B%d ", block->block_id()); print_bitmap(block->live_kill()));723} // end of block iteration724725// propagate local calculated information into LinearScan object726_has_fpu_registers = local_has_fpu_registers;727compilation()->set_has_fpu_code(local_has_fpu_registers);728729_num_calls = local_num_calls;730_interval_in_loop = local_interval_in_loop;731}732733734// ********** Phase 3: perform a backward dataflow analysis to compute global live sets735// (sets live_in and live_out for each block)736737void LinearScan::compute_global_live_sets() {738TIME_LINEAR_SCAN(timer_compute_global_live_sets);739740int num_blocks = block_count();741bool change_occurred;742bool change_occurred_in_block;743int iteration_count = 0;744ResourceBitMap live_out(live_set_size()); // scratch set for calculations745746// Perform a backward dataflow analysis to compute live_out and live_in for each block.747// The loop is executed until a fixpoint is reached (no changes in an iteration)748// Exception handlers must be processed because not all live values are749// present in the state array, e.g. because of global value numbering750do {751change_occurred = false;752753// iterate all blocks in reverse order754for (int i = num_blocks - 1; i >= 0; i--) {755BlockBegin* block = block_at(i);756757change_occurred_in_block = false;758759// live_out(block) is the union of live_in(sux), for successors sux of block760int n = block->number_of_sux();761int e = block->number_of_exception_handlers();762if (n + e > 0) {763// block has successors764if (n > 0) {765live_out.set_from(block->sux_at(0)->live_in());766for (int j = 1; j < n; j++) {767live_out.set_union(block->sux_at(j)->live_in());768}769} else {770live_out.clear();771}772for (int j = 0; j < e; j++) {773live_out.set_union(block->exception_handler_at(j)->live_in());774}775776if (!block->live_out().is_same(live_out)) {777// A change occurred. Swap the old and new live out sets to avoid copying.778ResourceBitMap temp = block->live_out();779block->set_live_out(live_out);780live_out = temp;781782change_occurred = true;783change_occurred_in_block = true;784}785}786787if (iteration_count == 0 || change_occurred_in_block) {788// live_in(block) is the union of live_gen(block) with (live_out(block) & !live_kill(block))789// note: live_in has to be computed only in first iteration or if live_out has changed!790ResourceBitMap live_in = block->live_in();791live_in.set_from(block->live_out());792live_in.set_difference(block->live_kill());793live_in.set_union(block->live_gen());794}795796#ifdef ASSERT797if (TraceLinearScanLevel >= 4) {798char c = ' ';799if (iteration_count == 0 || change_occurred_in_block) {800c = '*';801}802tty->print("(%d) live_in%c B%d ", iteration_count, c, block->block_id()); print_bitmap(block->live_in());803tty->print("(%d) live_out%c B%d ", iteration_count, c, block->block_id()); print_bitmap(block->live_out());804}805#endif806}807iteration_count++;808809if (change_occurred && iteration_count > 50) {810BAILOUT("too many iterations in compute_global_live_sets");811}812} while (change_occurred);813814815#ifdef ASSERT816// check that fixed intervals are not live at block boundaries817// (live set must be empty at fixed intervals)818for (int i = 0; i < num_blocks; i++) {819BlockBegin* block = block_at(i);820for (int j = 0; j < LIR_OprDesc::vreg_base; j++) {821assert(block->live_in().at(j) == false, "live_in set of fixed register must be empty");822assert(block->live_out().at(j) == false, "live_out set of fixed register must be empty");823assert(block->live_gen().at(j) == false, "live_gen set of fixed register must be empty");824}825}826#endif827828// check that the live_in set of the first block is empty829ResourceBitMap live_in_args(ir()->start()->live_in().size());830if (!ir()->start()->live_in().is_same(live_in_args)) {831#ifdef ASSERT832tty->print_cr("Error: live_in set of first block must be empty (when this fails, virtual registers are used before they are defined)");833tty->print_cr("affected registers:");834print_bitmap(ir()->start()->live_in());835836// print some additional information to simplify debugging837for (unsigned int i = 0; i < ir()->start()->live_in().size(); i++) {838if (ir()->start()->live_in().at(i)) {839Instruction* instr = gen()->instruction_for_vreg(i);840tty->print_cr("* vreg %d (HIR instruction %c%d)", i, instr == NULL ? ' ' : instr->type()->tchar(), instr == NULL ? 0 : instr->id());841842for (int j = 0; j < num_blocks; j++) {843BlockBegin* block = block_at(j);844if (block->live_gen().at(i)) {845tty->print_cr(" used in block B%d", block->block_id());846}847if (block->live_kill().at(i)) {848tty->print_cr(" defined in block B%d", block->block_id());849}850}851}852}853854#endif855// when this fails, virtual registers are used before they are defined.856assert(false, "live_in set of first block must be empty");857// bailout of if this occurs in product mode.858bailout("live_in set of first block not empty");859}860}861862863// ********** Phase 4: build intervals864// (fills the list _intervals)865866void LinearScan::add_use(Value value, int from, int to, IntervalUseKind use_kind) {867assert(!value->type()->is_illegal(), "if this value is used by the interpreter it shouldn't be of indeterminate type");868LIR_Opr opr = value->operand();869Constant* con = value->as_Constant();870871if ((con == NULL || con->is_pinned()) && opr->is_register()) {872assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");873add_use(opr, from, to, use_kind);874}875}876877878void LinearScan::add_def(LIR_Opr opr, int def_pos, IntervalUseKind use_kind) {879TRACE_LINEAR_SCAN(2, tty->print(" def "); opr->print(tty); tty->print_cr(" def_pos %d (%d)", def_pos, use_kind));880assert(opr->is_register(), "should not be called otherwise");881882if (opr->is_virtual_register()) {883assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");884add_def(opr->vreg_number(), def_pos, use_kind, opr->type_register());885886} else {887int reg = reg_num(opr);888if (is_processed_reg_num(reg)) {889add_def(reg, def_pos, use_kind, opr->type_register());890}891reg = reg_numHi(opr);892if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {893add_def(reg, def_pos, use_kind, opr->type_register());894}895}896}897898void LinearScan::add_use(LIR_Opr opr, int from, int to, IntervalUseKind use_kind) {899TRACE_LINEAR_SCAN(2, tty->print(" use "); opr->print(tty); tty->print_cr(" from %d to %d (%d)", from, to, use_kind));900assert(opr->is_register(), "should not be called otherwise");901902if (opr->is_virtual_register()) {903assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");904add_use(opr->vreg_number(), from, to, use_kind, opr->type_register());905906} else {907int reg = reg_num(opr);908if (is_processed_reg_num(reg)) {909add_use(reg, from, to, use_kind, opr->type_register());910}911reg = reg_numHi(opr);912if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {913add_use(reg, from, to, use_kind, opr->type_register());914}915}916}917918void LinearScan::add_temp(LIR_Opr opr, int temp_pos, IntervalUseKind use_kind) {919TRACE_LINEAR_SCAN(2, tty->print(" temp "); opr->print(tty); tty->print_cr(" temp_pos %d (%d)", temp_pos, use_kind));920assert(opr->is_register(), "should not be called otherwise");921922if (opr->is_virtual_register()) {923assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");924add_temp(opr->vreg_number(), temp_pos, use_kind, opr->type_register());925926} else {927int reg = reg_num(opr);928if (is_processed_reg_num(reg)) {929add_temp(reg, temp_pos, use_kind, opr->type_register());930}931reg = reg_numHi(opr);932if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {933add_temp(reg, temp_pos, use_kind, opr->type_register());934}935}936}937938939void LinearScan::add_def(int reg_num, int def_pos, IntervalUseKind use_kind, BasicType type) {940Interval* interval = interval_at(reg_num);941if (interval != NULL) {942assert(interval->reg_num() == reg_num, "wrong interval");943944if (type != T_ILLEGAL) {945interval->set_type(type);946}947948Range* r = interval->first();949if (r->from() <= def_pos) {950// Update the starting point (when a range is first created for a use, its951// start is the beginning of the current block until a def is encountered.)952r->set_from(def_pos);953interval->add_use_pos(def_pos, use_kind);954955} else {956// Dead value - make vacuous interval957// also add use_kind for dead intervals958interval->add_range(def_pos, def_pos + 1);959interval->add_use_pos(def_pos, use_kind);960TRACE_LINEAR_SCAN(2, tty->print_cr("Warning: def of reg %d at %d occurs without use", reg_num, def_pos));961}962963} else {964// Dead value - make vacuous interval965// also add use_kind for dead intervals966interval = create_interval(reg_num);967if (type != T_ILLEGAL) {968interval->set_type(type);969}970971interval->add_range(def_pos, def_pos + 1);972interval->add_use_pos(def_pos, use_kind);973TRACE_LINEAR_SCAN(2, tty->print_cr("Warning: dead value %d at %d in live intervals", reg_num, def_pos));974}975976change_spill_definition_pos(interval, def_pos);977if (use_kind == noUse && interval->spill_state() <= startInMemory) {978// detection of method-parameters and roundfp-results979// TODO: move this directly to position where use-kind is computed980interval->set_spill_state(startInMemory);981}982}983984void LinearScan::add_use(int reg_num, int from, int to, IntervalUseKind use_kind, BasicType type) {985Interval* interval = interval_at(reg_num);986if (interval == NULL) {987interval = create_interval(reg_num);988}989assert(interval->reg_num() == reg_num, "wrong interval");990991if (type != T_ILLEGAL) {992interval->set_type(type);993}994995interval->add_range(from, to);996interval->add_use_pos(to, use_kind);997}998999void LinearScan::add_temp(int reg_num, int temp_pos, IntervalUseKind use_kind, BasicType type) {1000Interval* interval = interval_at(reg_num);1001if (interval == NULL) {1002interval = create_interval(reg_num);1003}1004assert(interval->reg_num() == reg_num, "wrong interval");10051006if (type != T_ILLEGAL) {1007interval->set_type(type);1008}10091010interval->add_range(temp_pos, temp_pos + 1);1011interval->add_use_pos(temp_pos, use_kind);1012}101310141015// the results of this functions are used for optimizing spilling and reloading1016// 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) {1019if (op->code() == lir_move) {1020assert(op->as_Op1() != NULL, "lir_move must be LIR_Op1");1021LIR_Op1* move = (LIR_Op1*)op;1022LIR_Opr res = move->result_opr();1023bool result_in_memory = res->is_virtual() && gen()->is_vreg_flag_set(res->vreg_number(), LIRGenerator::must_start_in_memory);10241025if (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.1028return noUse;10291030} else if (move->in_opr()->is_stack()) {1031// method argument (condition must be equal to handle_method_arguments)1032return noUse;10331034} else if (move->in_opr()->is_register() && move->result_opr()->is_register()) {1035// Move from register to register1036if (block_of_op_with_id(op->id())->is_set(BlockBegin::osr_entry_flag)) {1037// special handling of phi-function moves inside osr-entry blocks1038// input operand must have a register instead of output operand (leads to better register allocation)1039return shouldHaveRegister;1040}1041}1042}10431044if (opr->is_virtual() &&1045gen()->is_vreg_flag_set(opr->vreg_number(), LIRGenerator::must_start_in_memory)) {1046// result is a stack-slot, so prevent immediate reloading1047return noUse;1048}10491050// all other operands require a register1051return mustHaveRegister;1052}10531054IntervalUseKind LinearScan::use_kind_of_input_operand(LIR_Op* op, LIR_Opr opr) {1055if (op->code() == lir_move) {1056assert(op->as_Op1() != NULL, "lir_move must be LIR_Op1");1057LIR_Op1* move = (LIR_Op1*)op;1058LIR_Opr res = move->result_opr();1059bool result_in_memory = res->is_virtual() && gen()->is_vreg_flag_set(res->vreg_number(), LIRGenerator::must_start_in_memory);10601061if (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 register1064return mustHaveRegister;10651066} else if (move->in_opr()->is_register() && move->result_opr()->is_register()) {1067// Move from register to register1068if (block_of_op_with_id(op->id())->is_set(BlockBegin::osr_entry_flag)) {1069// special handling of phi-function moves inside osr-entry blocks1070// input operand must have a register instead of output operand (leads to better register allocation)1071return mustHaveRegister;1072}10731074// 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 register1076return shouldHaveRegister;1077}1078}107910801081#if defined(X86) || defined(S390)1082if (op->code() == lir_cmove) {1083// conditional moves can handle stack operands1084assert(op->result_opr()->is_register(), "result must always be in a register");1085return shouldHaveRegister;1086}10871088// optimizations for second input operand of arithmehtic operations on Intel1089// this operand is allowed to be on the stack in some cases1090BasicType opr_type = opr->type_register();1091if (opr_type == T_FLOAT || opr_type == T_DOUBLE) {1092if (IA32_ONLY( (UseSSE == 1 && opr_type == T_FLOAT) || UseSSE >= 2 ) NOT_IA32( true )) {1093// SSE float instruction (T_DOUBLE only supported with SSE2)1094switch (op->code()) {1095case lir_cmp:1096case lir_add:1097case lir_sub:1098case lir_mul:1099case lir_div:1100{1101assert(op->as_Op2() != NULL, "must be LIR_Op2");1102LIR_Op2* op2 = (LIR_Op2*)op;1103if (op2->in_opr1() != op2->in_opr2() && op2->in_opr2() == opr) {1104assert((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");1105return shouldHaveRegister;1106}1107}1108default:1109break;1110}1111} else {1112// FPU stack float instruction1113switch (op->code()) {1114case lir_add:1115case lir_sub:1116case lir_mul:1117case lir_div:1118{1119assert(op->as_Op2() != NULL, "must be LIR_Op2");1120LIR_Op2* op2 = (LIR_Op2*)op;1121if (op2->in_opr1() != op2->in_opr2() && op2->in_opr2() == opr) {1122assert((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");1123return shouldHaveRegister;1124}1125}1126default:1127break;1128}1129}1130// We want to sometimes use logical operations on pointers, in particular in GC barriers.1131// Since 64bit logical operations do not current support operands on stack, we have to make sure1132// T_OBJECT doesn't get spilled along with T_LONG.1133} else if (opr_type != T_LONG LP64_ONLY(&& opr_type != T_OBJECT)) {1134// integer instruction (note: long operands must always be in register)1135switch (op->code()) {1136case lir_cmp:1137case lir_add:1138case lir_sub:1139case lir_logic_and:1140case lir_logic_or:1141case lir_logic_xor:1142{1143assert(op->as_Op2() != NULL, "must be LIR_Op2");1144LIR_Op2* op2 = (LIR_Op2*)op;1145if (op2->in_opr1() != op2->in_opr2() && op2->in_opr2() == opr) {1146assert((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");1147return shouldHaveRegister;1148}1149}1150default:1151break;1152}1153}1154#endif // X86 || S39011551156// all other operands require a register1157return mustHaveRegister;1158}115911601161void LinearScan::handle_method_arguments(LIR_Op* op) {1162// special handling for method arguments (moves from stack to virtual register):1163// the interval gets no register assigned, but the stack slot.1164// it is split before the first use by the register allocator.11651166if (op->code() == lir_move) {1167assert(op->as_Op1() != NULL, "must be LIR_Op1");1168LIR_Op1* move = (LIR_Op1*)op;11691170if (move->in_opr()->is_stack()) {1171#ifdef ASSERT1172int arg_size = compilation()->method()->arg_size();1173LIR_Opr o = move->in_opr();1174if (o->is_single_stack()) {1175assert(o->single_stack_ix() >= 0 && o->single_stack_ix() < arg_size, "out of range");1176} else if (o->is_double_stack()) {1177assert(o->double_stack_ix() >= 0 && o->double_stack_ix() < arg_size, "out of range");1178} else {1179ShouldNotReachHere();1180}11811182assert(move->id() > 0, "invalid id");1183assert(block_of_op_with_id(move->id())->number_of_preds() == 0, "move from stack must be in first block");1184assert(move->result_opr()->is_virtual(), "result of move must be a virtual register");11851186TRACE_LINEAR_SCAN(4, tty->print_cr("found move from stack slot %d to vreg %d", o->is_single_stack() ? o->single_stack_ix() : o->double_stack_ix(), reg_num(move->result_opr())));1187#endif11881189Interval* interval = interval_at(reg_num(move->result_opr()));11901191int stack_slot = LinearScan::nof_regs + (move->in_opr()->is_single_stack() ? move->in_opr()->single_stack_ix() : move->in_opr()->double_stack_ix());1192interval->set_canonical_spill_slot(stack_slot);1193interval->assign_reg(stack_slot);1194}1195}1196}11971198void LinearScan::handle_doubleword_moves(LIR_Op* op) {1199// special handling for doubleword move from memory to register:1200// in this case the registers of the input address and the result1201// registers must not overlap -> add a temp range for the input registers1202if (op->code() == lir_move) {1203assert(op->as_Op1() != NULL, "must be LIR_Op1");1204LIR_Op1* move = (LIR_Op1*)op;12051206if (move->result_opr()->is_double_cpu() && move->in_opr()->is_pointer()) {1207LIR_Address* address = move->in_opr()->as_address_ptr();1208if (address != NULL) {1209if (address->base()->is_valid()) {1210add_temp(address->base(), op->id(), noUse);1211}1212if (address->index()->is_valid()) {1213add_temp(address->index(), op->id(), noUse);1214}1215}1216}1217}1218}12191220void LinearScan::add_register_hints(LIR_Op* op) {1221switch (op->code()) {1222case lir_move: // fall through1223case lir_convert: {1224assert(op->as_Op1() != NULL, "lir_move, lir_convert must be LIR_Op1");1225LIR_Op1* move = (LIR_Op1*)op;12261227LIR_Opr move_from = move->in_opr();1228LIR_Opr move_to = move->result_opr();12291230if (move_to->is_register() && move_from->is_register()) {1231Interval* from = interval_at(reg_num(move_from));1232Interval* to = interval_at(reg_num(move_to));1233if (from != NULL && to != NULL) {1234to->set_register_hint(from);1235TRACE_LINEAR_SCAN(4, tty->print_cr("operation at op_id %d: added hint from interval %d to %d", move->id(), from->reg_num(), to->reg_num()));1236}1237}1238break;1239}1240case lir_cmove: {1241assert(op->as_Op2() != NULL, "lir_cmove must be LIR_Op2");1242LIR_Op2* cmove = (LIR_Op2*)op;12431244LIR_Opr move_from = cmove->in_opr1();1245LIR_Opr move_to = cmove->result_opr();12461247if (move_to->is_register() && move_from->is_register()) {1248Interval* from = interval_at(reg_num(move_from));1249Interval* to = interval_at(reg_num(move_to));1250if (from != NULL && to != NULL) {1251to->set_register_hint(from);1252TRACE_LINEAR_SCAN(4, tty->print_cr("operation at op_id %d: added hint from interval %d to %d", cmove->id(), from->reg_num(), to->reg_num()));1253}1254}1255break;1256}1257default:1258break;1259}1260}126112621263void LinearScan::build_intervals() {1264TIME_LINEAR_SCAN(timer_build_intervals);12651266// initialize interval list with expected number of intervals1267// (32 is added to have some space for split children without having to resize the list)1268_intervals = IntervalList(num_virtual_regs() + 32);1269// initialize all slots that are used by build_intervals1270_intervals.at_put_grow(num_virtual_regs() - 1, NULL, NULL);12711272// create a list with all caller-save registers (cpu, fpu, xmm)1273// when an instruction is a call, a temp range is created for all these registers1274int num_caller_save_registers = 0;1275int caller_save_registers[LinearScan::nof_regs];12761277int i;1278for (i = 0; i < FrameMap::nof_caller_save_cpu_regs(); i++) {1279LIR_Opr opr = FrameMap::caller_save_cpu_reg_at(i);1280assert(opr->is_valid() && opr->is_register(), "FrameMap should not return invalid operands");1281assert(reg_numHi(opr) == -1, "missing addition of range for hi-register");1282caller_save_registers[num_caller_save_registers++] = reg_num(opr);1283}12841285// temp ranges for fpu registers are only created when the method has1286// virtual fpu operands. Otherwise no allocation for fpu registers is1287// performed and so the temp ranges would be useless1288if (has_fpu_registers()) {1289#ifdef X861290if (UseSSE < 2) {1291#endif // X861292for (i = 0; i < FrameMap::nof_caller_save_fpu_regs; i++) {1293LIR_Opr opr = FrameMap::caller_save_fpu_reg_at(i);1294assert(opr->is_valid() && opr->is_register(), "FrameMap should not return invalid operands");1295assert(reg_numHi(opr) == -1, "missing addition of range for hi-register");1296caller_save_registers[num_caller_save_registers++] = reg_num(opr);1297}1298#ifdef X861299}1300#endif // X8613011302#ifdef X861303if (UseSSE > 0) {1304int num_caller_save_xmm_regs = FrameMap::get_num_caller_save_xmms();1305for (i = 0; i < num_caller_save_xmm_regs; i ++) {1306LIR_Opr opr = FrameMap::caller_save_xmm_reg_at(i);1307assert(opr->is_valid() && opr->is_register(), "FrameMap should not return invalid operands");1308assert(reg_numHi(opr) == -1, "missing addition of range for hi-register");1309caller_save_registers[num_caller_save_registers++] = reg_num(opr);1310}1311}1312#endif // X861313}1314assert(num_caller_save_registers <= LinearScan::nof_regs, "out of bounds");131513161317LIR_OpVisitState visitor;13181319// iterate all blocks in reverse order1320for (i = block_count() - 1; i >= 0; i--) {1321BlockBegin* block = block_at(i);1322LIR_OpList* instructions = block->lir()->instructions_list();1323int block_from = block->first_lir_instruction_id();1324int block_to = block->last_lir_instruction_id();13251326assert(block_from == instructions->at(0)->id(), "must be");1327assert(block_to == instructions->at(instructions->length() - 1)->id(), "must be");13281329// Update intervals for registers live at the end of this block;1330ResourceBitMap live = block->live_out();1331int size = (int)live.size();1332for (int number = (int)live.get_next_one_offset(0, size); number < size; number = (int)live.get_next_one_offset(number + 1, size)) {1333assert(live.at(number), "should not stop here otherwise");1334assert(number >= LIR_OprDesc::vreg_base, "fixed intervals must not be live on block bounds");1335TRACE_LINEAR_SCAN(2, tty->print_cr("live in %d to %d", number, block_to + 2));13361337add_use(number, block_from, block_to + 2, noUse, T_ILLEGAL);13381339// add special use positions for loop-end blocks when the1340// interval is used anywhere inside this loop. It's possible1341// that the block was part of a non-natural loop, so it might1342// have an invalid loop index.1343if (block->is_set(BlockBegin::linear_scan_loop_end_flag) &&1344block->loop_index() != -1 &&1345is_interval_in_loop(number, block->loop_index())) {1346interval_at(number)->add_use_pos(block_to + 1, loopEndMarker);1347}1348}13491350// iterate all instructions of the block in reverse order.1351// skip the first instruction because it is always a label1352// definitions of intervals are processed before uses1353assert(visitor.no_operands(instructions->at(0)), "first operation must always be a label");1354for (int j = instructions->length() - 1; j >= 1; j--) {1355LIR_Op* op = instructions->at(j);1356int op_id = op->id();13571358// visit operation to collect all operands1359visitor.visit(op);13601361// add a temp range for each register if operation destroys caller-save registers1362if (visitor.has_call()) {1363for (int k = 0; k < num_caller_save_registers; k++) {1364add_temp(caller_save_registers[k], op_id, noUse, T_ILLEGAL);1365}1366TRACE_LINEAR_SCAN(4, tty->print_cr("operation destroys all caller-save registers"));1367}13681369// Add any platform dependent temps1370pd_add_temps(op);13711372// visit definitions (output and temp operands)1373int k, n;1374n = visitor.opr_count(LIR_OpVisitState::outputMode);1375for (k = 0; k < n; k++) {1376LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::outputMode, k);1377assert(opr->is_register(), "visitor should only return register operands");1378add_def(opr, op_id, use_kind_of_output_operand(op, opr));1379}13801381n = visitor.opr_count(LIR_OpVisitState::tempMode);1382for (k = 0; k < n; k++) {1383LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::tempMode, k);1384assert(opr->is_register(), "visitor should only return register operands");1385add_temp(opr, op_id, mustHaveRegister);1386}13871388// visit uses (input operands)1389n = visitor.opr_count(LIR_OpVisitState::inputMode);1390for (k = 0; k < n; k++) {1391LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::inputMode, k);1392assert(opr->is_register(), "visitor should only return register operands");1393add_use(opr, block_from, op_id, use_kind_of_input_operand(op, opr));1394}13951396// Add uses of live locals from interpreter's point of view for proper1397// debug information generation1398// Treat these operands as temp values (if the life range is extended1399// to a call site, the value would be in a register at the call otherwise)1400n = visitor.info_count();1401for (k = 0; k < n; k++) {1402CodeEmitInfo* info = visitor.info_at(k);1403ValueStack* stack = info->stack();1404for_each_state_value(stack, value,1405add_use(value, block_from, op_id + 1, noUse);1406);1407}14081409// special steps for some instructions (especially moves)1410handle_method_arguments(op);1411handle_doubleword_moves(op);1412add_register_hints(op);14131414} // end of instruction iteration1415} // end of block iteration141614171418// add the range [0, 1[ to all fixed intervals1419// -> the register allocator need not handle unhandled fixed intervals1420for (int n = 0; n < LinearScan::nof_regs; n++) {1421Interval* interval = interval_at(n);1422if (interval != NULL) {1423interval->add_range(0, 1);1424}1425}1426}142714281429// ********** Phase 5: actual register allocation14301431int LinearScan::interval_cmp(Interval** a, Interval** b) {1432if (*a != NULL) {1433if (*b != NULL) {1434return (*a)->from() - (*b)->from();1435} else {1436return -1;1437}1438} else {1439if (*b != NULL) {1440return 1;1441} else {1442return 0;1443}1444}1445}14461447#ifndef PRODUCT1448int interval_cmp(Interval* const& l, Interval* const& r) {1449return l->from() - r->from();1450}14511452bool find_interval(Interval* interval, IntervalArray* intervals) {1453bool found;1454int idx = intervals->find_sorted<Interval*, interval_cmp>(interval, found);14551456if (!found) {1457return false;1458}14591460int from = interval->from();14611462// The index we've found using binary search is pointing to an interval1463// that is defined in the same place as the interval we were looking for.1464// So now we have to look around that index and find exact interval.1465for (int i = idx; i >= 0; i--) {1466if (intervals->at(i) == interval) {1467return true;1468}1469if (intervals->at(i)->from() != from) {1470break;1471}1472}14731474for (int i = idx + 1; i < intervals->length(); i++) {1475if (intervals->at(i) == interval) {1476return true;1477}1478if (intervals->at(i)->from() != from) {1479break;1480}1481}14821483return false;1484}14851486bool LinearScan::is_sorted(IntervalArray* intervals) {1487int from = -1;1488int null_count = 0;14891490for (int i = 0; i < intervals->length(); i++) {1491Interval* it = intervals->at(i);1492if (it != NULL) {1493assert(from <= it->from(), "Intervals are unordered");1494from = it->from();1495} else {1496null_count++;1497}1498}14991500assert(null_count == 0, "Sorted intervals should not contain nulls");15011502null_count = 0;15031504for (int i = 0; i < interval_count(); i++) {1505Interval* interval = interval_at(i);1506if (interval != NULL) {1507assert(find_interval(interval, intervals), "Lists do not contain same intervals");1508} else {1509null_count++;1510}1511}15121513assert(interval_count() - null_count == intervals->length(),1514"Sorted list should contain the same amount of non-NULL intervals as unsorted list");15151516return true;1517}1518#endif15191520void LinearScan::add_to_list(Interval** first, Interval** prev, Interval* interval) {1521if (*prev != NULL) {1522(*prev)->set_next(interval);1523} else {1524*first = interval;1525}1526*prev = interval;1527}15281529void LinearScan::create_unhandled_lists(Interval** list1, Interval** list2, bool (is_list1)(const Interval* i), bool (is_list2)(const Interval* i)) {1530assert(is_sorted(_sorted_intervals), "interval list is not sorted");15311532*list1 = *list2 = Interval::end();15331534Interval* list1_prev = NULL;1535Interval* list2_prev = NULL;1536Interval* v;15371538const int n = _sorted_intervals->length();1539for (int i = 0; i < n; i++) {1540v = _sorted_intervals->at(i);1541if (v == NULL) continue;15421543if (is_list1(v)) {1544add_to_list(list1, &list1_prev, v);1545} else if (is_list2 == NULL || is_list2(v)) {1546add_to_list(list2, &list2_prev, v);1547}1548}15491550if (list1_prev != NULL) list1_prev->set_next(Interval::end());1551if (list2_prev != NULL) list2_prev->set_next(Interval::end());15521553assert(list1_prev == NULL || list1_prev->next() == Interval::end(), "linear list ends not with sentinel");1554assert(list2_prev == NULL || list2_prev->next() == Interval::end(), "linear list ends not with sentinel");1555}155615571558void LinearScan::sort_intervals_before_allocation() {1559TIME_LINEAR_SCAN(timer_sort_intervals_before);15601561if (_needs_full_resort) {1562// There is no known reason why this should occur but just in case...1563assert(false, "should never occur");1564// Re-sort existing interval list because an Interval::from() has changed1565_sorted_intervals->sort(interval_cmp);1566_needs_full_resort = false;1567}15681569IntervalList* unsorted_list = &_intervals;1570int unsorted_len = unsorted_list->length();1571int sorted_len = 0;1572int unsorted_idx;1573int sorted_idx = 0;1574int sorted_from_max = -1;15751576// calc number of items for sorted list (sorted list must not contain NULL values)1577for (unsorted_idx = 0; unsorted_idx < unsorted_len; unsorted_idx++) {1578if (unsorted_list->at(unsorted_idx) != NULL) {1579sorted_len++;1580}1581}1582IntervalArray* sorted_list = new IntervalArray(sorted_len, sorted_len, NULL);15831584// special sorting algorithm: the original interval-list is almost sorted,1585// only some intervals are swapped. So this is much faster than a complete QuickSort1586for (unsorted_idx = 0; unsorted_idx < unsorted_len; unsorted_idx++) {1587Interval* cur_interval = unsorted_list->at(unsorted_idx);15881589if (cur_interval != NULL) {1590int cur_from = cur_interval->from();15911592if (sorted_from_max <= cur_from) {1593sorted_list->at_put(sorted_idx++, cur_interval);1594sorted_from_max = cur_interval->from();1595} else {1596// the asumption that the intervals are already sorted failed,1597// so this interval must be sorted in manually1598int j;1599for (j = sorted_idx - 1; j >= 0 && cur_from < sorted_list->at(j)->from(); j--) {1600sorted_list->at_put(j + 1, sorted_list->at(j));1601}1602sorted_list->at_put(j + 1, cur_interval);1603sorted_idx++;1604}1605}1606}1607_sorted_intervals = sorted_list;1608assert(is_sorted(_sorted_intervals), "intervals unsorted");1609}16101611void LinearScan::sort_intervals_after_allocation() {1612TIME_LINEAR_SCAN(timer_sort_intervals_after);16131614if (_needs_full_resort) {1615// Re-sort existing interval list because an Interval::from() has changed1616_sorted_intervals->sort(interval_cmp);1617_needs_full_resort = false;1618}16191620IntervalArray* old_list = _sorted_intervals;1621IntervalList* new_list = _new_intervals_from_allocation;1622int old_len = old_list->length();1623int new_len = new_list == NULL ? 0 : new_list->length();16241625if (new_len == 0) {1626// no intervals have been added during allocation, so sorted list is already up to date1627assert(is_sorted(_sorted_intervals), "intervals unsorted");1628return;1629}16301631// conventional sort-algorithm for new intervals1632new_list->sort(interval_cmp);16331634// merge old and new list (both already sorted) into one combined list1635int combined_list_len = old_len + new_len;1636IntervalArray* combined_list = new IntervalArray(combined_list_len, combined_list_len, NULL);1637int old_idx = 0;1638int new_idx = 0;16391640while (old_idx + new_idx < old_len + new_len) {1641if (new_idx >= new_len || (old_idx < old_len && old_list->at(old_idx)->from() <= new_list->at(new_idx)->from())) {1642combined_list->at_put(old_idx + new_idx, old_list->at(old_idx));1643old_idx++;1644} else {1645combined_list->at_put(old_idx + new_idx, new_list->at(new_idx));1646new_idx++;1647}1648}16491650_sorted_intervals = combined_list;1651assert(is_sorted(_sorted_intervals), "intervals unsorted");1652}165316541655void LinearScan::allocate_registers() {1656TIME_LINEAR_SCAN(timer_allocate_registers);16571658Interval* precolored_cpu_intervals, *not_precolored_cpu_intervals;1659Interval* precolored_fpu_intervals, *not_precolored_fpu_intervals;16601661// allocate cpu registers1662create_unhandled_lists(&precolored_cpu_intervals, ¬_precolored_cpu_intervals,1663is_precolored_cpu_interval, is_virtual_cpu_interval);16641665// allocate fpu registers1666create_unhandled_lists(&precolored_fpu_intervals, ¬_precolored_fpu_intervals,1667is_precolored_fpu_interval, is_virtual_fpu_interval);16681669// the fpu interval allocation cannot be moved down below with the fpu section as1670// the cpu_lsw.walk() changes interval positions.16711672LinearScanWalker cpu_lsw(this, precolored_cpu_intervals, not_precolored_cpu_intervals);1673cpu_lsw.walk();1674cpu_lsw.finish_allocation();16751676if (has_fpu_registers()) {1677LinearScanWalker fpu_lsw(this, precolored_fpu_intervals, not_precolored_fpu_intervals);1678fpu_lsw.walk();1679fpu_lsw.finish_allocation();1680}1681}168216831684// ********** Phase 6: resolve data flow1685// (insert moves at edges between blocks if intervals have been split)16861687// wrapper for Interval::split_child_at_op_id that performs a bailout in product mode1688// instead of returning NULL1689Interval* LinearScan::split_child_at_op_id(Interval* interval, int op_id, LIR_OpVisitState::OprMode mode) {1690Interval* result = interval->split_child_at_op_id(op_id, mode);1691if (result != NULL) {1692return result;1693}16941695assert(false, "must find an interval, but do a clean bailout in product mode");1696result = new Interval(LIR_OprDesc::vreg_base);1697result->assign_reg(0);1698result->set_type(T_INT);1699BAILOUT_("LinearScan: interval is NULL", result);1700}170117021703Interval* LinearScan::interval_at_block_begin(BlockBegin* block, int reg_num) {1704assert(LinearScan::nof_regs <= reg_num && reg_num < num_virtual_regs(), "register number out of bounds");1705assert(interval_at(reg_num) != NULL, "no interval found");17061707return split_child_at_op_id(interval_at(reg_num), block->first_lir_instruction_id(), LIR_OpVisitState::outputMode);1708}17091710Interval* LinearScan::interval_at_block_end(BlockBegin* block, int reg_num) {1711assert(LinearScan::nof_regs <= reg_num && reg_num < num_virtual_regs(), "register number out of bounds");1712assert(interval_at(reg_num) != NULL, "no interval found");17131714return split_child_at_op_id(interval_at(reg_num), block->last_lir_instruction_id() + 1, LIR_OpVisitState::outputMode);1715}17161717Interval* LinearScan::interval_at_op_id(int reg_num, int op_id) {1718assert(LinearScan::nof_regs <= reg_num && reg_num < num_virtual_regs(), "register number out of bounds");1719assert(interval_at(reg_num) != NULL, "no interval found");17201721return split_child_at_op_id(interval_at(reg_num), op_id, LIR_OpVisitState::inputMode);1722}172317241725void LinearScan::resolve_collect_mappings(BlockBegin* from_block, BlockBegin* to_block, MoveResolver &move_resolver) {1726DEBUG_ONLY(move_resolver.check_empty());17271728const int size = live_set_size();1729const ResourceBitMap live_at_edge = to_block->live_in();17301731// visit all registers where the live_at_edge bit is set1732for (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)) {1733assert(r < num_virtual_regs(), "live information set for not exisiting interval");1734assert(from_block->live_out().at(r) && to_block->live_in().at(r), "interval not live at this edge");17351736Interval* from_interval = interval_at_block_end(from_block, r);1737Interval* to_interval = interval_at_block_begin(to_block, r);17381739if (from_interval != to_interval && (from_interval->assigned_reg() != to_interval->assigned_reg() || from_interval->assigned_regHi() != to_interval->assigned_regHi())) {1740// need to insert move instruction1741move_resolver.add_mapping(from_interval, to_interval);1742}1743}1744}174517461747void LinearScan::resolve_find_insert_pos(BlockBegin* from_block, BlockBegin* to_block, MoveResolver &move_resolver) {1748if (from_block->number_of_sux() <= 1) {1749TRACE_LINEAR_SCAN(4, tty->print_cr("inserting moves at end of from_block B%d", from_block->block_id()));17501751LIR_OpList* instructions = from_block->lir()->instructions_list();1752LIR_OpBranch* branch = instructions->last()->as_OpBranch();1753if (branch != NULL) {1754// insert moves before branch1755assert(branch->cond() == lir_cond_always, "block does not end with an unconditional jump");1756move_resolver.set_insert_position(from_block->lir(), instructions->length() - 2);1757} else {1758move_resolver.set_insert_position(from_block->lir(), instructions->length() - 1);1759}17601761} else {1762TRACE_LINEAR_SCAN(4, tty->print_cr("inserting moves at beginning of to_block B%d", to_block->block_id()));1763#ifdef ASSERT1764assert(from_block->lir()->instructions_list()->at(0)->as_OpLabel() != NULL, "block does not start with a label");17651766// because the number of predecessor edges matches the number of1767// successor edges, blocks which are reached by switch statements1768// may have be more than one predecessor but it will be guaranteed1769// that all predecessors will be the same.1770for (int i = 0; i < to_block->number_of_preds(); i++) {1771assert(from_block == to_block->pred_at(i), "all critical edges must be broken");1772}1773#endif17741775move_resolver.set_insert_position(to_block->lir(), 0);1776}1777}177817791780// insert necessary moves (spilling or reloading) at edges between blocks if interval has been split1781void LinearScan::resolve_data_flow() {1782TIME_LINEAR_SCAN(timer_resolve_data_flow);17831784int num_blocks = block_count();1785MoveResolver move_resolver(this);1786ResourceBitMap block_completed(num_blocks);1787ResourceBitMap already_resolved(num_blocks);17881789int i;1790for (i = 0; i < num_blocks; i++) {1791BlockBegin* block = block_at(i);17921793// check if block has only one predecessor and only one successor1794if (block->number_of_preds() == 1 && block->number_of_sux() == 1 && block->number_of_exception_handlers() == 0) {1795LIR_OpList* instructions = block->lir()->instructions_list();1796assert(instructions->at(0)->code() == lir_label, "block must start with label");1797assert(instructions->last()->code() == lir_branch, "block with successors must end with branch");1798assert(instructions->last()->as_OpBranch()->cond() == lir_cond_always, "block with successor must end with unconditional branch");17991800// check if block is empty (only label and branch)1801if (instructions->length() == 2) {1802BlockBegin* pred = block->pred_at(0);1803BlockBegin* sux = block->sux_at(0);18041805// prevent optimization of two consecutive blocks1806if (!block_completed.at(pred->linear_scan_number()) && !block_completed.at(sux->linear_scan_number())) {1807TRACE_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()));1808block_completed.set_bit(block->linear_scan_number());18091810// directly resolve between pred and sux (without looking at the empty block between)1811resolve_collect_mappings(pred, sux, move_resolver);1812if (move_resolver.has_mappings()) {1813move_resolver.set_insert_position(block->lir(), 0);1814move_resolver.resolve_and_append_moves();1815}1816}1817}1818}1819}182018211822for (i = 0; i < num_blocks; i++) {1823if (!block_completed.at(i)) {1824BlockBegin* from_block = block_at(i);1825already_resolved.set_from(block_completed);18261827int num_sux = from_block->number_of_sux();1828for (int s = 0; s < num_sux; s++) {1829BlockBegin* to_block = from_block->sux_at(s);18301831// check for duplicate edges between the same blocks (can happen with switch blocks)1832if (!already_resolved.at(to_block->linear_scan_number())) {1833TRACE_LINEAR_SCAN(3, tty->print_cr("**** processing edge between B%d and B%d", from_block->block_id(), to_block->block_id()));1834already_resolved.set_bit(to_block->linear_scan_number());18351836// collect all intervals that have been split between from_block and to_block1837resolve_collect_mappings(from_block, to_block, move_resolver);1838if (move_resolver.has_mappings()) {1839resolve_find_insert_pos(from_block, to_block, move_resolver);1840move_resolver.resolve_and_append_moves();1841}1842}1843}1844}1845}1846}184718481849void LinearScan::resolve_exception_entry(BlockBegin* block, int reg_num, MoveResolver &move_resolver) {1850if (interval_at(reg_num) == NULL) {1851// if a phi function is never used, no interval is created -> ignore this1852return;1853}18541855Interval* interval = interval_at_block_begin(block, reg_num);1856int reg = interval->assigned_reg();1857int regHi = interval->assigned_regHi();18581859if ((reg < nof_regs && interval->always_in_memory()) ||1860(use_fpu_stack_allocation() && reg >= pd_first_fpu_reg && reg <= pd_last_fpu_reg)) {1861// the interval is split to get a short range that is located on the stack1862// in the following two cases:1863// * the interval started in memory (e.g. method parameter), but is currently in a register1864// this is an optimization for exception handling that reduces the number of moves that1865// are necessary for resolving the states when an exception uses this exception handler1866// * the interval would be on the fpu stack at the begin of the exception handler1867// this is not allowed because of the complicated fpu stack handling on Intel18681869// range that will be spilled to memory1870int from_op_id = block->first_lir_instruction_id();1871int to_op_id = from_op_id + 1; // short live range of length 11872assert(interval->from() <= from_op_id && interval->to() >= to_op_id,1873"no split allowed between exception entry and first instruction");18741875if (interval->from() != from_op_id) {1876// the part before from_op_id is unchanged1877interval = interval->split(from_op_id);1878interval->assign_reg(reg, regHi);1879append_interval(interval);1880} else {1881_needs_full_resort = true;1882}1883assert(interval->from() == from_op_id, "must be true now");18841885Interval* spilled_part = interval;1886if (interval->to() != to_op_id) {1887// the part after to_op_id is unchanged1888spilled_part = interval->split_from_start(to_op_id);1889append_interval(spilled_part);1890move_resolver.add_mapping(spilled_part, interval);1891}1892assign_spill_slot(spilled_part);18931894assert(spilled_part->from() == from_op_id && spilled_part->to() == to_op_id, "just checking");1895}1896}18971898void LinearScan::resolve_exception_entry(BlockBegin* block, MoveResolver &move_resolver) {1899assert(block->is_set(BlockBegin::exception_entry_flag), "should not call otherwise");1900DEBUG_ONLY(move_resolver.check_empty());19011902// visit all registers where the live_in bit is set1903int size = live_set_size();1904for (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)) {1905resolve_exception_entry(block, r, move_resolver);1906}19071908// the live_in bits are not set for phi functions of the xhandler entry, so iterate them separately1909for_each_phi_fun(block, phi,1910if (!phi->is_illegal()) { resolve_exception_entry(block, phi->operand()->vreg_number(), move_resolver); }1911);19121913if (move_resolver.has_mappings()) {1914// insert moves after first instruction1915move_resolver.set_insert_position(block->lir(), 0);1916move_resolver.resolve_and_append_moves();1917}1918}191919201921void LinearScan::resolve_exception_edge(XHandler* handler, int throwing_op_id, int reg_num, Phi* phi, MoveResolver &move_resolver) {1922if (interval_at(reg_num) == NULL) {1923// if a phi function is never used, no interval is created -> ignore this1924return;1925}19261927// the computation of to_interval is equal to resolve_collect_mappings,1928// but from_interval is more complicated because of phi functions1929BlockBegin* to_block = handler->entry_block();1930Interval* to_interval = interval_at_block_begin(to_block, reg_num);19311932if (phi != NULL) {1933// phi function of the exception entry block1934// no moves are created for this phi function in the LIR_Generator, so the1935// interval at the throwing instruction must be searched using the operands1936// of the phi function1937Value from_value = phi->operand_at(handler->phi_operand());19381939// with phi functions it can happen that the same from_value is used in1940// multiple mappings, so notify move-resolver that this is allowed1941move_resolver.set_multiple_reads_allowed();19421943Constant* con = from_value->as_Constant();1944if (con != NULL && (!con->is_pinned() || con->operand()->is_constant())) {1945// Need a mapping from constant to interval if unpinned (may have no register) or if the operand is a constant (no register).1946move_resolver.add_mapping(LIR_OprFact::value_type(con->type()), to_interval);1947} else {1948// search split child at the throwing op_id1949Interval* from_interval = interval_at_op_id(from_value->operand()->vreg_number(), throwing_op_id);1950move_resolver.add_mapping(from_interval, to_interval);1951}1952} else {1953// no phi function, so use reg_num also for from_interval1954// search split child at the throwing op_id1955Interval* from_interval = interval_at_op_id(reg_num, throwing_op_id);1956if (from_interval != to_interval) {1957// optimization to reduce number of moves: when to_interval is on stack and1958// the stack slot is known to be always correct, then no move is necessary1959if (!from_interval->always_in_memory() || from_interval->canonical_spill_slot() != to_interval->assigned_reg()) {1960move_resolver.add_mapping(from_interval, to_interval);1961}1962}1963}1964}19651966void LinearScan::resolve_exception_edge(XHandler* handler, int throwing_op_id, MoveResolver &move_resolver) {1967TRACE_LINEAR_SCAN(4, tty->print_cr("resolving exception handler B%d: throwing_op_id=%d", handler->entry_block()->block_id(), throwing_op_id));19681969DEBUG_ONLY(move_resolver.check_empty());1970assert(handler->lir_op_id() == -1, "already processed this xhandler");1971DEBUG_ONLY(handler->set_lir_op_id(throwing_op_id));1972assert(handler->entry_code() == NULL, "code already present");19731974// visit all registers where the live_in bit is set1975BlockBegin* block = handler->entry_block();1976int size = live_set_size();1977for (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)) {1978resolve_exception_edge(handler, throwing_op_id, r, NULL, move_resolver);1979}19801981// the live_in bits are not set for phi functions of the xhandler entry, so iterate them separately1982for_each_phi_fun(block, phi,1983if (!phi->is_illegal()) { resolve_exception_edge(handler, throwing_op_id, phi->operand()->vreg_number(), phi, move_resolver); }1984);19851986if (move_resolver.has_mappings()) {1987LIR_List* entry_code = new LIR_List(compilation());1988move_resolver.set_insert_position(entry_code, 0);1989move_resolver.resolve_and_append_moves();19901991entry_code->jump(handler->entry_block());1992handler->set_entry_code(entry_code);1993}1994}199519961997void LinearScan::resolve_exception_handlers() {1998MoveResolver move_resolver(this);1999LIR_OpVisitState visitor;2000int num_blocks = block_count();20012002int i;2003for (i = 0; i < num_blocks; i++) {2004BlockBegin* block = block_at(i);2005if (block->is_set(BlockBegin::exception_entry_flag)) {2006resolve_exception_entry(block, move_resolver);2007}2008}20092010for (i = 0; i < num_blocks; i++) {2011BlockBegin* block = block_at(i);2012LIR_List* ops = block->lir();2013int num_ops = ops->length();20142015// iterate all instructions of the block. skip the first because it is always a label2016assert(visitor.no_operands(ops->at(0)), "first operation must always be a label");2017for (int j = 1; j < num_ops; j++) {2018LIR_Op* op = ops->at(j);2019int op_id = op->id();20202021if (op_id != -1 && has_info(op_id)) {2022// visit operation to collect all operands2023visitor.visit(op);2024assert(visitor.info_count() > 0, "should not visit otherwise");20252026XHandlers* xhandlers = visitor.all_xhandler();2027int n = xhandlers->length();2028for (int k = 0; k < n; k++) {2029resolve_exception_edge(xhandlers->handler_at(k), op_id, move_resolver);2030}20312032#ifdef ASSERT2033} else {2034visitor.visit(op);2035assert(visitor.all_xhandler()->length() == 0, "missed exception handler");2036#endif2037}2038}2039}2040}204120422043// ********** Phase 7: assign register numbers back to LIR2044// (includes computation of debug information and oop maps)20452046VMReg LinearScan::vm_reg_for_interval(Interval* interval) {2047VMReg reg = interval->cached_vm_reg();2048if (!reg->is_valid() ) {2049reg = vm_reg_for_operand(operand_for_interval(interval));2050interval->set_cached_vm_reg(reg);2051}2052assert(reg == vm_reg_for_operand(operand_for_interval(interval)), "wrong cached value");2053return reg;2054}20552056VMReg LinearScan::vm_reg_for_operand(LIR_Opr opr) {2057assert(opr->is_oop(), "currently only implemented for oop operands");2058return frame_map()->regname(opr);2059}206020612062LIR_Opr LinearScan::operand_for_interval(Interval* interval) {2063LIR_Opr opr = interval->cached_opr();2064if (opr->is_illegal()) {2065opr = calc_operand_for_interval(interval);2066interval->set_cached_opr(opr);2067}20682069assert(opr == calc_operand_for_interval(interval), "wrong cached value");2070return opr;2071}20722073LIR_Opr LinearScan::calc_operand_for_interval(const Interval* interval) {2074int assigned_reg = interval->assigned_reg();2075BasicType type = interval->type();20762077if (assigned_reg >= nof_regs) {2078// stack slot2079assert(interval->assigned_regHi() == any_reg, "must not have hi register");2080return LIR_OprFact::stack(assigned_reg - nof_regs, type);20812082} else {2083// register2084switch (type) {2085case T_OBJECT: {2086assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");2087assert(interval->assigned_regHi() == any_reg, "must not have hi register");2088return LIR_OprFact::single_cpu_oop(assigned_reg);2089}20902091case T_ADDRESS: {2092assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");2093assert(interval->assigned_regHi() == any_reg, "must not have hi register");2094return LIR_OprFact::single_cpu_address(assigned_reg);2095}20962097case T_METADATA: {2098assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");2099assert(interval->assigned_regHi() == any_reg, "must not have hi register");2100return LIR_OprFact::single_cpu_metadata(assigned_reg);2101}21022103#ifdef __SOFTFP__2104case T_FLOAT: // fall through2105#endif // __SOFTFP__2106case T_INT: {2107assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");2108assert(interval->assigned_regHi() == any_reg, "must not have hi register");2109return LIR_OprFact::single_cpu(assigned_reg);2110}21112112#ifdef __SOFTFP__2113case T_DOUBLE: // fall through2114#endif // __SOFTFP__2115case T_LONG: {2116int assigned_regHi = interval->assigned_regHi();2117assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");2118assert(num_physical_regs(T_LONG) == 1 ||2119(assigned_regHi >= pd_first_cpu_reg && assigned_regHi <= pd_last_cpu_reg), "no cpu register");21202121assert(assigned_reg != assigned_regHi, "invalid allocation");2122assert(num_physical_regs(T_LONG) == 1 || assigned_reg < assigned_regHi,2123"register numbers must be sorted (ensure that e.g. a move from eax,ebx to ebx,eax can not occur)");2124assert((assigned_regHi != any_reg) ^ (num_physical_regs(T_LONG) == 1), "must be match");2125if (requires_adjacent_regs(T_LONG)) {2126assert(assigned_reg % 2 == 0 && assigned_reg + 1 == assigned_regHi, "must be sequential and even");2127}21282129#ifdef _LP642130return LIR_OprFact::double_cpu(assigned_reg, assigned_reg);2131#else2132#if defined(PPC32)2133return LIR_OprFact::double_cpu(assigned_regHi, assigned_reg);2134#else2135return LIR_OprFact::double_cpu(assigned_reg, assigned_regHi);2136#endif // PPC322137#endif // LP642138}21392140#ifndef __SOFTFP__2141case T_FLOAT: {2142#ifdef X862143if (UseSSE >= 1) {2144int last_xmm_reg = pd_last_xmm_reg;2145#ifdef _LP642146if (UseAVX < 3) {2147last_xmm_reg = pd_first_xmm_reg + (pd_nof_xmm_regs_frame_map / 2) - 1;2148}2149#endif // LP642150assert(assigned_reg >= pd_first_xmm_reg && assigned_reg <= last_xmm_reg, "no xmm register");2151assert(interval->assigned_regHi() == any_reg, "must not have hi register");2152return LIR_OprFact::single_xmm(assigned_reg - pd_first_xmm_reg);2153}2154#endif // X8621552156assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");2157assert(interval->assigned_regHi() == any_reg, "must not have hi register");2158return LIR_OprFact::single_fpu(assigned_reg - pd_first_fpu_reg);2159}21602161case T_DOUBLE: {2162#ifdef X862163if (UseSSE >= 2) {2164int last_xmm_reg = pd_last_xmm_reg;2165#ifdef _LP642166if (UseAVX < 3) {2167last_xmm_reg = pd_first_xmm_reg + (pd_nof_xmm_regs_frame_map / 2) - 1;2168}2169#endif // LP642170assert(assigned_reg >= pd_first_xmm_reg && assigned_reg <= last_xmm_reg, "no xmm register");2171assert(interval->assigned_regHi() == any_reg, "must not have hi register (double xmm values are stored in one register)");2172return LIR_OprFact::double_xmm(assigned_reg - pd_first_xmm_reg);2173}2174#endif // X8621752176#if defined(ARM32)2177assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");2178assert(interval->assigned_regHi() >= pd_first_fpu_reg && interval->assigned_regHi() <= pd_last_fpu_reg, "no fpu register");2179assert(assigned_reg % 2 == 0 && assigned_reg + 1 == interval->assigned_regHi(), "must be sequential and even");2180LIR_Opr result = LIR_OprFact::double_fpu(assigned_reg - pd_first_fpu_reg, interval->assigned_regHi() - pd_first_fpu_reg);2181#else2182assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");2183assert(interval->assigned_regHi() == any_reg, "must not have hi register (double fpu values are stored in one register on Intel)");2184LIR_Opr result = LIR_OprFact::double_fpu(assigned_reg - pd_first_fpu_reg);2185#endif2186return result;2187}2188#endif // __SOFTFP__21892190default: {2191ShouldNotReachHere();2192return LIR_OprFact::illegalOpr;2193}2194}2195}2196}21972198LIR_Opr LinearScan::canonical_spill_opr(Interval* interval) {2199assert(interval->canonical_spill_slot() >= nof_regs, "canonical spill slot not set");2200return LIR_OprFact::stack(interval->canonical_spill_slot() - nof_regs, interval->type());2201}22022203LIR_Opr LinearScan::color_lir_opr(LIR_Opr opr, int op_id, LIR_OpVisitState::OprMode mode) {2204assert(opr->is_virtual(), "should not call this otherwise");22052206Interval* interval = interval_at(opr->vreg_number());2207assert(interval != NULL, "interval must exist");22082209if (op_id != -1) {2210#ifdef ASSERT2211BlockBegin* block = block_of_op_with_id(op_id);2212if (block->number_of_sux() <= 1 && op_id == block->last_lir_instruction_id()) {2213// check if spill moves could have been appended at the end of this block, but2214// before the branch instruction. So the split child information for this branch would2215// be incorrect.2216LIR_OpBranch* branch = block->lir()->instructions_list()->last()->as_OpBranch();2217if (branch != NULL) {2218if (block->live_out().at(opr->vreg_number())) {2219assert(branch->cond() == lir_cond_always, "block does not end with an unconditional jump");2220assert(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)");2221}2222}2223}2224#endif22252226// operands are not changed when an interval is split during allocation,2227// so search the right interval here2228interval = split_child_at_op_id(interval, op_id, mode);2229}22302231LIR_Opr res = operand_for_interval(interval);22322233#ifdef X862234// new semantic for is_last_use: not only set on definite end of interval,2235// but also before hole2236// This may still miss some cases (e.g. for dead values), but it is not necessary that the2237// last use information is completely correct2238// information is only needed for fpu stack allocation2239if (res->is_fpu_register()) {2240if (opr->is_last_use() || op_id == interval->to() || (op_id != -1 && interval->has_hole_between(op_id, op_id + 1))) {2241assert(op_id == -1 || !is_block_begin(op_id), "holes at begin of block may also result from control flow");2242res = res->make_last_use();2243}2244}2245#endif22462247assert(!gen()->is_vreg_flag_set(opr->vreg_number(), LIRGenerator::callee_saved) || !FrameMap::is_caller_save_register(res), "bad allocation");22482249return res;2250}225122522253#ifdef ASSERT2254// some methods used to check correctness of debug information22552256void assert_no_register_values(GrowableArray<ScopeValue*>* values) {2257if (values == NULL) {2258return;2259}22602261for (int i = 0; i < values->length(); i++) {2262ScopeValue* value = values->at(i);22632264if (value->is_location()) {2265Location location = ((LocationValue*)value)->location();2266assert(location.where() == Location::on_stack, "value is in register");2267}2268}2269}22702271void assert_no_register_values(GrowableArray<MonitorValue*>* values) {2272if (values == NULL) {2273return;2274}22752276for (int i = 0; i < values->length(); i++) {2277MonitorValue* value = values->at(i);22782279if (value->owner()->is_location()) {2280Location location = ((LocationValue*)value->owner())->location();2281assert(location.where() == Location::on_stack, "owner is in register");2282}2283assert(value->basic_lock().where() == Location::on_stack, "basic_lock is in register");2284}2285}22862287void assert_equal(Location l1, Location l2) {2288assert(l1.where() == l2.where() && l1.type() == l2.type() && l1.offset() == l2.offset(), "");2289}22902291void assert_equal(ScopeValue* v1, ScopeValue* v2) {2292if (v1->is_location()) {2293assert(v2->is_location(), "");2294assert_equal(((LocationValue*)v1)->location(), ((LocationValue*)v2)->location());2295} else if (v1->is_constant_int()) {2296assert(v2->is_constant_int(), "");2297assert(((ConstantIntValue*)v1)->value() == ((ConstantIntValue*)v2)->value(), "");2298} else if (v1->is_constant_double()) {2299assert(v2->is_constant_double(), "");2300assert(((ConstantDoubleValue*)v1)->value() == ((ConstantDoubleValue*)v2)->value(), "");2301} else if (v1->is_constant_long()) {2302assert(v2->is_constant_long(), "");2303assert(((ConstantLongValue*)v1)->value() == ((ConstantLongValue*)v2)->value(), "");2304} else if (v1->is_constant_oop()) {2305assert(v2->is_constant_oop(), "");2306assert(((ConstantOopWriteValue*)v1)->value() == ((ConstantOopWriteValue*)v2)->value(), "");2307} else {2308ShouldNotReachHere();2309}2310}23112312void assert_equal(MonitorValue* m1, MonitorValue* m2) {2313assert_equal(m1->owner(), m2->owner());2314assert_equal(m1->basic_lock(), m2->basic_lock());2315}23162317void assert_equal(IRScopeDebugInfo* d1, IRScopeDebugInfo* d2) {2318assert(d1->scope() == d2->scope(), "not equal");2319assert(d1->bci() == d2->bci(), "not equal");23202321if (d1->locals() != NULL) {2322assert(d1->locals() != NULL && d2->locals() != NULL, "not equal");2323assert(d1->locals()->length() == d2->locals()->length(), "not equal");2324for (int i = 0; i < d1->locals()->length(); i++) {2325assert_equal(d1->locals()->at(i), d2->locals()->at(i));2326}2327} else {2328assert(d1->locals() == NULL && d2->locals() == NULL, "not equal");2329}23302331if (d1->expressions() != NULL) {2332assert(d1->expressions() != NULL && d2->expressions() != NULL, "not equal");2333assert(d1->expressions()->length() == d2->expressions()->length(), "not equal");2334for (int i = 0; i < d1->expressions()->length(); i++) {2335assert_equal(d1->expressions()->at(i), d2->expressions()->at(i));2336}2337} else {2338assert(d1->expressions() == NULL && d2->expressions() == NULL, "not equal");2339}23402341if (d1->monitors() != NULL) {2342assert(d1->monitors() != NULL && d2->monitors() != NULL, "not equal");2343assert(d1->monitors()->length() == d2->monitors()->length(), "not equal");2344for (int i = 0; i < d1->monitors()->length(); i++) {2345assert_equal(d1->monitors()->at(i), d2->monitors()->at(i));2346}2347} else {2348assert(d1->monitors() == NULL && d2->monitors() == NULL, "not equal");2349}23502351if (d1->caller() != NULL) {2352assert(d1->caller() != NULL && d2->caller() != NULL, "not equal");2353assert_equal(d1->caller(), d2->caller());2354} else {2355assert(d1->caller() == NULL && d2->caller() == NULL, "not equal");2356}2357}23582359void check_stack_depth(CodeEmitInfo* info, int stack_end) {2360if (info->stack()->bci() != SynchronizationEntryBCI && !info->scope()->method()->is_native()) {2361Bytecodes::Code code = info->scope()->method()->java_code_at_bci(info->stack()->bci());2362switch (code) {2363case Bytecodes::_ifnull : // fall through2364case Bytecodes::_ifnonnull : // fall through2365case Bytecodes::_ifeq : // fall through2366case Bytecodes::_ifne : // fall through2367case Bytecodes::_iflt : // fall through2368case Bytecodes::_ifge : // fall through2369case Bytecodes::_ifgt : // fall through2370case Bytecodes::_ifle : // fall through2371case Bytecodes::_if_icmpeq : // fall through2372case Bytecodes::_if_icmpne : // fall through2373case Bytecodes::_if_icmplt : // fall through2374case Bytecodes::_if_icmpge : // fall through2375case Bytecodes::_if_icmpgt : // fall through2376case Bytecodes::_if_icmple : // fall through2377case Bytecodes::_if_acmpeq : // fall through2378case Bytecodes::_if_acmpne :2379assert(stack_end >= -Bytecodes::depth(code), "must have non-empty expression stack at if bytecode");2380break;2381default:2382break;2383}2384}2385}23862387#endif // ASSERT238823892390IntervalWalker* LinearScan::init_compute_oop_maps() {2391// setup lists of potential oops for walking2392Interval* oop_intervals;2393Interval* non_oop_intervals;23942395create_unhandled_lists(&oop_intervals, &non_oop_intervals, is_oop_interval, NULL);23962397// intervals that have no oops inside need not to be processed2398// to ensure a walking until the last instruction id, add a dummy interval2399// with a high operation id2400non_oop_intervals = new Interval(any_reg);2401non_oop_intervals->add_range(max_jint - 2, max_jint - 1);24022403return new IntervalWalker(this, oop_intervals, non_oop_intervals);2404}240524062407OopMap* LinearScan::compute_oop_map(IntervalWalker* iw, LIR_Op* op, CodeEmitInfo* info, bool is_call_site) {2408TRACE_LINEAR_SCAN(3, tty->print_cr("creating oop map at op_id %d", op->id()));24092410// walk before the current operation -> intervals that start at2411// the operation (= output operands of the operation) are not2412// included in the oop map2413iw->walk_before(op->id());24142415int frame_size = frame_map()->framesize();2416int arg_count = frame_map()->oop_map_arg_count();2417OopMap* map = new OopMap(frame_size, arg_count);24182419// Iterate through active intervals2420for (Interval* interval = iw->active_first(fixedKind); interval != Interval::end(); interval = interval->next()) {2421int assigned_reg = interval->assigned_reg();24222423assert(interval->current_from() <= op->id() && op->id() <= interval->current_to(), "interval should not be active otherwise");2424assert(interval->assigned_regHi() == any_reg, "oop must be single word");2425assert(interval->reg_num() >= LIR_OprDesc::vreg_base, "fixed interval found");24262427// Check if this range covers the instruction. Intervals that2428// start or end at the current operation are not included in the2429// oop map, except in the case of patching moves. For patching2430// moves, any intervals which end at this instruction are included2431// in the oop map since we may safepoint while doing the patch2432// before we've consumed the inputs.2433if (op->is_patching() || op->id() < interval->current_to()) {24342435// caller-save registers must not be included into oop-maps at calls2436assert(!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");24372438VMReg name = vm_reg_for_interval(interval);2439set_oop(map, name);24402441// Spill optimization: when the stack value is guaranteed to be always correct,2442// then it must be added to the oop map even if the interval is currently in a register2443if (interval->always_in_memory() &&2444op->id() > interval->spill_definition_pos() &&2445interval->assigned_reg() != interval->canonical_spill_slot()) {2446assert(interval->spill_definition_pos() > 0, "position not set correctly");2447assert(interval->canonical_spill_slot() >= LinearScan::nof_regs, "no spill slot assigned");2448assert(interval->assigned_reg() < LinearScan::nof_regs, "interval is on stack, so stack slot is registered twice");24492450set_oop(map, frame_map()->slot_regname(interval->canonical_spill_slot() - LinearScan::nof_regs));2451}2452}2453}24542455// add oops from lock stack2456assert(info->stack() != NULL, "CodeEmitInfo must always have a stack");2457int locks_count = info->stack()->total_locks_size();2458for (int i = 0; i < locks_count; i++) {2459set_oop(map, frame_map()->monitor_object_regname(i));2460}24612462return map;2463}246424652466void LinearScan::compute_oop_map(IntervalWalker* iw, const LIR_OpVisitState &visitor, LIR_Op* op) {2467assert(visitor.info_count() > 0, "no oop map needed");24682469// compute oop_map only for first CodeEmitInfo2470// because it is (in most cases) equal for all other infos of the same operation2471CodeEmitInfo* first_info = visitor.info_at(0);2472OopMap* first_oop_map = compute_oop_map(iw, op, first_info, visitor.has_call());24732474for (int i = 0; i < visitor.info_count(); i++) {2475CodeEmitInfo* info = visitor.info_at(i);2476OopMap* oop_map = first_oop_map;24772478// compute worst case interpreter size in case of a deoptimization2479_compilation->update_interpreter_frame_size(info->interpreter_frame_size());24802481if (info->stack()->locks_size() != first_info->stack()->locks_size()) {2482// this info has a different number of locks then the precomputed oop map2483// (possible for lock and unlock instructions) -> compute oop map with2484// correct lock information2485oop_map = compute_oop_map(iw, op, info, visitor.has_call());2486}24872488if (info->_oop_map == NULL) {2489info->_oop_map = oop_map;2490} else {2491// a CodeEmitInfo can not be shared between different LIR-instructions2492// because interval splitting can occur anywhere between two instructions2493// and so the oop maps must be different2494// -> check if the already set oop_map is exactly the one calculated for this operation2495assert(info->_oop_map == oop_map, "same CodeEmitInfo used for multiple LIR instructions");2496}2497}2498}249925002501// frequently used constants2502// Allocate them with new so they are never destroyed (otherwise, a2503// forced exit could destroy these objects while they are still in2504// use).2505ConstantOopWriteValue* LinearScan::_oop_null_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantOopWriteValue(NULL);2506ConstantIntValue* LinearScan::_int_m1_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue(-1);2507ConstantIntValue* LinearScan::_int_0_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue((jint)0);2508ConstantIntValue* LinearScan::_int_1_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue(1);2509ConstantIntValue* LinearScan::_int_2_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue(2);2510LocationValue* _illegal_value = new (ResourceObj::C_HEAP, mtCompiler) LocationValue(Location());25112512void LinearScan::init_compute_debug_info() {2513// cache for frequently used scope values2514// (cpu registers and stack slots)2515int cache_size = (LinearScan::nof_cpu_regs + frame_map()->argcount() + max_spills()) * 2;2516_scope_value_cache = ScopeValueArray(cache_size, cache_size, NULL);2517}25182519MonitorValue* LinearScan::location_for_monitor_index(int monitor_index) {2520Location loc;2521if (!frame_map()->location_for_monitor_object(monitor_index, &loc)) {2522bailout("too large frame");2523}2524ScopeValue* object_scope_value = new LocationValue(loc);25252526if (!frame_map()->location_for_monitor_lock(monitor_index, &loc)) {2527bailout("too large frame");2528}2529return new MonitorValue(object_scope_value, loc);2530}25312532LocationValue* LinearScan::location_for_name(int name, Location::Type loc_type) {2533Location loc;2534if (!frame_map()->locations_for_slot(name, loc_type, &loc)) {2535bailout("too large frame");2536}2537return new LocationValue(loc);2538}253925402541int LinearScan::append_scope_value_for_constant(LIR_Opr opr, GrowableArray<ScopeValue*>* scope_values) {2542assert(opr->is_constant(), "should not be called otherwise");25432544LIR_Const* c = opr->as_constant_ptr();2545BasicType t = c->type();2546switch (t) {2547case T_OBJECT: {2548jobject value = c->as_jobject();2549if (value == NULL) {2550scope_values->append(_oop_null_scope_value);2551} else {2552scope_values->append(new ConstantOopWriteValue(c->as_jobject()));2553}2554return 1;2555}25562557case T_INT: // fall through2558case T_FLOAT: {2559int value = c->as_jint_bits();2560switch (value) {2561case -1: scope_values->append(_int_m1_scope_value); break;2562case 0: scope_values->append(_int_0_scope_value); break;2563case 1: scope_values->append(_int_1_scope_value); break;2564case 2: scope_values->append(_int_2_scope_value); break;2565default: scope_values->append(new ConstantIntValue(c->as_jint_bits())); break;2566}2567return 1;2568}25692570case T_LONG: // fall through2571case T_DOUBLE: {2572#ifdef _LP642573scope_values->append(_int_0_scope_value);2574scope_values->append(new ConstantLongValue(c->as_jlong_bits()));2575#else2576if (hi_word_offset_in_bytes > lo_word_offset_in_bytes) {2577scope_values->append(new ConstantIntValue(c->as_jint_hi_bits()));2578scope_values->append(new ConstantIntValue(c->as_jint_lo_bits()));2579} else {2580scope_values->append(new ConstantIntValue(c->as_jint_lo_bits()));2581scope_values->append(new ConstantIntValue(c->as_jint_hi_bits()));2582}2583#endif2584return 2;2585}25862587case T_ADDRESS: {2588#ifdef _LP642589scope_values->append(new ConstantLongValue(c->as_jint()));2590#else2591scope_values->append(new ConstantIntValue(c->as_jint()));2592#endif2593return 1;2594}25952596default:2597ShouldNotReachHere();2598return -1;2599}2600}26012602int LinearScan::append_scope_value_for_operand(LIR_Opr opr, GrowableArray<ScopeValue*>* scope_values) {2603if (opr->is_single_stack()) {2604int stack_idx = opr->single_stack_ix();2605bool is_oop = opr->is_oop_register();2606int cache_idx = (stack_idx + LinearScan::nof_cpu_regs) * 2 + (is_oop ? 1 : 0);26072608ScopeValue* sv = _scope_value_cache.at(cache_idx);2609if (sv == NULL) {2610Location::Type loc_type = is_oop ? Location::oop : Location::normal;2611sv = location_for_name(stack_idx, loc_type);2612_scope_value_cache.at_put(cache_idx, sv);2613}26142615// check if cached value is correct2616DEBUG_ONLY(assert_equal(sv, location_for_name(stack_idx, is_oop ? Location::oop : Location::normal)));26172618scope_values->append(sv);2619return 1;26202621} else if (opr->is_single_cpu()) {2622bool is_oop = opr->is_oop_register();2623int cache_idx = opr->cpu_regnr() * 2 + (is_oop ? 1 : 0);2624Location::Type int_loc_type = NOT_LP64(Location::normal) LP64_ONLY(Location::int_in_long);26252626ScopeValue* sv = _scope_value_cache.at(cache_idx);2627if (sv == NULL) {2628Location::Type loc_type = is_oop ? Location::oop : int_loc_type;2629VMReg rname = frame_map()->regname(opr);2630sv = new LocationValue(Location::new_reg_loc(loc_type, rname));2631_scope_value_cache.at_put(cache_idx, sv);2632}26332634// check if cached value is correct2635DEBUG_ONLY(assert_equal(sv, new LocationValue(Location::new_reg_loc(is_oop ? Location::oop : int_loc_type, frame_map()->regname(opr)))));26362637scope_values->append(sv);2638return 1;26392640#ifdef X862641} else if (opr->is_single_xmm()) {2642VMReg rname = opr->as_xmm_float_reg()->as_VMReg();2643LocationValue* sv = new LocationValue(Location::new_reg_loc(Location::normal, rname));26442645scope_values->append(sv);2646return 1;2647#endif26482649} else if (opr->is_single_fpu()) {2650#ifdef IA322651// the exact location of fpu stack values is only known2652// during fpu stack allocation, so the stack allocator object2653// must be present2654assert(use_fpu_stack_allocation(), "should not have float stack values without fpu stack allocation (all floats must be SSE2)");2655assert(_fpu_stack_allocator != NULL, "must be present");2656opr = _fpu_stack_allocator->to_fpu_stack(opr);2657#elif defined(AMD64)2658assert(false, "FPU not used on x86-64");2659#endif26602661Location::Type loc_type = float_saved_as_double ? Location::float_in_dbl : Location::normal;2662VMReg rname = frame_map()->fpu_regname(opr->fpu_regnr());2663#ifndef __SOFTFP__2664#ifndef VM_LITTLE_ENDIAN2665// On S390 a (single precision) float value occupies only the high2666// word of the full double register. So when the double register is2667// stored to memory (e.g. by the RegisterSaver), then the float value2668// is found at offset 0. I.e. the code below is not needed on S390.2669#ifndef S3902670if (! float_saved_as_double) {2671// On big endian system, we may have an issue if float registers use only2672// the low half of the (same) double registers.2673// Both the float and the double could have the same regnr but would correspond2674// to two different addresses once saved.26752676// get next safely (no assertion checks)2677VMReg next = VMRegImpl::as_VMReg(1+rname->value());2678if (next->is_reg() &&2679(next->as_FloatRegister() == rname->as_FloatRegister())) {2680// the back-end does use the same numbering for the double and the float2681rname = next; // VMReg for the low bits, e.g. the real VMReg for the float2682}2683}2684#endif // !S3902685#endif2686#endif2687LocationValue* sv = new LocationValue(Location::new_reg_loc(loc_type, rname));26882689scope_values->append(sv);2690return 1;26912692} else {2693// double-size operands26942695ScopeValue* first;2696ScopeValue* second;26972698if (opr->is_double_stack()) {2699#ifdef _LP642700Location loc1;2701Location::Type loc_type = opr->type() == T_LONG ? Location::lng : Location::dbl;2702if (!frame_map()->locations_for_slot(opr->double_stack_ix(), loc_type, &loc1, NULL)) {2703bailout("too large frame");2704}27052706first = new LocationValue(loc1);2707second = _int_0_scope_value;2708#else2709Location loc1, loc2;2710if (!frame_map()->locations_for_slot(opr->double_stack_ix(), Location::normal, &loc1, &loc2)) {2711bailout("too large frame");2712}2713first = new LocationValue(loc1);2714second = new LocationValue(loc2);2715#endif // _LP6427162717} else if (opr->is_double_cpu()) {2718#ifdef _LP642719VMReg rname_first = opr->as_register_lo()->as_VMReg();2720first = new LocationValue(Location::new_reg_loc(Location::lng, rname_first));2721second = _int_0_scope_value;2722#else2723VMReg rname_first = opr->as_register_lo()->as_VMReg();2724VMReg rname_second = opr->as_register_hi()->as_VMReg();27252726if (hi_word_offset_in_bytes < lo_word_offset_in_bytes) {2727// lo/hi and swapped relative to first and second, so swap them2728VMReg tmp = rname_first;2729rname_first = rname_second;2730rname_second = tmp;2731}27322733first = new LocationValue(Location::new_reg_loc(Location::normal, rname_first));2734second = new LocationValue(Location::new_reg_loc(Location::normal, rname_second));2735#endif //_LP64273627372738#ifdef X862739} else if (opr->is_double_xmm()) {2740assert(opr->fpu_regnrLo() == opr->fpu_regnrHi(), "assumed in calculation");2741VMReg rname_first = opr->as_xmm_double_reg()->as_VMReg();2742# ifdef _LP642743first = new LocationValue(Location::new_reg_loc(Location::dbl, rname_first));2744second = _int_0_scope_value;2745# else2746first = new LocationValue(Location::new_reg_loc(Location::normal, rname_first));2747// %%% This is probably a waste but we'll keep things as they were for now2748if (true) {2749VMReg rname_second = rname_first->next();2750second = new LocationValue(Location::new_reg_loc(Location::normal, rname_second));2751}2752# endif2753#endif27542755} else if (opr->is_double_fpu()) {2756// On SPARC, fpu_regnrLo/fpu_regnrHi represents the two halves of2757// the double as float registers in the native ordering. On X86,2758// fpu_regnrLo is a FPU stack slot whose VMReg represents2759// the low-order word of the double and fpu_regnrLo + 1 is the2760// name for the other half. *first and *second must represent the2761// least and most significant words, respectively.27622763#ifdef IA322764// the exact location of fpu stack values is only known2765// during fpu stack allocation, so the stack allocator object2766// must be present2767assert(use_fpu_stack_allocation(), "should not have float stack values without fpu stack allocation (all floats must be SSE2)");2768assert(_fpu_stack_allocator != NULL, "must be present");2769opr = _fpu_stack_allocator->to_fpu_stack(opr);27702771assert(opr->fpu_regnrLo() == opr->fpu_regnrHi(), "assumed in calculation (only fpu_regnrLo is used)");2772#endif2773#ifdef AMD642774assert(false, "FPU not used on x86-64");2775#endif2776#ifdef ARM322777assert(opr->fpu_regnrHi() == opr->fpu_regnrLo() + 1, "assumed in calculation (only fpu_regnrLo is used)");2778#endif2779#ifdef PPC322780assert(opr->fpu_regnrLo() == opr->fpu_regnrHi(), "assumed in calculation (only fpu_regnrHi is used)");2781#endif27822783#ifdef VM_LITTLE_ENDIAN2784VMReg rname_first = frame_map()->fpu_regname(opr->fpu_regnrLo());2785#else2786VMReg rname_first = frame_map()->fpu_regname(opr->fpu_regnrHi());2787#endif27882789#ifdef _LP642790first = new LocationValue(Location::new_reg_loc(Location::dbl, rname_first));2791second = _int_0_scope_value;2792#else2793first = new LocationValue(Location::new_reg_loc(Location::normal, rname_first));2794// %%% This is probably a waste but we'll keep things as they were for now2795if (true) {2796VMReg rname_second = rname_first->next();2797second = new LocationValue(Location::new_reg_loc(Location::normal, rname_second));2798}2799#endif28002801} else {2802ShouldNotReachHere();2803first = NULL;2804second = NULL;2805}28062807assert(first != NULL && second != NULL, "must be set");2808// The convention the interpreter uses is that the second local2809// holds the first raw word of the native double representation.2810// This is actually reasonable, since locals and stack arrays2811// grow downwards in all implementations.2812// (If, on some machine, the interpreter's Java locals or stack2813// were to grow upwards, the embedded doubles would be word-swapped.)2814scope_values->append(second);2815scope_values->append(first);2816return 2;2817}2818}281928202821int LinearScan::append_scope_value(int op_id, Value value, GrowableArray<ScopeValue*>* scope_values) {2822if (value != NULL) {2823LIR_Opr opr = value->operand();2824Constant* con = value->as_Constant();28252826assert(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)");2827assert(con != NULL || opr->is_virtual(), "asumption: non-Constant instructions have only virtual operands");28282829if (con != NULL && !con->is_pinned() && !opr->is_constant()) {2830// Unpinned constants may have a virtual operand for a part of the lifetime2831// or may be illegal when it was optimized away,2832// so always use a constant operand2833opr = LIR_OprFact::value_type(con->type());2834}2835assert(opr->is_virtual() || opr->is_constant(), "other cases not allowed here");28362837if (opr->is_virtual()) {2838LIR_OpVisitState::OprMode mode = LIR_OpVisitState::inputMode;28392840BlockBegin* block = block_of_op_with_id(op_id);2841if (block->number_of_sux() == 1 && op_id == block->last_lir_instruction_id()) {2842// generating debug information for the last instruction of a block.2843// if this instruction is a branch, spill moves are inserted before this branch2844// and so the wrong operand would be returned (spill moves at block boundaries are not2845// considered in the live ranges of intervals)2846// Solution: use the first op_id of the branch target block instead.2847if (block->lir()->instructions_list()->last()->as_OpBranch() != NULL) {2848if (block->live_out().at(opr->vreg_number())) {2849op_id = block->sux_at(0)->first_lir_instruction_id();2850mode = LIR_OpVisitState::outputMode;2851}2852}2853}28542855// Get current location of operand2856// The operand must be live because debug information is considered when building the intervals2857// if the interval is not live, color_lir_opr will cause an assertion failure2858opr = color_lir_opr(opr, op_id, mode);2859assert(!has_call(op_id) || opr->is_stack() || !is_caller_save(reg_num(opr)), "can not have caller-save register operands at calls");28602861// Append to ScopeValue array2862return append_scope_value_for_operand(opr, scope_values);28632864} else {2865assert(value->as_Constant() != NULL, "all other instructions have only virtual operands");2866assert(opr->is_constant(), "operand must be constant");28672868return append_scope_value_for_constant(opr, scope_values);2869}2870} else {2871// append a dummy value because real value not needed2872scope_values->append(_illegal_value);2873return 1;2874}2875}287628772878IRScopeDebugInfo* LinearScan::compute_debug_info_for_scope(int op_id, IRScope* cur_scope, ValueStack* cur_state, ValueStack* innermost_state) {2879IRScopeDebugInfo* caller_debug_info = NULL;28802881ValueStack* caller_state = cur_state->caller_state();2882if (caller_state != NULL) {2883// process recursively to compute outermost scope first2884caller_debug_info = compute_debug_info_for_scope(op_id, cur_scope->caller(), caller_state, innermost_state);2885}28862887// initialize these to null.2888// If we don't need deopt info or there are no locals, expressions or monitors,2889// then these get recorded as no information and avoids the allocation of 0 length arrays.2890GrowableArray<ScopeValue*>* locals = NULL;2891GrowableArray<ScopeValue*>* expressions = NULL;2892GrowableArray<MonitorValue*>* monitors = NULL;28932894// describe local variable values2895int nof_locals = cur_state->locals_size();2896if (nof_locals > 0) {2897locals = new GrowableArray<ScopeValue*>(nof_locals);28982899int pos = 0;2900while (pos < nof_locals) {2901assert(pos < cur_state->locals_size(), "why not?");29022903Value local = cur_state->local_at(pos);2904pos += append_scope_value(op_id, local, locals);29052906assert(locals->length() == pos, "must match");2907}2908assert(locals->length() == cur_scope->method()->max_locals(), "wrong number of locals");2909assert(locals->length() == cur_state->locals_size(), "wrong number of locals");2910} else if (cur_scope->method()->max_locals() > 0) {2911assert(cur_state->kind() == ValueStack::EmptyExceptionState, "should be");2912nof_locals = cur_scope->method()->max_locals();2913locals = new GrowableArray<ScopeValue*>(nof_locals);2914for(int i = 0; i < nof_locals; i++) {2915locals->append(_illegal_value);2916}2917}29182919// describe expression stack2920int nof_stack = cur_state->stack_size();2921if (nof_stack > 0) {2922expressions = new GrowableArray<ScopeValue*>(nof_stack);29232924int pos = 0;2925while (pos < nof_stack) {2926Value expression = cur_state->stack_at_inc(pos);2927append_scope_value(op_id, expression, expressions);29282929assert(expressions->length() == pos, "must match");2930}2931assert(expressions->length() == cur_state->stack_size(), "wrong number of stack entries");2932}29332934// describe monitors2935int nof_locks = cur_state->locks_size();2936if (nof_locks > 0) {2937int lock_offset = cur_state->caller_state() != NULL ? cur_state->caller_state()->total_locks_size() : 0;2938monitors = new GrowableArray<MonitorValue*>(nof_locks);2939for (int i = 0; i < nof_locks; i++) {2940monitors->append(location_for_monitor_index(lock_offset + i));2941}2942}29432944return new IRScopeDebugInfo(cur_scope, cur_state->bci(), locals, expressions, monitors, caller_debug_info);2945}294629472948void LinearScan::compute_debug_info(CodeEmitInfo* info, int op_id) {2949TRACE_LINEAR_SCAN(3, tty->print_cr("creating debug information at op_id %d", op_id));29502951IRScope* innermost_scope = info->scope();2952ValueStack* innermost_state = info->stack();29532954assert(innermost_scope != NULL && innermost_state != NULL, "why is it missing?");29552956DEBUG_ONLY(check_stack_depth(info, innermost_state->stack_size()));29572958if (info->_scope_debug_info == NULL) {2959// compute debug information2960info->_scope_debug_info = compute_debug_info_for_scope(op_id, innermost_scope, innermost_state, innermost_state);2961} else {2962// debug information already set. Check that it is correct from the current point of view2963DEBUG_ONLY(assert_equal(info->_scope_debug_info, compute_debug_info_for_scope(op_id, innermost_scope, innermost_state, innermost_state)));2964}2965}296629672968void LinearScan::assign_reg_num(LIR_OpList* instructions, IntervalWalker* iw) {2969LIR_OpVisitState visitor;2970int num_inst = instructions->length();2971bool has_dead = false;29722973for (int j = 0; j < num_inst; j++) {2974LIR_Op* op = instructions->at(j);2975if (op == NULL) { // this can happen when spill-moves are removed in eliminate_spill_moves2976has_dead = true;2977continue;2978}2979int op_id = op->id();29802981// visit instruction to get list of operands2982visitor.visit(op);29832984// iterate all modes of the visitor and process all virtual operands2985for_each_visitor_mode(mode) {2986int n = visitor.opr_count(mode);2987for (int k = 0; k < n; k++) {2988LIR_Opr opr = visitor.opr_at(mode, k);2989if (opr->is_virtual_register()) {2990visitor.set_opr_at(mode, k, color_lir_opr(opr, op_id, mode));2991}2992}2993}29942995if (visitor.info_count() > 0) {2996// exception handling2997if (compilation()->has_exception_handlers()) {2998XHandlers* xhandlers = visitor.all_xhandler();2999int n = xhandlers->length();3000for (int k = 0; k < n; k++) {3001XHandler* handler = xhandlers->handler_at(k);3002if (handler->entry_code() != NULL) {3003assign_reg_num(handler->entry_code()->instructions_list(), NULL);3004}3005}3006} else {3007assert(visitor.all_xhandler()->length() == 0, "missed exception handler");3008}30093010// compute oop map3011assert(iw != NULL, "needed for compute_oop_map");3012compute_oop_map(iw, visitor, op);30133014// compute debug information3015if (!use_fpu_stack_allocation()) {3016// compute debug information if fpu stack allocation is not needed.3017// when fpu stack allocation is needed, the debug information can not3018// be computed here because the exact location of fpu operands is not known3019// -> debug information is created inside the fpu stack allocator3020int n = visitor.info_count();3021for (int k = 0; k < n; k++) {3022compute_debug_info(visitor.info_at(k), op_id);3023}3024}3025}30263027#ifdef ASSERT3028// make sure we haven't made the op invalid.3029op->verify();3030#endif30313032// remove useless moves3033if (op->code() == lir_move) {3034assert(op->as_Op1() != NULL, "move must be LIR_Op1");3035LIR_Op1* move = (LIR_Op1*)op;3036LIR_Opr src = move->in_opr();3037LIR_Opr dst = move->result_opr();3038if (dst == src ||3039(!dst->is_pointer() && !src->is_pointer() &&3040src->is_same_register(dst))) {3041instructions->at_put(j, NULL);3042has_dead = true;3043}3044}3045}30463047if (has_dead) {3048// iterate all instructions of the block and remove all null-values.3049int insert_point = 0;3050for (int j = 0; j < num_inst; j++) {3051LIR_Op* op = instructions->at(j);3052if (op != NULL) {3053if (insert_point != j) {3054instructions->at_put(insert_point, op);3055}3056insert_point++;3057}3058}3059instructions->trunc_to(insert_point);3060}3061}30623063void LinearScan::assign_reg_num() {3064TIME_LINEAR_SCAN(timer_assign_reg_num);30653066init_compute_debug_info();3067IntervalWalker* iw = init_compute_oop_maps();30683069int num_blocks = block_count();3070for (int i = 0; i < num_blocks; i++) {3071BlockBegin* block = block_at(i);3072assign_reg_num(block->lir()->instructions_list(), iw);3073}3074}307530763077void LinearScan::do_linear_scan() {3078NOT_PRODUCT(_total_timer.begin_method());30793080number_instructions();30813082NOT_PRODUCT(print_lir(1, "Before Register Allocation"));30833084compute_local_live_sets();3085compute_global_live_sets();3086CHECK_BAILOUT();30873088build_intervals();3089CHECK_BAILOUT();3090sort_intervals_before_allocation();30913092NOT_PRODUCT(print_intervals("Before Register Allocation"));3093NOT_PRODUCT(LinearScanStatistic::compute(this, _stat_before_alloc));30943095allocate_registers();3096CHECK_BAILOUT();30973098resolve_data_flow();3099if (compilation()->has_exception_handlers()) {3100resolve_exception_handlers();3101}3102// fill in number of spill slots into frame_map3103propagate_spill_slots();3104CHECK_BAILOUT();31053106NOT_PRODUCT(print_intervals("After Register Allocation"));3107NOT_PRODUCT(print_lir(2, "LIR after register allocation:"));31083109sort_intervals_after_allocation();31103111DEBUG_ONLY(verify());31123113eliminate_spill_moves();3114assign_reg_num();3115CHECK_BAILOUT();31163117NOT_PRODUCT(print_lir(2, "LIR after assignment of register numbers:"));3118NOT_PRODUCT(LinearScanStatistic::compute(this, _stat_after_asign));31193120{ TIME_LINEAR_SCAN(timer_allocate_fpu_stack);31213122if (use_fpu_stack_allocation()) {3123allocate_fpu_stack(); // Only has effect on Intel3124NOT_PRODUCT(print_lir(2, "LIR after FPU stack allocation:"));3125}3126}31273128{ TIME_LINEAR_SCAN(timer_optimize_lir);31293130EdgeMoveOptimizer::optimize(ir()->code());3131ControlFlowOptimizer::optimize(ir()->code());3132// check that cfg is still correct after optimizations3133ir()->verify();3134}31353136NOT_PRODUCT(print_lir(1, "Before Code Generation", false));3137NOT_PRODUCT(LinearScanStatistic::compute(this, _stat_final));3138NOT_PRODUCT(_total_timer.end_method(this));3139}314031413142// ********** Printing functions31433144#ifndef PRODUCT31453146void LinearScan::print_timers(double total) {3147_total_timer.print(total);3148}31493150void LinearScan::print_statistics() {3151_stat_before_alloc.print("before allocation");3152_stat_after_asign.print("after assignment of register");3153_stat_final.print("after optimization");3154}31553156void LinearScan::print_bitmap(BitMap& b) {3157for (unsigned int i = 0; i < b.size(); i++) {3158if (b.at(i)) tty->print("%d ", i);3159}3160tty->cr();3161}31623163void LinearScan::print_intervals(const char* label) {3164if (TraceLinearScanLevel >= 1) {3165int i;3166tty->cr();3167tty->print_cr("%s", label);31683169for (i = 0; i < interval_count(); i++) {3170Interval* interval = interval_at(i);3171if (interval != NULL) {3172interval->print();3173}3174}31753176tty->cr();3177tty->print_cr("--- Basic Blocks ---");3178for (i = 0; i < block_count(); i++) {3179BlockBegin* block = block_at(i);3180tty->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());3181}3182tty->cr();3183tty->cr();3184}31853186if (PrintCFGToFile) {3187CFGPrinter::print_intervals(&_intervals, label);3188}3189}31903191void LinearScan::print_lir(int level, const char* label, bool hir_valid) {3192if (TraceLinearScanLevel >= level) {3193tty->cr();3194tty->print_cr("%s", label);3195print_LIR(ir()->linear_scan_order());3196tty->cr();3197}31983199if (level == 1 && PrintCFGToFile) {3200CFGPrinter::print_cfg(ir()->linear_scan_order(), label, hir_valid, true);3201}3202}32033204void LinearScan::print_reg_num(outputStream* out, int reg_num) {3205if (reg_num == -1) {3206out->print("[ANY]");3207return;3208} else if (reg_num >= LIR_OprDesc::vreg_base) {3209out->print("[VREG %d]", reg_num);3210return;3211}32123213LIR_Opr opr = get_operand(reg_num);3214assert(opr->is_valid(), "unknown register");3215opr->print(out);3216}32173218LIR_Opr LinearScan::get_operand(int reg_num) {3219LIR_Opr opr = LIR_OprFact::illegal();32203221#ifdef X863222int last_xmm_reg = pd_last_xmm_reg;3223#ifdef _LP643224if (UseAVX < 3) {3225last_xmm_reg = pd_first_xmm_reg + (pd_nof_xmm_regs_frame_map / 2) - 1;3226}3227#endif3228#endif3229if (reg_num >= pd_first_cpu_reg && reg_num <= pd_last_cpu_reg) {3230opr = LIR_OprFact::single_cpu(reg_num);3231} else if (reg_num >= pd_first_fpu_reg && reg_num <= pd_last_fpu_reg) {3232opr = LIR_OprFact::single_fpu(reg_num - pd_first_fpu_reg);3233#ifdef X863234} else if (reg_num >= pd_first_xmm_reg && reg_num <= last_xmm_reg) {3235opr = LIR_OprFact::single_xmm(reg_num - pd_first_xmm_reg);3236#endif3237} else {3238// reg_num == -1 or a virtual register, return the illegal operand3239}3240return opr;3241}32423243Interval* LinearScan::find_interval_at(int reg_num) const {3244if (reg_num < 0 || reg_num >= _intervals.length()) {3245return NULL;3246}3247return interval_at(reg_num);3248}32493250#endif // PRODUCT325132523253// ********** verification functions for allocation3254// (check that all intervals have a correct register and that no registers are overwritten)3255#ifdef ASSERT32563257void LinearScan::verify() {3258TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying intervals ******************************************"));3259verify_intervals();32603261TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying that no oops are in fixed intervals ****************"));3262verify_no_oops_in_fixed_intervals();32633264TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying that unpinned constants are not alive across block boundaries"));3265verify_constants();32663267TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying register allocation ********************************"));3268verify_registers();32693270TRACE_LINEAR_SCAN(2, tty->print_cr("********* no errors found **********************************************"));3271}32723273void LinearScan::verify_intervals() {3274int len = interval_count();3275bool has_error = false;32763277for (int i = 0; i < len; i++) {3278Interval* i1 = interval_at(i);3279if (i1 == NULL) continue;32803281i1->check_split_children();32823283if (i1->reg_num() != i) {3284tty->print_cr("Interval %d is on position %d in list", i1->reg_num(), i); i1->print(); tty->cr();3285has_error = true;3286}32873288if (i1->reg_num() >= LIR_OprDesc::vreg_base && i1->type() == T_ILLEGAL) {3289tty->print_cr("Interval %d has no type assigned", i1->reg_num()); i1->print(); tty->cr();3290has_error = true;3291}32923293if (i1->assigned_reg() == any_reg) {3294tty->print_cr("Interval %d has no register assigned", i1->reg_num()); i1->print(); tty->cr();3295has_error = true;3296}32973298if (i1->assigned_reg() == i1->assigned_regHi()) {3299tty->print_cr("Interval %d: low and high register equal", i1->reg_num()); i1->print(); tty->cr();3300has_error = true;3301}33023303if (!is_processed_reg_num(i1->assigned_reg())) {3304tty->print_cr("Can not have an Interval for an ignored register"); i1->print(); tty->cr();3305has_error = true;3306}33073308// special intervals that are created in MoveResolver3309// -> ignore them because the range information has no meaning there3310if (i1->from() == 1 && i1->to() == 2) continue;33113312if (i1->first() == Range::end()) {3313tty->print_cr("Interval %d has no Range", i1->reg_num()); i1->print(); tty->cr();3314has_error = true;3315}33163317for (Range* r = i1->first(); r != Range::end(); r = r->next()) {3318if (r->from() >= r->to()) {3319tty->print_cr("Interval %d has zero length range", i1->reg_num()); i1->print(); tty->cr();3320has_error = true;3321}3322}33233324for (int j = i + 1; j < len; j++) {3325Interval* i2 = interval_at(j);3326if (i2 == NULL || (i2->from() == 1 && i2->to() == 2)) continue;33273328int r1 = i1->assigned_reg();3329int r1Hi = i1->assigned_regHi();3330int r2 = i2->assigned_reg();3331int r2Hi = i2->assigned_regHi();3332if ((r1 == r2 || r1 == r2Hi || (r1Hi != any_reg && (r1Hi == r2 || r1Hi == r2Hi))) && i1->intersects(i2)) {3333tty->print_cr("Intervals %d and %d overlap and have the same register assigned", i1->reg_num(), i2->reg_num());3334i1->print(); tty->cr();3335i2->print(); tty->cr();3336has_error = true;3337}3338}3339}33403341assert(has_error == false, "register allocation invalid");3342}334333443345void LinearScan::verify_no_oops_in_fixed_intervals() {3346Interval* fixed_intervals;3347Interval* other_intervals;3348create_unhandled_lists(&fixed_intervals, &other_intervals, is_precolored_cpu_interval, NULL);33493350// to ensure a walking until the last instruction id, add a dummy interval3351// with a high operation id3352other_intervals = new Interval(any_reg);3353other_intervals->add_range(max_jint - 2, max_jint - 1);3354IntervalWalker* iw = new IntervalWalker(this, fixed_intervals, other_intervals);33553356LIR_OpVisitState visitor;3357for (int i = 0; i < block_count(); i++) {3358BlockBegin* block = block_at(i);33593360LIR_OpList* instructions = block->lir()->instructions_list();33613362for (int j = 0; j < instructions->length(); j++) {3363LIR_Op* op = instructions->at(j);3364int op_id = op->id();33653366visitor.visit(op);33673368if (visitor.info_count() > 0) {3369iw->walk_before(op->id());3370bool check_live = true;3371if (op->code() == lir_move) {3372LIR_Op1* move = (LIR_Op1*)op;3373check_live = (move->patch_code() == lir_patch_none);3374}3375LIR_OpBranch* branch = op->as_OpBranch();3376if (branch != NULL && branch->stub() != NULL && branch->stub()->is_exception_throw_stub()) {3377// Don't bother checking the stub in this case since the3378// exception stub will never return to normal control flow.3379check_live = false;3380}33813382// Make sure none of the fixed registers is live across an3383// oopmap since we can't handle that correctly.3384if (check_live) {3385for (Interval* interval = iw->active_first(fixedKind);3386interval != Interval::end();3387interval = interval->next()) {3388if (interval->current_to() > op->id() + 1) {3389// This interval is live out of this op so make sure3390// that this interval represents some value that's3391// referenced by this op either as an input or output.3392bool ok = false;3393for_each_visitor_mode(mode) {3394int n = visitor.opr_count(mode);3395for (int k = 0; k < n; k++) {3396LIR_Opr opr = visitor.opr_at(mode, k);3397if (opr->is_fixed_cpu()) {3398if (interval_at(reg_num(opr)) == interval) {3399ok = true;3400break;3401}3402int hi = reg_numHi(opr);3403if (hi != -1 && interval_at(hi) == interval) {3404ok = true;3405break;3406}3407}3408}3409}3410assert(ok, "fixed intervals should never be live across an oopmap point");3411}3412}3413}3414}34153416// oop-maps at calls do not contain registers, so check is not needed3417if (!visitor.has_call()) {34183419for_each_visitor_mode(mode) {3420int n = visitor.opr_count(mode);3421for (int k = 0; k < n; k++) {3422LIR_Opr opr = visitor.opr_at(mode, k);34233424if (opr->is_fixed_cpu() && opr->is_oop()) {3425// operand is a non-virtual cpu register and contains an oop3426TRACE_LINEAR_SCAN(4, op->print_on(tty); tty->print("checking operand "); opr->print(); tty->cr());34273428Interval* interval = interval_at(reg_num(opr));3429assert(interval != NULL, "no interval");34303431if (mode == LIR_OpVisitState::inputMode) {3432if (interval->to() >= op_id + 1) {3433assert(interval->to() < op_id + 2 ||3434interval->has_hole_between(op_id, op_id + 2),3435"oop input operand live after instruction");3436}3437} else if (mode == LIR_OpVisitState::outputMode) {3438if (interval->from() <= op_id - 1) {3439assert(interval->has_hole_between(op_id - 1, op_id),3440"oop input operand live after instruction");3441}3442}3443}3444}3445}3446}3447}3448}3449}345034513452void LinearScan::verify_constants() {3453int num_regs = num_virtual_regs();3454int size = live_set_size();3455int num_blocks = block_count();34563457for (int i = 0; i < num_blocks; i++) {3458BlockBegin* block = block_at(i);3459ResourceBitMap live_at_edge = block->live_in();34603461// visit all registers where the live_at_edge bit is set3462for (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)) {3463TRACE_LINEAR_SCAN(4, tty->print("checking interval %d of block B%d", r, block->block_id()));34643465Value value = gen()->instruction_for_vreg(r);34663467assert(value != NULL, "all intervals live across block boundaries must have Value");3468assert(value->operand()->is_register() && value->operand()->is_virtual(), "value must have virtual operand");3469assert(value->operand()->vreg_number() == r, "register number must match");3470// TKR assert(value->as_Constant() == NULL || value->is_pinned(), "only pinned constants can be alive accross block boundaries");3471}3472}3473}347434753476class RegisterVerifier: public StackObj {3477private:3478LinearScan* _allocator;3479BlockList _work_list; // all blocks that must be processed3480IntervalsList _saved_states; // saved information of previous check34813482// simplified access to methods of LinearScan3483Compilation* compilation() const { return _allocator->compilation(); }3484Interval* interval_at(int reg_num) const { return _allocator->interval_at(reg_num); }3485int reg_num(LIR_Opr opr) const { return _allocator->reg_num(opr); }34863487// currently, only registers are processed3488int state_size() { return LinearScan::nof_regs; }34893490// accessors3491IntervalList* state_for_block(BlockBegin* block) { return _saved_states.at(block->block_id()); }3492void set_state_for_block(BlockBegin* block, IntervalList* saved_state) { _saved_states.at_put(block->block_id(), saved_state); }3493void add_to_work_list(BlockBegin* block) { if (!_work_list.contains(block)) _work_list.append(block); }34943495// helper functions3496IntervalList* copy(IntervalList* input_state);3497void state_put(IntervalList* input_state, int reg, Interval* interval);3498bool check_state(IntervalList* input_state, int reg, Interval* interval);34993500void process_block(BlockBegin* block);3501void process_xhandler(XHandler* xhandler, IntervalList* input_state);3502void process_successor(BlockBegin* block, IntervalList* input_state);3503void process_operations(LIR_List* ops, IntervalList* input_state);35043505public:3506RegisterVerifier(LinearScan* allocator)3507: _allocator(allocator)3508, _work_list(16)3509, _saved_states(BlockBegin::number_of_blocks(), BlockBegin::number_of_blocks(), NULL)3510{ }35113512void verify(BlockBegin* start);3513};351435153516// entry function from LinearScan that starts the verification3517void LinearScan::verify_registers() {3518RegisterVerifier verifier(this);3519verifier.verify(block_at(0));3520}352135223523void RegisterVerifier::verify(BlockBegin* start) {3524// setup input registers (method arguments) for first block3525int input_state_len = state_size();3526IntervalList* input_state = new IntervalList(input_state_len, input_state_len, NULL);3527CallingConvention* args = compilation()->frame_map()->incoming_arguments();3528for (int n = 0; n < args->length(); n++) {3529LIR_Opr opr = args->at(n);3530if (opr->is_register()) {3531Interval* interval = interval_at(reg_num(opr));35323533if (interval->assigned_reg() < state_size()) {3534input_state->at_put(interval->assigned_reg(), interval);3535}3536if (interval->assigned_regHi() != LinearScan::any_reg && interval->assigned_regHi() < state_size()) {3537input_state->at_put(interval->assigned_regHi(), interval);3538}3539}3540}35413542set_state_for_block(start, input_state);3543add_to_work_list(start);35443545// main loop for verification3546do {3547BlockBegin* block = _work_list.at(0);3548_work_list.remove_at(0);35493550process_block(block);3551} while (!_work_list.is_empty());3552}35533554void RegisterVerifier::process_block(BlockBegin* block) {3555TRACE_LINEAR_SCAN(2, tty->cr(); tty->print_cr("process_block B%d", block->block_id()));35563557// must copy state because it is modified3558IntervalList* input_state = copy(state_for_block(block));35593560if (TraceLinearScanLevel >= 4) {3561tty->print_cr("Input-State of intervals:");3562tty->print(" ");3563for (int i = 0; i < state_size(); i++) {3564if (input_state->at(i) != NULL) {3565tty->print(" %4d", input_state->at(i)->reg_num());3566} else {3567tty->print(" __");3568}3569}3570tty->cr();3571tty->cr();3572}35733574// process all operations of the block3575process_operations(block->lir(), input_state);35763577// iterate all successors3578for (int i = 0; i < block->number_of_sux(); i++) {3579process_successor(block->sux_at(i), input_state);3580}3581}35823583void RegisterVerifier::process_xhandler(XHandler* xhandler, IntervalList* input_state) {3584TRACE_LINEAR_SCAN(2, tty->print_cr("process_xhandler B%d", xhandler->entry_block()->block_id()));35853586// must copy state because it is modified3587input_state = copy(input_state);35883589if (xhandler->entry_code() != NULL) {3590process_operations(xhandler->entry_code(), input_state);3591}3592process_successor(xhandler->entry_block(), input_state);3593}35943595void RegisterVerifier::process_successor(BlockBegin* block, IntervalList* input_state) {3596IntervalList* saved_state = state_for_block(block);35973598if (saved_state != NULL) {3599// this block was already processed before.3600// check if new input_state is consistent with saved_state36013602bool saved_state_correct = true;3603for (int i = 0; i < state_size(); i++) {3604if (input_state->at(i) != saved_state->at(i)) {3605// current input_state and previous saved_state assume a different3606// interval in this register -> assume that this register is invalid3607if (saved_state->at(i) != NULL) {3608// invalidate old calculation only if it assumed that3609// register was valid. when the register was already invalid,3610// then the old calculation was correct.3611saved_state_correct = false;3612saved_state->at_put(i, NULL);36133614TRACE_LINEAR_SCAN(4, tty->print_cr("process_successor B%d: invalidating slot %d", block->block_id(), i));3615}3616}3617}36183619if (saved_state_correct) {3620// already processed block with correct input_state3621TRACE_LINEAR_SCAN(2, tty->print_cr("process_successor B%d: previous visit already correct", block->block_id()));3622} else {3623// must re-visit this block3624TRACE_LINEAR_SCAN(2, tty->print_cr("process_successor B%d: must re-visit because input state changed", block->block_id()));3625add_to_work_list(block);3626}36273628} else {3629// block was not processed before, so set initial input_state3630TRACE_LINEAR_SCAN(2, tty->print_cr("process_successor B%d: initial visit", block->block_id()));36313632set_state_for_block(block, copy(input_state));3633add_to_work_list(block);3634}3635}363636373638IntervalList* RegisterVerifier::copy(IntervalList* input_state) {3639IntervalList* copy_state = new IntervalList(input_state->length());3640copy_state->appendAll(input_state);3641return copy_state;3642}36433644void RegisterVerifier::state_put(IntervalList* input_state, int reg, Interval* interval) {3645if (reg != LinearScan::any_reg && reg < state_size()) {3646if (interval != NULL) {3647TRACE_LINEAR_SCAN(4, tty->print_cr(" reg[%d] = %d", reg, interval->reg_num()));3648} else if (input_state->at(reg) != NULL) {3649TRACE_LINEAR_SCAN(4, tty->print_cr(" reg[%d] = NULL", reg));3650}36513652input_state->at_put(reg, interval);3653}3654}36553656bool RegisterVerifier::check_state(IntervalList* input_state, int reg, Interval* interval) {3657if (reg != LinearScan::any_reg && reg < state_size()) {3658if (input_state->at(reg) != interval) {3659tty->print_cr("!! Error in register allocation: register %d does not contain interval %d", reg, interval->reg_num());3660return true;3661}3662}3663return false;3664}36653666void RegisterVerifier::process_operations(LIR_List* ops, IntervalList* input_state) {3667// visit all instructions of the block3668LIR_OpVisitState visitor;3669bool has_error = false;36703671for (int i = 0; i < ops->length(); i++) {3672LIR_Op* op = ops->at(i);3673visitor.visit(op);36743675TRACE_LINEAR_SCAN(4, op->print_on(tty));36763677// check if input operands are correct3678int j;3679int n = visitor.opr_count(LIR_OpVisitState::inputMode);3680for (j = 0; j < n; j++) {3681LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::inputMode, j);3682if (opr->is_register() && LinearScan::is_processed_reg_num(reg_num(opr))) {3683Interval* interval = interval_at(reg_num(opr));3684if (op->id() != -1) {3685interval = interval->split_child_at_op_id(op->id(), LIR_OpVisitState::inputMode);3686}36873688has_error |= check_state(input_state, interval->assigned_reg(), interval->split_parent());3689has_error |= check_state(input_state, interval->assigned_regHi(), interval->split_parent());36903691// When an operand is marked with is_last_use, then the fpu stack allocator3692// removes the register from the fpu stack -> the register contains no value3693if (opr->is_last_use()) {3694state_put(input_state, interval->assigned_reg(), NULL);3695state_put(input_state, interval->assigned_regHi(), NULL);3696}3697}3698}36993700// invalidate all caller save registers at calls3701if (visitor.has_call()) {3702for (j = 0; j < FrameMap::nof_caller_save_cpu_regs(); j++) {3703state_put(input_state, reg_num(FrameMap::caller_save_cpu_reg_at(j)), NULL);3704}3705for (j = 0; j < FrameMap::nof_caller_save_fpu_regs; j++) {3706state_put(input_state, reg_num(FrameMap::caller_save_fpu_reg_at(j)), NULL);3707}37083709#ifdef X863710int num_caller_save_xmm_regs = FrameMap::get_num_caller_save_xmms();3711for (j = 0; j < num_caller_save_xmm_regs; j++) {3712state_put(input_state, reg_num(FrameMap::caller_save_xmm_reg_at(j)), NULL);3713}3714#endif3715}37163717// process xhandler before output and temp operands3718XHandlers* xhandlers = visitor.all_xhandler();3719n = xhandlers->length();3720for (int k = 0; k < n; k++) {3721process_xhandler(xhandlers->handler_at(k), input_state);3722}37233724// set temp operands (some operations use temp operands also as output operands, so can't set them NULL)3725n = visitor.opr_count(LIR_OpVisitState::tempMode);3726for (j = 0; j < n; j++) {3727LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::tempMode, j);3728if (opr->is_register() && LinearScan::is_processed_reg_num(reg_num(opr))) {3729Interval* interval = interval_at(reg_num(opr));3730if (op->id() != -1) {3731interval = interval->split_child_at_op_id(op->id(), LIR_OpVisitState::tempMode);3732}37333734state_put(input_state, interval->assigned_reg(), interval->split_parent());3735state_put(input_state, interval->assigned_regHi(), interval->split_parent());3736}3737}37383739// set output operands3740n = visitor.opr_count(LIR_OpVisitState::outputMode);3741for (j = 0; j < n; j++) {3742LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::outputMode, j);3743if (opr->is_register() && LinearScan::is_processed_reg_num(reg_num(opr))) {3744Interval* interval = interval_at(reg_num(opr));3745if (op->id() != -1) {3746interval = interval->split_child_at_op_id(op->id(), LIR_OpVisitState::outputMode);3747}37483749state_put(input_state, interval->assigned_reg(), interval->split_parent());3750state_put(input_state, interval->assigned_regHi(), interval->split_parent());3751}3752}3753}3754assert(has_error == false, "Error in register allocation");3755}37563757#endif // ASSERT3758375937603761// **** Implementation of MoveResolver ******************************37623763MoveResolver::MoveResolver(LinearScan* allocator) :3764_allocator(allocator),3765_insert_list(NULL),3766_insert_idx(-1),3767_insertion_buffer(),3768_mapping_from(8),3769_mapping_from_opr(8),3770_mapping_to(8),3771_multiple_reads_allowed(false)3772{3773for (int i = 0; i < LinearScan::nof_regs; i++) {3774_register_blocked[i] = 0;3775}3776DEBUG_ONLY(check_empty());3777}377837793780#ifdef ASSERT37813782void MoveResolver::check_empty() {3783assert(_mapping_from.length() == 0 && _mapping_from_opr.length() == 0 && _mapping_to.length() == 0, "list must be empty before and after processing");3784for (int i = 0; i < LinearScan::nof_regs; i++) {3785assert(register_blocked(i) == 0, "register map must be empty before and after processing");3786}3787assert(_multiple_reads_allowed == false, "must have default value");3788}37893790void MoveResolver::verify_before_resolve() {3791assert(_mapping_from.length() == _mapping_from_opr.length(), "length must be equal");3792assert(_mapping_from.length() == _mapping_to.length(), "length must be equal");3793assert(_insert_list != NULL && _insert_idx != -1, "insert position not set");37943795int i, j;3796if (!_multiple_reads_allowed) {3797for (i = 0; i < _mapping_from.length(); i++) {3798for (j = i + 1; j < _mapping_from.length(); j++) {3799assert(_mapping_from.at(i) == NULL || _mapping_from.at(i) != _mapping_from.at(j), "cannot read from same interval twice");3800}3801}3802}38033804for (i = 0; i < _mapping_to.length(); i++) {3805for (j = i + 1; j < _mapping_to.length(); j++) {3806assert(_mapping_to.at(i) != _mapping_to.at(j), "cannot write to same interval twice");3807}3808}380938103811ResourceBitMap used_regs(LinearScan::nof_regs + allocator()->frame_map()->argcount() + allocator()->max_spills());3812if (!_multiple_reads_allowed) {3813for (i = 0; i < _mapping_from.length(); i++) {3814Interval* it = _mapping_from.at(i);3815if (it != NULL) {3816assert(!used_regs.at(it->assigned_reg()), "cannot read from same register twice");3817used_regs.set_bit(it->assigned_reg());38183819if (it->assigned_regHi() != LinearScan::any_reg) {3820assert(!used_regs.at(it->assigned_regHi()), "cannot read from same register twice");3821used_regs.set_bit(it->assigned_regHi());3822}3823}3824}3825}38263827used_regs.clear();3828for (i = 0; i < _mapping_to.length(); i++) {3829Interval* it = _mapping_to.at(i);3830assert(!used_regs.at(it->assigned_reg()), "cannot write to same register twice");3831used_regs.set_bit(it->assigned_reg());38323833if (it->assigned_regHi() != LinearScan::any_reg) {3834assert(!used_regs.at(it->assigned_regHi()), "cannot write to same register twice");3835used_regs.set_bit(it->assigned_regHi());3836}3837}38383839used_regs.clear();3840for (i = 0; i < _mapping_from.length(); i++) {3841Interval* it = _mapping_from.at(i);3842if (it != NULL && it->assigned_reg() >= LinearScan::nof_regs) {3843used_regs.set_bit(it->assigned_reg());3844}3845}3846for (i = 0; i < _mapping_to.length(); i++) {3847Interval* it = _mapping_to.at(i);3848assert(!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");3849}3850}38513852#endif // ASSERT385338543855// mark assigned_reg and assigned_regHi of the interval as blocked3856void MoveResolver::block_registers(Interval* it) {3857int reg = it->assigned_reg();3858if (reg < LinearScan::nof_regs) {3859assert(_multiple_reads_allowed || register_blocked(reg) == 0, "register already marked as used");3860set_register_blocked(reg, 1);3861}3862reg = it->assigned_regHi();3863if (reg != LinearScan::any_reg && reg < LinearScan::nof_regs) {3864assert(_multiple_reads_allowed || register_blocked(reg) == 0, "register already marked as used");3865set_register_blocked(reg, 1);3866}3867}38683869// mark assigned_reg and assigned_regHi of the interval as unblocked3870void MoveResolver::unblock_registers(Interval* it) {3871int reg = it->assigned_reg();3872if (reg < LinearScan::nof_regs) {3873assert(register_blocked(reg) > 0, "register already marked as unused");3874set_register_blocked(reg, -1);3875}3876reg = it->assigned_regHi();3877if (reg != LinearScan::any_reg && reg < LinearScan::nof_regs) {3878assert(register_blocked(reg) > 0, "register already marked as unused");3879set_register_blocked(reg, -1);3880}3881}38823883// check if assigned_reg and assigned_regHi of the to-interval are not blocked (or only blocked by from)3884bool MoveResolver::save_to_process_move(Interval* from, Interval* to) {3885int from_reg = -1;3886int from_regHi = -1;3887if (from != NULL) {3888from_reg = from->assigned_reg();3889from_regHi = from->assigned_regHi();3890}38913892int reg = to->assigned_reg();3893if (reg < LinearScan::nof_regs) {3894if (register_blocked(reg) > 1 || (register_blocked(reg) == 1 && reg != from_reg && reg != from_regHi)) {3895return false;3896}3897}3898reg = to->assigned_regHi();3899if (reg != LinearScan::any_reg && reg < LinearScan::nof_regs) {3900if (register_blocked(reg) > 1 || (register_blocked(reg) == 1 && reg != from_reg && reg != from_regHi)) {3901return false;3902}3903}39043905return true;3906}390739083909void MoveResolver::create_insertion_buffer(LIR_List* list) {3910assert(!_insertion_buffer.initialized(), "overwriting existing buffer");3911_insertion_buffer.init(list);3912}39133914void MoveResolver::append_insertion_buffer() {3915if (_insertion_buffer.initialized()) {3916_insertion_buffer.lir_list()->append(&_insertion_buffer);3917}3918assert(!_insertion_buffer.initialized(), "must be uninitialized now");39193920_insert_list = NULL;3921_insert_idx = -1;3922}39233924void MoveResolver::insert_move(Interval* from_interval, Interval* to_interval) {3925assert(from_interval->reg_num() != to_interval->reg_num(), "from and to interval equal");3926assert(from_interval->type() == to_interval->type(), "move between different types");3927assert(_insert_list != NULL && _insert_idx != -1, "must setup insert position first");3928assert(_insertion_buffer.lir_list() == _insert_list, "wrong insertion buffer");39293930LIR_Opr from_opr = get_virtual_register(from_interval);3931LIR_Opr to_opr = get_virtual_register(to_interval);39323933if (!_multiple_reads_allowed) {3934// the last_use flag is an optimization for FPU stack allocation. When the same3935// input interval is used in more than one move, then it is too difficult to determine3936// if this move is really the last use.3937from_opr = from_opr->make_last_use();3938}3939_insertion_buffer.move(_insert_idx, from_opr, to_opr);39403941TRACE_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()));3942}39433944void MoveResolver::insert_move(LIR_Opr from_opr, Interval* to_interval) {3945assert(from_opr->type() == to_interval->type(), "move between different types");3946assert(_insert_list != NULL && _insert_idx != -1, "must setup insert position first");3947assert(_insertion_buffer.lir_list() == _insert_list, "wrong insertion buffer");39483949LIR_Opr to_opr = get_virtual_register(to_interval);3950_insertion_buffer.move(_insert_idx, from_opr, to_opr);39513952TRACE_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()));3953}39543955LIR_Opr MoveResolver::get_virtual_register(Interval* interval) {3956// Add a little fudge factor for the bailout since the bailout is only checked periodically. This allows us to hand out3957// a few extra registers before we really run out which helps to avoid to trip over assertions.3958int reg_num = interval->reg_num();3959if (reg_num + 20 >= LIR_OprDesc::vreg_max) {3960_allocator->bailout("out of virtual registers in linear scan");3961if (reg_num + 2 >= LIR_OprDesc::vreg_max) {3962// Wrap it around and continue until bailout really happens to avoid hitting assertions.3963reg_num = LIR_OprDesc::vreg_base;3964}3965}3966LIR_Opr vreg = LIR_OprFact::virtual_register(reg_num, interval->type());3967assert(vreg != LIR_OprFact::illegal(), "ran out of virtual registers");3968return vreg;3969}39703971void MoveResolver::resolve_mappings() {3972TRACE_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));3973DEBUG_ONLY(verify_before_resolve());39743975// Block all registers that are used as input operands of a move.3976// When a register is blocked, no move to this register is emitted.3977// This is necessary for detecting cycles in moves.3978int i;3979for (i = _mapping_from.length() - 1; i >= 0; i--) {3980Interval* from_interval = _mapping_from.at(i);3981if (from_interval != NULL) {3982block_registers(from_interval);3983}3984}39853986int spill_candidate = -1;3987while (_mapping_from.length() > 0) {3988bool processed_interval = false;39893990for (i = _mapping_from.length() - 1; i >= 0; i--) {3991Interval* from_interval = _mapping_from.at(i);3992Interval* to_interval = _mapping_to.at(i);39933994if (save_to_process_move(from_interval, to_interval)) {3995// this inverval can be processed because target is free3996if (from_interval != NULL) {3997insert_move(from_interval, to_interval);3998unblock_registers(from_interval);3999} else {4000insert_move(_mapping_from_opr.at(i), to_interval);4001}4002_mapping_from.remove_at(i);4003_mapping_from_opr.remove_at(i);4004_mapping_to.remove_at(i);40054006processed_interval = true;4007} else if (from_interval != NULL && from_interval->assigned_reg() < LinearScan::nof_regs) {4008// this interval cannot be processed now because target is not free4009// it starts in a register, so it is a possible candidate for spilling4010spill_candidate = i;4011}4012}40134014if (!processed_interval) {4015// no move could be processed because there is a cycle in the move list4016// (e.g. r1 -> r2, r2 -> r1), so one interval must be spilled to memory4017guarantee(spill_candidate != -1, "no interval in register for spilling found");40184019// create a new spill interval and assign a stack slot to it4020Interval* from_interval = _mapping_from.at(spill_candidate);4021Interval* spill_interval = new Interval(-1);4022spill_interval->set_type(from_interval->type());40234024// add a dummy range because real position is difficult to calculate4025// Note: this range is a special case when the integrity of the allocation is checked4026spill_interval->add_range(1, 2);40274028// do not allocate a new spill slot for temporary interval, but4029// use spill slot assigned to from_interval. Otherwise moves from4030// one stack slot to another can happen (not allowed by LIR_Assembler4031int spill_slot = from_interval->canonical_spill_slot();4032if (spill_slot < 0) {4033spill_slot = allocator()->allocate_spill_slot(type2spill_size[spill_interval->type()] == 2);4034from_interval->set_canonical_spill_slot(spill_slot);4035}4036spill_interval->assign_reg(spill_slot);4037allocator()->append_interval(spill_interval);40384039TRACE_LINEAR_SCAN(4, tty->print_cr("created new Interval %d for spilling", spill_interval->reg_num()));40404041// insert a move from register to stack and update the mapping4042insert_move(from_interval, spill_interval);4043_mapping_from.at_put(spill_candidate, spill_interval);4044unblock_registers(from_interval);4045}4046}40474048// reset to default value4049_multiple_reads_allowed = false;40504051// check that all intervals have been processed4052DEBUG_ONLY(check_empty());4053}405440554056void MoveResolver::set_insert_position(LIR_List* insert_list, int insert_idx) {4057TRACE_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));4058assert(_insert_list == NULL && _insert_idx == -1, "use move_insert_position instead of set_insert_position when data already set");40594060create_insertion_buffer(insert_list);4061_insert_list = insert_list;4062_insert_idx = insert_idx;4063}40644065void MoveResolver::move_insert_position(LIR_List* insert_list, int insert_idx) {4066TRACE_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));40674068if (_insert_list != NULL && (insert_list != _insert_list || insert_idx != _insert_idx)) {4069// insert position changed -> resolve current mappings4070resolve_mappings();4071}40724073if (insert_list != _insert_list) {4074// block changed -> append insertion_buffer because it is4075// bound to a specific block and create a new insertion_buffer4076append_insertion_buffer();4077create_insertion_buffer(insert_list);4078}40794080_insert_list = insert_list;4081_insert_idx = insert_idx;4082}40834084void MoveResolver::add_mapping(Interval* from_interval, Interval* to_interval) {4085TRACE_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()));40864087_mapping_from.append(from_interval);4088_mapping_from_opr.append(LIR_OprFact::illegalOpr);4089_mapping_to.append(to_interval);4090}409140924093void MoveResolver::add_mapping(LIR_Opr from_opr, Interval* to_interval) {4094TRACE_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()));4095assert(from_opr->is_constant(), "only for constants");40964097_mapping_from.append(NULL);4098_mapping_from_opr.append(from_opr);4099_mapping_to.append(to_interval);4100}41014102void MoveResolver::resolve_and_append_moves() {4103if (has_mappings()) {4104resolve_mappings();4105}4106append_insertion_buffer();4107}4108410941104111// **** Implementation of Range *************************************41124113Range::Range(int from, int to, Range* next) :4114_from(from),4115_to(to),4116_next(next)4117{4118}41194120// initialize sentinel4121Range* Range::_end = NULL;4122void Range::initialize(Arena* arena) {4123_end = new (arena) Range(max_jint, max_jint, NULL);4124}41254126int Range::intersects_at(Range* r2) const {4127const Range* r1 = this;41284129assert(r1 != NULL && r2 != NULL, "null ranges not allowed");4130assert(r1 != _end && r2 != _end, "empty ranges not allowed");41314132do {4133if (r1->from() < r2->from()) {4134if (r1->to() <= r2->from()) {4135r1 = r1->next(); if (r1 == _end) return -1;4136} else {4137return r2->from();4138}4139} else if (r2->from() < r1->from()) {4140if (r2->to() <= r1->from()) {4141r2 = r2->next(); if (r2 == _end) return -1;4142} else {4143return r1->from();4144}4145} else { // r1->from() == r2->from()4146if (r1->from() == r1->to()) {4147r1 = r1->next(); if (r1 == _end) return -1;4148} else if (r2->from() == r2->to()) {4149r2 = r2->next(); if (r2 == _end) return -1;4150} else {4151return r1->from();4152}4153}4154} while (true);4155}41564157#ifndef PRODUCT4158void Range::print(outputStream* out) const {4159out->print("[%d, %d[ ", _from, _to);4160}4161#endif4162416341644165// **** Implementation of Interval **********************************41664167// initialize sentinel4168Interval* Interval::_end = NULL;4169void Interval::initialize(Arena* arena) {4170Range::initialize(arena);4171_end = new (arena) Interval(-1);4172}41734174Interval::Interval(int reg_num) :4175_reg_num(reg_num),4176_type(T_ILLEGAL),4177_first(Range::end()),4178_use_pos_and_kinds(12),4179_current(Range::end()),4180_next(_end),4181_state(invalidState),4182_assigned_reg(LinearScan::any_reg),4183_assigned_regHi(LinearScan::any_reg),4184_cached_to(-1),4185_cached_opr(LIR_OprFact::illegalOpr),4186_cached_vm_reg(VMRegImpl::Bad()),4187_split_children(NULL),4188_canonical_spill_slot(-1),4189_insert_move_when_activated(false),4190_spill_state(noDefinitionFound),4191_spill_definition_pos(-1),4192_register_hint(NULL)4193{4194_split_parent = this;4195_current_split_child = this;4196}41974198int Interval::calc_to() {4199assert(_first != Range::end(), "interval has no range");42004201Range* r = _first;4202while (r->next() != Range::end()) {4203r = r->next();4204}4205return r->to();4206}420742084209#ifdef ASSERT4210// consistency check of split-children4211void Interval::check_split_children() {4212if (_split_children != NULL && _split_children->length() > 0) {4213assert(is_split_parent(), "only split parents can have children");42144215for (int i = 0; i < _split_children->length(); i++) {4216Interval* i1 = _split_children->at(i);42174218assert(i1->split_parent() == this, "not a split child of this interval");4219assert(i1->type() == type(), "must be equal for all split children");4220assert(i1->canonical_spill_slot() == canonical_spill_slot(), "must be equal for all split children");42214222for (int j = i + 1; j < _split_children->length(); j++) {4223Interval* i2 = _split_children->at(j);42244225assert(i1->reg_num() != i2->reg_num(), "same register number");42264227if (i1->from() < i2->from()) {4228assert(i1->to() <= i2->from() && i1->to() < i2->to(), "intervals overlapping");4229} else {4230assert(i2->from() < i1->from(), "intervals start at same op_id");4231assert(i2->to() <= i1->from() && i2->to() < i1->to(), "intervals overlapping");4232}4233}4234}4235}4236}4237#endif // ASSERT42384239Interval* Interval::register_hint(bool search_split_child) const {4240if (!search_split_child) {4241return _register_hint;4242}42434244if (_register_hint != NULL) {4245assert(_register_hint->is_split_parent(), "ony split parents are valid hint registers");42464247if (_register_hint->assigned_reg() >= 0 && _register_hint->assigned_reg() < LinearScan::nof_regs) {4248return _register_hint;42494250} else if (_register_hint->_split_children != NULL && _register_hint->_split_children->length() > 0) {4251// search the first split child that has a register assigned4252int len = _register_hint->_split_children->length();4253for (int i = 0; i < len; i++) {4254Interval* cur = _register_hint->_split_children->at(i);42554256if (cur->assigned_reg() >= 0 && cur->assigned_reg() < LinearScan::nof_regs) {4257return cur;4258}4259}4260}4261}42624263// no hint interval found that has a register assigned4264return NULL;4265}426642674268Interval* Interval::split_child_at_op_id(int op_id, LIR_OpVisitState::OprMode mode) {4269assert(is_split_parent(), "can only be called for split parents");4270assert(op_id >= 0, "invalid op_id (method can not be called for spill moves)");42714272Interval* result;4273if (_split_children == NULL || _split_children->length() == 0) {4274result = this;4275} else {4276result = NULL;4277int len = _split_children->length();42784279// in outputMode, the end of the interval (op_id == cur->to()) is not valid4280int to_offset = (mode == LIR_OpVisitState::outputMode ? 0 : 1);42814282int i;4283for (i = 0; i < len; i++) {4284Interval* cur = _split_children->at(i);4285if (cur->from() <= op_id && op_id < cur->to() + to_offset) {4286if (i > 0) {4287// exchange current split child to start of list (faster access for next call)4288_split_children->at_put(i, _split_children->at(0));4289_split_children->at_put(0, cur);4290}42914292// interval found4293result = cur;4294break;4295}4296}42974298#ifdef ASSERT4299for (i = 0; i < len; i++) {4300Interval* tmp = _split_children->at(i);4301if (tmp != result && tmp->from() <= op_id && op_id < tmp->to() + to_offset) {4302tty->print_cr("two valid result intervals found for op_id %d: %d and %d", op_id, result->reg_num(), tmp->reg_num());4303result->print();4304tmp->print();4305assert(false, "two valid result intervals found");4306}4307}4308#endif4309}43104311assert(result != NULL, "no matching interval found");4312assert(result->covers(op_id, mode), "op_id not covered by interval");43134314return result;4315}431643174318// returns the last split child that ends before the given op_id4319Interval* Interval::split_child_before_op_id(int op_id) {4320assert(op_id >= 0, "invalid op_id");43214322Interval* parent = split_parent();4323Interval* result = NULL;43244325assert(parent->_split_children != NULL, "no split children available");4326int len = parent->_split_children->length();4327assert(len > 0, "no split children available");43284329for (int i = len - 1; i >= 0; i--) {4330Interval* cur = parent->_split_children->at(i);4331if (cur->to() <= op_id && (result == NULL || result->to() < cur->to())) {4332result = cur;4333}4334}43354336assert(result != NULL, "no split child found");4337return result;4338}433943404341// Note: use positions are sorted descending -> first use has highest index4342int Interval::first_usage(IntervalUseKind min_use_kind) const {4343assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");43444345for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {4346if (_use_pos_and_kinds.at(i + 1) >= min_use_kind) {4347return _use_pos_and_kinds.at(i);4348}4349}4350return max_jint;4351}43524353int Interval::next_usage(IntervalUseKind min_use_kind, int from) const {4354assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");43554356for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {4357if (_use_pos_and_kinds.at(i) >= from && _use_pos_and_kinds.at(i + 1) >= min_use_kind) {4358return _use_pos_and_kinds.at(i);4359}4360}4361return max_jint;4362}43634364int Interval::next_usage_exact(IntervalUseKind exact_use_kind, int from) const {4365assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");43664367for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {4368if (_use_pos_and_kinds.at(i) >= from && _use_pos_and_kinds.at(i + 1) == exact_use_kind) {4369return _use_pos_and_kinds.at(i);4370}4371}4372return max_jint;4373}43744375int Interval::previous_usage(IntervalUseKind min_use_kind, int from) const {4376assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");43774378int prev = 0;4379for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {4380if (_use_pos_and_kinds.at(i) > from) {4381return prev;4382}4383if (_use_pos_and_kinds.at(i + 1) >= min_use_kind) {4384prev = _use_pos_and_kinds.at(i);4385}4386}4387return prev;4388}43894390void Interval::add_use_pos(int pos, IntervalUseKind use_kind) {4391assert(covers(pos, LIR_OpVisitState::inputMode), "use position not covered by live range");43924393// do not add use positions for precolored intervals because4394// they are never used4395if (use_kind != noUse && reg_num() >= LIR_OprDesc::vreg_base) {4396#ifdef ASSERT4397assert(_use_pos_and_kinds.length() % 2 == 0, "must be");4398for (int i = 0; i < _use_pos_and_kinds.length(); i += 2) {4399assert(pos <= _use_pos_and_kinds.at(i), "already added a use-position with lower position");4400assert(_use_pos_and_kinds.at(i + 1) >= firstValidKind && _use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");4401if (i > 0) {4402assert(_use_pos_and_kinds.at(i) < _use_pos_and_kinds.at(i - 2), "not sorted descending");4403}4404}4405#endif44064407// Note: add_use is called in descending order, so list gets sorted4408// automatically by just appending new use positions4409int len = _use_pos_and_kinds.length();4410if (len == 0 || _use_pos_and_kinds.at(len - 2) > pos) {4411_use_pos_and_kinds.append(pos);4412_use_pos_and_kinds.append(use_kind);4413} else if (_use_pos_and_kinds.at(len - 1) < use_kind) {4414assert(_use_pos_and_kinds.at(len - 2) == pos, "list not sorted correctly");4415_use_pos_and_kinds.at_put(len - 1, use_kind);4416}4417}4418}44194420void Interval::add_range(int from, int to) {4421assert(from < to, "invalid range");4422assert(first() == Range::end() || to < first()->next()->from(), "not inserting at begin of interval");4423assert(from <= first()->to(), "not inserting at begin of interval");44244425if (first()->from() <= to) {4426// join intersecting ranges4427first()->set_from(MIN2(from, first()->from()));4428first()->set_to (MAX2(to, first()->to()));4429} else {4430// insert new range4431_first = new Range(from, to, first());4432}4433}44344435Interval* Interval::new_split_child() {4436// allocate new interval4437Interval* result = new Interval(-1);4438result->set_type(type());44394440Interval* parent = split_parent();4441result->_split_parent = parent;4442result->set_register_hint(parent);44434444// insert new interval in children-list of parent4445if (parent->_split_children == NULL) {4446assert(is_split_parent(), "list must be initialized at first split");44474448parent->_split_children = new IntervalList(4);4449parent->_split_children->append(this);4450}4451parent->_split_children->append(result);44524453return result;4454}44554456// split this interval at the specified position and return4457// the remainder as a new interval.4458//4459// when an interval is split, a bi-directional link is established between the original interval4460// (the split parent) and the intervals that are split off this interval (the split children)4461// When a split child is split again, the new created interval is also a direct child4462// of the original parent (there is no tree of split children stored, but a flat list)4463// All split children are spilled to the same stack slot (stored in _canonical_spill_slot)4464//4465// Note: The new interval has no valid reg_num4466Interval* Interval::split(int split_pos) {4467assert(LinearScan::is_virtual_interval(this), "cannot split fixed intervals");44684469// allocate new interval4470Interval* result = new_split_child();44714472// split the ranges4473Range* prev = NULL;4474Range* cur = _first;4475while (cur != Range::end() && cur->to() <= split_pos) {4476prev = cur;4477cur = cur->next();4478}4479assert(cur != Range::end(), "split interval after end of last range");44804481if (cur->from() < split_pos) {4482result->_first = new Range(split_pos, cur->to(), cur->next());4483cur->set_to(split_pos);4484cur->set_next(Range::end());44854486} else {4487assert(prev != NULL, "split before start of first range");4488result->_first = cur;4489prev->set_next(Range::end());4490}4491result->_current = result->_first;4492_cached_to = -1; // clear cached value44934494// split list of use positions4495int total_len = _use_pos_and_kinds.length();4496int start_idx = total_len - 2;4497while (start_idx >= 0 && _use_pos_and_kinds.at(start_idx) < split_pos) {4498start_idx -= 2;4499}45004501intStack new_use_pos_and_kinds(total_len - start_idx);4502int i;4503for (i = start_idx + 2; i < total_len; i++) {4504new_use_pos_and_kinds.append(_use_pos_and_kinds.at(i));4505}45064507_use_pos_and_kinds.trunc_to(start_idx + 2);4508result->_use_pos_and_kinds = _use_pos_and_kinds;4509_use_pos_and_kinds = new_use_pos_and_kinds;45104511#ifdef ASSERT4512assert(_use_pos_and_kinds.length() % 2 == 0, "must have use kind for each use pos");4513assert(result->_use_pos_and_kinds.length() % 2 == 0, "must have use kind for each use pos");4514assert(_use_pos_and_kinds.length() + result->_use_pos_and_kinds.length() == total_len, "missed some entries");45154516for (i = 0; i < _use_pos_and_kinds.length(); i += 2) {4517assert(_use_pos_and_kinds.at(i) < split_pos, "must be");4518assert(_use_pos_and_kinds.at(i + 1) >= firstValidKind && _use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");4519}4520for (i = 0; i < result->_use_pos_and_kinds.length(); i += 2) {4521assert(result->_use_pos_and_kinds.at(i) >= split_pos, "must be");4522assert(result->_use_pos_and_kinds.at(i + 1) >= firstValidKind && result->_use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");4523}4524#endif45254526return result;4527}45284529// split this interval at the specified position and return4530// the head as a new interval (the original interval is the tail)4531//4532// Currently, only the first range can be split, and the new interval4533// must not have split positions4534Interval* Interval::split_from_start(int split_pos) {4535assert(LinearScan::is_virtual_interval(this), "cannot split fixed intervals");4536assert(split_pos > from() && split_pos < to(), "can only split inside interval");4537assert(split_pos > _first->from() && split_pos <= _first->to(), "can only split inside first range");4538assert(first_usage(noUse) > split_pos, "can not split when use positions are present");45394540// allocate new interval4541Interval* result = new_split_child();45424543// the new created interval has only one range (checked by assertion above),4544// so the splitting of the ranges is very simple4545result->add_range(_first->from(), split_pos);45464547if (split_pos == _first->to()) {4548assert(_first->next() != Range::end(), "must not be at end");4549_first = _first->next();4550} else {4551_first->set_from(split_pos);4552}45534554return result;4555}455645574558// returns true if the op_id is inside the interval4559bool Interval::covers(int op_id, LIR_OpVisitState::OprMode mode) const {4560Range* cur = _first;45614562while (cur != Range::end() && cur->to() < op_id) {4563cur = cur->next();4564}4565if (cur != Range::end()) {4566assert(cur->to() != cur->next()->from(), "ranges not separated");45674568if (mode == LIR_OpVisitState::outputMode) {4569return cur->from() <= op_id && op_id < cur->to();4570} else {4571return cur->from() <= op_id && op_id <= cur->to();4572}4573}4574return false;4575}45764577// returns true if the interval has any hole between hole_from and hole_to4578// (even if the hole has only the length 1)4579bool Interval::has_hole_between(int hole_from, int hole_to) {4580assert(hole_from < hole_to, "check");4581assert(from() <= hole_from && hole_to <= to(), "index out of interval");45824583Range* cur = _first;4584while (cur != Range::end()) {4585assert(cur->to() < cur->next()->from(), "no space between ranges");45864587// hole-range starts before this range -> hole4588if (hole_from < cur->from()) {4589return true;45904591// hole-range completely inside this range -> no hole4592} else if (hole_to <= cur->to()) {4593return false;45944595// overlapping of hole-range with this range -> hole4596} else if (hole_from <= cur->to()) {4597return true;4598}45994600cur = cur->next();4601}46024603return false;4604}46054606// Check if there is an intersection with any of the split children of 'interval'4607bool Interval::intersects_any_children_of(Interval* interval) const {4608if (interval->_split_children != NULL) {4609for (int i = 0; i < interval->_split_children->length(); i++) {4610if (intersects(interval->_split_children->at(i))) {4611return true;4612}4613}4614}4615return false;4616}461746184619#ifndef PRODUCT4620void Interval::print_on(outputStream* out, bool is_cfg_printer) const {4621const char* SpillState2Name[] = { "no definition", "no spill store", "one spill store", "store at definition", "start in memory", "no optimization" };4622const char* UseKind2Name[] = { "N", "L", "S", "M" };46234624const char* type_name;4625if (reg_num() < LIR_OprDesc::vreg_base) {4626type_name = "fixed";4627} else {4628type_name = type2name(type());4629}4630out->print("%d %s ", reg_num(), type_name);46314632if (is_cfg_printer) {4633// Special version for compatibility with C1 Visualizer.4634LIR_Opr opr = LinearScan::get_operand(reg_num());4635if (opr->is_valid()) {4636out->print("\"");4637opr->print(out);4638out->print("\" ");4639}4640} else {4641// Improved output for normal debugging.4642if (reg_num() < LIR_OprDesc::vreg_base) {4643LinearScan::print_reg_num(out, assigned_reg());4644} else if (assigned_reg() != -1 && (LinearScan::num_physical_regs(type()) == 1 || assigned_regHi() != -1)) {4645LinearScan::calc_operand_for_interval(this)->print(out);4646} else {4647// Virtual register that has no assigned register yet.4648out->print("[ANY]");4649}4650out->print(" ");4651}4652out->print("%d %d ", split_parent()->reg_num(), (register_hint(false) != NULL ? register_hint(false)->reg_num() : -1));46534654// print ranges4655Range* cur = _first;4656while (cur != Range::end()) {4657cur->print(out);4658cur = cur->next();4659assert(cur != NULL, "range list not closed with range sentinel");4660}46614662// print use positions4663int prev = 0;4664assert(_use_pos_and_kinds.length() % 2 == 0, "must be");4665for (int i =_use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {4666assert(_use_pos_and_kinds.at(i + 1) >= firstValidKind && _use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");4667assert(prev < _use_pos_and_kinds.at(i), "use positions not sorted");46684669out->print("%d %s ", _use_pos_and_kinds.at(i), UseKind2Name[_use_pos_and_kinds.at(i + 1)]);4670prev = _use_pos_and_kinds.at(i);4671}46724673out->print(" \"%s\"", SpillState2Name[spill_state()]);4674out->cr();4675}46764677void Interval::print_parent() const {4678if (_split_parent != this) {4679_split_parent->print_on(tty);4680} else {4681tty->print_cr("Parent: this");4682}4683}46844685void Interval::print_children() const {4686if (_split_children == NULL) {4687tty->print_cr("Children: []");4688} else {4689tty->print_cr("Children:");4690for (int i = 0; i < _split_children->length(); i++) {4691tty->print("%d: ", i);4692_split_children->at(i)->print_on(tty);4693}4694}4695}4696#endif // NOT PRODUCT46974698469947004701// **** Implementation of IntervalWalker ****************************47024703IntervalWalker::IntervalWalker(LinearScan* allocator, Interval* unhandled_fixed_first, Interval* unhandled_any_first)4704: _compilation(allocator->compilation())4705, _allocator(allocator)4706{4707_unhandled_first[fixedKind] = unhandled_fixed_first;4708_unhandled_first[anyKind] = unhandled_any_first;4709_active_first[fixedKind] = Interval::end();4710_inactive_first[fixedKind] = Interval::end();4711_active_first[anyKind] = Interval::end();4712_inactive_first[anyKind] = Interval::end();4713_current_position = -1;4714_current = NULL;4715next_interval();4716}471747184719// append interval in order of current range from()4720void IntervalWalker::append_sorted(Interval** list, Interval* interval) {4721Interval* prev = NULL;4722Interval* cur = *list;4723while (cur->current_from() < interval->current_from()) {4724prev = cur; cur = cur->next();4725}4726if (prev == NULL) {4727*list = interval;4728} else {4729prev->set_next(interval);4730}4731interval->set_next(cur);4732}47334734void IntervalWalker::append_to_unhandled(Interval** list, Interval* interval) {4735assert(interval->from() >= current()->current_from(), "cannot append new interval before current walk position");47364737Interval* prev = NULL;4738Interval* cur = *list;4739while (cur->from() < interval->from() || (cur->from() == interval->from() && cur->first_usage(noUse) < interval->first_usage(noUse))) {4740prev = cur; cur = cur->next();4741}4742if (prev == NULL) {4743*list = interval;4744} else {4745prev->set_next(interval);4746}4747interval->set_next(cur);4748}474947504751inline bool IntervalWalker::remove_from_list(Interval** list, Interval* i) {4752while (*list != Interval::end() && *list != i) {4753list = (*list)->next_addr();4754}4755if (*list != Interval::end()) {4756assert(*list == i, "check");4757*list = (*list)->next();4758return true;4759} else {4760return false;4761}4762}47634764void IntervalWalker::remove_from_list(Interval* i) {4765bool deleted;47664767if (i->state() == activeState) {4768deleted = remove_from_list(active_first_addr(anyKind), i);4769} else {4770assert(i->state() == inactiveState, "invalid state");4771deleted = remove_from_list(inactive_first_addr(anyKind), i);4772}47734774assert(deleted, "interval has not been found in list");4775}477647774778void IntervalWalker::walk_to(IntervalState state, int from) {4779assert (state == activeState || state == inactiveState, "wrong state");4780for_each_interval_kind(kind) {4781Interval** prev = state == activeState ? active_first_addr(kind) : inactive_first_addr(kind);4782Interval* next = *prev;4783while (next->current_from() <= from) {4784Interval* cur = next;4785next = cur->next();47864787bool range_has_changed = false;4788while (cur->current_to() <= from) {4789cur->next_range();4790range_has_changed = true;4791}47924793// also handle move from inactive list to active list4794range_has_changed = range_has_changed || (state == inactiveState && cur->current_from() <= from);47954796if (range_has_changed) {4797// remove cur from list4798*prev = next;4799if (cur->current_at_end()) {4800// move to handled state (not maintained as a list)4801cur->set_state(handledState);4802DEBUG_ONLY(interval_moved(cur, kind, state, handledState);)4803} else if (cur->current_from() <= from){4804// sort into active list4805append_sorted(active_first_addr(kind), cur);4806cur->set_state(activeState);4807if (*prev == cur) {4808assert(state == activeState, "check");4809prev = cur->next_addr();4810}4811DEBUG_ONLY(interval_moved(cur, kind, state, activeState);)4812} else {4813// sort into inactive list4814append_sorted(inactive_first_addr(kind), cur);4815cur->set_state(inactiveState);4816if (*prev == cur) {4817assert(state == inactiveState, "check");4818prev = cur->next_addr();4819}4820DEBUG_ONLY(interval_moved(cur, kind, state, inactiveState);)4821}4822} else {4823prev = cur->next_addr();4824continue;4825}4826}4827}4828}482948304831void IntervalWalker::next_interval() {4832IntervalKind kind;4833Interval* any = _unhandled_first[anyKind];4834Interval* fixed = _unhandled_first[fixedKind];48354836if (any != Interval::end()) {4837// intervals may start at same position -> prefer fixed interval4838kind = fixed != Interval::end() && fixed->from() <= any->from() ? fixedKind : anyKind;48394840assert (kind == fixedKind && fixed->from() <= any->from() ||4841kind == anyKind && any->from() <= fixed->from(), "wrong interval!!!");4842assert(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");48434844} else if (fixed != Interval::end()) {4845kind = fixedKind;4846} else {4847_current = NULL; return;4848}4849_current_kind = kind;4850_current = _unhandled_first[kind];4851_unhandled_first[kind] = _current->next();4852_current->set_next(Interval::end());4853_current->rewind_range();4854}485548564857void IntervalWalker::walk_to(int lir_op_id) {4858assert(_current_position <= lir_op_id, "can not walk backwards");4859while (current() != NULL) {4860bool is_active = current()->from() <= lir_op_id;4861int id = is_active ? current()->from() : lir_op_id;48624863TRACE_LINEAR_SCAN(2, if (_current_position < id) { tty->cr(); tty->print_cr("walk_to(%d) **************************************************************", id); })48644865// set _current_position prior to call of walk_to4866_current_position = id;48674868// call walk_to even if _current_position == id4869walk_to(activeState, id);4870walk_to(inactiveState, id);48714872if (is_active) {4873current()->set_state(activeState);4874if (activate_current()) {4875append_sorted(active_first_addr(current_kind()), current());4876DEBUG_ONLY(interval_moved(current(), current_kind(), unhandledState, activeState);)4877}48784879next_interval();4880} else {4881return;4882}4883}4884}48854886#ifdef ASSERT4887void IntervalWalker::interval_moved(Interval* interval, IntervalKind kind, IntervalState from, IntervalState to) {4888if (TraceLinearScanLevel >= 4) {4889#define print_state(state) \4890switch(state) {\4891case unhandledState: tty->print("unhandled"); break;\4892case activeState: tty->print("active"); break;\4893case inactiveState: tty->print("inactive"); break;\4894case handledState: tty->print("handled"); break;\4895default: ShouldNotReachHere(); \4896}48974898print_state(from); tty->print(" to "); print_state(to);4899tty->fill_to(23);4900interval->print();49014902#undef print_state4903}4904}4905#endif // ASSERT49064907// **** Implementation of LinearScanWalker **************************49084909LinearScanWalker::LinearScanWalker(LinearScan* allocator, Interval* unhandled_fixed_first, Interval* unhandled_any_first)4910: IntervalWalker(allocator, unhandled_fixed_first, unhandled_any_first)4911, _move_resolver(allocator)4912{4913for (int i = 0; i < LinearScan::nof_regs; i++) {4914_spill_intervals[i] = new IntervalList(2);4915}4916}491749184919inline void LinearScanWalker::init_use_lists(bool only_process_use_pos) {4920for (int i = _first_reg; i <= _last_reg; i++) {4921_use_pos[i] = max_jint;49224923if (!only_process_use_pos) {4924_block_pos[i] = max_jint;4925_spill_intervals[i]->clear();4926}4927}4928}49294930inline void LinearScanWalker::exclude_from_use(int reg) {4931assert(reg < LinearScan::nof_regs, "interval must have a register assigned (stack slots not allowed)");4932if (reg >= _first_reg && reg <= _last_reg) {4933_use_pos[reg] = 0;4934}4935}4936inline void LinearScanWalker::exclude_from_use(Interval* i) {4937assert(i->assigned_reg() != any_reg, "interval has no register assigned");49384939exclude_from_use(i->assigned_reg());4940exclude_from_use(i->assigned_regHi());4941}49424943inline void LinearScanWalker::set_use_pos(int reg, Interval* i, int use_pos, bool only_process_use_pos) {4944assert(use_pos != 0, "must use exclude_from_use to set use_pos to 0");49454946if (reg >= _first_reg && reg <= _last_reg) {4947if (_use_pos[reg] > use_pos) {4948_use_pos[reg] = use_pos;4949}4950if (!only_process_use_pos) {4951_spill_intervals[reg]->append(i);4952}4953}4954}4955inline void LinearScanWalker::set_use_pos(Interval* i, int use_pos, bool only_process_use_pos) {4956assert(i->assigned_reg() != any_reg, "interval has no register assigned");4957if (use_pos != -1) {4958set_use_pos(i->assigned_reg(), i, use_pos, only_process_use_pos);4959set_use_pos(i->assigned_regHi(), i, use_pos, only_process_use_pos);4960}4961}49624963inline void LinearScanWalker::set_block_pos(int reg, Interval* i, int block_pos) {4964if (reg >= _first_reg && reg <= _last_reg) {4965if (_block_pos[reg] > block_pos) {4966_block_pos[reg] = block_pos;4967}4968if (_use_pos[reg] > block_pos) {4969_use_pos[reg] = block_pos;4970}4971}4972}4973inline void LinearScanWalker::set_block_pos(Interval* i, int block_pos) {4974assert(i->assigned_reg() != any_reg, "interval has no register assigned");4975if (block_pos != -1) {4976set_block_pos(i->assigned_reg(), i, block_pos);4977set_block_pos(i->assigned_regHi(), i, block_pos);4978}4979}498049814982void LinearScanWalker::free_exclude_active_fixed() {4983Interval* list = active_first(fixedKind);4984while (list != Interval::end()) {4985assert(list->assigned_reg() < LinearScan::nof_regs, "active interval must have a register assigned");4986exclude_from_use(list);4987list = list->next();4988}4989}49904991void LinearScanWalker::free_exclude_active_any() {4992Interval* list = active_first(anyKind);4993while (list != Interval::end()) {4994exclude_from_use(list);4995list = list->next();4996}4997}49984999void LinearScanWalker::free_collect_inactive_fixed(Interval* cur) {5000Interval* list = inactive_first(fixedKind);5001while (list != Interval::end()) {5002if (cur->to() <= list->current_from()) {5003assert(list->current_intersects_at(cur) == -1, "must not intersect");5004set_use_pos(list, list->current_from(), true);5005} else {5006set_use_pos(list, list->current_intersects_at(cur), true);5007}5008list = list->next();5009}5010}50115012void LinearScanWalker::free_collect_inactive_any(Interval* cur) {5013Interval* list = inactive_first(anyKind);5014while (list != Interval::end()) {5015set_use_pos(list, list->current_intersects_at(cur), true);5016list = list->next();5017}5018}50195020void LinearScanWalker::spill_exclude_active_fixed() {5021Interval* list = active_first(fixedKind);5022while (list != Interval::end()) {5023exclude_from_use(list);5024list = list->next();5025}5026}50275028void LinearScanWalker::spill_block_inactive_fixed(Interval* cur) {5029Interval* list = inactive_first(fixedKind);5030while (list != Interval::end()) {5031if (cur->to() > list->current_from()) {5032set_block_pos(list, list->current_intersects_at(cur));5033} else {5034assert(list->current_intersects_at(cur) == -1, "invalid optimization: intervals intersect");5035}50365037list = list->next();5038}5039}50405041void LinearScanWalker::spill_collect_active_any() {5042Interval* list = active_first(anyKind);5043while (list != Interval::end()) {5044set_use_pos(list, MIN2(list->next_usage(loopEndMarker, _current_position), list->to()), false);5045list = list->next();5046}5047}50485049void LinearScanWalker::spill_collect_inactive_any(Interval* cur) {5050Interval* list = inactive_first(anyKind);5051while (list != Interval::end()) {5052if (list->current_intersects(cur)) {5053set_use_pos(list, MIN2(list->next_usage(loopEndMarker, _current_position), list->to()), false);5054}5055list = list->next();5056}5057}505850595060void LinearScanWalker::insert_move(int op_id, Interval* src_it, Interval* dst_it) {5061// output all moves here. When source and target are equal, the move is5062// optimized away later in assign_reg_nums50635064op_id = (op_id + 1) & ~1;5065BlockBegin* op_block = allocator()->block_of_op_with_id(op_id);5066assert(op_id > 0 && allocator()->block_of_op_with_id(op_id - 2) == op_block, "cannot insert move at block boundary");50675068// calculate index of instruction inside instruction list of current block5069// the minimal index (for a block with no spill moves) can be calculated because the5070// numbering of instructions is known.5071// When the block already contains spill moves, the index must be increased until the5072// correct index is reached.5073LIR_OpList* list = op_block->lir()->instructions_list();5074int index = (op_id - list->at(0)->id()) / 2;5075assert(list->at(index)->id() <= op_id, "error in calculation");50765077while (list->at(index)->id() != op_id) {5078index++;5079assert(0 <= index && index < list->length(), "index out of bounds");5080}5081assert(1 <= index && index < list->length(), "index out of bounds");5082assert(list->at(index)->id() == op_id, "error in calculation");50835084// insert new instruction before instruction at position index5085_move_resolver.move_insert_position(op_block->lir(), index - 1);5086_move_resolver.add_mapping(src_it, dst_it);5087}508850895090int LinearScanWalker::find_optimal_split_pos(BlockBegin* min_block, BlockBegin* max_block, int max_split_pos) {5091int from_block_nr = min_block->linear_scan_number();5092int to_block_nr = max_block->linear_scan_number();50935094assert(0 <= from_block_nr && from_block_nr < block_count(), "out of range");5095assert(0 <= to_block_nr && to_block_nr < block_count(), "out of range");5096assert(from_block_nr < to_block_nr, "must cross block boundary");50975098// Try to split at end of max_block. If this would be after5099// max_split_pos, then use the begin of max_block5100int optimal_split_pos = max_block->last_lir_instruction_id() + 2;5101if (optimal_split_pos > max_split_pos) {5102optimal_split_pos = max_block->first_lir_instruction_id();5103}51045105int min_loop_depth = max_block->loop_depth();5106for (int i = to_block_nr - 1; i >= from_block_nr; i--) {5107BlockBegin* cur = block_at(i);51085109if (cur->loop_depth() < min_loop_depth) {5110// block with lower loop-depth found -> split at the end of this block5111min_loop_depth = cur->loop_depth();5112optimal_split_pos = cur->last_lir_instruction_id() + 2;5113}5114}5115assert(optimal_split_pos > allocator()->max_lir_op_id() || allocator()->is_block_begin(optimal_split_pos), "algorithm must move split pos to block boundary");51165117return optimal_split_pos;5118}511951205121int LinearScanWalker::find_optimal_split_pos(Interval* it, int min_split_pos, int max_split_pos, bool do_loop_optimization) {5122int optimal_split_pos = -1;5123if (min_split_pos == max_split_pos) {5124// trivial case, no optimization of split position possible5125TRACE_LINEAR_SCAN(4, tty->print_cr(" min-pos and max-pos are equal, no optimization possible"));5126optimal_split_pos = min_split_pos;51275128} else {5129assert(min_split_pos < max_split_pos, "must be true then");5130assert(min_split_pos > 0, "cannot access min_split_pos - 1 otherwise");51315132// reason for using min_split_pos - 1: when the minimal split pos is exactly at the5133// beginning of a block, then min_split_pos is also a possible split position.5134// Use the block before as min_block, because then min_block->last_lir_instruction_id() + 2 == min_split_pos5135BlockBegin* min_block = allocator()->block_of_op_with_id(min_split_pos - 1);51365137// reason for using max_split_pos - 1: otherwise there would be an assertion failure5138// when an interval ends at the end of the last block of the method5139// (in this case, max_split_pos == allocator()->max_lir_op_id() + 2, and there is no5140// block at this op_id)5141BlockBegin* max_block = allocator()->block_of_op_with_id(max_split_pos - 1);51425143assert(min_block->linear_scan_number() <= max_block->linear_scan_number(), "invalid order");5144if (min_block == max_block) {5145// split position cannot be moved to block boundary, so split as late as possible5146TRACE_LINEAR_SCAN(4, tty->print_cr(" cannot move split pos to block boundary because min_pos and max_pos are in same block"));5147optimal_split_pos = max_split_pos;51485149} else if (it->has_hole_between(max_split_pos - 1, max_split_pos) && !allocator()->is_block_begin(max_split_pos)) {5150// Do not move split position if the interval has a hole before max_split_pos.5151// Intervals resulting from Phi-Functions have more than one definition (marked5152// as mustHaveRegister) with a hole before each definition. When the register is needed5153// for the second definition, an earlier reloading is unnecessary.5154TRACE_LINEAR_SCAN(4, tty->print_cr(" interval has hole just before max_split_pos, so splitting at max_split_pos"));5155optimal_split_pos = max_split_pos;51565157} else {5158// seach optimal block boundary between min_split_pos and max_split_pos5159TRACE_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()));51605161if (do_loop_optimization) {5162// Loop optimization: if a loop-end marker is found between min- and max-position,5163// then split before this loop5164int loop_end_pos = it->next_usage_exact(loopEndMarker, min_block->last_lir_instruction_id() + 2);5165TRACE_LINEAR_SCAN(4, tty->print_cr(" loop optimization: loop end found at pos %d", loop_end_pos));51665167assert(loop_end_pos > min_split_pos, "invalid order");5168if (loop_end_pos < max_split_pos) {5169// loop-end marker found between min- and max-position5170// if it is not the end marker for the same loop as the min-position, then move5171// the max-position to this loop block.5172// Desired result: uses tagged as shouldHaveRegister inside a loop cause a reloading5173// of the interval (normally, only mustHaveRegister causes a reloading)5174BlockBegin* loop_block = allocator()->block_of_op_with_id(loop_end_pos);51755176TRACE_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()));5177assert(loop_block != min_block, "loop_block and min_block must be different because block boundary is needed between");51785179optimal_split_pos = find_optimal_split_pos(min_block, loop_block, loop_block->last_lir_instruction_id() + 2);5180if (optimal_split_pos == loop_block->last_lir_instruction_id() + 2) {5181optimal_split_pos = -1;5182TRACE_LINEAR_SCAN(4, tty->print_cr(" loop optimization not necessary"));5183} else {5184TRACE_LINEAR_SCAN(4, tty->print_cr(" loop optimization successful"));5185}5186}5187}51885189if (optimal_split_pos == -1) {5190// not calculated by loop optimization5191optimal_split_pos = find_optimal_split_pos(min_block, max_block, max_split_pos);5192}5193}5194}5195TRACE_LINEAR_SCAN(4, tty->print_cr(" optimal split position: %d", optimal_split_pos));51965197return optimal_split_pos;5198}519952005201/*5202split an interval at the optimal position between min_split_pos and5203max_split_pos in two parts:52041) the left part has already a location assigned52052) the right part is sorted into to the unhandled-list5206*/5207void LinearScanWalker::split_before_usage(Interval* it, int min_split_pos, int max_split_pos) {5208TRACE_LINEAR_SCAN(2, tty->print ("----- splitting interval: "); it->print());5209TRACE_LINEAR_SCAN(2, tty->print_cr(" between %d and %d", min_split_pos, max_split_pos));52105211assert(it->from() < min_split_pos, "cannot split at start of interval");5212assert(current_position() < min_split_pos, "cannot split before current position");5213assert(min_split_pos <= max_split_pos, "invalid order");5214assert(max_split_pos <= it->to(), "cannot split after end of interval");52155216int optimal_split_pos = find_optimal_split_pos(it, min_split_pos, max_split_pos, true);52175218assert(min_split_pos <= optimal_split_pos && optimal_split_pos <= max_split_pos, "out of range");5219assert(optimal_split_pos <= it->to(), "cannot split after end of interval");5220assert(optimal_split_pos > it->from(), "cannot split at start of interval");52215222if (optimal_split_pos == it->to() && it->next_usage(mustHaveRegister, min_split_pos) == max_jint) {5223// the split position would be just before the end of the interval5224// -> no split at all necessary5225TRACE_LINEAR_SCAN(4, tty->print_cr(" no split necessary because optimal split position is at end of interval"));5226return;5227}52285229// must calculate this before the actual split is performed and before split position is moved to odd op_id5230bool move_necessary = !allocator()->is_block_begin(optimal_split_pos) && !it->has_hole_between(optimal_split_pos - 1, optimal_split_pos);52315232if (!allocator()->is_block_begin(optimal_split_pos)) {5233// move position before actual instruction (odd op_id)5234optimal_split_pos = (optimal_split_pos - 1) | 1;5235}52365237TRACE_LINEAR_SCAN(4, tty->print_cr(" splitting at position %d", optimal_split_pos));5238assert(allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 1), "split pos must be odd when not on block boundary");5239assert(!allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 0), "split pos must be even on block boundary");52405241Interval* split_part = it->split(optimal_split_pos);52425243allocator()->append_interval(split_part);5244allocator()->copy_register_flags(it, split_part);5245split_part->set_insert_move_when_activated(move_necessary);5246append_to_unhandled(unhandled_first_addr(anyKind), split_part);52475248TRACE_LINEAR_SCAN(2, tty->print_cr(" split interval in two parts (insert_move_when_activated: %d)", move_necessary));5249TRACE_LINEAR_SCAN(2, tty->print (" "); it->print());5250TRACE_LINEAR_SCAN(2, tty->print (" "); split_part->print());5251}52525253/*5254split an interval at the optimal position between min_split_pos and5255max_split_pos in two parts:52561) the left part has already a location assigned52572) the right part is always on the stack and therefore ignored in further processing5258*/5259void LinearScanWalker::split_for_spilling(Interval* it) {5260// calculate allowed range of splitting position5261int max_split_pos = current_position();5262int min_split_pos = MAX2(it->previous_usage(shouldHaveRegister, max_split_pos) + 1, it->from());52635264TRACE_LINEAR_SCAN(2, tty->print ("----- splitting and spilling interval: "); it->print());5265TRACE_LINEAR_SCAN(2, tty->print_cr(" between %d and %d", min_split_pos, max_split_pos));52665267assert(it->state() == activeState, "why spill interval that is not active?");5268assert(it->from() <= min_split_pos, "cannot split before start of interval");5269assert(min_split_pos <= max_split_pos, "invalid order");5270assert(max_split_pos < it->to(), "cannot split at end end of interval");5271assert(current_position() < it->to(), "interval must not end before current position");52725273if (min_split_pos == it->from()) {5274// the whole interval is never used, so spill it entirely to memory5275TRACE_LINEAR_SCAN(2, tty->print_cr(" spilling entire interval because split pos is at beginning of interval"));5276assert(it->first_usage(shouldHaveRegister) > current_position(), "interval must not have use position before current_position");52775278allocator()->assign_spill_slot(it);5279allocator()->change_spill_state(it, min_split_pos);52805281// Also kick parent intervals out of register to memory when they have no use5282// position. This avoids short interval in register surrounded by intervals in5283// memory -> avoid useless moves from memory to register and back5284Interval* parent = it;5285while (parent != NULL && parent->is_split_child()) {5286parent = parent->split_child_before_op_id(parent->from());52875288if (parent->assigned_reg() < LinearScan::nof_regs) {5289if (parent->first_usage(shouldHaveRegister) == max_jint) {5290// parent is never used, so kick it out of its assigned register5291TRACE_LINEAR_SCAN(4, tty->print_cr(" kicking out interval %d out of its register because it is never used", parent->reg_num()));5292allocator()->assign_spill_slot(parent);5293} else {5294// do not go further back because the register is actually used by the interval5295parent = NULL;5296}5297}5298}52995300} else {5301// search optimal split pos, split interval and spill only the right hand part5302int optimal_split_pos = find_optimal_split_pos(it, min_split_pos, max_split_pos, false);53035304assert(min_split_pos <= optimal_split_pos && optimal_split_pos <= max_split_pos, "out of range");5305assert(optimal_split_pos < it->to(), "cannot split at end of interval");5306assert(optimal_split_pos >= it->from(), "cannot split before start of interval");53075308if (!allocator()->is_block_begin(optimal_split_pos)) {5309// move position before actual instruction (odd op_id)5310optimal_split_pos = (optimal_split_pos - 1) | 1;5311}53125313TRACE_LINEAR_SCAN(4, tty->print_cr(" splitting at position %d", optimal_split_pos));5314assert(allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 1), "split pos must be odd when not on block boundary");5315assert(!allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 0), "split pos must be even on block boundary");53165317Interval* spilled_part = it->split(optimal_split_pos);5318allocator()->append_interval(spilled_part);5319allocator()->assign_spill_slot(spilled_part);5320allocator()->change_spill_state(spilled_part, optimal_split_pos);53215322if (!allocator()->is_block_begin(optimal_split_pos)) {5323TRACE_LINEAR_SCAN(4, tty->print_cr(" inserting move from interval %d to %d", it->reg_num(), spilled_part->reg_num()));5324insert_move(optimal_split_pos, it, spilled_part);5325}53265327// the current_split_child is needed later when moves are inserted for reloading5328assert(spilled_part->current_split_child() == it, "overwriting wrong current_split_child");5329spilled_part->make_current_split_child();53305331TRACE_LINEAR_SCAN(2, tty->print_cr(" split interval in two parts"));5332TRACE_LINEAR_SCAN(2, tty->print (" "); it->print());5333TRACE_LINEAR_SCAN(2, tty->print (" "); spilled_part->print());5334}5335}533653375338void LinearScanWalker::split_stack_interval(Interval* it) {5339int min_split_pos = current_position() + 1;5340int max_split_pos = MIN2(it->first_usage(shouldHaveRegister), it->to());53415342split_before_usage(it, min_split_pos, max_split_pos);5343}53445345void LinearScanWalker::split_when_partial_register_available(Interval* it, int register_available_until) {5346int min_split_pos = MAX2(it->previous_usage(shouldHaveRegister, register_available_until), it->from() + 1);5347int max_split_pos = register_available_until;53485349split_before_usage(it, min_split_pos, max_split_pos);5350}53515352void LinearScanWalker::split_and_spill_interval(Interval* it) {5353assert(it->state() == activeState || it->state() == inactiveState, "other states not allowed");53545355int current_pos = current_position();5356if (it->state() == inactiveState) {5357// the interval is currently inactive, so no spill slot is needed for now.5358// when the split part is activated, the interval has a new chance to get a register,5359// so in the best case no stack slot is necessary5360assert(it->has_hole_between(current_pos - 1, current_pos + 1), "interval can not be inactive otherwise");5361split_before_usage(it, current_pos + 1, current_pos + 1);53625363} else {5364// search the position where the interval must have a register and split5365// at the optimal position before.5366// The new created part is added to the unhandled list and will get a register5367// when it is activated5368int min_split_pos = current_pos + 1;5369int max_split_pos = MIN2(it->next_usage(mustHaveRegister, min_split_pos), it->to());53705371split_before_usage(it, min_split_pos, max_split_pos);53725373assert(it->next_usage(mustHaveRegister, current_pos) == max_jint, "the remaining part is spilled to stack and therefore has no register");5374split_for_spilling(it);5375}5376}53775378int LinearScanWalker::find_free_reg(int reg_needed_until, int interval_to, int hint_reg, int ignore_reg, bool* need_split) {5379int min_full_reg = any_reg;5380int max_partial_reg = any_reg;53815382for (int i = _first_reg; i <= _last_reg; i++) {5383if (i == ignore_reg) {5384// this register must be ignored53855386} else if (_use_pos[i] >= interval_to) {5387// this register is free for the full interval5388if (min_full_reg == any_reg || i == hint_reg || (_use_pos[i] < _use_pos[min_full_reg] && min_full_reg != hint_reg)) {5389min_full_reg = i;5390}5391} else if (_use_pos[i] > reg_needed_until) {5392// this register is at least free until reg_needed_until5393if (max_partial_reg == any_reg || i == hint_reg || (_use_pos[i] > _use_pos[max_partial_reg] && max_partial_reg != hint_reg)) {5394max_partial_reg = i;5395}5396}5397}53985399if (min_full_reg != any_reg) {5400return min_full_reg;5401} else if (max_partial_reg != any_reg) {5402*need_split = true;5403return max_partial_reg;5404} else {5405return any_reg;5406}5407}54085409int LinearScanWalker::find_free_double_reg(int reg_needed_until, int interval_to, int hint_reg, bool* need_split) {5410assert((_last_reg - _first_reg + 1) % 2 == 0, "adjust algorithm");54115412int min_full_reg = any_reg;5413int max_partial_reg = any_reg;54145415for (int i = _first_reg; i < _last_reg; i+=2) {5416if (_use_pos[i] >= interval_to && _use_pos[i + 1] >= interval_to) {5417// this register is free for the full interval5418if (min_full_reg == any_reg || i == hint_reg || (_use_pos[i] < _use_pos[min_full_reg] && min_full_reg != hint_reg)) {5419min_full_reg = i;5420}5421} else if (_use_pos[i] > reg_needed_until && _use_pos[i + 1] > reg_needed_until) {5422// this register is at least free until reg_needed_until5423if (max_partial_reg == any_reg || i == hint_reg || (_use_pos[i] > _use_pos[max_partial_reg] && max_partial_reg != hint_reg)) {5424max_partial_reg = i;5425}5426}5427}54285429if (min_full_reg != any_reg) {5430return min_full_reg;5431} else if (max_partial_reg != any_reg) {5432*need_split = true;5433return max_partial_reg;5434} else {5435return any_reg;5436}5437}54385439bool LinearScanWalker::alloc_free_reg(Interval* cur) {5440TRACE_LINEAR_SCAN(2, tty->print("trying to find free register for "); cur->print());54415442init_use_lists(true);5443free_exclude_active_fixed();5444free_exclude_active_any();5445free_collect_inactive_fixed(cur);5446free_collect_inactive_any(cur);5447assert(unhandled_first(fixedKind) == Interval::end(), "must not have unhandled fixed intervals because all fixed intervals have a use at position 0");54485449// _use_pos contains the start of the next interval that has this register assigned5450// (either as a fixed register or a normal allocated register in the past)5451// only intervals overlapping with cur are processed, non-overlapping invervals can be ignored safely5452#ifdef ASSERT5453if (TraceLinearScanLevel >= 4) {5454tty->print_cr(" state of registers:");5455for (int i = _first_reg; i <= _last_reg; i++) {5456tty->print(" reg %d (", i);5457LinearScan::print_reg_num(i);5458tty->print_cr("): use_pos: %d", _use_pos[i]);5459}5460}5461#endif54625463int hint_reg, hint_regHi;5464Interval* register_hint = cur->register_hint();5465if (register_hint != NULL) {5466hint_reg = register_hint->assigned_reg();5467hint_regHi = register_hint->assigned_regHi();54685469if (_num_phys_regs == 2 && allocator()->is_precolored_cpu_interval(register_hint)) {5470assert(hint_reg != any_reg && hint_regHi == any_reg, "must be for fixed intervals");5471hint_regHi = hint_reg + 1; // connect e.g. eax-edx5472}5473#ifdef ASSERT5474if (TraceLinearScanLevel >= 4) {5475tty->print(" hint registers %d (", hint_reg);5476LinearScan::print_reg_num(hint_reg);5477tty->print("), %d (", hint_regHi);5478LinearScan::print_reg_num(hint_regHi);5479tty->print(") from interval ");5480register_hint->print();5481}5482#endif5483} else {5484hint_reg = any_reg;5485hint_regHi = any_reg;5486}5487assert(hint_reg == any_reg || hint_reg != hint_regHi, "hint reg and regHi equal");5488assert(cur->assigned_reg() == any_reg && cur->assigned_regHi() == any_reg, "register already assigned to interval");54895490// the register must be free at least until this position5491int reg_needed_until = cur->from() + 1;5492int interval_to = cur->to();54935494bool need_split = false;5495int split_pos;5496int reg;5497int regHi = any_reg;54985499if (_adjacent_regs) {5500reg = find_free_double_reg(reg_needed_until, interval_to, hint_reg, &need_split);5501regHi = reg + 1;5502if (reg == any_reg) {5503return false;5504}5505split_pos = MIN2(_use_pos[reg], _use_pos[regHi]);55065507} else {5508reg = find_free_reg(reg_needed_until, interval_to, hint_reg, any_reg, &need_split);5509if (reg == any_reg) {5510return false;5511}5512split_pos = _use_pos[reg];55135514if (_num_phys_regs == 2) {5515regHi = find_free_reg(reg_needed_until, interval_to, hint_regHi, reg, &need_split);55165517if (_use_pos[reg] < interval_to && regHi == any_reg) {5518// do not split interval if only one register can be assigned until the split pos5519// (when one register is found for the whole interval, split&spill is only5520// performed for the hi register)5521return false;55225523} else if (regHi != any_reg) {5524split_pos = MIN2(split_pos, _use_pos[regHi]);55255526// sort register numbers to prevent e.g. a move from eax,ebx to ebx,eax5527if (reg > regHi) {5528int temp = reg;5529reg = regHi;5530regHi = temp;5531}5532}5533}5534}55355536cur->assign_reg(reg, regHi);5537#ifdef ASSERT5538if (TraceLinearScanLevel >= 2) {5539tty->print(" selected registers %d (", reg);5540LinearScan::print_reg_num(reg);5541tty->print("), %d (", regHi);5542LinearScan::print_reg_num(regHi);5543tty->print_cr(")");5544}5545#endif5546assert(split_pos > 0, "invalid split_pos");5547if (need_split) {5548// register not available for full interval, so split it5549split_when_partial_register_available(cur, split_pos);5550}55515552// only return true if interval is completely assigned5553return _num_phys_regs == 1 || regHi != any_reg;5554}555555565557int LinearScanWalker::find_locked_reg(int reg_needed_until, int interval_to, int ignore_reg, bool* need_split) {5558int max_reg = any_reg;55595560for (int i = _first_reg; i <= _last_reg; i++) {5561if (i == ignore_reg) {5562// this register must be ignored55635564} else if (_use_pos[i] > reg_needed_until) {5565if (max_reg == any_reg || _use_pos[i] > _use_pos[max_reg]) {5566max_reg = i;5567}5568}5569}55705571if (max_reg != any_reg && _block_pos[max_reg] <= interval_to) {5572*need_split = true;5573}55745575return max_reg;5576}55775578int LinearScanWalker::find_locked_double_reg(int reg_needed_until, int interval_to, bool* need_split) {5579assert((_last_reg - _first_reg + 1) % 2 == 0, "adjust algorithm");55805581int max_reg = any_reg;55825583for (int i = _first_reg; i < _last_reg; i+=2) {5584if (_use_pos[i] > reg_needed_until && _use_pos[i + 1] > reg_needed_until) {5585if (max_reg == any_reg || _use_pos[i] > _use_pos[max_reg]) {5586max_reg = i;5587}5588}5589}55905591if (max_reg != any_reg &&5592(_block_pos[max_reg] <= interval_to || _block_pos[max_reg + 1] <= interval_to)) {5593*need_split = true;5594}55955596return max_reg;5597}55985599void LinearScanWalker::split_and_spill_intersecting_intervals(int reg, int regHi) {5600assert(reg != any_reg, "no register assigned");56015602for (int i = 0; i < _spill_intervals[reg]->length(); i++) {5603Interval* it = _spill_intervals[reg]->at(i);5604remove_from_list(it);5605split_and_spill_interval(it);5606}56075608if (regHi != any_reg) {5609IntervalList* processed = _spill_intervals[reg];5610for (int i = 0; i < _spill_intervals[regHi]->length(); i++) {5611Interval* it = _spill_intervals[regHi]->at(i);5612if (processed->find(it) == -1) {5613remove_from_list(it);5614split_and_spill_interval(it);5615}5616}5617}5618}561956205621// Split an Interval and spill it to memory so that cur can be placed in a register5622void LinearScanWalker::alloc_locked_reg(Interval* cur) {5623TRACE_LINEAR_SCAN(2, tty->print("need to split and spill to get register for "); cur->print());56245625// collect current usage of registers5626init_use_lists(false);5627spill_exclude_active_fixed();5628assert(unhandled_first(fixedKind) == Interval::end(), "must not have unhandled fixed intervals because all fixed intervals have a use at position 0");5629spill_block_inactive_fixed(cur);5630spill_collect_active_any();5631spill_collect_inactive_any(cur);56325633#ifdef ASSERT5634if (TraceLinearScanLevel >= 4) {5635tty->print_cr(" state of registers:");5636for (int i = _first_reg; i <= _last_reg; i++) {5637tty->print(" reg %d(", i);5638LinearScan::print_reg_num(i);5639tty->print("): use_pos: %d, block_pos: %d, intervals: ", _use_pos[i], _block_pos[i]);5640for (int j = 0; j < _spill_intervals[i]->length(); j++) {5641tty->print("%d ", _spill_intervals[i]->at(j)->reg_num());5642}5643tty->cr();5644}5645}5646#endif56475648// the register must be free at least until this position5649int reg_needed_until = MIN2(cur->first_usage(mustHaveRegister), cur->from() + 1);5650int interval_to = cur->to();5651assert (reg_needed_until > 0 && reg_needed_until < max_jint, "interval has no use");56525653int split_pos = 0;5654int use_pos = 0;5655bool need_split = false;5656int reg, regHi;56575658if (_adjacent_regs) {5659reg = find_locked_double_reg(reg_needed_until, interval_to, &need_split);5660regHi = reg + 1;56615662if (reg != any_reg) {5663use_pos = MIN2(_use_pos[reg], _use_pos[regHi]);5664split_pos = MIN2(_block_pos[reg], _block_pos[regHi]);5665}5666} else {5667reg = find_locked_reg(reg_needed_until, interval_to, cur->assigned_reg(), &need_split);5668regHi = any_reg;56695670if (reg != any_reg) {5671use_pos = _use_pos[reg];5672split_pos = _block_pos[reg];56735674if (_num_phys_regs == 2) {5675if (cur->assigned_reg() != any_reg) {5676regHi = reg;5677reg = cur->assigned_reg();5678} else {5679regHi = find_locked_reg(reg_needed_until, interval_to, reg, &need_split);5680if (regHi != any_reg) {5681use_pos = MIN2(use_pos, _use_pos[regHi]);5682split_pos = MIN2(split_pos, _block_pos[regHi]);5683}5684}56855686if (regHi != any_reg && reg > regHi) {5687// sort register numbers to prevent e.g. a move from eax,ebx to ebx,eax5688int temp = reg;5689reg = regHi;5690regHi = temp;5691}5692}5693}5694}56955696if (reg == any_reg || (_num_phys_regs == 2 && regHi == any_reg) || use_pos <= cur->first_usage(mustHaveRegister)) {5697// the first use of cur is later than the spilling position -> spill cur5698TRACE_LINEAR_SCAN(4, tty->print_cr("able to spill current interval. first_usage(register): %d, use_pos: %d", cur->first_usage(mustHaveRegister), use_pos));56995700if (cur->first_usage(mustHaveRegister) <= cur->from() + 1) {5701assert(false, "cannot spill interval that is used in first instruction (possible reason: no register found)");5702// assign a reasonable register and do a bailout in product mode to avoid errors5703allocator()->assign_spill_slot(cur);5704BAILOUT("LinearScan: no register found");5705}57065707split_and_spill_interval(cur);5708} else {5709#ifdef ASSERT5710if (TraceLinearScanLevel >= 4) {5711tty->print("decided to use register %d (", reg);5712LinearScan::print_reg_num(reg);5713tty->print("), %d (", regHi);5714LinearScan::print_reg_num(regHi);5715tty->print_cr(")");5716}5717#endif5718assert(reg != any_reg && (_num_phys_regs == 1 || regHi != any_reg), "no register found");5719assert(split_pos > 0, "invalid split_pos");5720assert(need_split == false || split_pos > cur->from(), "splitting interval at from");57215722cur->assign_reg(reg, regHi);5723if (need_split) {5724// register not available for full interval, so split it5725split_when_partial_register_available(cur, split_pos);5726}57275728// perform splitting and spilling for all affected intervalls5729split_and_spill_intersecting_intervals(reg, regHi);5730}5731}57325733bool LinearScanWalker::no_allocation_possible(Interval* cur) {5734#ifdef X865735// fast calculation of intervals that can never get a register because the5736// the next instruction is a call that blocks all registers5737// Note: this does not work if callee-saved registers are available (e.g. on Sparc)57385739// check if this interval is the result of a split operation5740// (an interval got a register until this position)5741int pos = cur->from();5742if ((pos & 1) == 1) {5743// the current instruction is a call that blocks all registers5744if (pos < allocator()->max_lir_op_id() && allocator()->has_call(pos + 1)) {5745TRACE_LINEAR_SCAN(4, tty->print_cr(" free register cannot be available because all registers blocked by following call"));57465747// safety check that there is really no register available5748assert(alloc_free_reg(cur) == false, "found a register for this interval");5749return true;5750}57515752}5753#endif5754return false;5755}57565757void LinearScanWalker::init_vars_for_alloc(Interval* cur) {5758BasicType type = cur->type();5759_num_phys_regs = LinearScan::num_physical_regs(type);5760_adjacent_regs = LinearScan::requires_adjacent_regs(type);57615762if (pd_init_regs_for_alloc(cur)) {5763// the appropriate register range was selected.5764} else if (type == T_FLOAT || type == T_DOUBLE) {5765_first_reg = pd_first_fpu_reg;5766_last_reg = pd_last_fpu_reg;5767} else {5768_first_reg = pd_first_cpu_reg;5769_last_reg = FrameMap::last_cpu_reg();5770}57715772assert(0 <= _first_reg && _first_reg < LinearScan::nof_regs, "out of range");5773assert(0 <= _last_reg && _last_reg < LinearScan::nof_regs, "out of range");5774}577557765777bool LinearScanWalker::is_move(LIR_Op* op, Interval* from, Interval* to) {5778if (op->code() != lir_move) {5779return false;5780}5781assert(op->as_Op1() != NULL, "move must be LIR_Op1");57825783LIR_Opr in = ((LIR_Op1*)op)->in_opr();5784LIR_Opr res = ((LIR_Op1*)op)->result_opr();5785return in->is_virtual() && res->is_virtual() && in->vreg_number() == from->reg_num() && res->vreg_number() == to->reg_num();5786}57875788// optimization (especially for phi functions of nested loops):5789// assign same spill slot to non-intersecting intervals5790void LinearScanWalker::combine_spilled_intervals(Interval* cur) {5791if (cur->is_split_child()) {5792// optimization is only suitable for split parents5793return;5794}57955796Interval* register_hint = cur->register_hint(false);5797if (register_hint == NULL) {5798// cur is not the target of a move, otherwise register_hint would be set5799return;5800}5801assert(register_hint->is_split_parent(), "register hint must be split parent");58025803if (cur->spill_state() != noOptimization || register_hint->spill_state() != noOptimization) {5804// combining the stack slots for intervals where spill move optimization is applied5805// is not benefitial and would cause problems5806return;5807}58085809int begin_pos = cur->from();5810int end_pos = cur->to();5811if (end_pos > allocator()->max_lir_op_id() || (begin_pos & 1) != 0 || (end_pos & 1) != 0) {5812// safety check that lir_op_with_id is allowed5813return;5814}58155816if (!is_move(allocator()->lir_op_with_id(begin_pos), register_hint, cur) || !is_move(allocator()->lir_op_with_id(end_pos), cur, register_hint)) {5817// cur and register_hint are not connected with two moves5818return;5819}58205821Interval* begin_hint = register_hint->split_child_at_op_id(begin_pos, LIR_OpVisitState::inputMode);5822Interval* end_hint = register_hint->split_child_at_op_id(end_pos, LIR_OpVisitState::outputMode);5823if (begin_hint == end_hint || begin_hint->to() != begin_pos || end_hint->from() != end_pos) {5824// register_hint must be split, otherwise the re-writing of use positions does not work5825return;5826}58275828assert(begin_hint->assigned_reg() != any_reg, "must have register assigned");5829assert(end_hint->assigned_reg() == any_reg, "must not have register assigned");5830assert(cur->first_usage(mustHaveRegister) == begin_pos, "must have use position at begin of interval because of move");5831assert(end_hint->first_usage(mustHaveRegister) == end_pos, "must have use position at begin of interval because of move");58325833if (begin_hint->assigned_reg() < LinearScan::nof_regs) {5834// register_hint is not spilled at begin_pos, so it would not be benefitial to immediately spill cur5835return;5836}5837assert(register_hint->canonical_spill_slot() != -1, "must be set when part of interval was spilled");5838assert(!cur->intersects(register_hint), "cur should not intersect register_hint");58395840if (cur->intersects_any_children_of(register_hint)) {5841// Bail out if cur intersects any split children of register_hint, which have the same spill slot as their parent. An overlap of two intervals with5842// the same spill slot could result in a situation where both intervals are spilled at the same time to the same stack location which is not correct.5843return;5844}58455846// modify intervals such that cur gets the same stack slot as register_hint5847// delete use positions to prevent the intervals to get a register at beginning5848cur->set_canonical_spill_slot(register_hint->canonical_spill_slot());5849cur->remove_first_use_pos();5850end_hint->remove_first_use_pos();5851}585258535854// allocate a physical register or memory location to an interval5855bool LinearScanWalker::activate_current() {5856Interval* cur = current();5857bool result = true;58585859TRACE_LINEAR_SCAN(2, tty->print ("+++++ activating interval "); cur->print());5860TRACE_LINEAR_SCAN(4, tty->print_cr(" split_parent: %d, insert_move_when_activated: %d", cur->split_parent()->reg_num(), cur->insert_move_when_activated()));58615862if (cur->assigned_reg() >= LinearScan::nof_regs) {5863// activating an interval that has a stack slot assigned -> split it at first use position5864// used for method parameters5865TRACE_LINEAR_SCAN(4, tty->print_cr(" interval has spill slot assigned (method parameter) -> split it before first use"));58665867split_stack_interval(cur);5868result = false;58695870} else if (allocator()->gen()->is_vreg_flag_set(cur->reg_num(), LIRGenerator::must_start_in_memory)) {5871// activating an interval that must start in a stack slot, but may get a register later5872// used for lir_roundfp: rounding is done by store to stack and reload later5873TRACE_LINEAR_SCAN(4, tty->print_cr(" interval must start in stack slot -> split it before first use"));5874assert(cur->assigned_reg() == any_reg && cur->assigned_regHi() == any_reg, "register already assigned");58755876allocator()->assign_spill_slot(cur);5877split_stack_interval(cur);5878result = false;58795880} else if (cur->assigned_reg() == any_reg) {5881// interval has not assigned register -> normal allocation5882// (this is the normal case for most intervals)5883TRACE_LINEAR_SCAN(4, tty->print_cr(" normal allocation of register"));58845885// assign same spill slot to non-intersecting intervals5886combine_spilled_intervals(cur);58875888init_vars_for_alloc(cur);5889if (no_allocation_possible(cur) || !alloc_free_reg(cur)) {5890// no empty register available.5891// split and spill another interval so that this interval gets a register5892alloc_locked_reg(cur);5893}58945895// spilled intervals need not be move to active-list5896if (cur->assigned_reg() >= LinearScan::nof_regs) {5897result = false;5898}5899}59005901// load spilled values that become active from stack slot to register5902if (cur->insert_move_when_activated()) {5903assert(cur->is_split_child(), "must be");5904assert(cur->current_split_child() != NULL, "must be");5905assert(cur->current_split_child()->reg_num() != cur->reg_num(), "cannot insert move between same interval");5906TRACE_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()));59075908insert_move(cur->from(), cur->current_split_child(), cur);5909}5910cur->make_current_split_child();59115912return result; // true = interval is moved to active list5913}591459155916// Implementation of EdgeMoveOptimizer59175918EdgeMoveOptimizer::EdgeMoveOptimizer() :5919_edge_instructions(4),5920_edge_instructions_idx(4)5921{5922}59235924void EdgeMoveOptimizer::optimize(BlockList* code) {5925EdgeMoveOptimizer optimizer = EdgeMoveOptimizer();59265927// ignore the first block in the list (index 0 is not processed)5928for (int i = code->length() - 1; i >= 1; i--) {5929BlockBegin* block = code->at(i);59305931if (block->number_of_preds() > 1 && !block->is_set(BlockBegin::exception_entry_flag)) {5932optimizer.optimize_moves_at_block_end(block);5933}5934if (block->number_of_sux() == 2) {5935optimizer.optimize_moves_at_block_begin(block);5936}5937}5938}593959405941// clear all internal data structures5942void EdgeMoveOptimizer::init_instructions() {5943_edge_instructions.clear();5944_edge_instructions_idx.clear();5945}59465947// append a lir-instruction-list and the index of the current operation in to the list5948void EdgeMoveOptimizer::append_instructions(LIR_OpList* instructions, int instructions_idx) {5949_edge_instructions.append(instructions);5950_edge_instructions_idx.append(instructions_idx);5951}59525953// return the current operation of the given edge (predecessor or successor)5954LIR_Op* EdgeMoveOptimizer::instruction_at(int edge) {5955LIR_OpList* instructions = _edge_instructions.at(edge);5956int idx = _edge_instructions_idx.at(edge);59575958if (idx < instructions->length()) {5959return instructions->at(idx);5960} else {5961return NULL;5962}5963}59645965// removes the current operation of the given edge (predecessor or successor)5966void EdgeMoveOptimizer::remove_cur_instruction(int edge, bool decrement_index) {5967LIR_OpList* instructions = _edge_instructions.at(edge);5968int idx = _edge_instructions_idx.at(edge);5969instructions->remove_at(idx);59705971if (decrement_index) {5972_edge_instructions_idx.at_put(edge, idx - 1);5973}5974}597559765977bool EdgeMoveOptimizer::operations_different(LIR_Op* op1, LIR_Op* op2) {5978if (op1 == NULL || op2 == NULL) {5979// at least one block is already empty -> no optimization possible5980return true;5981}59825983if (op1->code() == lir_move && op2->code() == lir_move) {5984assert(op1->as_Op1() != NULL, "move must be LIR_Op1");5985assert(op2->as_Op1() != NULL, "move must be LIR_Op1");5986LIR_Op1* move1 = (LIR_Op1*)op1;5987LIR_Op1* move2 = (LIR_Op1*)op2;5988if (move1->info() == move2->info() && move1->in_opr() == move2->in_opr() && move1->result_opr() == move2->result_opr()) {5989// these moves are exactly equal and can be optimized5990return false;5991}59925993} else if (op1->code() == lir_fxch && op2->code() == lir_fxch) {5994assert(op1->as_Op1() != NULL, "fxch must be LIR_Op1");5995assert(op2->as_Op1() != NULL, "fxch must be LIR_Op1");5996LIR_Op1* fxch1 = (LIR_Op1*)op1;5997LIR_Op1* fxch2 = (LIR_Op1*)op2;5998if (fxch1->in_opr()->as_jint() == fxch2->in_opr()->as_jint()) {5999// equal FPU stack operations can be optimized6000return false;6001}60026003} else if (op1->code() == lir_fpop_raw && op2->code() == lir_fpop_raw) {6004// equal FPU stack operations can be optimized6005return false;6006}60076008// no optimization possible6009return true;6010}60116012void EdgeMoveOptimizer::optimize_moves_at_block_end(BlockBegin* block) {6013TRACE_LINEAR_SCAN(4, tty->print_cr("optimizing moves at end of block B%d", block->block_id()));60146015if (block->is_predecessor(block)) {6016// currently we can't handle this correctly.6017return;6018}60196020init_instructions();6021int num_preds = block->number_of_preds();6022assert(num_preds > 1, "do not call otherwise");6023assert(!block->is_set(BlockBegin::exception_entry_flag), "exception handlers not allowed");60246025// setup a list with the lir-instructions of all predecessors6026int i;6027for (i = 0; i < num_preds; i++) {6028BlockBegin* pred = block->pred_at(i);6029LIR_OpList* pred_instructions = pred->lir()->instructions_list();60306031if (pred->number_of_sux() != 1) {6032// this can happen with switch-statements where multiple edges are between6033// the same blocks.6034return;6035}60366037assert(pred->number_of_sux() == 1, "can handle only one successor");6038assert(pred->sux_at(0) == block, "invalid control flow");6039assert(pred_instructions->last()->code() == lir_branch, "block with successor must end with branch");6040assert(pred_instructions->last()->as_OpBranch() != NULL, "branch must be LIR_OpBranch");6041assert(pred_instructions->last()->as_OpBranch()->cond() == lir_cond_always, "block must end with unconditional branch");60426043if (pred_instructions->last()->info() != NULL) {6044// can not optimize instructions when debug info is needed6045return;6046}60476048// ignore the unconditional branch at the end of the block6049append_instructions(pred_instructions, pred_instructions->length() - 2);6050}605160526053// process lir-instructions while all predecessors end with the same instruction6054while (true) {6055LIR_Op* op = instruction_at(0);6056for (i = 1; i < num_preds; i++) {6057if (operations_different(op, instruction_at(i))) {6058// these instructions are different and cannot be optimized ->6059// no further optimization possible6060return;6061}6062}60636064TRACE_LINEAR_SCAN(4, tty->print("found instruction that is equal in all %d predecessors: ", num_preds); op->print());60656066// insert the instruction at the beginning of the current block6067block->lir()->insert_before(1, op);60686069// delete the instruction at the end of all predecessors6070for (i = 0; i < num_preds; i++) {6071remove_cur_instruction(i, true);6072}6073}6074}607560766077void EdgeMoveOptimizer::optimize_moves_at_block_begin(BlockBegin* block) {6078TRACE_LINEAR_SCAN(4, tty->print_cr("optimization moves at begin of block B%d", block->block_id()));60796080init_instructions();6081int num_sux = block->number_of_sux();60826083LIR_OpList* cur_instructions = block->lir()->instructions_list();60846085assert(num_sux == 2, "method should not be called otherwise");6086assert(cur_instructions->last()->code() == lir_branch, "block with successor must end with branch");6087assert(cur_instructions->last()->as_OpBranch() != NULL, "branch must be LIR_OpBranch");6088assert(cur_instructions->last()->as_OpBranch()->cond() == lir_cond_always, "block must end with unconditional branch");60896090if (cur_instructions->last()->info() != NULL) {6091// can no optimize instructions when debug info is needed6092return;6093}60946095LIR_Op* branch = cur_instructions->at(cur_instructions->length() - 2);6096if (branch->info() != NULL || (branch->code() != lir_branch && branch->code() != lir_cond_float_branch)) {6097// not a valid case for optimization6098// currently, only blocks that end with two branches (conditional branch followed6099// by unconditional branch) are optimized6100return;6101}61026103// now it is guaranteed that the block ends with two branch instructions.6104// the instructions are inserted at the end of the block before these two branches6105int insert_idx = cur_instructions->length() - 2;61066107int i;6108#ifdef ASSERT6109for (i = insert_idx - 1; i >= 0; i--) {6110LIR_Op* op = cur_instructions->at(i);6111if ((op->code() == lir_branch || op->code() == lir_cond_float_branch) && ((LIR_OpBranch*)op)->block() != NULL) {6112assert(false, "block with two successors can have only two branch instructions");6113}6114}6115#endif61166117// setup a list with the lir-instructions of all successors6118for (i = 0; i < num_sux; i++) {6119BlockBegin* sux = block->sux_at(i);6120LIR_OpList* sux_instructions = sux->lir()->instructions_list();61216122assert(sux_instructions->at(0)->code() == lir_label, "block must start with label");61236124if (sux->number_of_preds() != 1) {6125// this can happen with switch-statements where multiple edges are between6126// the same blocks.6127return;6128}6129assert(sux->pred_at(0) == block, "invalid control flow");6130assert(!sux->is_set(BlockBegin::exception_entry_flag), "exception handlers not allowed");61316132// ignore the label at the beginning of the block6133append_instructions(sux_instructions, 1);6134}61356136// process lir-instructions while all successors begin with the same instruction6137while (true) {6138LIR_Op* op = instruction_at(0);6139for (i = 1; i < num_sux; i++) {6140if (operations_different(op, instruction_at(i))) {6141// these instructions are different and cannot be optimized ->6142// no further optimization possible6143return;6144}6145}61466147TRACE_LINEAR_SCAN(4, tty->print("----- found instruction that is equal in all %d successors: ", num_sux); op->print());61486149// insert instruction at end of current block6150block->lir()->insert_before(insert_idx, op);6151insert_idx++;61526153// delete the instructions at the beginning of all successors6154for (i = 0; i < num_sux; i++) {6155remove_cur_instruction(i, false);6156}6157}6158}615961606161// Implementation of ControlFlowOptimizer61626163ControlFlowOptimizer::ControlFlowOptimizer() :6164_original_preds(4)6165{6166}61676168void ControlFlowOptimizer::optimize(BlockList* code) {6169ControlFlowOptimizer optimizer = ControlFlowOptimizer();61706171// push the OSR entry block to the end so that we're not jumping over it.6172BlockBegin* osr_entry = code->at(0)->end()->as_Base()->osr_entry();6173if (osr_entry) {6174int index = osr_entry->linear_scan_number();6175assert(code->at(index) == osr_entry, "wrong index");6176code->remove_at(index);6177code->append(osr_entry);6178}61796180optimizer.reorder_short_loops(code);6181optimizer.delete_empty_blocks(code);6182optimizer.delete_unnecessary_jumps(code);6183optimizer.delete_jumps_to_return(code);6184}61856186void ControlFlowOptimizer::reorder_short_loop(BlockList* code, BlockBegin* header_block, int header_idx) {6187int i = header_idx + 1;6188int max_end = MIN2(header_idx + ShortLoopSize, code->length());6189while (i < max_end && code->at(i)->loop_depth() >= header_block->loop_depth()) {6190i++;6191}61926193if (i == code->length() || code->at(i)->loop_depth() < header_block->loop_depth()) {6194int end_idx = i - 1;6195BlockBegin* end_block = code->at(end_idx);61966197if (end_block->number_of_sux() == 1 && end_block->sux_at(0) == header_block) {6198// short loop from header_idx to end_idx found -> reorder blocks such that6199// the header_block is the last block instead of the first block of the loop6200TRACE_LINEAR_SCAN(1, tty->print_cr("Reordering short loop: length %d, header B%d, end B%d",6201end_idx - header_idx + 1,6202header_block->block_id(), end_block->block_id()));62036204for (int j = header_idx; j < end_idx; j++) {6205code->at_put(j, code->at(j + 1));6206}6207code->at_put(end_idx, header_block);62086209// correct the flags so that any loop alignment occurs in the right place.6210assert(code->at(end_idx)->is_set(BlockBegin::backward_branch_target_flag), "must be backward branch target");6211code->at(end_idx)->clear(BlockBegin::backward_branch_target_flag);6212code->at(header_idx)->set(BlockBegin::backward_branch_target_flag);6213}6214}6215}62166217void ControlFlowOptimizer::reorder_short_loops(BlockList* code) {6218for (int i = code->length() - 1; i >= 0; i--) {6219BlockBegin* block = code->at(i);62206221if (block->is_set(BlockBegin::linear_scan_loop_header_flag)) {6222reorder_short_loop(code, block, i);6223}6224}62256226DEBUG_ONLY(verify(code));6227}62286229// only blocks with exactly one successor can be deleted. Such blocks6230// must always end with an unconditional branch to this successor6231bool ControlFlowOptimizer::can_delete_block(BlockBegin* block) {6232if (block->number_of_sux() != 1 || block->number_of_exception_handlers() != 0 || block->is_entry_block()) {6233return false;6234}62356236LIR_OpList* instructions = block->lir()->instructions_list();62376238assert(instructions->length() >= 2, "block must have label and branch");6239assert(instructions->at(0)->code() == lir_label, "first instruction must always be a label");6240assert(instructions->last()->as_OpBranch() != NULL, "last instrcution must always be a branch");6241assert(instructions->last()->as_OpBranch()->cond() == lir_cond_always, "branch must be unconditional");6242assert(instructions->last()->as_OpBranch()->block() == block->sux_at(0), "branch target must be the successor");62436244// block must have exactly one successor62456246if (instructions->length() == 2 && instructions->last()->info() == NULL) {6247return true;6248}6249return false;6250}62516252// substitute branch targets in all branch-instructions of this blocks6253void ControlFlowOptimizer::substitute_branch_target(BlockBegin* block, BlockBegin* target_from, BlockBegin* target_to) {6254TRACE_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()));62556256LIR_OpList* instructions = block->lir()->instructions_list();62576258assert(instructions->at(0)->code() == lir_label, "first instruction must always be a label");6259for (int i = instructions->length() - 1; i >= 1; i--) {6260LIR_Op* op = instructions->at(i);62616262if (op->code() == lir_branch || op->code() == lir_cond_float_branch) {6263assert(op->as_OpBranch() != NULL, "branch must be of type LIR_OpBranch");6264LIR_OpBranch* branch = (LIR_OpBranch*)op;62656266if (branch->block() == target_from) {6267branch->change_block(target_to);6268}6269if (branch->ublock() == target_from) {6270branch->change_ublock(target_to);6271}6272}6273}6274}62756276void ControlFlowOptimizer::delete_empty_blocks(BlockList* code) {6277int old_pos = 0;6278int new_pos = 0;6279int num_blocks = code->length();62806281while (old_pos < num_blocks) {6282BlockBegin* block = code->at(old_pos);62836284if (can_delete_block(block)) {6285BlockBegin* new_target = block->sux_at(0);62866287// propagate backward branch target flag for correct code alignment6288if (block->is_set(BlockBegin::backward_branch_target_flag)) {6289new_target->set(BlockBegin::backward_branch_target_flag);6290}62916292// collect a list with all predecessors that contains each predecessor only once6293// the predecessors of cur are changed during the substitution, so a copy of the6294// predecessor list is necessary6295int j;6296_original_preds.clear();6297for (j = block->number_of_preds() - 1; j >= 0; j--) {6298BlockBegin* pred = block->pred_at(j);6299if (_original_preds.find(pred) == -1) {6300_original_preds.append(pred);6301}6302}63036304for (j = _original_preds.length() - 1; j >= 0; j--) {6305BlockBegin* pred = _original_preds.at(j);6306substitute_branch_target(pred, block, new_target);6307pred->substitute_sux(block, new_target);6308}6309} else {6310// adjust position of this block in the block list if blocks before6311// have been deleted6312if (new_pos != old_pos) {6313code->at_put(new_pos, code->at(old_pos));6314}6315new_pos++;6316}6317old_pos++;6318}6319code->trunc_to(new_pos);63206321DEBUG_ONLY(verify(code));6322}63236324void ControlFlowOptimizer::delete_unnecessary_jumps(BlockList* code) {6325// skip the last block because there a branch is always necessary6326for (int i = code->length() - 2; i >= 0; i--) {6327BlockBegin* block = code->at(i);6328LIR_OpList* instructions = block->lir()->instructions_list();63296330LIR_Op* last_op = instructions->last();6331if (last_op->code() == lir_branch) {6332assert(last_op->as_OpBranch() != NULL, "branch must be of type LIR_OpBranch");6333LIR_OpBranch* last_branch = (LIR_OpBranch*)last_op;63346335assert(last_branch->block() != NULL, "last branch must always have a block as target");6336assert(last_branch->label() == last_branch->block()->label(), "must be equal");63376338if (last_branch->info() == NULL) {6339if (last_branch->block() == code->at(i + 1)) {63406341TRACE_LINEAR_SCAN(3, tty->print_cr("Deleting unconditional branch at end of block B%d", block->block_id()));63426343// delete last branch instruction6344instructions->trunc_to(instructions->length() - 1);63456346} else {6347LIR_Op* prev_op = instructions->at(instructions->length() - 2);6348if (prev_op->code() == lir_branch || prev_op->code() == lir_cond_float_branch) {6349assert(prev_op->as_OpBranch() != NULL, "branch must be of type LIR_OpBranch");6350LIR_OpBranch* prev_branch = (LIR_OpBranch*)prev_op;63516352if (prev_branch->stub() == NULL) {63536354LIR_Op2* prev_cmp = NULL;6355// There might be a cmove inserted for profiling which depends on the same6356// compare. If we change the condition of the respective compare, we have6357// to take care of this cmove as well.6358LIR_Op2* prev_cmove = NULL;63596360for(int j = instructions->length() - 3; j >= 0 && prev_cmp == NULL; j--) {6361prev_op = instructions->at(j);6362// check for the cmove6363if (prev_op->code() == lir_cmove) {6364assert(prev_op->as_Op2() != NULL, "cmove must be of type LIR_Op2");6365prev_cmove = (LIR_Op2*)prev_op;6366assert(prev_branch->cond() == prev_cmove->condition(), "should be the same");6367}6368if (prev_op->code() == lir_cmp) {6369assert(prev_op->as_Op2() != NULL, "branch must be of type LIR_Op2");6370prev_cmp = (LIR_Op2*)prev_op;6371assert(prev_branch->cond() == prev_cmp->condition(), "should be the same");6372}6373}6374// Guarantee because it is dereferenced below.6375guarantee(prev_cmp != NULL, "should have found comp instruction for branch");6376if (prev_branch->block() == code->at(i + 1) && prev_branch->info() == NULL) {63776378TRACE_LINEAR_SCAN(3, tty->print_cr("Negating conditional branch and deleting unconditional branch at end of block B%d", block->block_id()));63796380// eliminate a conditional branch to the immediate successor6381prev_branch->change_block(last_branch->block());6382prev_branch->negate_cond();6383prev_cmp->set_condition(prev_branch->cond());6384instructions->trunc_to(instructions->length() - 1);6385// if we do change the condition, we have to change the cmove as well6386if (prev_cmove != NULL) {6387prev_cmove->set_condition(prev_branch->cond());6388LIR_Opr t = prev_cmove->in_opr1();6389prev_cmove->set_in_opr1(prev_cmove->in_opr2());6390prev_cmove->set_in_opr2(t);6391}6392}6393}6394}6395}6396}6397}6398}63996400DEBUG_ONLY(verify(code));6401}64026403void ControlFlowOptimizer::delete_jumps_to_return(BlockList* code) {6404#ifdef ASSERT6405ResourceBitMap return_converted(BlockBegin::number_of_blocks());6406#endif64076408for (int i = code->length() - 1; i >= 0; i--) {6409BlockBegin* block = code->at(i);6410LIR_OpList* cur_instructions = block->lir()->instructions_list();6411LIR_Op* cur_last_op = cur_instructions->last();64126413assert(cur_instructions->at(0)->code() == lir_label, "first instruction must always be a label");6414if (cur_instructions->length() == 2 && cur_last_op->code() == lir_return) {6415// the block contains only a label and a return6416// if a predecessor ends with an unconditional jump to this block, then the jump6417// can be replaced with a return instruction6418//6419// Note: the original block with only a return statement cannot be deleted completely6420// because the predecessors might have other (conditional) jumps to this block6421// -> this may lead to unnecesary return instructions in the final code64226423assert(cur_last_op->info() == NULL, "return instructions do not have debug information");6424assert(block->number_of_sux() == 0 ||6425(return_converted.at(block->block_id()) && block->number_of_sux() == 1),6426"blocks that end with return must not have successors");64276428assert(cur_last_op->as_Op1() != NULL, "return must be LIR_Op1");6429LIR_Opr return_opr = ((LIR_Op1*)cur_last_op)->in_opr();64306431for (int j = block->number_of_preds() - 1; j >= 0; j--) {6432BlockBegin* pred = block->pred_at(j);6433LIR_OpList* pred_instructions = pred->lir()->instructions_list();6434LIR_Op* pred_last_op = pred_instructions->last();64356436if (pred_last_op->code() == lir_branch) {6437assert(pred_last_op->as_OpBranch() != NULL, "branch must be LIR_OpBranch");6438LIR_OpBranch* pred_last_branch = (LIR_OpBranch*)pred_last_op;64396440if (pred_last_branch->block() == block && pred_last_branch->cond() == lir_cond_always && pred_last_branch->info() == NULL) {6441// replace the jump to a return with a direct return6442// Note: currently the edge between the blocks is not deleted6443pred_instructions->at_put(pred_instructions->length() - 1, new LIR_OpReturn(return_opr));6444#ifdef ASSERT6445return_converted.set_bit(pred->block_id());6446#endif6447}6448}6449}6450}6451}6452}645364546455#ifdef ASSERT6456void ControlFlowOptimizer::verify(BlockList* code) {6457for (int i = 0; i < code->length(); i++) {6458BlockBegin* block = code->at(i);6459LIR_OpList* instructions = block->lir()->instructions_list();64606461int j;6462for (j = 0; j < instructions->length(); j++) {6463LIR_OpBranch* op_branch = instructions->at(j)->as_OpBranch();64646465if (op_branch != NULL) {6466assert(op_branch->block() == NULL || code->find(op_branch->block()) != -1, "branch target not valid");6467assert(op_branch->ublock() == NULL || code->find(op_branch->ublock()) != -1, "branch target not valid");6468}6469}64706471for (j = 0; j < block->number_of_sux() - 1; j++) {6472BlockBegin* sux = block->sux_at(j);6473assert(code->find(sux) != -1, "successor not valid");6474}64756476for (j = 0; j < block->number_of_preds() - 1; j++) {6477BlockBegin* pred = block->pred_at(j);6478assert(code->find(pred) != -1, "successor not valid");6479}6480}6481}6482#endif648364846485#ifndef PRODUCT64866487// Implementation of LinearStatistic64886489const char* LinearScanStatistic::counter_name(int counter_idx) {6490switch (counter_idx) {6491case counter_method: return "compiled methods";6492case counter_fpu_method: return "methods using fpu";6493case counter_loop_method: return "methods with loops";6494case counter_exception_method:return "methods with xhandler";64956496case counter_loop: return "loops";6497case counter_block: return "blocks";6498case counter_loop_block: return "blocks inside loop";6499case counter_exception_block: return "exception handler entries";6500case counter_interval: return "intervals";6501case counter_fixed_interval: return "fixed intervals";6502case counter_range: return "ranges";6503case counter_fixed_range: return "fixed ranges";6504case counter_use_pos: return "use positions";6505case counter_fixed_use_pos: return "fixed use positions";6506case counter_spill_slots: return "spill slots";65076508// counter for classes of lir instructions6509case counter_instruction: return "total instructions";6510case counter_label: return "labels";6511case counter_entry: return "method entries";6512case counter_return: return "method returns";6513case counter_call: return "method calls";6514case counter_move: return "moves";6515case counter_cmp: return "compare";6516case counter_cond_branch: return "conditional branches";6517case counter_uncond_branch: return "unconditional branches";6518case counter_stub_branch: return "branches to stub";6519case counter_alu: return "artithmetic + logic";6520case counter_alloc: return "allocations";6521case counter_sync: return "synchronisation";6522case counter_throw: return "throw";6523case counter_unwind: return "unwind";6524case counter_typecheck: return "type+null-checks";6525case counter_fpu_stack: return "fpu-stack";6526case counter_misc_inst: return "other instructions";6527case counter_other_inst: return "misc. instructions";65286529// counter for different types of moves6530case counter_move_total: return "total moves";6531case counter_move_reg_reg: return "register->register";6532case counter_move_reg_stack: return "register->stack";6533case counter_move_stack_reg: return "stack->register";6534case counter_move_stack_stack:return "stack->stack";6535case counter_move_reg_mem: return "register->memory";6536case counter_move_mem_reg: return "memory->register";6537case counter_move_const_any: return "constant->any";65386539case blank_line_1: return "";6540case blank_line_2: return "";65416542default: ShouldNotReachHere(); return "";6543}6544}65456546LinearScanStatistic::Counter LinearScanStatistic::base_counter(int counter_idx) {6547if (counter_idx == counter_fpu_method || counter_idx == counter_loop_method || counter_idx == counter_exception_method) {6548return counter_method;6549} else if (counter_idx == counter_loop_block || counter_idx == counter_exception_block) {6550return counter_block;6551} else if (counter_idx >= counter_instruction && counter_idx <= counter_other_inst) {6552return counter_instruction;6553} else if (counter_idx >= counter_move_total && counter_idx <= counter_move_const_any) {6554return counter_move_total;6555}6556return invalid_counter;6557}65586559LinearScanStatistic::LinearScanStatistic() {6560for (int i = 0; i < number_of_counters; i++) {6561_counters_sum[i] = 0;6562_counters_max[i] = -1;6563}65646565}65666567// add the method-local numbers to the total sum6568void LinearScanStatistic::sum_up(LinearScanStatistic &method_statistic) {6569for (int i = 0; i < number_of_counters; i++) {6570_counters_sum[i] += method_statistic._counters_sum[i];6571_counters_max[i] = MAX2(_counters_max[i], method_statistic._counters_sum[i]);6572}6573}65746575void LinearScanStatistic::print(const char* title) {6576if (CountLinearScan || TraceLinearScanLevel > 0) {6577tty->cr();6578tty->print_cr("***** LinearScan statistic - %s *****", title);65796580for (int i = 0; i < number_of_counters; i++) {6581if (_counters_sum[i] > 0 || _counters_max[i] >= 0) {6582tty->print("%25s: %8d", counter_name(i), _counters_sum[i]);65836584LinearScanStatistic::Counter cntr = base_counter(i);6585if (cntr != invalid_counter) {6586tty->print(" (%5.1f%%) ", _counters_sum[i] * 100.0 / _counters_sum[cntr]);6587} else {6588tty->print(" ");6589}65906591if (_counters_max[i] >= 0) {6592tty->print("%8d", _counters_max[i]);6593}6594}6595tty->cr();6596}6597}6598}65996600void LinearScanStatistic::collect(LinearScan* allocator) {6601inc_counter(counter_method);6602if (allocator->has_fpu_registers()) {6603inc_counter(counter_fpu_method);6604}6605if (allocator->num_loops() > 0) {6606inc_counter(counter_loop_method);6607}6608inc_counter(counter_loop, allocator->num_loops());6609inc_counter(counter_spill_slots, allocator->max_spills());66106611int i;6612for (i = 0; i < allocator->interval_count(); i++) {6613Interval* cur = allocator->interval_at(i);66146615if (cur != NULL) {6616inc_counter(counter_interval);6617inc_counter(counter_use_pos, cur->num_use_positions());6618if (LinearScan::is_precolored_interval(cur)) {6619inc_counter(counter_fixed_interval);6620inc_counter(counter_fixed_use_pos, cur->num_use_positions());6621}66226623Range* range = cur->first();6624while (range != Range::end()) {6625inc_counter(counter_range);6626if (LinearScan::is_precolored_interval(cur)) {6627inc_counter(counter_fixed_range);6628}6629range = range->next();6630}6631}6632}66336634bool has_xhandlers = false;6635// Note: only count blocks that are in code-emit order6636for (i = 0; i < allocator->ir()->code()->length(); i++) {6637BlockBegin* cur = allocator->ir()->code()->at(i);66386639inc_counter(counter_block);6640if (cur->loop_depth() > 0) {6641inc_counter(counter_loop_block);6642}6643if (cur->is_set(BlockBegin::exception_entry_flag)) {6644inc_counter(counter_exception_block);6645has_xhandlers = true;6646}66476648LIR_OpList* instructions = cur->lir()->instructions_list();6649for (int j = 0; j < instructions->length(); j++) {6650LIR_Op* op = instructions->at(j);66516652inc_counter(counter_instruction);66536654switch (op->code()) {6655case lir_label: inc_counter(counter_label); break;6656case lir_std_entry:6657case lir_osr_entry: inc_counter(counter_entry); break;6658case lir_return: inc_counter(counter_return); break;66596660case lir_rtcall:6661case lir_static_call:6662case lir_optvirtual_call: inc_counter(counter_call); break;66636664case lir_move: {6665inc_counter(counter_move);6666inc_counter(counter_move_total);66676668LIR_Opr in = op->as_Op1()->in_opr();6669LIR_Opr res = op->as_Op1()->result_opr();6670if (in->is_register()) {6671if (res->is_register()) {6672inc_counter(counter_move_reg_reg);6673} else if (res->is_stack()) {6674inc_counter(counter_move_reg_stack);6675} else if (res->is_address()) {6676inc_counter(counter_move_reg_mem);6677} else {6678ShouldNotReachHere();6679}6680} else if (in->is_stack()) {6681if (res->is_register()) {6682inc_counter(counter_move_stack_reg);6683} else {6684inc_counter(counter_move_stack_stack);6685}6686} else if (in->is_address()) {6687assert(res->is_register(), "must be");6688inc_counter(counter_move_mem_reg);6689} else if (in->is_constant()) {6690inc_counter(counter_move_const_any);6691} else {6692ShouldNotReachHere();6693}6694break;6695}66966697case lir_cmp: inc_counter(counter_cmp); break;66986699case lir_branch:6700case lir_cond_float_branch: {6701LIR_OpBranch* branch = op->as_OpBranch();6702if (branch->block() == NULL) {6703inc_counter(counter_stub_branch);6704} else if (branch->cond() == lir_cond_always) {6705inc_counter(counter_uncond_branch);6706} else {6707inc_counter(counter_cond_branch);6708}6709break;6710}67116712case lir_neg:6713case lir_add:6714case lir_sub:6715case lir_mul:6716case lir_div:6717case lir_rem:6718case lir_sqrt:6719case lir_abs:6720case lir_log10:6721case lir_logic_and:6722case lir_logic_or:6723case lir_logic_xor:6724case lir_shl:6725case lir_shr:6726case lir_ushr: inc_counter(counter_alu); break;67276728case lir_alloc_object:6729case lir_alloc_array: inc_counter(counter_alloc); break;67306731case lir_monaddr:6732case lir_lock:6733case lir_unlock: inc_counter(counter_sync); break;67346735case lir_throw: inc_counter(counter_throw); break;67366737case lir_unwind: inc_counter(counter_unwind); break;67386739case lir_null_check:6740case lir_leal:6741case lir_instanceof:6742case lir_checkcast:6743case lir_store_check: inc_counter(counter_typecheck); break;67446745case lir_fpop_raw:6746case lir_fxch:6747case lir_fld: inc_counter(counter_fpu_stack); break;67486749case lir_nop:6750case lir_push:6751case lir_pop:6752case lir_convert:6753case lir_roundfp:6754case lir_cmove: inc_counter(counter_misc_inst); break;67556756default: inc_counter(counter_other_inst); break;6757}6758}6759}67606761if (has_xhandlers) {6762inc_counter(counter_exception_method);6763}6764}67656766void LinearScanStatistic::compute(LinearScan* allocator, LinearScanStatistic &global_statistic) {6767if (CountLinearScan || TraceLinearScanLevel > 0) {67686769LinearScanStatistic local_statistic = LinearScanStatistic();67706771local_statistic.collect(allocator);6772global_statistic.sum_up(local_statistic);67736774if (TraceLinearScanLevel > 2) {6775local_statistic.print("current local statistic");6776}6777}6778}677967806781// Implementation of LinearTimers67826783LinearScanTimers::LinearScanTimers() {6784for (int i = 0; i < number_of_timers; i++) {6785timer(i)->reset();6786}6787}67886789const char* LinearScanTimers::timer_name(int idx) {6790switch (idx) {6791case timer_do_nothing: return "Nothing (Time Check)";6792case timer_number_instructions: return "Number Instructions";6793case timer_compute_local_live_sets: return "Local Live Sets";6794case timer_compute_global_live_sets: return "Global Live Sets";6795case timer_build_intervals: return "Build Intervals";6796case timer_sort_intervals_before: return "Sort Intervals Before";6797case timer_allocate_registers: return "Allocate Registers";6798case timer_resolve_data_flow: return "Resolve Data Flow";6799case timer_sort_intervals_after: return "Sort Intervals After";6800case timer_eliminate_spill_moves: return "Spill optimization";6801case timer_assign_reg_num: return "Assign Reg Num";6802case timer_allocate_fpu_stack: return "Allocate FPU Stack";6803case timer_optimize_lir: return "Optimize LIR";6804default: ShouldNotReachHere(); return "";6805}6806}68076808void LinearScanTimers::begin_method() {6809if (TimeEachLinearScan) {6810// reset all timers to measure only current method6811for (int i = 0; i < number_of_timers; i++) {6812timer(i)->reset();6813}6814}6815}68166817void LinearScanTimers::end_method(LinearScan* allocator) {6818if (TimeEachLinearScan) {68196820double c = timer(timer_do_nothing)->seconds();6821double total = 0;6822for (int i = 1; i < number_of_timers; i++) {6823total += timer(i)->seconds() - c;6824}68256826if (total >= 0.0005) {6827// print all information in one line for automatic processing6828tty->print("@"); allocator->compilation()->method()->print_name();68296830tty->print("@ %d ", allocator->compilation()->method()->code_size());6831tty->print("@ %d ", allocator->block_at(allocator->block_count() - 1)->last_lir_instruction_id() / 2);6832tty->print("@ %d ", allocator->block_count());6833tty->print("@ %d ", allocator->num_virtual_regs());6834tty->print("@ %d ", allocator->interval_count());6835tty->print("@ %d ", allocator->_num_calls);6836tty->print("@ %d ", allocator->num_loops());68376838tty->print("@ %6.6f ", total);6839for (int i = 1; i < number_of_timers; i++) {6840tty->print("@ %4.1f ", ((timer(i)->seconds() - c) / total) * 100);6841}6842tty->cr();6843}6844}6845}68466847void LinearScanTimers::print(double total_time) {6848if (TimeLinearScan) {6849// correction value: sum of dummy-timer that only measures the time that6850// is necesary to start and stop itself6851double c = timer(timer_do_nothing)->seconds();68526853for (int i = 0; i < number_of_timers; i++) {6854double t = timer(i)->seconds();6855tty->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);6856}6857}6858}68596860#endif // #ifndef PRODUCT686168626863