Path: blob/master/src/hotspot/share/c1/c1_LinearScan.cpp
64440 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);646local_has_fpu_registers = local_has_fpu_registers || value->type()->is_float_kind();647);648}649650// iterate temp operands of instruction651n = visitor.opr_count(LIR_OpVisitState::tempMode);652for (k = 0; k < n; k++) {653LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::tempMode, k);654assert(opr->is_register(), "visitor should only return register operands");655656if (opr->is_virtual_register()) {657assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");658reg = opr->vreg_number();659live_kill.set_bit(reg);660if (block->loop_index() >= 0) {661local_interval_in_loop.set_bit(reg, block->loop_index());662}663local_has_fpu_registers = local_has_fpu_registers || opr->is_virtual_fpu();664}665666#ifdef ASSERT667// fixed intervals are never live at block boundaries, so668// they need not be processed in live sets669// process them only in debug mode so that this can be checked670if (!opr->is_virtual_register()) {671reg = reg_num(opr);672if (is_processed_reg_num(reg)) {673live_kill.set_bit(reg_num(opr));674}675reg = reg_numHi(opr);676if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {677live_kill.set_bit(reg);678}679}680#endif681}682683// iterate output operands of instruction684n = visitor.opr_count(LIR_OpVisitState::outputMode);685for (k = 0; k < n; k++) {686LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::outputMode, k);687assert(opr->is_register(), "visitor should only return register operands");688689if (opr->is_virtual_register()) {690assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");691reg = opr->vreg_number();692live_kill.set_bit(reg);693if (block->loop_index() >= 0) {694local_interval_in_loop.set_bit(reg, block->loop_index());695}696local_has_fpu_registers = local_has_fpu_registers || opr->is_virtual_fpu();697}698699#ifdef ASSERT700// fixed intervals are never live at block boundaries, so701// they need not be processed in live sets702// process them only in debug mode so that this can be checked703if (!opr->is_virtual_register()) {704reg = reg_num(opr);705if (is_processed_reg_num(reg)) {706live_kill.set_bit(reg_num(opr));707}708reg = reg_numHi(opr);709if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {710live_kill.set_bit(reg);711}712}713#endif714}715} // end of instruction iteration716717block->set_live_gen (live_gen);718block->set_live_kill(live_kill);719block->set_live_in (ResourceBitMap(live_size));720block->set_live_out (ResourceBitMap(live_size));721722TRACE_LINEAR_SCAN(4, tty->print("live_gen B%d ", block->block_id()); print_bitmap(block->live_gen()));723TRACE_LINEAR_SCAN(4, tty->print("live_kill B%d ", block->block_id()); print_bitmap(block->live_kill()));724} // end of block iteration725726// propagate local calculated information into LinearScan object727_has_fpu_registers = local_has_fpu_registers;728compilation()->set_has_fpu_code(local_has_fpu_registers);729730_num_calls = local_num_calls;731_interval_in_loop = local_interval_in_loop;732}733734735// ********** Phase 3: perform a backward dataflow analysis to compute global live sets736// (sets live_in and live_out for each block)737738void LinearScan::compute_global_live_sets() {739TIME_LINEAR_SCAN(timer_compute_global_live_sets);740741int num_blocks = block_count();742bool change_occurred;743bool change_occurred_in_block;744int iteration_count = 0;745ResourceBitMap live_out(live_set_size()); // scratch set for calculations746747// Perform a backward dataflow analysis to compute live_out and live_in for each block.748// The loop is executed until a fixpoint is reached (no changes in an iteration)749// Exception handlers must be processed because not all live values are750// present in the state array, e.g. because of global value numbering751do {752change_occurred = false;753754// iterate all blocks in reverse order755for (int i = num_blocks - 1; i >= 0; i--) {756BlockBegin* block = block_at(i);757758change_occurred_in_block = false;759760// live_out(block) is the union of live_in(sux), for successors sux of block761int n = block->number_of_sux();762int e = block->number_of_exception_handlers();763if (n + e > 0) {764// block has successors765if (n > 0) {766live_out.set_from(block->sux_at(0)->live_in());767for (int j = 1; j < n; j++) {768live_out.set_union(block->sux_at(j)->live_in());769}770} else {771live_out.clear();772}773for (int j = 0; j < e; j++) {774live_out.set_union(block->exception_handler_at(j)->live_in());775}776777if (!block->live_out().is_same(live_out)) {778// A change occurred. Swap the old and new live out sets to avoid copying.779ResourceBitMap temp = block->live_out();780block->set_live_out(live_out);781live_out = temp;782783change_occurred = true;784change_occurred_in_block = true;785}786}787788if (iteration_count == 0 || change_occurred_in_block) {789// live_in(block) is the union of live_gen(block) with (live_out(block) & !live_kill(block))790// note: live_in has to be computed only in first iteration or if live_out has changed!791ResourceBitMap live_in = block->live_in();792live_in.set_from(block->live_out());793live_in.set_difference(block->live_kill());794live_in.set_union(block->live_gen());795}796797#ifdef ASSERT798if (TraceLinearScanLevel >= 4) {799char c = ' ';800if (iteration_count == 0 || change_occurred_in_block) {801c = '*';802}803tty->print("(%d) live_in%c B%d ", iteration_count, c, block->block_id()); print_bitmap(block->live_in());804tty->print("(%d) live_out%c B%d ", iteration_count, c, block->block_id()); print_bitmap(block->live_out());805}806#endif807}808iteration_count++;809810if (change_occurred && iteration_count > 50) {811BAILOUT("too many iterations in compute_global_live_sets");812}813} while (change_occurred);814815816#ifdef ASSERT817// check that fixed intervals are not live at block boundaries818// (live set must be empty at fixed intervals)819for (int i = 0; i < num_blocks; i++) {820BlockBegin* block = block_at(i);821for (int j = 0; j < LIR_OprDesc::vreg_base; j++) {822assert(block->live_in().at(j) == false, "live_in set of fixed register must be empty");823assert(block->live_out().at(j) == false, "live_out set of fixed register must be empty");824assert(block->live_gen().at(j) == false, "live_gen set of fixed register must be empty");825}826}827#endif828829// check that the live_in set of the first block is empty830ResourceBitMap live_in_args(ir()->start()->live_in().size());831if (!ir()->start()->live_in().is_same(live_in_args)) {832#ifdef ASSERT833tty->print_cr("Error: live_in set of first block must be empty (when this fails, virtual registers are used before they are defined)");834tty->print_cr("affected registers:");835print_bitmap(ir()->start()->live_in());836837// print some additional information to simplify debugging838for (unsigned int i = 0; i < ir()->start()->live_in().size(); i++) {839if (ir()->start()->live_in().at(i)) {840Instruction* instr = gen()->instruction_for_vreg(i);841tty->print_cr("* vreg %d (HIR instruction %c%d)", i, instr == NULL ? ' ' : instr->type()->tchar(), instr == NULL ? 0 : instr->id());842843for (int j = 0; j < num_blocks; j++) {844BlockBegin* block = block_at(j);845if (block->live_gen().at(i)) {846tty->print_cr(" used in block B%d", block->block_id());847}848if (block->live_kill().at(i)) {849tty->print_cr(" defined in block B%d", block->block_id());850}851}852}853}854855#endif856// when this fails, virtual registers are used before they are defined.857assert(false, "live_in set of first block must be empty");858// bailout of if this occurs in product mode.859bailout("live_in set of first block not empty");860}861}862863864// ********** Phase 4: build intervals865// (fills the list _intervals)866867void LinearScan::add_use(Value value, int from, int to, IntervalUseKind use_kind) {868assert(!value->type()->is_illegal(), "if this value is used by the interpreter it shouldn't be of indeterminate type");869LIR_Opr opr = value->operand();870Constant* con = value->as_Constant();871872if ((con == NULL || con->is_pinned()) && opr->is_register()) {873assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");874add_use(opr, from, to, use_kind);875}876}877878879void LinearScan::add_def(LIR_Opr opr, int def_pos, IntervalUseKind use_kind) {880TRACE_LINEAR_SCAN(2, tty->print(" def "); opr->print(tty); tty->print_cr(" def_pos %d (%d)", def_pos, use_kind));881assert(opr->is_register(), "should not be called otherwise");882883if (opr->is_virtual_register()) {884assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");885add_def(opr->vreg_number(), def_pos, use_kind, opr->type_register());886887} else {888int reg = reg_num(opr);889if (is_processed_reg_num(reg)) {890add_def(reg, def_pos, use_kind, opr->type_register());891}892reg = reg_numHi(opr);893if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {894add_def(reg, def_pos, use_kind, opr->type_register());895}896}897}898899void LinearScan::add_use(LIR_Opr opr, int from, int to, IntervalUseKind use_kind) {900TRACE_LINEAR_SCAN(2, tty->print(" use "); opr->print(tty); tty->print_cr(" from %d to %d (%d)", from, to, use_kind));901assert(opr->is_register(), "should not be called otherwise");902903if (opr->is_virtual_register()) {904assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");905add_use(opr->vreg_number(), from, to, use_kind, opr->type_register());906907} else {908int reg = reg_num(opr);909if (is_processed_reg_num(reg)) {910add_use(reg, from, to, use_kind, opr->type_register());911}912reg = reg_numHi(opr);913if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {914add_use(reg, from, to, use_kind, opr->type_register());915}916}917}918919void LinearScan::add_temp(LIR_Opr opr, int temp_pos, IntervalUseKind use_kind) {920TRACE_LINEAR_SCAN(2, tty->print(" temp "); opr->print(tty); tty->print_cr(" temp_pos %d (%d)", temp_pos, use_kind));921assert(opr->is_register(), "should not be called otherwise");922923if (opr->is_virtual_register()) {924assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");925add_temp(opr->vreg_number(), temp_pos, use_kind, opr->type_register());926927} else {928int reg = reg_num(opr);929if (is_processed_reg_num(reg)) {930add_temp(reg, temp_pos, use_kind, opr->type_register());931}932reg = reg_numHi(opr);933if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {934add_temp(reg, temp_pos, use_kind, opr->type_register());935}936}937}938939940void LinearScan::add_def(int reg_num, int def_pos, IntervalUseKind use_kind, BasicType type) {941Interval* interval = interval_at(reg_num);942if (interval != NULL) {943assert(interval->reg_num() == reg_num, "wrong interval");944945if (type != T_ILLEGAL) {946interval->set_type(type);947}948949Range* r = interval->first();950if (r->from() <= def_pos) {951// Update the starting point (when a range is first created for a use, its952// start is the beginning of the current block until a def is encountered.)953r->set_from(def_pos);954interval->add_use_pos(def_pos, use_kind);955956} else {957// Dead value - make vacuous interval958// also add use_kind for dead intervals959interval->add_range(def_pos, def_pos + 1);960interval->add_use_pos(def_pos, use_kind);961TRACE_LINEAR_SCAN(2, tty->print_cr("Warning: def of reg %d at %d occurs without use", reg_num, def_pos));962}963964} else {965// Dead value - make vacuous interval966// also add use_kind for dead intervals967interval = create_interval(reg_num);968if (type != T_ILLEGAL) {969interval->set_type(type);970}971972interval->add_range(def_pos, def_pos + 1);973interval->add_use_pos(def_pos, use_kind);974TRACE_LINEAR_SCAN(2, tty->print_cr("Warning: dead value %d at %d in live intervals", reg_num, def_pos));975}976977change_spill_definition_pos(interval, def_pos);978if (use_kind == noUse && interval->spill_state() <= startInMemory) {979// detection of method-parameters and roundfp-results980// TODO: move this directly to position where use-kind is computed981interval->set_spill_state(startInMemory);982}983}984985void LinearScan::add_use(int reg_num, int from, int to, IntervalUseKind use_kind, BasicType type) {986Interval* interval = interval_at(reg_num);987if (interval == NULL) {988interval = create_interval(reg_num);989}990assert(interval->reg_num() == reg_num, "wrong interval");991992if (type != T_ILLEGAL) {993interval->set_type(type);994}995996interval->add_range(from, to);997interval->add_use_pos(to, use_kind);998}9991000void LinearScan::add_temp(int reg_num, int temp_pos, IntervalUseKind use_kind, BasicType type) {1001Interval* interval = interval_at(reg_num);1002if (interval == NULL) {1003interval = create_interval(reg_num);1004}1005assert(interval->reg_num() == reg_num, "wrong interval");10061007if (type != T_ILLEGAL) {1008interval->set_type(type);1009}10101011interval->add_range(temp_pos, temp_pos + 1);1012interval->add_use_pos(temp_pos, use_kind);1013}101410151016// the results of this functions are used for optimizing spilling and reloading1017// if the functions return shouldHaveRegister and the interval is spilled,1018// it is not reloaded to a register.1019IntervalUseKind LinearScan::use_kind_of_output_operand(LIR_Op* op, LIR_Opr opr) {1020if (op->code() == lir_move) {1021assert(op->as_Op1() != NULL, "lir_move must be LIR_Op1");1022LIR_Op1* move = (LIR_Op1*)op;1023LIR_Opr res = move->result_opr();1024bool result_in_memory = res->is_virtual() && gen()->is_vreg_flag_set(res->vreg_number(), LIRGenerator::must_start_in_memory);10251026if (result_in_memory) {1027// Begin of an interval with must_start_in_memory set.1028// This interval will always get a stack slot first, so return noUse.1029return noUse;10301031} else if (move->in_opr()->is_stack()) {1032// method argument (condition must be equal to handle_method_arguments)1033return noUse;10341035} else if (move->in_opr()->is_register() && move->result_opr()->is_register()) {1036// Move from register to register1037if (block_of_op_with_id(op->id())->is_set(BlockBegin::osr_entry_flag)) {1038// special handling of phi-function moves inside osr-entry blocks1039// input operand must have a register instead of output operand (leads to better register allocation)1040return shouldHaveRegister;1041}1042}1043}10441045if (opr->is_virtual() &&1046gen()->is_vreg_flag_set(opr->vreg_number(), LIRGenerator::must_start_in_memory)) {1047// result is a stack-slot, so prevent immediate reloading1048return noUse;1049}10501051// all other operands require a register1052return mustHaveRegister;1053}10541055IntervalUseKind LinearScan::use_kind_of_input_operand(LIR_Op* op, LIR_Opr opr) {1056if (op->code() == lir_move) {1057assert(op->as_Op1() != NULL, "lir_move must be LIR_Op1");1058LIR_Op1* move = (LIR_Op1*)op;1059LIR_Opr res = move->result_opr();1060bool result_in_memory = res->is_virtual() && gen()->is_vreg_flag_set(res->vreg_number(), LIRGenerator::must_start_in_memory);10611062if (result_in_memory) {1063// Move to an interval with must_start_in_memory set.1064// To avoid moves from stack to stack (not allowed) force the input operand to a register1065return mustHaveRegister;10661067} else if (move->in_opr()->is_register() && move->result_opr()->is_register()) {1068// Move from register to register1069if (block_of_op_with_id(op->id())->is_set(BlockBegin::osr_entry_flag)) {1070// special handling of phi-function moves inside osr-entry blocks1071// input operand must have a register instead of output operand (leads to better register allocation)1072return mustHaveRegister;1073}10741075// The input operand is not forced to a register (moves from stack to register are allowed),1076// but it is faster if the input operand is in a register1077return shouldHaveRegister;1078}1079}108010811082#if defined(X86) || defined(S390)1083if (op->code() == lir_cmove) {1084// conditional moves can handle stack operands1085assert(op->result_opr()->is_register(), "result must always be in a register");1086return shouldHaveRegister;1087}10881089// optimizations for second input operand of arithmehtic operations on Intel1090// this operand is allowed to be on the stack in some cases1091BasicType opr_type = opr->type_register();1092if (opr_type == T_FLOAT || opr_type == T_DOUBLE) {1093if (IA32_ONLY( (UseSSE == 1 && opr_type == T_FLOAT) || UseSSE >= 2 ) NOT_IA32( true )) {1094// SSE float instruction (T_DOUBLE only supported with SSE2)1095switch (op->code()) {1096case lir_cmp:1097case lir_add:1098case lir_sub:1099case lir_mul:1100case lir_div:1101{1102assert(op->as_Op2() != NULL, "must be LIR_Op2");1103LIR_Op2* op2 = (LIR_Op2*)op;1104if (op2->in_opr1() != op2->in_opr2() && op2->in_opr2() == opr) {1105assert((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");1106return shouldHaveRegister;1107}1108}1109default:1110break;1111}1112} else {1113// FPU stack float instruction1114switch (op->code()) {1115case lir_add:1116case lir_sub:1117case lir_mul:1118case lir_div:1119{1120assert(op->as_Op2() != NULL, "must be LIR_Op2");1121LIR_Op2* op2 = (LIR_Op2*)op;1122if (op2->in_opr1() != op2->in_opr2() && op2->in_opr2() == opr) {1123assert((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");1124return shouldHaveRegister;1125}1126}1127default:1128break;1129}1130}1131// We want to sometimes use logical operations on pointers, in particular in GC barriers.1132// Since 64bit logical operations do not current support operands on stack, we have to make sure1133// T_OBJECT doesn't get spilled along with T_LONG.1134} else if (opr_type != T_LONG LP64_ONLY(&& opr_type != T_OBJECT)) {1135// integer instruction (note: long operands must always be in register)1136switch (op->code()) {1137case lir_cmp:1138case lir_add:1139case lir_sub:1140case lir_logic_and:1141case lir_logic_or:1142case lir_logic_xor:1143{1144assert(op->as_Op2() != NULL, "must be LIR_Op2");1145LIR_Op2* op2 = (LIR_Op2*)op;1146if (op2->in_opr1() != op2->in_opr2() && op2->in_opr2() == opr) {1147assert((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");1148return shouldHaveRegister;1149}1150}1151default:1152break;1153}1154}1155#endif // X86 || S39011561157// all other operands require a register1158return mustHaveRegister;1159}116011611162void LinearScan::handle_method_arguments(LIR_Op* op) {1163// special handling for method arguments (moves from stack to virtual register):1164// the interval gets no register assigned, but the stack slot.1165// it is split before the first use by the register allocator.11661167if (op->code() == lir_move) {1168assert(op->as_Op1() != NULL, "must be LIR_Op1");1169LIR_Op1* move = (LIR_Op1*)op;11701171if (move->in_opr()->is_stack()) {1172#ifdef ASSERT1173int arg_size = compilation()->method()->arg_size();1174LIR_Opr o = move->in_opr();1175if (o->is_single_stack()) {1176assert(o->single_stack_ix() >= 0 && o->single_stack_ix() < arg_size, "out of range");1177} else if (o->is_double_stack()) {1178assert(o->double_stack_ix() >= 0 && o->double_stack_ix() < arg_size, "out of range");1179} else {1180ShouldNotReachHere();1181}11821183assert(move->id() > 0, "invalid id");1184assert(block_of_op_with_id(move->id())->number_of_preds() == 0, "move from stack must be in first block");1185assert(move->result_opr()->is_virtual(), "result of move must be a virtual register");11861187TRACE_LINEAR_SCAN(4, tty->print_cr("found move from stack slot %d to vreg %d", o->is_single_stack() ? o->single_stack_ix() : o->double_stack_ix(), reg_num(move->result_opr())));1188#endif11891190Interval* interval = interval_at(reg_num(move->result_opr()));11911192int stack_slot = LinearScan::nof_regs + (move->in_opr()->is_single_stack() ? move->in_opr()->single_stack_ix() : move->in_opr()->double_stack_ix());1193interval->set_canonical_spill_slot(stack_slot);1194interval->assign_reg(stack_slot);1195}1196}1197}11981199void LinearScan::handle_doubleword_moves(LIR_Op* op) {1200// special handling for doubleword move from memory to register:1201// in this case the registers of the input address and the result1202// registers must not overlap -> add a temp range for the input registers1203if (op->code() == lir_move) {1204assert(op->as_Op1() != NULL, "must be LIR_Op1");1205LIR_Op1* move = (LIR_Op1*)op;12061207if (move->result_opr()->is_double_cpu() && move->in_opr()->is_pointer()) {1208LIR_Address* address = move->in_opr()->as_address_ptr();1209if (address != NULL) {1210if (address->base()->is_valid()) {1211add_temp(address->base(), op->id(), noUse);1212}1213if (address->index()->is_valid()) {1214add_temp(address->index(), op->id(), noUse);1215}1216}1217}1218}1219}12201221void LinearScan::add_register_hints(LIR_Op* op) {1222switch (op->code()) {1223case lir_move: // fall through1224case lir_convert: {1225assert(op->as_Op1() != NULL, "lir_move, lir_convert must be LIR_Op1");1226LIR_Op1* move = (LIR_Op1*)op;12271228LIR_Opr move_from = move->in_opr();1229LIR_Opr move_to = move->result_opr();12301231if (move_to->is_register() && move_from->is_register()) {1232Interval* from = interval_at(reg_num(move_from));1233Interval* to = interval_at(reg_num(move_to));1234if (from != NULL && to != NULL) {1235to->set_register_hint(from);1236TRACE_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()));1237}1238}1239break;1240}1241case lir_cmove: {1242assert(op->as_Op2() != NULL, "lir_cmove must be LIR_Op2");1243LIR_Op2* cmove = (LIR_Op2*)op;12441245LIR_Opr move_from = cmove->in_opr1();1246LIR_Opr move_to = cmove->result_opr();12471248if (move_to->is_register() && move_from->is_register()) {1249Interval* from = interval_at(reg_num(move_from));1250Interval* to = interval_at(reg_num(move_to));1251if (from != NULL && to != NULL) {1252to->set_register_hint(from);1253TRACE_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()));1254}1255}1256break;1257}1258default:1259break;1260}1261}126212631264void LinearScan::build_intervals() {1265TIME_LINEAR_SCAN(timer_build_intervals);12661267// initialize interval list with expected number of intervals1268// (32 is added to have some space for split children without having to resize the list)1269_intervals = IntervalList(num_virtual_regs() + 32);1270// initialize all slots that are used by build_intervals1271_intervals.at_put_grow(num_virtual_regs() - 1, NULL, NULL);12721273// create a list with all caller-save registers (cpu, fpu, xmm)1274// when an instruction is a call, a temp range is created for all these registers1275int num_caller_save_registers = 0;1276int caller_save_registers[LinearScan::nof_regs];12771278int i;1279for (i = 0; i < FrameMap::nof_caller_save_cpu_regs(); i++) {1280LIR_Opr opr = FrameMap::caller_save_cpu_reg_at(i);1281assert(opr->is_valid() && opr->is_register(), "FrameMap should not return invalid operands");1282assert(reg_numHi(opr) == -1, "missing addition of range for hi-register");1283caller_save_registers[num_caller_save_registers++] = reg_num(opr);1284}12851286// temp ranges for fpu registers are only created when the method has1287// virtual fpu operands. Otherwise no allocation for fpu registers is1288// performed and so the temp ranges would be useless1289if (has_fpu_registers()) {1290#ifdef X861291if (UseSSE < 2) {1292#endif // X861293for (i = 0; i < FrameMap::nof_caller_save_fpu_regs; i++) {1294LIR_Opr opr = FrameMap::caller_save_fpu_reg_at(i);1295assert(opr->is_valid() && opr->is_register(), "FrameMap should not return invalid operands");1296assert(reg_numHi(opr) == -1, "missing addition of range for hi-register");1297caller_save_registers[num_caller_save_registers++] = reg_num(opr);1298}1299#ifdef X861300}1301#endif // X8613021303#ifdef X861304if (UseSSE > 0) {1305int num_caller_save_xmm_regs = FrameMap::get_num_caller_save_xmms();1306for (i = 0; i < num_caller_save_xmm_regs; i ++) {1307LIR_Opr opr = FrameMap::caller_save_xmm_reg_at(i);1308assert(opr->is_valid() && opr->is_register(), "FrameMap should not return invalid operands");1309assert(reg_numHi(opr) == -1, "missing addition of range for hi-register");1310caller_save_registers[num_caller_save_registers++] = reg_num(opr);1311}1312}1313#endif // X861314}1315assert(num_caller_save_registers <= LinearScan::nof_regs, "out of bounds");131613171318LIR_OpVisitState visitor;13191320// iterate all blocks in reverse order1321for (i = block_count() - 1; i >= 0; i--) {1322BlockBegin* block = block_at(i);1323LIR_OpList* instructions = block->lir()->instructions_list();1324int block_from = block->first_lir_instruction_id();1325int block_to = block->last_lir_instruction_id();13261327assert(block_from == instructions->at(0)->id(), "must be");1328assert(block_to == instructions->at(instructions->length() - 1)->id(), "must be");13291330// Update intervals for registers live at the end of this block;1331ResourceBitMap live = block->live_out();1332int size = (int)live.size();1333for (int number = (int)live.get_next_one_offset(0, size); number < size; number = (int)live.get_next_one_offset(number + 1, size)) {1334assert(live.at(number), "should not stop here otherwise");1335assert(number >= LIR_OprDesc::vreg_base, "fixed intervals must not be live on block bounds");1336TRACE_LINEAR_SCAN(2, tty->print_cr("live in %d to %d", number, block_to + 2));13371338add_use(number, block_from, block_to + 2, noUse, T_ILLEGAL);13391340// add special use positions for loop-end blocks when the1341// interval is used anywhere inside this loop. It's possible1342// that the block was part of a non-natural loop, so it might1343// have an invalid loop index.1344if (block->is_set(BlockBegin::linear_scan_loop_end_flag) &&1345block->loop_index() != -1 &&1346is_interval_in_loop(number, block->loop_index())) {1347interval_at(number)->add_use_pos(block_to + 1, loopEndMarker);1348}1349}13501351// iterate all instructions of the block in reverse order.1352// skip the first instruction because it is always a label1353// definitions of intervals are processed before uses1354assert(visitor.no_operands(instructions->at(0)), "first operation must always be a label");1355for (int j = instructions->length() - 1; j >= 1; j--) {1356LIR_Op* op = instructions->at(j);1357int op_id = op->id();13581359// visit operation to collect all operands1360visitor.visit(op);13611362// add a temp range for each register if operation destroys caller-save registers1363if (visitor.has_call()) {1364for (int k = 0; k < num_caller_save_registers; k++) {1365add_temp(caller_save_registers[k], op_id, noUse, T_ILLEGAL);1366}1367TRACE_LINEAR_SCAN(4, tty->print_cr("operation destroys all caller-save registers"));1368}13691370// Add any platform dependent temps1371pd_add_temps(op);13721373// visit definitions (output and temp operands)1374int k, n;1375n = visitor.opr_count(LIR_OpVisitState::outputMode);1376for (k = 0; k < n; k++) {1377LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::outputMode, k);1378assert(opr->is_register(), "visitor should only return register operands");1379add_def(opr, op_id, use_kind_of_output_operand(op, opr));1380}13811382n = visitor.opr_count(LIR_OpVisitState::tempMode);1383for (k = 0; k < n; k++) {1384LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::tempMode, k);1385assert(opr->is_register(), "visitor should only return register operands");1386add_temp(opr, op_id, mustHaveRegister);1387}13881389// visit uses (input operands)1390n = visitor.opr_count(LIR_OpVisitState::inputMode);1391for (k = 0; k < n; k++) {1392LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::inputMode, k);1393assert(opr->is_register(), "visitor should only return register operands");1394add_use(opr, block_from, op_id, use_kind_of_input_operand(op, opr));1395}13961397// Add uses of live locals from interpreter's point of view for proper1398// debug information generation1399// Treat these operands as temp values (if the life range is extended1400// to a call site, the value would be in a register at the call otherwise)1401n = visitor.info_count();1402for (k = 0; k < n; k++) {1403CodeEmitInfo* info = visitor.info_at(k);1404ValueStack* stack = info->stack();1405for_each_state_value(stack, value,1406add_use(value, block_from, op_id + 1, noUse);1407);1408}14091410// special steps for some instructions (especially moves)1411handle_method_arguments(op);1412handle_doubleword_moves(op);1413add_register_hints(op);14141415} // end of instruction iteration1416} // end of block iteration141714181419// add the range [0, 1[ to all fixed intervals1420// -> the register allocator need not handle unhandled fixed intervals1421for (int n = 0; n < LinearScan::nof_regs; n++) {1422Interval* interval = interval_at(n);1423if (interval != NULL) {1424interval->add_range(0, 1);1425}1426}1427}142814291430// ********** Phase 5: actual register allocation14311432int LinearScan::interval_cmp(Interval** a, Interval** b) {1433if (*a != NULL) {1434if (*b != NULL) {1435return (*a)->from() - (*b)->from();1436} else {1437return -1;1438}1439} else {1440if (*b != NULL) {1441return 1;1442} else {1443return 0;1444}1445}1446}14471448#ifndef PRODUCT1449int interval_cmp(Interval* const& l, Interval* const& r) {1450return l->from() - r->from();1451}14521453bool find_interval(Interval* interval, IntervalArray* intervals) {1454bool found;1455int idx = intervals->find_sorted<Interval*, interval_cmp>(interval, found);14561457if (!found) {1458return false;1459}14601461int from = interval->from();14621463// The index we've found using binary search is pointing to an interval1464// that is defined in the same place as the interval we were looking for.1465// So now we have to look around that index and find exact interval.1466for (int i = idx; i >= 0; i--) {1467if (intervals->at(i) == interval) {1468return true;1469}1470if (intervals->at(i)->from() != from) {1471break;1472}1473}14741475for (int i = idx + 1; i < intervals->length(); i++) {1476if (intervals->at(i) == interval) {1477return true;1478}1479if (intervals->at(i)->from() != from) {1480break;1481}1482}14831484return false;1485}14861487bool LinearScan::is_sorted(IntervalArray* intervals) {1488int from = -1;1489int null_count = 0;14901491for (int i = 0; i < intervals->length(); i++) {1492Interval* it = intervals->at(i);1493if (it != NULL) {1494assert(from <= it->from(), "Intervals are unordered");1495from = it->from();1496} else {1497null_count++;1498}1499}15001501assert(null_count == 0, "Sorted intervals should not contain nulls");15021503null_count = 0;15041505for (int i = 0; i < interval_count(); i++) {1506Interval* interval = interval_at(i);1507if (interval != NULL) {1508assert(find_interval(interval, intervals), "Lists do not contain same intervals");1509} else {1510null_count++;1511}1512}15131514assert(interval_count() - null_count == intervals->length(),1515"Sorted list should contain the same amount of non-NULL intervals as unsorted list");15161517return true;1518}1519#endif15201521void LinearScan::add_to_list(Interval** first, Interval** prev, Interval* interval) {1522if (*prev != NULL) {1523(*prev)->set_next(interval);1524} else {1525*first = interval;1526}1527*prev = interval;1528}15291530void LinearScan::create_unhandled_lists(Interval** list1, Interval** list2, bool (is_list1)(const Interval* i), bool (is_list2)(const Interval* i)) {1531assert(is_sorted(_sorted_intervals), "interval list is not sorted");15321533*list1 = *list2 = Interval::end();15341535Interval* list1_prev = NULL;1536Interval* list2_prev = NULL;1537Interval* v;15381539const int n = _sorted_intervals->length();1540for (int i = 0; i < n; i++) {1541v = _sorted_intervals->at(i);1542if (v == NULL) continue;15431544if (is_list1(v)) {1545add_to_list(list1, &list1_prev, v);1546} else if (is_list2 == NULL || is_list2(v)) {1547add_to_list(list2, &list2_prev, v);1548}1549}15501551if (list1_prev != NULL) list1_prev->set_next(Interval::end());1552if (list2_prev != NULL) list2_prev->set_next(Interval::end());15531554assert(list1_prev == NULL || list1_prev->next() == Interval::end(), "linear list ends not with sentinel");1555assert(list2_prev == NULL || list2_prev->next() == Interval::end(), "linear list ends not with sentinel");1556}155715581559void LinearScan::sort_intervals_before_allocation() {1560TIME_LINEAR_SCAN(timer_sort_intervals_before);15611562if (_needs_full_resort) {1563// There is no known reason why this should occur but just in case...1564assert(false, "should never occur");1565// Re-sort existing interval list because an Interval::from() has changed1566_sorted_intervals->sort(interval_cmp);1567_needs_full_resort = false;1568}15691570IntervalList* unsorted_list = &_intervals;1571int unsorted_len = unsorted_list->length();1572int sorted_len = 0;1573int unsorted_idx;1574int sorted_idx = 0;1575int sorted_from_max = -1;15761577// calc number of items for sorted list (sorted list must not contain NULL values)1578for (unsorted_idx = 0; unsorted_idx < unsorted_len; unsorted_idx++) {1579if (unsorted_list->at(unsorted_idx) != NULL) {1580sorted_len++;1581}1582}1583IntervalArray* sorted_list = new IntervalArray(sorted_len, sorted_len, NULL);15841585// special sorting algorithm: the original interval-list is almost sorted,1586// only some intervals are swapped. So this is much faster than a complete QuickSort1587for (unsorted_idx = 0; unsorted_idx < unsorted_len; unsorted_idx++) {1588Interval* cur_interval = unsorted_list->at(unsorted_idx);15891590if (cur_interval != NULL) {1591int cur_from = cur_interval->from();15921593if (sorted_from_max <= cur_from) {1594sorted_list->at_put(sorted_idx++, cur_interval);1595sorted_from_max = cur_interval->from();1596} else {1597// the asumption that the intervals are already sorted failed,1598// so this interval must be sorted in manually1599int j;1600for (j = sorted_idx - 1; j >= 0 && cur_from < sorted_list->at(j)->from(); j--) {1601sorted_list->at_put(j + 1, sorted_list->at(j));1602}1603sorted_list->at_put(j + 1, cur_interval);1604sorted_idx++;1605}1606}1607}1608_sorted_intervals = sorted_list;1609assert(is_sorted(_sorted_intervals), "intervals unsorted");1610}16111612void LinearScan::sort_intervals_after_allocation() {1613TIME_LINEAR_SCAN(timer_sort_intervals_after);16141615if (_needs_full_resort) {1616// Re-sort existing interval list because an Interval::from() has changed1617_sorted_intervals->sort(interval_cmp);1618_needs_full_resort = false;1619}16201621IntervalArray* old_list = _sorted_intervals;1622IntervalList* new_list = _new_intervals_from_allocation;1623int old_len = old_list->length();1624int new_len = new_list == NULL ? 0 : new_list->length();16251626if (new_len == 0) {1627// no intervals have been added during allocation, so sorted list is already up to date1628assert(is_sorted(_sorted_intervals), "intervals unsorted");1629return;1630}16311632// conventional sort-algorithm for new intervals1633new_list->sort(interval_cmp);16341635// merge old and new list (both already sorted) into one combined list1636int combined_list_len = old_len + new_len;1637IntervalArray* combined_list = new IntervalArray(combined_list_len, combined_list_len, NULL);1638int old_idx = 0;1639int new_idx = 0;16401641while (old_idx + new_idx < old_len + new_len) {1642if (new_idx >= new_len || (old_idx < old_len && old_list->at(old_idx)->from() <= new_list->at(new_idx)->from())) {1643combined_list->at_put(old_idx + new_idx, old_list->at(old_idx));1644old_idx++;1645} else {1646combined_list->at_put(old_idx + new_idx, new_list->at(new_idx));1647new_idx++;1648}1649}16501651_sorted_intervals = combined_list;1652assert(is_sorted(_sorted_intervals), "intervals unsorted");1653}165416551656void LinearScan::allocate_registers() {1657TIME_LINEAR_SCAN(timer_allocate_registers);16581659Interval* precolored_cpu_intervals, *not_precolored_cpu_intervals;1660Interval* precolored_fpu_intervals, *not_precolored_fpu_intervals;16611662// collect cpu intervals1663create_unhandled_lists(&precolored_cpu_intervals, ¬_precolored_cpu_intervals,1664is_precolored_cpu_interval, is_virtual_cpu_interval);16651666// collect fpu intervals1667create_unhandled_lists(&precolored_fpu_intervals, ¬_precolored_fpu_intervals,1668is_precolored_fpu_interval, is_virtual_fpu_interval);1669// this fpu interval collection cannot be moved down below with the allocation section as1670// the cpu_lsw.walk() changes interval positions.16711672if (!has_fpu_registers()) {1673#ifdef ASSERT1674assert(not_precolored_fpu_intervals == Interval::end(), "missed an uncolored fpu interval");1675#else1676if (not_precolored_fpu_intervals != Interval::end()) {1677BAILOUT("missed an uncolored fpu interval");1678}1679#endif1680}16811682// allocate cpu registers1683LinearScanWalker cpu_lsw(this, precolored_cpu_intervals, not_precolored_cpu_intervals);1684cpu_lsw.walk();1685cpu_lsw.finish_allocation();16861687if (has_fpu_registers()) {1688// allocate fpu registers1689LinearScanWalker fpu_lsw(this, precolored_fpu_intervals, not_precolored_fpu_intervals);1690fpu_lsw.walk();1691fpu_lsw.finish_allocation();1692}1693}169416951696// ********** Phase 6: resolve data flow1697// (insert moves at edges between blocks if intervals have been split)16981699// wrapper for Interval::split_child_at_op_id that performs a bailout in product mode1700// instead of returning NULL1701Interval* LinearScan::split_child_at_op_id(Interval* interval, int op_id, LIR_OpVisitState::OprMode mode) {1702Interval* result = interval->split_child_at_op_id(op_id, mode);1703if (result != NULL) {1704return result;1705}17061707assert(false, "must find an interval, but do a clean bailout in product mode");1708result = new Interval(LIR_OprDesc::vreg_base);1709result->assign_reg(0);1710result->set_type(T_INT);1711BAILOUT_("LinearScan: interval is NULL", result);1712}171317141715Interval* LinearScan::interval_at_block_begin(BlockBegin* block, int reg_num) {1716assert(LinearScan::nof_regs <= reg_num && reg_num < num_virtual_regs(), "register number out of bounds");1717assert(interval_at(reg_num) != NULL, "no interval found");17181719return split_child_at_op_id(interval_at(reg_num), block->first_lir_instruction_id(), LIR_OpVisitState::outputMode);1720}17211722Interval* LinearScan::interval_at_block_end(BlockBegin* block, int reg_num) {1723assert(LinearScan::nof_regs <= reg_num && reg_num < num_virtual_regs(), "register number out of bounds");1724assert(interval_at(reg_num) != NULL, "no interval found");17251726return split_child_at_op_id(interval_at(reg_num), block->last_lir_instruction_id() + 1, LIR_OpVisitState::outputMode);1727}17281729Interval* LinearScan::interval_at_op_id(int reg_num, int op_id) {1730assert(LinearScan::nof_regs <= reg_num && reg_num < num_virtual_regs(), "register number out of bounds");1731assert(interval_at(reg_num) != NULL, "no interval found");17321733return split_child_at_op_id(interval_at(reg_num), op_id, LIR_OpVisitState::inputMode);1734}173517361737void LinearScan::resolve_collect_mappings(BlockBegin* from_block, BlockBegin* to_block, MoveResolver &move_resolver) {1738DEBUG_ONLY(move_resolver.check_empty());17391740const int size = live_set_size();1741const ResourceBitMap live_at_edge = to_block->live_in();17421743// visit all registers where the live_at_edge bit is set1744for (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)) {1745assert(r < num_virtual_regs(), "live information set for not exisiting interval");1746assert(from_block->live_out().at(r) && to_block->live_in().at(r), "interval not live at this edge");17471748Interval* from_interval = interval_at_block_end(from_block, r);1749Interval* to_interval = interval_at_block_begin(to_block, r);17501751if (from_interval != to_interval && (from_interval->assigned_reg() != to_interval->assigned_reg() || from_interval->assigned_regHi() != to_interval->assigned_regHi())) {1752// need to insert move instruction1753move_resolver.add_mapping(from_interval, to_interval);1754}1755}1756}175717581759void LinearScan::resolve_find_insert_pos(BlockBegin* from_block, BlockBegin* to_block, MoveResolver &move_resolver) {1760if (from_block->number_of_sux() <= 1) {1761TRACE_LINEAR_SCAN(4, tty->print_cr("inserting moves at end of from_block B%d", from_block->block_id()));17621763LIR_OpList* instructions = from_block->lir()->instructions_list();1764LIR_OpBranch* branch = instructions->last()->as_OpBranch();1765if (branch != NULL) {1766// insert moves before branch1767assert(branch->cond() == lir_cond_always, "block does not end with an unconditional jump");1768move_resolver.set_insert_position(from_block->lir(), instructions->length() - 2);1769} else {1770move_resolver.set_insert_position(from_block->lir(), instructions->length() - 1);1771}17721773} else {1774TRACE_LINEAR_SCAN(4, tty->print_cr("inserting moves at beginning of to_block B%d", to_block->block_id()));1775#ifdef ASSERT1776assert(from_block->lir()->instructions_list()->at(0)->as_OpLabel() != NULL, "block does not start with a label");17771778// because the number of predecessor edges matches the number of1779// successor edges, blocks which are reached by switch statements1780// may have be more than one predecessor but it will be guaranteed1781// that all predecessors will be the same.1782for (int i = 0; i < to_block->number_of_preds(); i++) {1783assert(from_block == to_block->pred_at(i), "all critical edges must be broken");1784}1785#endif17861787move_resolver.set_insert_position(to_block->lir(), 0);1788}1789}179017911792// insert necessary moves (spilling or reloading) at edges between blocks if interval has been split1793void LinearScan::resolve_data_flow() {1794TIME_LINEAR_SCAN(timer_resolve_data_flow);17951796int num_blocks = block_count();1797MoveResolver move_resolver(this);1798ResourceBitMap block_completed(num_blocks);1799ResourceBitMap already_resolved(num_blocks);18001801int i;1802for (i = 0; i < num_blocks; i++) {1803BlockBegin* block = block_at(i);18041805// check if block has only one predecessor and only one successor1806if (block->number_of_preds() == 1 && block->number_of_sux() == 1 && block->number_of_exception_handlers() == 0) {1807LIR_OpList* instructions = block->lir()->instructions_list();1808assert(instructions->at(0)->code() == lir_label, "block must start with label");1809assert(instructions->last()->code() == lir_branch, "block with successors must end with branch");1810assert(instructions->last()->as_OpBranch()->cond() == lir_cond_always, "block with successor must end with unconditional branch");18111812// check if block is empty (only label and branch)1813if (instructions->length() == 2) {1814BlockBegin* pred = block->pred_at(0);1815BlockBegin* sux = block->sux_at(0);18161817// prevent optimization of two consecutive blocks1818if (!block_completed.at(pred->linear_scan_number()) && !block_completed.at(sux->linear_scan_number())) {1819TRACE_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()));1820block_completed.set_bit(block->linear_scan_number());18211822// directly resolve between pred and sux (without looking at the empty block between)1823resolve_collect_mappings(pred, sux, move_resolver);1824if (move_resolver.has_mappings()) {1825move_resolver.set_insert_position(block->lir(), 0);1826move_resolver.resolve_and_append_moves();1827}1828}1829}1830}1831}183218331834for (i = 0; i < num_blocks; i++) {1835if (!block_completed.at(i)) {1836BlockBegin* from_block = block_at(i);1837already_resolved.set_from(block_completed);18381839int num_sux = from_block->number_of_sux();1840for (int s = 0; s < num_sux; s++) {1841BlockBegin* to_block = from_block->sux_at(s);18421843// check for duplicate edges between the same blocks (can happen with switch blocks)1844if (!already_resolved.at(to_block->linear_scan_number())) {1845TRACE_LINEAR_SCAN(3, tty->print_cr("**** processing edge between B%d and B%d", from_block->block_id(), to_block->block_id()));1846already_resolved.set_bit(to_block->linear_scan_number());18471848// collect all intervals that have been split between from_block and to_block1849resolve_collect_mappings(from_block, to_block, move_resolver);1850if (move_resolver.has_mappings()) {1851resolve_find_insert_pos(from_block, to_block, move_resolver);1852move_resolver.resolve_and_append_moves();1853}1854}1855}1856}1857}1858}185918601861void LinearScan::resolve_exception_entry(BlockBegin* block, int reg_num, MoveResolver &move_resolver) {1862if (interval_at(reg_num) == NULL) {1863// if a phi function is never used, no interval is created -> ignore this1864return;1865}18661867Interval* interval = interval_at_block_begin(block, reg_num);1868int reg = interval->assigned_reg();1869int regHi = interval->assigned_regHi();18701871if ((reg < nof_regs && interval->always_in_memory()) ||1872(use_fpu_stack_allocation() && reg >= pd_first_fpu_reg && reg <= pd_last_fpu_reg)) {1873// the interval is split to get a short range that is located on the stack1874// in the following two cases:1875// * the interval started in memory (e.g. method parameter), but is currently in a register1876// this is an optimization for exception handling that reduces the number of moves that1877// are necessary for resolving the states when an exception uses this exception handler1878// * the interval would be on the fpu stack at the begin of the exception handler1879// this is not allowed because of the complicated fpu stack handling on Intel18801881// range that will be spilled to memory1882int from_op_id = block->first_lir_instruction_id();1883int to_op_id = from_op_id + 1; // short live range of length 11884assert(interval->from() <= from_op_id && interval->to() >= to_op_id,1885"no split allowed between exception entry and first instruction");18861887if (interval->from() != from_op_id) {1888// the part before from_op_id is unchanged1889interval = interval->split(from_op_id);1890interval->assign_reg(reg, regHi);1891append_interval(interval);1892} else {1893_needs_full_resort = true;1894}1895assert(interval->from() == from_op_id, "must be true now");18961897Interval* spilled_part = interval;1898if (interval->to() != to_op_id) {1899// the part after to_op_id is unchanged1900spilled_part = interval->split_from_start(to_op_id);1901append_interval(spilled_part);1902move_resolver.add_mapping(spilled_part, interval);1903}1904assign_spill_slot(spilled_part);19051906assert(spilled_part->from() == from_op_id && spilled_part->to() == to_op_id, "just checking");1907}1908}19091910void LinearScan::resolve_exception_entry(BlockBegin* block, MoveResolver &move_resolver) {1911assert(block->is_set(BlockBegin::exception_entry_flag), "should not call otherwise");1912DEBUG_ONLY(move_resolver.check_empty());19131914// visit all registers where the live_in bit is set1915int size = live_set_size();1916for (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)) {1917resolve_exception_entry(block, r, move_resolver);1918}19191920// the live_in bits are not set for phi functions of the xhandler entry, so iterate them separately1921for_each_phi_fun(block, phi,1922if (!phi->is_illegal()) { resolve_exception_entry(block, phi->operand()->vreg_number(), move_resolver); }1923);19241925if (move_resolver.has_mappings()) {1926// insert moves after first instruction1927move_resolver.set_insert_position(block->lir(), 0);1928move_resolver.resolve_and_append_moves();1929}1930}193119321933void LinearScan::resolve_exception_edge(XHandler* handler, int throwing_op_id, int reg_num, Phi* phi, MoveResolver &move_resolver) {1934if (interval_at(reg_num) == NULL) {1935// if a phi function is never used, no interval is created -> ignore this1936return;1937}19381939// the computation of to_interval is equal to resolve_collect_mappings,1940// but from_interval is more complicated because of phi functions1941BlockBegin* to_block = handler->entry_block();1942Interval* to_interval = interval_at_block_begin(to_block, reg_num);19431944if (phi != NULL) {1945// phi function of the exception entry block1946// no moves are created for this phi function in the LIR_Generator, so the1947// interval at the throwing instruction must be searched using the operands1948// of the phi function1949Value from_value = phi->operand_at(handler->phi_operand());19501951// with phi functions it can happen that the same from_value is used in1952// multiple mappings, so notify move-resolver that this is allowed1953move_resolver.set_multiple_reads_allowed();19541955Constant* con = from_value->as_Constant();1956if (con != NULL && (!con->is_pinned() || con->operand()->is_constant())) {1957// Need a mapping from constant to interval if unpinned (may have no register) or if the operand is a constant (no register).1958move_resolver.add_mapping(LIR_OprFact::value_type(con->type()), to_interval);1959} else {1960// search split child at the throwing op_id1961Interval* from_interval = interval_at_op_id(from_value->operand()->vreg_number(), throwing_op_id);1962move_resolver.add_mapping(from_interval, to_interval);1963}1964} else {1965// no phi function, so use reg_num also for from_interval1966// search split child at the throwing op_id1967Interval* from_interval = interval_at_op_id(reg_num, throwing_op_id);1968if (from_interval != to_interval) {1969// optimization to reduce number of moves: when to_interval is on stack and1970// the stack slot is known to be always correct, then no move is necessary1971if (!from_interval->always_in_memory() || from_interval->canonical_spill_slot() != to_interval->assigned_reg()) {1972move_resolver.add_mapping(from_interval, to_interval);1973}1974}1975}1976}19771978void LinearScan::resolve_exception_edge(XHandler* handler, int throwing_op_id, MoveResolver &move_resolver) {1979TRACE_LINEAR_SCAN(4, tty->print_cr("resolving exception handler B%d: throwing_op_id=%d", handler->entry_block()->block_id(), throwing_op_id));19801981DEBUG_ONLY(move_resolver.check_empty());1982assert(handler->lir_op_id() == -1, "already processed this xhandler");1983DEBUG_ONLY(handler->set_lir_op_id(throwing_op_id));1984assert(handler->entry_code() == NULL, "code already present");19851986// visit all registers where the live_in bit is set1987BlockBegin* block = handler->entry_block();1988int size = live_set_size();1989for (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)) {1990resolve_exception_edge(handler, throwing_op_id, r, NULL, move_resolver);1991}19921993// the live_in bits are not set for phi functions of the xhandler entry, so iterate them separately1994for_each_phi_fun(block, phi,1995if (!phi->is_illegal()) { resolve_exception_edge(handler, throwing_op_id, phi->operand()->vreg_number(), phi, move_resolver); }1996);19971998if (move_resolver.has_mappings()) {1999LIR_List* entry_code = new LIR_List(compilation());2000move_resolver.set_insert_position(entry_code, 0);2001move_resolver.resolve_and_append_moves();20022003entry_code->jump(handler->entry_block());2004handler->set_entry_code(entry_code);2005}2006}200720082009void LinearScan::resolve_exception_handlers() {2010MoveResolver move_resolver(this);2011LIR_OpVisitState visitor;2012int num_blocks = block_count();20132014int i;2015for (i = 0; i < num_blocks; i++) {2016BlockBegin* block = block_at(i);2017if (block->is_set(BlockBegin::exception_entry_flag)) {2018resolve_exception_entry(block, move_resolver);2019}2020}20212022for (i = 0; i < num_blocks; i++) {2023BlockBegin* block = block_at(i);2024LIR_List* ops = block->lir();2025int num_ops = ops->length();20262027// iterate all instructions of the block. skip the first because it is always a label2028assert(visitor.no_operands(ops->at(0)), "first operation must always be a label");2029for (int j = 1; j < num_ops; j++) {2030LIR_Op* op = ops->at(j);2031int op_id = op->id();20322033if (op_id != -1 && has_info(op_id)) {2034// visit operation to collect all operands2035visitor.visit(op);2036assert(visitor.info_count() > 0, "should not visit otherwise");20372038XHandlers* xhandlers = visitor.all_xhandler();2039int n = xhandlers->length();2040for (int k = 0; k < n; k++) {2041resolve_exception_edge(xhandlers->handler_at(k), op_id, move_resolver);2042}20432044#ifdef ASSERT2045} else {2046visitor.visit(op);2047assert(visitor.all_xhandler()->length() == 0, "missed exception handler");2048#endif2049}2050}2051}2052}205320542055// ********** Phase 7: assign register numbers back to LIR2056// (includes computation of debug information and oop maps)20572058VMReg LinearScan::vm_reg_for_interval(Interval* interval) {2059VMReg reg = interval->cached_vm_reg();2060if (!reg->is_valid() ) {2061reg = vm_reg_for_operand(operand_for_interval(interval));2062interval->set_cached_vm_reg(reg);2063}2064assert(reg == vm_reg_for_operand(operand_for_interval(interval)), "wrong cached value");2065return reg;2066}20672068VMReg LinearScan::vm_reg_for_operand(LIR_Opr opr) {2069assert(opr->is_oop(), "currently only implemented for oop operands");2070return frame_map()->regname(opr);2071}207220732074LIR_Opr LinearScan::operand_for_interval(Interval* interval) {2075LIR_Opr opr = interval->cached_opr();2076if (opr->is_illegal()) {2077opr = calc_operand_for_interval(interval);2078interval->set_cached_opr(opr);2079}20802081assert(opr == calc_operand_for_interval(interval), "wrong cached value");2082return opr;2083}20842085LIR_Opr LinearScan::calc_operand_for_interval(const Interval* interval) {2086int assigned_reg = interval->assigned_reg();2087BasicType type = interval->type();20882089if (assigned_reg >= nof_regs) {2090// stack slot2091assert(interval->assigned_regHi() == any_reg, "must not have hi register");2092return LIR_OprFact::stack(assigned_reg - nof_regs, type);20932094} else {2095// register2096switch (type) {2097case T_OBJECT: {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_oop(assigned_reg);2101}21022103case T_ADDRESS: {2104assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");2105assert(interval->assigned_regHi() == any_reg, "must not have hi register");2106return LIR_OprFact::single_cpu_address(assigned_reg);2107}21082109case T_METADATA: {2110assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");2111assert(interval->assigned_regHi() == any_reg, "must not have hi register");2112return LIR_OprFact::single_cpu_metadata(assigned_reg);2113}21142115#ifdef __SOFTFP__2116case T_FLOAT: // fall through2117#endif // __SOFTFP__2118case T_INT: {2119assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");2120assert(interval->assigned_regHi() == any_reg, "must not have hi register");2121return LIR_OprFact::single_cpu(assigned_reg);2122}21232124#ifdef __SOFTFP__2125case T_DOUBLE: // fall through2126#endif // __SOFTFP__2127case T_LONG: {2128int assigned_regHi = interval->assigned_regHi();2129assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");2130assert(num_physical_regs(T_LONG) == 1 ||2131(assigned_regHi >= pd_first_cpu_reg && assigned_regHi <= pd_last_cpu_reg), "no cpu register");21322133assert(assigned_reg != assigned_regHi, "invalid allocation");2134assert(num_physical_regs(T_LONG) == 1 || assigned_reg < assigned_regHi,2135"register numbers must be sorted (ensure that e.g. a move from eax,ebx to ebx,eax can not occur)");2136assert((assigned_regHi != any_reg) ^ (num_physical_regs(T_LONG) == 1), "must be match");2137if (requires_adjacent_regs(T_LONG)) {2138assert(assigned_reg % 2 == 0 && assigned_reg + 1 == assigned_regHi, "must be sequential and even");2139}21402141#ifdef _LP642142return LIR_OprFact::double_cpu(assigned_reg, assigned_reg);2143#else2144#if defined(PPC32)2145return LIR_OprFact::double_cpu(assigned_regHi, assigned_reg);2146#else2147return LIR_OprFact::double_cpu(assigned_reg, assigned_regHi);2148#endif // PPC322149#endif // LP642150}21512152#ifndef __SOFTFP__2153case T_FLOAT: {2154#ifdef X862155if (UseSSE >= 1) {2156int last_xmm_reg = pd_last_xmm_reg;2157#ifdef _LP642158if (UseAVX < 3) {2159last_xmm_reg = pd_first_xmm_reg + (pd_nof_xmm_regs_frame_map / 2) - 1;2160}2161#endif // LP642162assert(assigned_reg >= pd_first_xmm_reg && assigned_reg <= last_xmm_reg, "no xmm register");2163assert(interval->assigned_regHi() == any_reg, "must not have hi register");2164return LIR_OprFact::single_xmm(assigned_reg - pd_first_xmm_reg);2165}2166#endif // X8621672168assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");2169assert(interval->assigned_regHi() == any_reg, "must not have hi register");2170return LIR_OprFact::single_fpu(assigned_reg - pd_first_fpu_reg);2171}21722173case T_DOUBLE: {2174#ifdef X862175if (UseSSE >= 2) {2176int last_xmm_reg = pd_last_xmm_reg;2177#ifdef _LP642178if (UseAVX < 3) {2179last_xmm_reg = pd_first_xmm_reg + (pd_nof_xmm_regs_frame_map / 2) - 1;2180}2181#endif // LP642182assert(assigned_reg >= pd_first_xmm_reg && assigned_reg <= last_xmm_reg, "no xmm register");2183assert(interval->assigned_regHi() == any_reg, "must not have hi register (double xmm values are stored in one register)");2184return LIR_OprFact::double_xmm(assigned_reg - pd_first_xmm_reg);2185}2186#endif // X8621872188#if defined(ARM32)2189assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");2190assert(interval->assigned_regHi() >= pd_first_fpu_reg && interval->assigned_regHi() <= pd_last_fpu_reg, "no fpu register");2191assert(assigned_reg % 2 == 0 && assigned_reg + 1 == interval->assigned_regHi(), "must be sequential and even");2192LIR_Opr result = LIR_OprFact::double_fpu(assigned_reg - pd_first_fpu_reg, interval->assigned_regHi() - pd_first_fpu_reg);2193#else2194assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");2195assert(interval->assigned_regHi() == any_reg, "must not have hi register (double fpu values are stored in one register on Intel)");2196LIR_Opr result = LIR_OprFact::double_fpu(assigned_reg - pd_first_fpu_reg);2197#endif2198return result;2199}2200#endif // __SOFTFP__22012202default: {2203ShouldNotReachHere();2204return LIR_OprFact::illegalOpr;2205}2206}2207}2208}22092210LIR_Opr LinearScan::canonical_spill_opr(Interval* interval) {2211assert(interval->canonical_spill_slot() >= nof_regs, "canonical spill slot not set");2212return LIR_OprFact::stack(interval->canonical_spill_slot() - nof_regs, interval->type());2213}22142215LIR_Opr LinearScan::color_lir_opr(LIR_Opr opr, int op_id, LIR_OpVisitState::OprMode mode) {2216assert(opr->is_virtual(), "should not call this otherwise");22172218Interval* interval = interval_at(opr->vreg_number());2219assert(interval != NULL, "interval must exist");22202221if (op_id != -1) {2222#ifdef ASSERT2223BlockBegin* block = block_of_op_with_id(op_id);2224if (block->number_of_sux() <= 1 && op_id == block->last_lir_instruction_id()) {2225// check if spill moves could have been appended at the end of this block, but2226// before the branch instruction. So the split child information for this branch would2227// be incorrect.2228LIR_OpBranch* branch = block->lir()->instructions_list()->last()->as_OpBranch();2229if (branch != NULL) {2230if (block->live_out().at(opr->vreg_number())) {2231assert(branch->cond() == lir_cond_always, "block does not end with an unconditional jump");2232assert(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)");2233}2234}2235}2236#endif22372238// operands are not changed when an interval is split during allocation,2239// so search the right interval here2240interval = split_child_at_op_id(interval, op_id, mode);2241}22422243LIR_Opr res = operand_for_interval(interval);22442245#ifdef X862246// new semantic for is_last_use: not only set on definite end of interval,2247// but also before hole2248// This may still miss some cases (e.g. for dead values), but it is not necessary that the2249// last use information is completely correct2250// information is only needed for fpu stack allocation2251if (res->is_fpu_register()) {2252if (opr->is_last_use() || op_id == interval->to() || (op_id != -1 && interval->has_hole_between(op_id, op_id + 1))) {2253assert(op_id == -1 || !is_block_begin(op_id), "holes at begin of block may also result from control flow");2254res = res->make_last_use();2255}2256}2257#endif22582259assert(!gen()->is_vreg_flag_set(opr->vreg_number(), LIRGenerator::callee_saved) || !FrameMap::is_caller_save_register(res), "bad allocation");22602261return res;2262}226322642265#ifdef ASSERT2266// some methods used to check correctness of debug information22672268void assert_no_register_values(GrowableArray<ScopeValue*>* values) {2269if (values == NULL) {2270return;2271}22722273for (int i = 0; i < values->length(); i++) {2274ScopeValue* value = values->at(i);22752276if (value->is_location()) {2277Location location = ((LocationValue*)value)->location();2278assert(location.where() == Location::on_stack, "value is in register");2279}2280}2281}22822283void assert_no_register_values(GrowableArray<MonitorValue*>* values) {2284if (values == NULL) {2285return;2286}22872288for (int i = 0; i < values->length(); i++) {2289MonitorValue* value = values->at(i);22902291if (value->owner()->is_location()) {2292Location location = ((LocationValue*)value->owner())->location();2293assert(location.where() == Location::on_stack, "owner is in register");2294}2295assert(value->basic_lock().where() == Location::on_stack, "basic_lock is in register");2296}2297}22982299void assert_equal(Location l1, Location l2) {2300assert(l1.where() == l2.where() && l1.type() == l2.type() && l1.offset() == l2.offset(), "");2301}23022303void assert_equal(ScopeValue* v1, ScopeValue* v2) {2304if (v1->is_location()) {2305assert(v2->is_location(), "");2306assert_equal(((LocationValue*)v1)->location(), ((LocationValue*)v2)->location());2307} else if (v1->is_constant_int()) {2308assert(v2->is_constant_int(), "");2309assert(((ConstantIntValue*)v1)->value() == ((ConstantIntValue*)v2)->value(), "");2310} else if (v1->is_constant_double()) {2311assert(v2->is_constant_double(), "");2312assert(((ConstantDoubleValue*)v1)->value() == ((ConstantDoubleValue*)v2)->value(), "");2313} else if (v1->is_constant_long()) {2314assert(v2->is_constant_long(), "");2315assert(((ConstantLongValue*)v1)->value() == ((ConstantLongValue*)v2)->value(), "");2316} else if (v1->is_constant_oop()) {2317assert(v2->is_constant_oop(), "");2318assert(((ConstantOopWriteValue*)v1)->value() == ((ConstantOopWriteValue*)v2)->value(), "");2319} else {2320ShouldNotReachHere();2321}2322}23232324void assert_equal(MonitorValue* m1, MonitorValue* m2) {2325assert_equal(m1->owner(), m2->owner());2326assert_equal(m1->basic_lock(), m2->basic_lock());2327}23282329void assert_equal(IRScopeDebugInfo* d1, IRScopeDebugInfo* d2) {2330assert(d1->scope() == d2->scope(), "not equal");2331assert(d1->bci() == d2->bci(), "not equal");23322333if (d1->locals() != NULL) {2334assert(d1->locals() != NULL && d2->locals() != NULL, "not equal");2335assert(d1->locals()->length() == d2->locals()->length(), "not equal");2336for (int i = 0; i < d1->locals()->length(); i++) {2337assert_equal(d1->locals()->at(i), d2->locals()->at(i));2338}2339} else {2340assert(d1->locals() == NULL && d2->locals() == NULL, "not equal");2341}23422343if (d1->expressions() != NULL) {2344assert(d1->expressions() != NULL && d2->expressions() != NULL, "not equal");2345assert(d1->expressions()->length() == d2->expressions()->length(), "not equal");2346for (int i = 0; i < d1->expressions()->length(); i++) {2347assert_equal(d1->expressions()->at(i), d2->expressions()->at(i));2348}2349} else {2350assert(d1->expressions() == NULL && d2->expressions() == NULL, "not equal");2351}23522353if (d1->monitors() != NULL) {2354assert(d1->monitors() != NULL && d2->monitors() != NULL, "not equal");2355assert(d1->monitors()->length() == d2->monitors()->length(), "not equal");2356for (int i = 0; i < d1->monitors()->length(); i++) {2357assert_equal(d1->monitors()->at(i), d2->monitors()->at(i));2358}2359} else {2360assert(d1->monitors() == NULL && d2->monitors() == NULL, "not equal");2361}23622363if (d1->caller() != NULL) {2364assert(d1->caller() != NULL && d2->caller() != NULL, "not equal");2365assert_equal(d1->caller(), d2->caller());2366} else {2367assert(d1->caller() == NULL && d2->caller() == NULL, "not equal");2368}2369}23702371void check_stack_depth(CodeEmitInfo* info, int stack_end) {2372if (info->stack()->bci() != SynchronizationEntryBCI && !info->scope()->method()->is_native()) {2373Bytecodes::Code code = info->scope()->method()->java_code_at_bci(info->stack()->bci());2374switch (code) {2375case Bytecodes::_ifnull : // fall through2376case Bytecodes::_ifnonnull : // fall through2377case Bytecodes::_ifeq : // fall through2378case Bytecodes::_ifne : // fall through2379case Bytecodes::_iflt : // fall through2380case Bytecodes::_ifge : // fall through2381case Bytecodes::_ifgt : // fall through2382case Bytecodes::_ifle : // fall through2383case Bytecodes::_if_icmpeq : // fall through2384case Bytecodes::_if_icmpne : // fall through2385case Bytecodes::_if_icmplt : // fall through2386case Bytecodes::_if_icmpge : // fall through2387case Bytecodes::_if_icmpgt : // fall through2388case Bytecodes::_if_icmple : // fall through2389case Bytecodes::_if_acmpeq : // fall through2390case Bytecodes::_if_acmpne :2391assert(stack_end >= -Bytecodes::depth(code), "must have non-empty expression stack at if bytecode");2392break;2393default:2394break;2395}2396}2397}23982399#endif // ASSERT240024012402IntervalWalker* LinearScan::init_compute_oop_maps() {2403// setup lists of potential oops for walking2404Interval* oop_intervals;2405Interval* non_oop_intervals;24062407create_unhandled_lists(&oop_intervals, &non_oop_intervals, is_oop_interval, NULL);24082409// intervals that have no oops inside need not to be processed2410// to ensure a walking until the last instruction id, add a dummy interval2411// with a high operation id2412non_oop_intervals = new Interval(any_reg);2413non_oop_intervals->add_range(max_jint - 2, max_jint - 1);24142415return new IntervalWalker(this, oop_intervals, non_oop_intervals);2416}241724182419OopMap* LinearScan::compute_oop_map(IntervalWalker* iw, LIR_Op* op, CodeEmitInfo* info, bool is_call_site) {2420TRACE_LINEAR_SCAN(3, tty->print_cr("creating oop map at op_id %d", op->id()));24212422// walk before the current operation -> intervals that start at2423// the operation (= output operands of the operation) are not2424// included in the oop map2425iw->walk_before(op->id());24262427int frame_size = frame_map()->framesize();2428int arg_count = frame_map()->oop_map_arg_count();2429OopMap* map = new OopMap(frame_size, arg_count);24302431// Iterate through active intervals2432for (Interval* interval = iw->active_first(fixedKind); interval != Interval::end(); interval = interval->next()) {2433int assigned_reg = interval->assigned_reg();24342435assert(interval->current_from() <= op->id() && op->id() <= interval->current_to(), "interval should not be active otherwise");2436assert(interval->assigned_regHi() == any_reg, "oop must be single word");2437assert(interval->reg_num() >= LIR_OprDesc::vreg_base, "fixed interval found");24382439// Check if this range covers the instruction. Intervals that2440// start or end at the current operation are not included in the2441// oop map, except in the case of patching moves. For patching2442// moves, any intervals which end at this instruction are included2443// in the oop map since we may safepoint while doing the patch2444// before we've consumed the inputs.2445if (op->is_patching() || op->id() < interval->current_to()) {24462447// caller-save registers must not be included into oop-maps at calls2448assert(!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");24492450VMReg name = vm_reg_for_interval(interval);2451set_oop(map, name);24522453// Spill optimization: when the stack value is guaranteed to be always correct,2454// then it must be added to the oop map even if the interval is currently in a register2455if (interval->always_in_memory() &&2456op->id() > interval->spill_definition_pos() &&2457interval->assigned_reg() != interval->canonical_spill_slot()) {2458assert(interval->spill_definition_pos() > 0, "position not set correctly");2459assert(interval->canonical_spill_slot() >= LinearScan::nof_regs, "no spill slot assigned");2460assert(interval->assigned_reg() < LinearScan::nof_regs, "interval is on stack, so stack slot is registered twice");24612462set_oop(map, frame_map()->slot_regname(interval->canonical_spill_slot() - LinearScan::nof_regs));2463}2464}2465}24662467// add oops from lock stack2468assert(info->stack() != NULL, "CodeEmitInfo must always have a stack");2469int locks_count = info->stack()->total_locks_size();2470for (int i = 0; i < locks_count; i++) {2471set_oop(map, frame_map()->monitor_object_regname(i));2472}24732474return map;2475}247624772478void LinearScan::compute_oop_map(IntervalWalker* iw, const LIR_OpVisitState &visitor, LIR_Op* op) {2479assert(visitor.info_count() > 0, "no oop map needed");24802481// compute oop_map only for first CodeEmitInfo2482// because it is (in most cases) equal for all other infos of the same operation2483CodeEmitInfo* first_info = visitor.info_at(0);2484OopMap* first_oop_map = compute_oop_map(iw, op, first_info, visitor.has_call());24852486for (int i = 0; i < visitor.info_count(); i++) {2487CodeEmitInfo* info = visitor.info_at(i);2488OopMap* oop_map = first_oop_map;24892490// compute worst case interpreter size in case of a deoptimization2491_compilation->update_interpreter_frame_size(info->interpreter_frame_size());24922493if (info->stack()->locks_size() != first_info->stack()->locks_size()) {2494// this info has a different number of locks then the precomputed oop map2495// (possible for lock and unlock instructions) -> compute oop map with2496// correct lock information2497oop_map = compute_oop_map(iw, op, info, visitor.has_call());2498}24992500if (info->_oop_map == NULL) {2501info->_oop_map = oop_map;2502} else {2503// a CodeEmitInfo can not be shared between different LIR-instructions2504// because interval splitting can occur anywhere between two instructions2505// and so the oop maps must be different2506// -> check if the already set oop_map is exactly the one calculated for this operation2507assert(info->_oop_map == oop_map, "same CodeEmitInfo used for multiple LIR instructions");2508}2509}2510}251125122513// frequently used constants2514// Allocate them with new so they are never destroyed (otherwise, a2515// forced exit could destroy these objects while they are still in2516// use).2517ConstantOopWriteValue* LinearScan::_oop_null_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantOopWriteValue(NULL);2518ConstantIntValue* LinearScan::_int_m1_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue(-1);2519ConstantIntValue* LinearScan::_int_0_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue((jint)0);2520ConstantIntValue* LinearScan::_int_1_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue(1);2521ConstantIntValue* LinearScan::_int_2_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue(2);2522LocationValue* _illegal_value = new (ResourceObj::C_HEAP, mtCompiler) LocationValue(Location());25232524void LinearScan::init_compute_debug_info() {2525// cache for frequently used scope values2526// (cpu registers and stack slots)2527int cache_size = (LinearScan::nof_cpu_regs + frame_map()->argcount() + max_spills()) * 2;2528_scope_value_cache = ScopeValueArray(cache_size, cache_size, NULL);2529}25302531MonitorValue* LinearScan::location_for_monitor_index(int monitor_index) {2532Location loc;2533if (!frame_map()->location_for_monitor_object(monitor_index, &loc)) {2534bailout("too large frame");2535}2536ScopeValue* object_scope_value = new LocationValue(loc);25372538if (!frame_map()->location_for_monitor_lock(monitor_index, &loc)) {2539bailout("too large frame");2540}2541return new MonitorValue(object_scope_value, loc);2542}25432544LocationValue* LinearScan::location_for_name(int name, Location::Type loc_type) {2545Location loc;2546if (!frame_map()->locations_for_slot(name, loc_type, &loc)) {2547bailout("too large frame");2548}2549return new LocationValue(loc);2550}255125522553int LinearScan::append_scope_value_for_constant(LIR_Opr opr, GrowableArray<ScopeValue*>* scope_values) {2554assert(opr->is_constant(), "should not be called otherwise");25552556LIR_Const* c = opr->as_constant_ptr();2557BasicType t = c->type();2558switch (t) {2559case T_OBJECT: {2560jobject value = c->as_jobject();2561if (value == NULL) {2562scope_values->append(_oop_null_scope_value);2563} else {2564scope_values->append(new ConstantOopWriteValue(c->as_jobject()));2565}2566return 1;2567}25682569case T_INT: // fall through2570case T_FLOAT: {2571int value = c->as_jint_bits();2572switch (value) {2573case -1: scope_values->append(_int_m1_scope_value); break;2574case 0: scope_values->append(_int_0_scope_value); break;2575case 1: scope_values->append(_int_1_scope_value); break;2576case 2: scope_values->append(_int_2_scope_value); break;2577default: scope_values->append(new ConstantIntValue(c->as_jint_bits())); break;2578}2579return 1;2580}25812582case T_LONG: // fall through2583case T_DOUBLE: {2584#ifdef _LP642585scope_values->append(_int_0_scope_value);2586scope_values->append(new ConstantLongValue(c->as_jlong_bits()));2587#else2588if (hi_word_offset_in_bytes > lo_word_offset_in_bytes) {2589scope_values->append(new ConstantIntValue(c->as_jint_hi_bits()));2590scope_values->append(new ConstantIntValue(c->as_jint_lo_bits()));2591} else {2592scope_values->append(new ConstantIntValue(c->as_jint_lo_bits()));2593scope_values->append(new ConstantIntValue(c->as_jint_hi_bits()));2594}2595#endif2596return 2;2597}25982599case T_ADDRESS: {2600#ifdef _LP642601scope_values->append(new ConstantLongValue(c->as_jint()));2602#else2603scope_values->append(new ConstantIntValue(c->as_jint()));2604#endif2605return 1;2606}26072608default:2609ShouldNotReachHere();2610return -1;2611}2612}26132614int LinearScan::append_scope_value_for_operand(LIR_Opr opr, GrowableArray<ScopeValue*>* scope_values) {2615if (opr->is_single_stack()) {2616int stack_idx = opr->single_stack_ix();2617bool is_oop = opr->is_oop_register();2618int cache_idx = (stack_idx + LinearScan::nof_cpu_regs) * 2 + (is_oop ? 1 : 0);26192620ScopeValue* sv = _scope_value_cache.at(cache_idx);2621if (sv == NULL) {2622Location::Type loc_type = is_oop ? Location::oop : Location::normal;2623sv = location_for_name(stack_idx, loc_type);2624_scope_value_cache.at_put(cache_idx, sv);2625}26262627// check if cached value is correct2628DEBUG_ONLY(assert_equal(sv, location_for_name(stack_idx, is_oop ? Location::oop : Location::normal)));26292630scope_values->append(sv);2631return 1;26322633} else if (opr->is_single_cpu()) {2634bool is_oop = opr->is_oop_register();2635int cache_idx = opr->cpu_regnr() * 2 + (is_oop ? 1 : 0);2636Location::Type int_loc_type = NOT_LP64(Location::normal) LP64_ONLY(Location::int_in_long);26372638ScopeValue* sv = _scope_value_cache.at(cache_idx);2639if (sv == NULL) {2640Location::Type loc_type = is_oop ? Location::oop : int_loc_type;2641VMReg rname = frame_map()->regname(opr);2642sv = new LocationValue(Location::new_reg_loc(loc_type, rname));2643_scope_value_cache.at_put(cache_idx, sv);2644}26452646// check if cached value is correct2647DEBUG_ONLY(assert_equal(sv, new LocationValue(Location::new_reg_loc(is_oop ? Location::oop : int_loc_type, frame_map()->regname(opr)))));26482649scope_values->append(sv);2650return 1;26512652#ifdef X862653} else if (opr->is_single_xmm()) {2654VMReg rname = opr->as_xmm_float_reg()->as_VMReg();2655LocationValue* sv = new LocationValue(Location::new_reg_loc(Location::normal, rname));26562657scope_values->append(sv);2658return 1;2659#endif26602661} else if (opr->is_single_fpu()) {2662#ifdef IA322663// the exact location of fpu stack values is only known2664// during fpu stack allocation, so the stack allocator object2665// must be present2666assert(use_fpu_stack_allocation(), "should not have float stack values without fpu stack allocation (all floats must be SSE2)");2667assert(_fpu_stack_allocator != NULL, "must be present");2668opr = _fpu_stack_allocator->to_fpu_stack(opr);2669#elif defined(AMD64)2670assert(false, "FPU not used on x86-64");2671#endif26722673Location::Type loc_type = float_saved_as_double ? Location::float_in_dbl : Location::normal;2674VMReg rname = frame_map()->fpu_regname(opr->fpu_regnr());2675#ifndef __SOFTFP__2676#ifndef VM_LITTLE_ENDIAN2677// On S390 a (single precision) float value occupies only the high2678// word of the full double register. So when the double register is2679// stored to memory (e.g. by the RegisterSaver), then the float value2680// is found at offset 0. I.e. the code below is not needed on S390.2681#ifndef S3902682if (! float_saved_as_double) {2683// On big endian system, we may have an issue if float registers use only2684// the low half of the (same) double registers.2685// Both the float and the double could have the same regnr but would correspond2686// to two different addresses once saved.26872688// get next safely (no assertion checks)2689VMReg next = VMRegImpl::as_VMReg(1+rname->value());2690if (next->is_reg() &&2691(next->as_FloatRegister() == rname->as_FloatRegister())) {2692// the back-end does use the same numbering for the double and the float2693rname = next; // VMReg for the low bits, e.g. the real VMReg for the float2694}2695}2696#endif // !S3902697#endif2698#endif2699LocationValue* sv = new LocationValue(Location::new_reg_loc(loc_type, rname));27002701scope_values->append(sv);2702return 1;27032704} else {2705// double-size operands27062707ScopeValue* first;2708ScopeValue* second;27092710if (opr->is_double_stack()) {2711#ifdef _LP642712Location loc1;2713Location::Type loc_type = opr->type() == T_LONG ? Location::lng : Location::dbl;2714if (!frame_map()->locations_for_slot(opr->double_stack_ix(), loc_type, &loc1, NULL)) {2715bailout("too large frame");2716}27172718first = new LocationValue(loc1);2719second = _int_0_scope_value;2720#else2721Location loc1, loc2;2722if (!frame_map()->locations_for_slot(opr->double_stack_ix(), Location::normal, &loc1, &loc2)) {2723bailout("too large frame");2724}2725first = new LocationValue(loc1);2726second = new LocationValue(loc2);2727#endif // _LP6427282729} else if (opr->is_double_cpu()) {2730#ifdef _LP642731VMReg rname_first = opr->as_register_lo()->as_VMReg();2732first = new LocationValue(Location::new_reg_loc(Location::lng, rname_first));2733second = _int_0_scope_value;2734#else2735VMReg rname_first = opr->as_register_lo()->as_VMReg();2736VMReg rname_second = opr->as_register_hi()->as_VMReg();27372738if (hi_word_offset_in_bytes < lo_word_offset_in_bytes) {2739// lo/hi and swapped relative to first and second, so swap them2740VMReg tmp = rname_first;2741rname_first = rname_second;2742rname_second = tmp;2743}27442745first = new LocationValue(Location::new_reg_loc(Location::normal, rname_first));2746second = new LocationValue(Location::new_reg_loc(Location::normal, rname_second));2747#endif //_LP64274827492750#ifdef X862751} else if (opr->is_double_xmm()) {2752assert(opr->fpu_regnrLo() == opr->fpu_regnrHi(), "assumed in calculation");2753VMReg rname_first = opr->as_xmm_double_reg()->as_VMReg();2754# ifdef _LP642755first = new LocationValue(Location::new_reg_loc(Location::dbl, rname_first));2756second = _int_0_scope_value;2757# else2758first = new LocationValue(Location::new_reg_loc(Location::normal, rname_first));2759// %%% This is probably a waste but we'll keep things as they were for now2760if (true) {2761VMReg rname_second = rname_first->next();2762second = new LocationValue(Location::new_reg_loc(Location::normal, rname_second));2763}2764# endif2765#endif27662767} else if (opr->is_double_fpu()) {2768// On SPARC, fpu_regnrLo/fpu_regnrHi represents the two halves of2769// the double as float registers in the native ordering. On X86,2770// fpu_regnrLo is a FPU stack slot whose VMReg represents2771// the low-order word of the double and fpu_regnrLo + 1 is the2772// name for the other half. *first and *second must represent the2773// least and most significant words, respectively.27742775#ifdef IA322776// the exact location of fpu stack values is only known2777// during fpu stack allocation, so the stack allocator object2778// must be present2779assert(use_fpu_stack_allocation(), "should not have float stack values without fpu stack allocation (all floats must be SSE2)");2780assert(_fpu_stack_allocator != NULL, "must be present");2781opr = _fpu_stack_allocator->to_fpu_stack(opr);27822783assert(opr->fpu_regnrLo() == opr->fpu_regnrHi(), "assumed in calculation (only fpu_regnrLo is used)");2784#endif2785#ifdef AMD642786assert(false, "FPU not used on x86-64");2787#endif2788#ifdef ARM322789assert(opr->fpu_regnrHi() == opr->fpu_regnrLo() + 1, "assumed in calculation (only fpu_regnrLo is used)");2790#endif2791#ifdef PPC322792assert(opr->fpu_regnrLo() == opr->fpu_regnrHi(), "assumed in calculation (only fpu_regnrHi is used)");2793#endif27942795#ifdef VM_LITTLE_ENDIAN2796VMReg rname_first = frame_map()->fpu_regname(opr->fpu_regnrLo());2797#else2798VMReg rname_first = frame_map()->fpu_regname(opr->fpu_regnrHi());2799#endif28002801#ifdef _LP642802first = new LocationValue(Location::new_reg_loc(Location::dbl, rname_first));2803second = _int_0_scope_value;2804#else2805first = new LocationValue(Location::new_reg_loc(Location::normal, rname_first));2806// %%% This is probably a waste but we'll keep things as they were for now2807if (true) {2808VMReg rname_second = rname_first->next();2809second = new LocationValue(Location::new_reg_loc(Location::normal, rname_second));2810}2811#endif28122813} else {2814ShouldNotReachHere();2815first = NULL;2816second = NULL;2817}28182819assert(first != NULL && second != NULL, "must be set");2820// The convention the interpreter uses is that the second local2821// holds the first raw word of the native double representation.2822// This is actually reasonable, since locals and stack arrays2823// grow downwards in all implementations.2824// (If, on some machine, the interpreter's Java locals or stack2825// were to grow upwards, the embedded doubles would be word-swapped.)2826scope_values->append(second);2827scope_values->append(first);2828return 2;2829}2830}283128322833int LinearScan::append_scope_value(int op_id, Value value, GrowableArray<ScopeValue*>* scope_values) {2834if (value != NULL) {2835LIR_Opr opr = value->operand();2836Constant* con = value->as_Constant();28372838assert(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)");2839assert(con != NULL || opr->is_virtual(), "asumption: non-Constant instructions have only virtual operands");28402841if (con != NULL && !con->is_pinned() && !opr->is_constant()) {2842// Unpinned constants may have a virtual operand for a part of the lifetime2843// or may be illegal when it was optimized away,2844// so always use a constant operand2845opr = LIR_OprFact::value_type(con->type());2846}2847assert(opr->is_virtual() || opr->is_constant(), "other cases not allowed here");28482849if (opr->is_virtual()) {2850LIR_OpVisitState::OprMode mode = LIR_OpVisitState::inputMode;28512852BlockBegin* block = block_of_op_with_id(op_id);2853if (block->number_of_sux() == 1 && op_id == block->last_lir_instruction_id()) {2854// generating debug information for the last instruction of a block.2855// if this instruction is a branch, spill moves are inserted before this branch2856// and so the wrong operand would be returned (spill moves at block boundaries are not2857// considered in the live ranges of intervals)2858// Solution: use the first op_id of the branch target block instead.2859if (block->lir()->instructions_list()->last()->as_OpBranch() != NULL) {2860if (block->live_out().at(opr->vreg_number())) {2861op_id = block->sux_at(0)->first_lir_instruction_id();2862mode = LIR_OpVisitState::outputMode;2863}2864}2865}28662867// Get current location of operand2868// The operand must be live because debug information is considered when building the intervals2869// if the interval is not live, color_lir_opr will cause an assertion failure2870opr = color_lir_opr(opr, op_id, mode);2871assert(!has_call(op_id) || opr->is_stack() || !is_caller_save(reg_num(opr)), "can not have caller-save register operands at calls");28722873// Append to ScopeValue array2874return append_scope_value_for_operand(opr, scope_values);28752876} else {2877assert(value->as_Constant() != NULL, "all other instructions have only virtual operands");2878assert(opr->is_constant(), "operand must be constant");28792880return append_scope_value_for_constant(opr, scope_values);2881}2882} else {2883// append a dummy value because real value not needed2884scope_values->append(_illegal_value);2885return 1;2886}2887}288828892890IRScopeDebugInfo* LinearScan::compute_debug_info_for_scope(int op_id, IRScope* cur_scope, ValueStack* cur_state, ValueStack* innermost_state) {2891IRScopeDebugInfo* caller_debug_info = NULL;28922893ValueStack* caller_state = cur_state->caller_state();2894if (caller_state != NULL) {2895// process recursively to compute outermost scope first2896caller_debug_info = compute_debug_info_for_scope(op_id, cur_scope->caller(), caller_state, innermost_state);2897}28982899// initialize these to null.2900// If we don't need deopt info or there are no locals, expressions or monitors,2901// then these get recorded as no information and avoids the allocation of 0 length arrays.2902GrowableArray<ScopeValue*>* locals = NULL;2903GrowableArray<ScopeValue*>* expressions = NULL;2904GrowableArray<MonitorValue*>* monitors = NULL;29052906// describe local variable values2907int nof_locals = cur_state->locals_size();2908if (nof_locals > 0) {2909locals = new GrowableArray<ScopeValue*>(nof_locals);29102911int pos = 0;2912while (pos < nof_locals) {2913assert(pos < cur_state->locals_size(), "why not?");29142915Value local = cur_state->local_at(pos);2916pos += append_scope_value(op_id, local, locals);29172918assert(locals->length() == pos, "must match");2919}2920assert(locals->length() == cur_scope->method()->max_locals(), "wrong number of locals");2921assert(locals->length() == cur_state->locals_size(), "wrong number of locals");2922} else if (cur_scope->method()->max_locals() > 0) {2923assert(cur_state->kind() == ValueStack::EmptyExceptionState, "should be");2924nof_locals = cur_scope->method()->max_locals();2925locals = new GrowableArray<ScopeValue*>(nof_locals);2926for(int i = 0; i < nof_locals; i++) {2927locals->append(_illegal_value);2928}2929}29302931// describe expression stack2932int nof_stack = cur_state->stack_size();2933if (nof_stack > 0) {2934expressions = new GrowableArray<ScopeValue*>(nof_stack);29352936int pos = 0;2937while (pos < nof_stack) {2938Value expression = cur_state->stack_at_inc(pos);2939append_scope_value(op_id, expression, expressions);29402941assert(expressions->length() == pos, "must match");2942}2943assert(expressions->length() == cur_state->stack_size(), "wrong number of stack entries");2944}29452946// describe monitors2947int nof_locks = cur_state->locks_size();2948if (nof_locks > 0) {2949int lock_offset = cur_state->caller_state() != NULL ? cur_state->caller_state()->total_locks_size() : 0;2950monitors = new GrowableArray<MonitorValue*>(nof_locks);2951for (int i = 0; i < nof_locks; i++) {2952monitors->append(location_for_monitor_index(lock_offset + i));2953}2954}29552956return new IRScopeDebugInfo(cur_scope, cur_state->bci(), locals, expressions, monitors, caller_debug_info);2957}295829592960void LinearScan::compute_debug_info(CodeEmitInfo* info, int op_id) {2961TRACE_LINEAR_SCAN(3, tty->print_cr("creating debug information at op_id %d", op_id));29622963IRScope* innermost_scope = info->scope();2964ValueStack* innermost_state = info->stack();29652966assert(innermost_scope != NULL && innermost_state != NULL, "why is it missing?");29672968DEBUG_ONLY(check_stack_depth(info, innermost_state->stack_size()));29692970if (info->_scope_debug_info == NULL) {2971// compute debug information2972info->_scope_debug_info = compute_debug_info_for_scope(op_id, innermost_scope, innermost_state, innermost_state);2973} else {2974// debug information already set. Check that it is correct from the current point of view2975DEBUG_ONLY(assert_equal(info->_scope_debug_info, compute_debug_info_for_scope(op_id, innermost_scope, innermost_state, innermost_state)));2976}2977}297829792980void LinearScan::assign_reg_num(LIR_OpList* instructions, IntervalWalker* iw) {2981LIR_OpVisitState visitor;2982int num_inst = instructions->length();2983bool has_dead = false;29842985for (int j = 0; j < num_inst; j++) {2986LIR_Op* op = instructions->at(j);2987if (op == NULL) { // this can happen when spill-moves are removed in eliminate_spill_moves2988has_dead = true;2989continue;2990}2991int op_id = op->id();29922993// visit instruction to get list of operands2994visitor.visit(op);29952996// iterate all modes of the visitor and process all virtual operands2997for_each_visitor_mode(mode) {2998int n = visitor.opr_count(mode);2999for (int k = 0; k < n; k++) {3000LIR_Opr opr = visitor.opr_at(mode, k);3001if (opr->is_virtual_register()) {3002visitor.set_opr_at(mode, k, color_lir_opr(opr, op_id, mode));3003}3004}3005}30063007if (visitor.info_count() > 0) {3008// exception handling3009if (compilation()->has_exception_handlers()) {3010XHandlers* xhandlers = visitor.all_xhandler();3011int n = xhandlers->length();3012for (int k = 0; k < n; k++) {3013XHandler* handler = xhandlers->handler_at(k);3014if (handler->entry_code() != NULL) {3015assign_reg_num(handler->entry_code()->instructions_list(), NULL);3016}3017}3018} else {3019assert(visitor.all_xhandler()->length() == 0, "missed exception handler");3020}30213022// compute oop map3023assert(iw != NULL, "needed for compute_oop_map");3024compute_oop_map(iw, visitor, op);30253026// compute debug information3027if (!use_fpu_stack_allocation()) {3028// compute debug information if fpu stack allocation is not needed.3029// when fpu stack allocation is needed, the debug information can not3030// be computed here because the exact location of fpu operands is not known3031// -> debug information is created inside the fpu stack allocator3032int n = visitor.info_count();3033for (int k = 0; k < n; k++) {3034compute_debug_info(visitor.info_at(k), op_id);3035}3036}3037}30383039#ifdef ASSERT3040// make sure we haven't made the op invalid.3041op->verify();3042#endif30433044// remove useless moves3045if (op->code() == lir_move) {3046assert(op->as_Op1() != NULL, "move must be LIR_Op1");3047LIR_Op1* move = (LIR_Op1*)op;3048LIR_Opr src = move->in_opr();3049LIR_Opr dst = move->result_opr();3050if (dst == src ||3051(!dst->is_pointer() && !src->is_pointer() &&3052src->is_same_register(dst))) {3053instructions->at_put(j, NULL);3054has_dead = true;3055}3056}3057}30583059if (has_dead) {3060// iterate all instructions of the block and remove all null-values.3061int insert_point = 0;3062for (int j = 0; j < num_inst; j++) {3063LIR_Op* op = instructions->at(j);3064if (op != NULL) {3065if (insert_point != j) {3066instructions->at_put(insert_point, op);3067}3068insert_point++;3069}3070}3071instructions->trunc_to(insert_point);3072}3073}30743075void LinearScan::assign_reg_num() {3076TIME_LINEAR_SCAN(timer_assign_reg_num);30773078init_compute_debug_info();3079IntervalWalker* iw = init_compute_oop_maps();30803081int num_blocks = block_count();3082for (int i = 0; i < num_blocks; i++) {3083BlockBegin* block = block_at(i);3084assign_reg_num(block->lir()->instructions_list(), iw);3085}3086}308730883089void LinearScan::do_linear_scan() {3090NOT_PRODUCT(_total_timer.begin_method());30913092number_instructions();30933094NOT_PRODUCT(print_lir(1, "Before Register Allocation"));30953096compute_local_live_sets();3097compute_global_live_sets();3098CHECK_BAILOUT();30993100build_intervals();3101CHECK_BAILOUT();3102sort_intervals_before_allocation();31033104NOT_PRODUCT(print_intervals("Before Register Allocation"));3105NOT_PRODUCT(LinearScanStatistic::compute(this, _stat_before_alloc));31063107allocate_registers();3108CHECK_BAILOUT();31093110resolve_data_flow();3111if (compilation()->has_exception_handlers()) {3112resolve_exception_handlers();3113}3114// fill in number of spill slots into frame_map3115propagate_spill_slots();3116CHECK_BAILOUT();31173118NOT_PRODUCT(print_intervals("After Register Allocation"));3119NOT_PRODUCT(print_lir(2, "LIR after register allocation:"));31203121sort_intervals_after_allocation();31223123DEBUG_ONLY(verify());31243125eliminate_spill_moves();3126assign_reg_num();3127CHECK_BAILOUT();31283129NOT_PRODUCT(print_lir(2, "LIR after assignment of register numbers:"));3130NOT_PRODUCT(LinearScanStatistic::compute(this, _stat_after_asign));31313132{ TIME_LINEAR_SCAN(timer_allocate_fpu_stack);31333134if (use_fpu_stack_allocation()) {3135allocate_fpu_stack(); // Only has effect on Intel3136NOT_PRODUCT(print_lir(2, "LIR after FPU stack allocation:"));3137}3138}31393140{ TIME_LINEAR_SCAN(timer_optimize_lir);31413142EdgeMoveOptimizer::optimize(ir()->code());3143ControlFlowOptimizer::optimize(ir()->code());3144// check that cfg is still correct after optimizations3145ir()->verify();3146}31473148NOT_PRODUCT(print_lir(1, "Before Code Generation", false));3149NOT_PRODUCT(LinearScanStatistic::compute(this, _stat_final));3150NOT_PRODUCT(_total_timer.end_method(this));3151}315231533154// ********** Printing functions31553156#ifndef PRODUCT31573158void LinearScan::print_timers(double total) {3159_total_timer.print(total);3160}31613162void LinearScan::print_statistics() {3163_stat_before_alloc.print("before allocation");3164_stat_after_asign.print("after assignment of register");3165_stat_final.print("after optimization");3166}31673168void LinearScan::print_bitmap(BitMap& b) {3169for (unsigned int i = 0; i < b.size(); i++) {3170if (b.at(i)) tty->print("%d ", i);3171}3172tty->cr();3173}31743175void LinearScan::print_intervals(const char* label) {3176if (TraceLinearScanLevel >= 1) {3177int i;3178tty->cr();3179tty->print_cr("%s", label);31803181for (i = 0; i < interval_count(); i++) {3182Interval* interval = interval_at(i);3183if (interval != NULL) {3184interval->print();3185}3186}31873188tty->cr();3189tty->print_cr("--- Basic Blocks ---");3190for (i = 0; i < block_count(); i++) {3191BlockBegin* block = block_at(i);3192tty->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());3193}3194tty->cr();3195tty->cr();3196}31973198if (PrintCFGToFile) {3199CFGPrinter::print_intervals(&_intervals, label);3200}3201}32023203void LinearScan::print_lir(int level, const char* label, bool hir_valid) {3204if (TraceLinearScanLevel >= level) {3205tty->cr();3206tty->print_cr("%s", label);3207print_LIR(ir()->linear_scan_order());3208tty->cr();3209}32103211if (level == 1 && PrintCFGToFile) {3212CFGPrinter::print_cfg(ir()->linear_scan_order(), label, hir_valid, true);3213}3214}32153216void LinearScan::print_reg_num(outputStream* out, int reg_num) {3217if (reg_num == -1) {3218out->print("[ANY]");3219return;3220} else if (reg_num >= LIR_OprDesc::vreg_base) {3221out->print("[VREG %d]", reg_num);3222return;3223}32243225LIR_Opr opr = get_operand(reg_num);3226assert(opr->is_valid(), "unknown register");3227opr->print(out);3228}32293230LIR_Opr LinearScan::get_operand(int reg_num) {3231LIR_Opr opr = LIR_OprFact::illegal();32323233#ifdef X863234int last_xmm_reg = pd_last_xmm_reg;3235#ifdef _LP643236if (UseAVX < 3) {3237last_xmm_reg = pd_first_xmm_reg + (pd_nof_xmm_regs_frame_map / 2) - 1;3238}3239#endif3240#endif3241if (reg_num >= pd_first_cpu_reg && reg_num <= pd_last_cpu_reg) {3242opr = LIR_OprFact::single_cpu(reg_num);3243} else if (reg_num >= pd_first_fpu_reg && reg_num <= pd_last_fpu_reg) {3244opr = LIR_OprFact::single_fpu(reg_num - pd_first_fpu_reg);3245#ifdef X863246} else if (reg_num >= pd_first_xmm_reg && reg_num <= last_xmm_reg) {3247opr = LIR_OprFact::single_xmm(reg_num - pd_first_xmm_reg);3248#endif3249} else {3250// reg_num == -1 or a virtual register, return the illegal operand3251}3252return opr;3253}32543255Interval* LinearScan::find_interval_at(int reg_num) const {3256if (reg_num < 0 || reg_num >= _intervals.length()) {3257return NULL;3258}3259return interval_at(reg_num);3260}32613262#endif // PRODUCT326332643265// ********** verification functions for allocation3266// (check that all intervals have a correct register and that no registers are overwritten)3267#ifdef ASSERT32683269void LinearScan::verify() {3270TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying intervals ******************************************"));3271verify_intervals();32723273TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying that no oops are in fixed intervals ****************"));3274verify_no_oops_in_fixed_intervals();32753276TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying that unpinned constants are not alive across block boundaries"));3277verify_constants();32783279TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying register allocation ********************************"));3280verify_registers();32813282TRACE_LINEAR_SCAN(2, tty->print_cr("********* no errors found **********************************************"));3283}32843285void LinearScan::verify_intervals() {3286int len = interval_count();3287bool has_error = false;32883289for (int i = 0; i < len; i++) {3290Interval* i1 = interval_at(i);3291if (i1 == NULL) continue;32923293i1->check_split_children();32943295if (i1->reg_num() != i) {3296tty->print_cr("Interval %d is on position %d in list", i1->reg_num(), i); i1->print(); tty->cr();3297has_error = true;3298}32993300if (i1->reg_num() >= LIR_OprDesc::vreg_base && i1->type() == T_ILLEGAL) {3301tty->print_cr("Interval %d has no type assigned", i1->reg_num()); i1->print(); tty->cr();3302has_error = true;3303}33043305if (i1->assigned_reg() == any_reg) {3306tty->print_cr("Interval %d has no register assigned", i1->reg_num()); i1->print(); tty->cr();3307has_error = true;3308}33093310if (i1->assigned_reg() == i1->assigned_regHi()) {3311tty->print_cr("Interval %d: low and high register equal", i1->reg_num()); i1->print(); tty->cr();3312has_error = true;3313}33143315if (!is_processed_reg_num(i1->assigned_reg())) {3316tty->print_cr("Can not have an Interval for an ignored register"); i1->print(); tty->cr();3317has_error = true;3318}33193320// special intervals that are created in MoveResolver3321// -> ignore them because the range information has no meaning there3322if (i1->from() == 1 && i1->to() == 2) continue;33233324if (i1->first() == Range::end()) {3325tty->print_cr("Interval %d has no Range", i1->reg_num()); i1->print(); tty->cr();3326has_error = true;3327}33283329for (Range* r = i1->first(); r != Range::end(); r = r->next()) {3330if (r->from() >= r->to()) {3331tty->print_cr("Interval %d has zero length range", i1->reg_num()); i1->print(); tty->cr();3332has_error = true;3333}3334}33353336for (int j = i + 1; j < len; j++) {3337Interval* i2 = interval_at(j);3338if (i2 == NULL || (i2->from() == 1 && i2->to() == 2)) continue;33393340int r1 = i1->assigned_reg();3341int r1Hi = i1->assigned_regHi();3342int r2 = i2->assigned_reg();3343int r2Hi = i2->assigned_regHi();3344if ((r1 == r2 || r1 == r2Hi || (r1Hi != any_reg && (r1Hi == r2 || r1Hi == r2Hi))) && i1->intersects(i2)) {3345tty->print_cr("Intervals %d and %d overlap and have the same register assigned", i1->reg_num(), i2->reg_num());3346i1->print(); tty->cr();3347i2->print(); tty->cr();3348has_error = true;3349}3350}3351}33523353assert(has_error == false, "register allocation invalid");3354}335533563357void LinearScan::verify_no_oops_in_fixed_intervals() {3358Interval* fixed_intervals;3359Interval* other_intervals;3360create_unhandled_lists(&fixed_intervals, &other_intervals, is_precolored_cpu_interval, NULL);33613362// to ensure a walking until the last instruction id, add a dummy interval3363// with a high operation id3364other_intervals = new Interval(any_reg);3365other_intervals->add_range(max_jint - 2, max_jint - 1);3366IntervalWalker* iw = new IntervalWalker(this, fixed_intervals, other_intervals);33673368LIR_OpVisitState visitor;3369for (int i = 0; i < block_count(); i++) {3370BlockBegin* block = block_at(i);33713372LIR_OpList* instructions = block->lir()->instructions_list();33733374for (int j = 0; j < instructions->length(); j++) {3375LIR_Op* op = instructions->at(j);3376int op_id = op->id();33773378visitor.visit(op);33793380if (visitor.info_count() > 0) {3381iw->walk_before(op->id());3382bool check_live = true;3383if (op->code() == lir_move) {3384LIR_Op1* move = (LIR_Op1*)op;3385check_live = (move->patch_code() == lir_patch_none);3386}3387LIR_OpBranch* branch = op->as_OpBranch();3388if (branch != NULL && branch->stub() != NULL && branch->stub()->is_exception_throw_stub()) {3389// Don't bother checking the stub in this case since the3390// exception stub will never return to normal control flow.3391check_live = false;3392}33933394// Make sure none of the fixed registers is live across an3395// oopmap since we can't handle that correctly.3396if (check_live) {3397for (Interval* interval = iw->active_first(fixedKind);3398interval != Interval::end();3399interval = interval->next()) {3400if (interval->current_to() > op->id() + 1) {3401// This interval is live out of this op so make sure3402// that this interval represents some value that's3403// referenced by this op either as an input or output.3404bool ok = false;3405for_each_visitor_mode(mode) {3406int n = visitor.opr_count(mode);3407for (int k = 0; k < n; k++) {3408LIR_Opr opr = visitor.opr_at(mode, k);3409if (opr->is_fixed_cpu()) {3410if (interval_at(reg_num(opr)) == interval) {3411ok = true;3412break;3413}3414int hi = reg_numHi(opr);3415if (hi != -1 && interval_at(hi) == interval) {3416ok = true;3417break;3418}3419}3420}3421}3422assert(ok, "fixed intervals should never be live across an oopmap point");3423}3424}3425}3426}34273428// oop-maps at calls do not contain registers, so check is not needed3429if (!visitor.has_call()) {34303431for_each_visitor_mode(mode) {3432int n = visitor.opr_count(mode);3433for (int k = 0; k < n; k++) {3434LIR_Opr opr = visitor.opr_at(mode, k);34353436if (opr->is_fixed_cpu() && opr->is_oop()) {3437// operand is a non-virtual cpu register and contains an oop3438TRACE_LINEAR_SCAN(4, op->print_on(tty); tty->print("checking operand "); opr->print(); tty->cr());34393440Interval* interval = interval_at(reg_num(opr));3441assert(interval != NULL, "no interval");34423443if (mode == LIR_OpVisitState::inputMode) {3444if (interval->to() >= op_id + 1) {3445assert(interval->to() < op_id + 2 ||3446interval->has_hole_between(op_id, op_id + 2),3447"oop input operand live after instruction");3448}3449} else if (mode == LIR_OpVisitState::outputMode) {3450if (interval->from() <= op_id - 1) {3451assert(interval->has_hole_between(op_id - 1, op_id),3452"oop input operand live after instruction");3453}3454}3455}3456}3457}3458}3459}3460}3461}346234633464void LinearScan::verify_constants() {3465int num_regs = num_virtual_regs();3466int size = live_set_size();3467int num_blocks = block_count();34683469for (int i = 0; i < num_blocks; i++) {3470BlockBegin* block = block_at(i);3471ResourceBitMap live_at_edge = block->live_in();34723473// visit all registers where the live_at_edge bit is set3474for (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)) {3475TRACE_LINEAR_SCAN(4, tty->print("checking interval %d of block B%d", r, block->block_id()));34763477Value value = gen()->instruction_for_vreg(r);34783479assert(value != NULL, "all intervals live across block boundaries must have Value");3480assert(value->operand()->is_register() && value->operand()->is_virtual(), "value must have virtual operand");3481assert(value->operand()->vreg_number() == r, "register number must match");3482// TKR assert(value->as_Constant() == NULL || value->is_pinned(), "only pinned constants can be alive accross block boundaries");3483}3484}3485}348634873488class RegisterVerifier: public StackObj {3489private:3490LinearScan* _allocator;3491BlockList _work_list; // all blocks that must be processed3492IntervalsList _saved_states; // saved information of previous check34933494// simplified access to methods of LinearScan3495Compilation* compilation() const { return _allocator->compilation(); }3496Interval* interval_at(int reg_num) const { return _allocator->interval_at(reg_num); }3497int reg_num(LIR_Opr opr) const { return _allocator->reg_num(opr); }34983499// currently, only registers are processed3500int state_size() { return LinearScan::nof_regs; }35013502// accessors3503IntervalList* state_for_block(BlockBegin* block) { return _saved_states.at(block->block_id()); }3504void set_state_for_block(BlockBegin* block, IntervalList* saved_state) { _saved_states.at_put(block->block_id(), saved_state); }3505void add_to_work_list(BlockBegin* block) { if (!_work_list.contains(block)) _work_list.append(block); }35063507// helper functions3508IntervalList* copy(IntervalList* input_state);3509void state_put(IntervalList* input_state, int reg, Interval* interval);3510bool check_state(IntervalList* input_state, int reg, Interval* interval);35113512void process_block(BlockBegin* block);3513void process_xhandler(XHandler* xhandler, IntervalList* input_state);3514void process_successor(BlockBegin* block, IntervalList* input_state);3515void process_operations(LIR_List* ops, IntervalList* input_state);35163517public:3518RegisterVerifier(LinearScan* allocator)3519: _allocator(allocator)3520, _work_list(16)3521, _saved_states(BlockBegin::number_of_blocks(), BlockBegin::number_of_blocks(), NULL)3522{ }35233524void verify(BlockBegin* start);3525};352635273528// entry function from LinearScan that starts the verification3529void LinearScan::verify_registers() {3530RegisterVerifier verifier(this);3531verifier.verify(block_at(0));3532}353335343535void RegisterVerifier::verify(BlockBegin* start) {3536// setup input registers (method arguments) for first block3537int input_state_len = state_size();3538IntervalList* input_state = new IntervalList(input_state_len, input_state_len, NULL);3539CallingConvention* args = compilation()->frame_map()->incoming_arguments();3540for (int n = 0; n < args->length(); n++) {3541LIR_Opr opr = args->at(n);3542if (opr->is_register()) {3543Interval* interval = interval_at(reg_num(opr));35443545if (interval->assigned_reg() < state_size()) {3546input_state->at_put(interval->assigned_reg(), interval);3547}3548if (interval->assigned_regHi() != LinearScan::any_reg && interval->assigned_regHi() < state_size()) {3549input_state->at_put(interval->assigned_regHi(), interval);3550}3551}3552}35533554set_state_for_block(start, input_state);3555add_to_work_list(start);35563557// main loop for verification3558do {3559BlockBegin* block = _work_list.at(0);3560_work_list.remove_at(0);35613562process_block(block);3563} while (!_work_list.is_empty());3564}35653566void RegisterVerifier::process_block(BlockBegin* block) {3567TRACE_LINEAR_SCAN(2, tty->cr(); tty->print_cr("process_block B%d", block->block_id()));35683569// must copy state because it is modified3570IntervalList* input_state = copy(state_for_block(block));35713572if (TraceLinearScanLevel >= 4) {3573tty->print_cr("Input-State of intervals:");3574tty->print(" ");3575for (int i = 0; i < state_size(); i++) {3576if (input_state->at(i) != NULL) {3577tty->print(" %4d", input_state->at(i)->reg_num());3578} else {3579tty->print(" __");3580}3581}3582tty->cr();3583tty->cr();3584}35853586// process all operations of the block3587process_operations(block->lir(), input_state);35883589// iterate all successors3590for (int i = 0; i < block->number_of_sux(); i++) {3591process_successor(block->sux_at(i), input_state);3592}3593}35943595void RegisterVerifier::process_xhandler(XHandler* xhandler, IntervalList* input_state) {3596TRACE_LINEAR_SCAN(2, tty->print_cr("process_xhandler B%d", xhandler->entry_block()->block_id()));35973598// must copy state because it is modified3599input_state = copy(input_state);36003601if (xhandler->entry_code() != NULL) {3602process_operations(xhandler->entry_code(), input_state);3603}3604process_successor(xhandler->entry_block(), input_state);3605}36063607void RegisterVerifier::process_successor(BlockBegin* block, IntervalList* input_state) {3608IntervalList* saved_state = state_for_block(block);36093610if (saved_state != NULL) {3611// this block was already processed before.3612// check if new input_state is consistent with saved_state36133614bool saved_state_correct = true;3615for (int i = 0; i < state_size(); i++) {3616if (input_state->at(i) != saved_state->at(i)) {3617// current input_state and previous saved_state assume a different3618// interval in this register -> assume that this register is invalid3619if (saved_state->at(i) != NULL) {3620// invalidate old calculation only if it assumed that3621// register was valid. when the register was already invalid,3622// then the old calculation was correct.3623saved_state_correct = false;3624saved_state->at_put(i, NULL);36253626TRACE_LINEAR_SCAN(4, tty->print_cr("process_successor B%d: invalidating slot %d", block->block_id(), i));3627}3628}3629}36303631if (saved_state_correct) {3632// already processed block with correct input_state3633TRACE_LINEAR_SCAN(2, tty->print_cr("process_successor B%d: previous visit already correct", block->block_id()));3634} else {3635// must re-visit this block3636TRACE_LINEAR_SCAN(2, tty->print_cr("process_successor B%d: must re-visit because input state changed", block->block_id()));3637add_to_work_list(block);3638}36393640} else {3641// block was not processed before, so set initial input_state3642TRACE_LINEAR_SCAN(2, tty->print_cr("process_successor B%d: initial visit", block->block_id()));36433644set_state_for_block(block, copy(input_state));3645add_to_work_list(block);3646}3647}364836493650IntervalList* RegisterVerifier::copy(IntervalList* input_state) {3651IntervalList* copy_state = new IntervalList(input_state->length());3652copy_state->appendAll(input_state);3653return copy_state;3654}36553656void RegisterVerifier::state_put(IntervalList* input_state, int reg, Interval* interval) {3657if (reg != LinearScan::any_reg && reg < state_size()) {3658if (interval != NULL) {3659TRACE_LINEAR_SCAN(4, tty->print_cr(" reg[%d] = %d", reg, interval->reg_num()));3660} else if (input_state->at(reg) != NULL) {3661TRACE_LINEAR_SCAN(4, tty->print_cr(" reg[%d] = NULL", reg));3662}36633664input_state->at_put(reg, interval);3665}3666}36673668bool RegisterVerifier::check_state(IntervalList* input_state, int reg, Interval* interval) {3669if (reg != LinearScan::any_reg && reg < state_size()) {3670if (input_state->at(reg) != interval) {3671tty->print_cr("!! Error in register allocation: register %d does not contain interval %d", reg, interval->reg_num());3672return true;3673}3674}3675return false;3676}36773678void RegisterVerifier::process_operations(LIR_List* ops, IntervalList* input_state) {3679// visit all instructions of the block3680LIR_OpVisitState visitor;3681bool has_error = false;36823683for (int i = 0; i < ops->length(); i++) {3684LIR_Op* op = ops->at(i);3685visitor.visit(op);36863687TRACE_LINEAR_SCAN(4, op->print_on(tty));36883689// check if input operands are correct3690int j;3691int n = visitor.opr_count(LIR_OpVisitState::inputMode);3692for (j = 0; j < n; j++) {3693LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::inputMode, j);3694if (opr->is_register() && LinearScan::is_processed_reg_num(reg_num(opr))) {3695Interval* interval = interval_at(reg_num(opr));3696if (op->id() != -1) {3697interval = interval->split_child_at_op_id(op->id(), LIR_OpVisitState::inputMode);3698}36993700has_error |= check_state(input_state, interval->assigned_reg(), interval->split_parent());3701has_error |= check_state(input_state, interval->assigned_regHi(), interval->split_parent());37023703// When an operand is marked with is_last_use, then the fpu stack allocator3704// removes the register from the fpu stack -> the register contains no value3705if (opr->is_last_use()) {3706state_put(input_state, interval->assigned_reg(), NULL);3707state_put(input_state, interval->assigned_regHi(), NULL);3708}3709}3710}37113712// invalidate all caller save registers at calls3713if (visitor.has_call()) {3714for (j = 0; j < FrameMap::nof_caller_save_cpu_regs(); j++) {3715state_put(input_state, reg_num(FrameMap::caller_save_cpu_reg_at(j)), NULL);3716}3717for (j = 0; j < FrameMap::nof_caller_save_fpu_regs; j++) {3718state_put(input_state, reg_num(FrameMap::caller_save_fpu_reg_at(j)), NULL);3719}37203721#ifdef X863722int num_caller_save_xmm_regs = FrameMap::get_num_caller_save_xmms();3723for (j = 0; j < num_caller_save_xmm_regs; j++) {3724state_put(input_state, reg_num(FrameMap::caller_save_xmm_reg_at(j)), NULL);3725}3726#endif3727}37283729// process xhandler before output and temp operands3730XHandlers* xhandlers = visitor.all_xhandler();3731n = xhandlers->length();3732for (int k = 0; k < n; k++) {3733process_xhandler(xhandlers->handler_at(k), input_state);3734}37353736// set temp operands (some operations use temp operands also as output operands, so can't set them NULL)3737n = visitor.opr_count(LIR_OpVisitState::tempMode);3738for (j = 0; j < n; j++) {3739LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::tempMode, j);3740if (opr->is_register() && LinearScan::is_processed_reg_num(reg_num(opr))) {3741Interval* interval = interval_at(reg_num(opr));3742if (op->id() != -1) {3743interval = interval->split_child_at_op_id(op->id(), LIR_OpVisitState::tempMode);3744}37453746state_put(input_state, interval->assigned_reg(), interval->split_parent());3747state_put(input_state, interval->assigned_regHi(), interval->split_parent());3748}3749}37503751// set output operands3752n = visitor.opr_count(LIR_OpVisitState::outputMode);3753for (j = 0; j < n; j++) {3754LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::outputMode, j);3755if (opr->is_register() && LinearScan::is_processed_reg_num(reg_num(opr))) {3756Interval* interval = interval_at(reg_num(opr));3757if (op->id() != -1) {3758interval = interval->split_child_at_op_id(op->id(), LIR_OpVisitState::outputMode);3759}37603761state_put(input_state, interval->assigned_reg(), interval->split_parent());3762state_put(input_state, interval->assigned_regHi(), interval->split_parent());3763}3764}3765}3766assert(has_error == false, "Error in register allocation");3767}37683769#endif // ASSERT3770377137723773// **** Implementation of MoveResolver ******************************37743775MoveResolver::MoveResolver(LinearScan* allocator) :3776_allocator(allocator),3777_insert_list(NULL),3778_insert_idx(-1),3779_insertion_buffer(),3780_mapping_from(8),3781_mapping_from_opr(8),3782_mapping_to(8),3783_multiple_reads_allowed(false)3784{3785for (int i = 0; i < LinearScan::nof_regs; i++) {3786_register_blocked[i] = 0;3787}3788DEBUG_ONLY(check_empty());3789}379037913792#ifdef ASSERT37933794void MoveResolver::check_empty() {3795assert(_mapping_from.length() == 0 && _mapping_from_opr.length() == 0 && _mapping_to.length() == 0, "list must be empty before and after processing");3796for (int i = 0; i < LinearScan::nof_regs; i++) {3797assert(register_blocked(i) == 0, "register map must be empty before and after processing");3798}3799assert(_multiple_reads_allowed == false, "must have default value");3800}38013802void MoveResolver::verify_before_resolve() {3803assert(_mapping_from.length() == _mapping_from_opr.length(), "length must be equal");3804assert(_mapping_from.length() == _mapping_to.length(), "length must be equal");3805assert(_insert_list != NULL && _insert_idx != -1, "insert position not set");38063807int i, j;3808if (!_multiple_reads_allowed) {3809for (i = 0; i < _mapping_from.length(); i++) {3810for (j = i + 1; j < _mapping_from.length(); j++) {3811assert(_mapping_from.at(i) == NULL || _mapping_from.at(i) != _mapping_from.at(j), "cannot read from same interval twice");3812}3813}3814}38153816for (i = 0; i < _mapping_to.length(); i++) {3817for (j = i + 1; j < _mapping_to.length(); j++) {3818assert(_mapping_to.at(i) != _mapping_to.at(j), "cannot write to same interval twice");3819}3820}382138223823ResourceBitMap used_regs(LinearScan::nof_regs + allocator()->frame_map()->argcount() + allocator()->max_spills());3824if (!_multiple_reads_allowed) {3825for (i = 0; i < _mapping_from.length(); i++) {3826Interval* it = _mapping_from.at(i);3827if (it != NULL) {3828assert(!used_regs.at(it->assigned_reg()), "cannot read from same register twice");3829used_regs.set_bit(it->assigned_reg());38303831if (it->assigned_regHi() != LinearScan::any_reg) {3832assert(!used_regs.at(it->assigned_regHi()), "cannot read from same register twice");3833used_regs.set_bit(it->assigned_regHi());3834}3835}3836}3837}38383839used_regs.clear();3840for (i = 0; i < _mapping_to.length(); i++) {3841Interval* it = _mapping_to.at(i);3842assert(!used_regs.at(it->assigned_reg()), "cannot write to same register twice");3843used_regs.set_bit(it->assigned_reg());38443845if (it->assigned_regHi() != LinearScan::any_reg) {3846assert(!used_regs.at(it->assigned_regHi()), "cannot write to same register twice");3847used_regs.set_bit(it->assigned_regHi());3848}3849}38503851used_regs.clear();3852for (i = 0; i < _mapping_from.length(); i++) {3853Interval* it = _mapping_from.at(i);3854if (it != NULL && it->assigned_reg() >= LinearScan::nof_regs) {3855used_regs.set_bit(it->assigned_reg());3856}3857}3858for (i = 0; i < _mapping_to.length(); i++) {3859Interval* it = _mapping_to.at(i);3860assert(!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");3861}3862}38633864#endif // ASSERT386538663867// mark assigned_reg and assigned_regHi of the interval as blocked3868void MoveResolver::block_registers(Interval* it) {3869int reg = it->assigned_reg();3870if (reg < LinearScan::nof_regs) {3871assert(_multiple_reads_allowed || register_blocked(reg) == 0, "register already marked as used");3872set_register_blocked(reg, 1);3873}3874reg = it->assigned_regHi();3875if (reg != LinearScan::any_reg && reg < LinearScan::nof_regs) {3876assert(_multiple_reads_allowed || register_blocked(reg) == 0, "register already marked as used");3877set_register_blocked(reg, 1);3878}3879}38803881// mark assigned_reg and assigned_regHi of the interval as unblocked3882void MoveResolver::unblock_registers(Interval* it) {3883int reg = it->assigned_reg();3884if (reg < LinearScan::nof_regs) {3885assert(register_blocked(reg) > 0, "register already marked as unused");3886set_register_blocked(reg, -1);3887}3888reg = it->assigned_regHi();3889if (reg != LinearScan::any_reg && reg < LinearScan::nof_regs) {3890assert(register_blocked(reg) > 0, "register already marked as unused");3891set_register_blocked(reg, -1);3892}3893}38943895// check if assigned_reg and assigned_regHi of the to-interval are not blocked (or only blocked by from)3896bool MoveResolver::save_to_process_move(Interval* from, Interval* to) {3897int from_reg = -1;3898int from_regHi = -1;3899if (from != NULL) {3900from_reg = from->assigned_reg();3901from_regHi = from->assigned_regHi();3902}39033904int reg = to->assigned_reg();3905if (reg < LinearScan::nof_regs) {3906if (register_blocked(reg) > 1 || (register_blocked(reg) == 1 && reg != from_reg && reg != from_regHi)) {3907return false;3908}3909}3910reg = to->assigned_regHi();3911if (reg != LinearScan::any_reg && reg < LinearScan::nof_regs) {3912if (register_blocked(reg) > 1 || (register_blocked(reg) == 1 && reg != from_reg && reg != from_regHi)) {3913return false;3914}3915}39163917return true;3918}391939203921void MoveResolver::create_insertion_buffer(LIR_List* list) {3922assert(!_insertion_buffer.initialized(), "overwriting existing buffer");3923_insertion_buffer.init(list);3924}39253926void MoveResolver::append_insertion_buffer() {3927if (_insertion_buffer.initialized()) {3928_insertion_buffer.lir_list()->append(&_insertion_buffer);3929}3930assert(!_insertion_buffer.initialized(), "must be uninitialized now");39313932_insert_list = NULL;3933_insert_idx = -1;3934}39353936void MoveResolver::insert_move(Interval* from_interval, Interval* to_interval) {3937assert(from_interval->reg_num() != to_interval->reg_num(), "from and to interval equal");3938assert(from_interval->type() == to_interval->type(), "move between different types");3939assert(_insert_list != NULL && _insert_idx != -1, "must setup insert position first");3940assert(_insertion_buffer.lir_list() == _insert_list, "wrong insertion buffer");39413942LIR_Opr from_opr = get_virtual_register(from_interval);3943LIR_Opr to_opr = get_virtual_register(to_interval);39443945if (!_multiple_reads_allowed) {3946// the last_use flag is an optimization for FPU stack allocation. When the same3947// input interval is used in more than one move, then it is too difficult to determine3948// if this move is really the last use.3949from_opr = from_opr->make_last_use();3950}3951_insertion_buffer.move(_insert_idx, from_opr, to_opr);39523953TRACE_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()));3954}39553956void MoveResolver::insert_move(LIR_Opr from_opr, Interval* to_interval) {3957assert(from_opr->type() == to_interval->type(), "move between different types");3958assert(_insert_list != NULL && _insert_idx != -1, "must setup insert position first");3959assert(_insertion_buffer.lir_list() == _insert_list, "wrong insertion buffer");39603961LIR_Opr to_opr = get_virtual_register(to_interval);3962_insertion_buffer.move(_insert_idx, from_opr, to_opr);39633964TRACE_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()));3965}39663967LIR_Opr MoveResolver::get_virtual_register(Interval* interval) {3968// Add a little fudge factor for the bailout since the bailout is only checked periodically. This allows us to hand out3969// a few extra registers before we really run out which helps to avoid to trip over assertions.3970int reg_num = interval->reg_num();3971if (reg_num + 20 >= LIR_OprDesc::vreg_max) {3972_allocator->bailout("out of virtual registers in linear scan");3973if (reg_num + 2 >= LIR_OprDesc::vreg_max) {3974// Wrap it around and continue until bailout really happens to avoid hitting assertions.3975reg_num = LIR_OprDesc::vreg_base;3976}3977}3978LIR_Opr vreg = LIR_OprFact::virtual_register(reg_num, interval->type());3979assert(vreg != LIR_OprFact::illegal(), "ran out of virtual registers");3980return vreg;3981}39823983void MoveResolver::resolve_mappings() {3984TRACE_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));3985DEBUG_ONLY(verify_before_resolve());39863987// Block all registers that are used as input operands of a move.3988// When a register is blocked, no move to this register is emitted.3989// This is necessary for detecting cycles in moves.3990int i;3991for (i = _mapping_from.length() - 1; i >= 0; i--) {3992Interval* from_interval = _mapping_from.at(i);3993if (from_interval != NULL) {3994block_registers(from_interval);3995}3996}39973998int spill_candidate = -1;3999while (_mapping_from.length() > 0) {4000bool processed_interval = false;40014002for (i = _mapping_from.length() - 1; i >= 0; i--) {4003Interval* from_interval = _mapping_from.at(i);4004Interval* to_interval = _mapping_to.at(i);40054006if (save_to_process_move(from_interval, to_interval)) {4007// this inverval can be processed because target is free4008if (from_interval != NULL) {4009insert_move(from_interval, to_interval);4010unblock_registers(from_interval);4011} else {4012insert_move(_mapping_from_opr.at(i), to_interval);4013}4014_mapping_from.remove_at(i);4015_mapping_from_opr.remove_at(i);4016_mapping_to.remove_at(i);40174018processed_interval = true;4019} else if (from_interval != NULL && from_interval->assigned_reg() < LinearScan::nof_regs) {4020// this interval cannot be processed now because target is not free4021// it starts in a register, so it is a possible candidate for spilling4022spill_candidate = i;4023}4024}40254026if (!processed_interval) {4027// no move could be processed because there is a cycle in the move list4028// (e.g. r1 -> r2, r2 -> r1), so one interval must be spilled to memory4029guarantee(spill_candidate != -1, "no interval in register for spilling found");40304031// create a new spill interval and assign a stack slot to it4032Interval* from_interval = _mapping_from.at(spill_candidate);4033Interval* spill_interval = new Interval(-1);4034spill_interval->set_type(from_interval->type());40354036// add a dummy range because real position is difficult to calculate4037// Note: this range is a special case when the integrity of the allocation is checked4038spill_interval->add_range(1, 2);40394040// do not allocate a new spill slot for temporary interval, but4041// use spill slot assigned to from_interval. Otherwise moves from4042// one stack slot to another can happen (not allowed by LIR_Assembler4043int spill_slot = from_interval->canonical_spill_slot();4044if (spill_slot < 0) {4045spill_slot = allocator()->allocate_spill_slot(type2spill_size[spill_interval->type()] == 2);4046from_interval->set_canonical_spill_slot(spill_slot);4047}4048spill_interval->assign_reg(spill_slot);4049allocator()->append_interval(spill_interval);40504051TRACE_LINEAR_SCAN(4, tty->print_cr("created new Interval %d for spilling", spill_interval->reg_num()));40524053// insert a move from register to stack and update the mapping4054insert_move(from_interval, spill_interval);4055_mapping_from.at_put(spill_candidate, spill_interval);4056unblock_registers(from_interval);4057}4058}40594060// reset to default value4061_multiple_reads_allowed = false;40624063// check that all intervals have been processed4064DEBUG_ONLY(check_empty());4065}406640674068void MoveResolver::set_insert_position(LIR_List* insert_list, int insert_idx) {4069TRACE_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));4070assert(_insert_list == NULL && _insert_idx == -1, "use move_insert_position instead of set_insert_position when data already set");40714072create_insertion_buffer(insert_list);4073_insert_list = insert_list;4074_insert_idx = insert_idx;4075}40764077void MoveResolver::move_insert_position(LIR_List* insert_list, int insert_idx) {4078TRACE_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));40794080if (_insert_list != NULL && (insert_list != _insert_list || insert_idx != _insert_idx)) {4081// insert position changed -> resolve current mappings4082resolve_mappings();4083}40844085if (insert_list != _insert_list) {4086// block changed -> append insertion_buffer because it is4087// bound to a specific block and create a new insertion_buffer4088append_insertion_buffer();4089create_insertion_buffer(insert_list);4090}40914092_insert_list = insert_list;4093_insert_idx = insert_idx;4094}40954096void MoveResolver::add_mapping(Interval* from_interval, Interval* to_interval) {4097TRACE_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()));40984099_mapping_from.append(from_interval);4100_mapping_from_opr.append(LIR_OprFact::illegalOpr);4101_mapping_to.append(to_interval);4102}410341044105void MoveResolver::add_mapping(LIR_Opr from_opr, Interval* to_interval) {4106TRACE_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()));4107assert(from_opr->is_constant(), "only for constants");41084109_mapping_from.append(NULL);4110_mapping_from_opr.append(from_opr);4111_mapping_to.append(to_interval);4112}41134114void MoveResolver::resolve_and_append_moves() {4115if (has_mappings()) {4116resolve_mappings();4117}4118append_insertion_buffer();4119}4120412141224123// **** Implementation of Range *************************************41244125Range::Range(int from, int to, Range* next) :4126_from(from),4127_to(to),4128_next(next)4129{4130}41314132// initialize sentinel4133Range* Range::_end = NULL;4134void Range::initialize(Arena* arena) {4135_end = new (arena) Range(max_jint, max_jint, NULL);4136}41374138int Range::intersects_at(Range* r2) const {4139const Range* r1 = this;41404141assert(r1 != NULL && r2 != NULL, "null ranges not allowed");4142assert(r1 != _end && r2 != _end, "empty ranges not allowed");41434144do {4145if (r1->from() < r2->from()) {4146if (r1->to() <= r2->from()) {4147r1 = r1->next(); if (r1 == _end) return -1;4148} else {4149return r2->from();4150}4151} else if (r2->from() < r1->from()) {4152if (r2->to() <= r1->from()) {4153r2 = r2->next(); if (r2 == _end) return -1;4154} else {4155return r1->from();4156}4157} else { // r1->from() == r2->from()4158if (r1->from() == r1->to()) {4159r1 = r1->next(); if (r1 == _end) return -1;4160} else if (r2->from() == r2->to()) {4161r2 = r2->next(); if (r2 == _end) return -1;4162} else {4163return r1->from();4164}4165}4166} while (true);4167}41684169#ifndef PRODUCT4170void Range::print(outputStream* out) const {4171out->print("[%d, %d[ ", _from, _to);4172}4173#endif4174417541764177// **** Implementation of Interval **********************************41784179// initialize sentinel4180Interval* Interval::_end = NULL;4181void Interval::initialize(Arena* arena) {4182Range::initialize(arena);4183_end = new (arena) Interval(-1);4184}41854186Interval::Interval(int reg_num) :4187_reg_num(reg_num),4188_type(T_ILLEGAL),4189_first(Range::end()),4190_use_pos_and_kinds(12),4191_current(Range::end()),4192_next(_end),4193_state(invalidState),4194_assigned_reg(LinearScan::any_reg),4195_assigned_regHi(LinearScan::any_reg),4196_cached_to(-1),4197_cached_opr(LIR_OprFact::illegalOpr),4198_cached_vm_reg(VMRegImpl::Bad()),4199_split_children(NULL),4200_canonical_spill_slot(-1),4201_insert_move_when_activated(false),4202_spill_state(noDefinitionFound),4203_spill_definition_pos(-1),4204_register_hint(NULL)4205{4206_split_parent = this;4207_current_split_child = this;4208}42094210int Interval::calc_to() {4211assert(_first != Range::end(), "interval has no range");42124213Range* r = _first;4214while (r->next() != Range::end()) {4215r = r->next();4216}4217return r->to();4218}421942204221#ifdef ASSERT4222// consistency check of split-children4223void Interval::check_split_children() {4224if (_split_children != NULL && _split_children->length() > 0) {4225assert(is_split_parent(), "only split parents can have children");42264227for (int i = 0; i < _split_children->length(); i++) {4228Interval* i1 = _split_children->at(i);42294230assert(i1->split_parent() == this, "not a split child of this interval");4231assert(i1->type() == type(), "must be equal for all split children");4232assert(i1->canonical_spill_slot() == canonical_spill_slot(), "must be equal for all split children");42334234for (int j = i + 1; j < _split_children->length(); j++) {4235Interval* i2 = _split_children->at(j);42364237assert(i1->reg_num() != i2->reg_num(), "same register number");42384239if (i1->from() < i2->from()) {4240assert(i1->to() <= i2->from() && i1->to() < i2->to(), "intervals overlapping");4241} else {4242assert(i2->from() < i1->from(), "intervals start at same op_id");4243assert(i2->to() <= i1->from() && i2->to() < i1->to(), "intervals overlapping");4244}4245}4246}4247}4248}4249#endif // ASSERT42504251Interval* Interval::register_hint(bool search_split_child) const {4252if (!search_split_child) {4253return _register_hint;4254}42554256if (_register_hint != NULL) {4257assert(_register_hint->is_split_parent(), "ony split parents are valid hint registers");42584259if (_register_hint->assigned_reg() >= 0 && _register_hint->assigned_reg() < LinearScan::nof_regs) {4260return _register_hint;42614262} else if (_register_hint->_split_children != NULL && _register_hint->_split_children->length() > 0) {4263// search the first split child that has a register assigned4264int len = _register_hint->_split_children->length();4265for (int i = 0; i < len; i++) {4266Interval* cur = _register_hint->_split_children->at(i);42674268if (cur->assigned_reg() >= 0 && cur->assigned_reg() < LinearScan::nof_regs) {4269return cur;4270}4271}4272}4273}42744275// no hint interval found that has a register assigned4276return NULL;4277}427842794280Interval* Interval::split_child_at_op_id(int op_id, LIR_OpVisitState::OprMode mode) {4281assert(is_split_parent(), "can only be called for split parents");4282assert(op_id >= 0, "invalid op_id (method can not be called for spill moves)");42834284Interval* result;4285if (_split_children == NULL || _split_children->length() == 0) {4286result = this;4287} else {4288result = NULL;4289int len = _split_children->length();42904291// in outputMode, the end of the interval (op_id == cur->to()) is not valid4292int to_offset = (mode == LIR_OpVisitState::outputMode ? 0 : 1);42934294int i;4295for (i = 0; i < len; i++) {4296Interval* cur = _split_children->at(i);4297if (cur->from() <= op_id && op_id < cur->to() + to_offset) {4298if (i > 0) {4299// exchange current split child to start of list (faster access for next call)4300_split_children->at_put(i, _split_children->at(0));4301_split_children->at_put(0, cur);4302}43034304// interval found4305result = cur;4306break;4307}4308}43094310#ifdef ASSERT4311for (i = 0; i < len; i++) {4312Interval* tmp = _split_children->at(i);4313if (tmp != result && tmp->from() <= op_id && op_id < tmp->to() + to_offset) {4314tty->print_cr("two valid result intervals found for op_id %d: %d and %d", op_id, result->reg_num(), tmp->reg_num());4315result->print();4316tmp->print();4317assert(false, "two valid result intervals found");4318}4319}4320#endif4321}43224323assert(result != NULL, "no matching interval found");4324assert(result->covers(op_id, mode), "op_id not covered by interval");43254326return result;4327}432843294330// returns the last split child that ends before the given op_id4331Interval* Interval::split_child_before_op_id(int op_id) {4332assert(op_id >= 0, "invalid op_id");43334334Interval* parent = split_parent();4335Interval* result = NULL;43364337assert(parent->_split_children != NULL, "no split children available");4338int len = parent->_split_children->length();4339assert(len > 0, "no split children available");43404341for (int i = len - 1; i >= 0; i--) {4342Interval* cur = parent->_split_children->at(i);4343if (cur->to() <= op_id && (result == NULL || result->to() < cur->to())) {4344result = cur;4345}4346}43474348assert(result != NULL, "no split child found");4349return result;4350}435143524353// Note: use positions are sorted descending -> first use has highest index4354int Interval::first_usage(IntervalUseKind min_use_kind) const {4355assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");43564357for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {4358if (_use_pos_and_kinds.at(i + 1) >= min_use_kind) {4359return _use_pos_and_kinds.at(i);4360}4361}4362return max_jint;4363}43644365int Interval::next_usage(IntervalUseKind min_use_kind, int from) const {4366assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");43674368for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {4369if (_use_pos_and_kinds.at(i) >= from && _use_pos_and_kinds.at(i + 1) >= min_use_kind) {4370return _use_pos_and_kinds.at(i);4371}4372}4373return max_jint;4374}43754376int Interval::next_usage_exact(IntervalUseKind exact_use_kind, int from) const {4377assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");43784379for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {4380if (_use_pos_and_kinds.at(i) >= from && _use_pos_and_kinds.at(i + 1) == exact_use_kind) {4381return _use_pos_and_kinds.at(i);4382}4383}4384return max_jint;4385}43864387int Interval::previous_usage(IntervalUseKind min_use_kind, int from) const {4388assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");43894390int prev = 0;4391for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {4392if (_use_pos_and_kinds.at(i) > from) {4393return prev;4394}4395if (_use_pos_and_kinds.at(i + 1) >= min_use_kind) {4396prev = _use_pos_and_kinds.at(i);4397}4398}4399return prev;4400}44014402void Interval::add_use_pos(int pos, IntervalUseKind use_kind) {4403assert(covers(pos, LIR_OpVisitState::inputMode), "use position not covered by live range");44044405// do not add use positions for precolored intervals because4406// they are never used4407if (use_kind != noUse && reg_num() >= LIR_OprDesc::vreg_base) {4408#ifdef ASSERT4409assert(_use_pos_and_kinds.length() % 2 == 0, "must be");4410for (int i = 0; i < _use_pos_and_kinds.length(); i += 2) {4411assert(pos <= _use_pos_and_kinds.at(i), "already added a use-position with lower position");4412assert(_use_pos_and_kinds.at(i + 1) >= firstValidKind && _use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");4413if (i > 0) {4414assert(_use_pos_and_kinds.at(i) < _use_pos_and_kinds.at(i - 2), "not sorted descending");4415}4416}4417#endif44184419// Note: add_use is called in descending order, so list gets sorted4420// automatically by just appending new use positions4421int len = _use_pos_and_kinds.length();4422if (len == 0 || _use_pos_and_kinds.at(len - 2) > pos) {4423_use_pos_and_kinds.append(pos);4424_use_pos_and_kinds.append(use_kind);4425} else if (_use_pos_and_kinds.at(len - 1) < use_kind) {4426assert(_use_pos_and_kinds.at(len - 2) == pos, "list not sorted correctly");4427_use_pos_and_kinds.at_put(len - 1, use_kind);4428}4429}4430}44314432void Interval::add_range(int from, int to) {4433assert(from < to, "invalid range");4434assert(first() == Range::end() || to < first()->next()->from(), "not inserting at begin of interval");4435assert(from <= first()->to(), "not inserting at begin of interval");44364437if (first()->from() <= to) {4438// join intersecting ranges4439first()->set_from(MIN2(from, first()->from()));4440first()->set_to (MAX2(to, first()->to()));4441} else {4442// insert new range4443_first = new Range(from, to, first());4444}4445}44464447Interval* Interval::new_split_child() {4448// allocate new interval4449Interval* result = new Interval(-1);4450result->set_type(type());44514452Interval* parent = split_parent();4453result->_split_parent = parent;4454result->set_register_hint(parent);44554456// insert new interval in children-list of parent4457if (parent->_split_children == NULL) {4458assert(is_split_parent(), "list must be initialized at first split");44594460parent->_split_children = new IntervalList(4);4461parent->_split_children->append(this);4462}4463parent->_split_children->append(result);44644465return result;4466}44674468// split this interval at the specified position and return4469// the remainder as a new interval.4470//4471// when an interval is split, a bi-directional link is established between the original interval4472// (the split parent) and the intervals that are split off this interval (the split children)4473// When a split child is split again, the new created interval is also a direct child4474// of the original parent (there is no tree of split children stored, but a flat list)4475// All split children are spilled to the same stack slot (stored in _canonical_spill_slot)4476//4477// Note: The new interval has no valid reg_num4478Interval* Interval::split(int split_pos) {4479assert(LinearScan::is_virtual_interval(this), "cannot split fixed intervals");44804481// allocate new interval4482Interval* result = new_split_child();44834484// split the ranges4485Range* prev = NULL;4486Range* cur = _first;4487while (cur != Range::end() && cur->to() <= split_pos) {4488prev = cur;4489cur = cur->next();4490}4491assert(cur != Range::end(), "split interval after end of last range");44924493if (cur->from() < split_pos) {4494result->_first = new Range(split_pos, cur->to(), cur->next());4495cur->set_to(split_pos);4496cur->set_next(Range::end());44974498} else {4499assert(prev != NULL, "split before start of first range");4500result->_first = cur;4501prev->set_next(Range::end());4502}4503result->_current = result->_first;4504_cached_to = -1; // clear cached value45054506// split list of use positions4507int total_len = _use_pos_and_kinds.length();4508int start_idx = total_len - 2;4509while (start_idx >= 0 && _use_pos_and_kinds.at(start_idx) < split_pos) {4510start_idx -= 2;4511}45124513intStack new_use_pos_and_kinds(total_len - start_idx);4514int i;4515for (i = start_idx + 2; i < total_len; i++) {4516new_use_pos_and_kinds.append(_use_pos_and_kinds.at(i));4517}45184519_use_pos_and_kinds.trunc_to(start_idx + 2);4520result->_use_pos_and_kinds = _use_pos_and_kinds;4521_use_pos_and_kinds = new_use_pos_and_kinds;45224523#ifdef ASSERT4524assert(_use_pos_and_kinds.length() % 2 == 0, "must have use kind for each use pos");4525assert(result->_use_pos_and_kinds.length() % 2 == 0, "must have use kind for each use pos");4526assert(_use_pos_and_kinds.length() + result->_use_pos_and_kinds.length() == total_len, "missed some entries");45274528for (i = 0; i < _use_pos_and_kinds.length(); i += 2) {4529assert(_use_pos_and_kinds.at(i) < split_pos, "must be");4530assert(_use_pos_and_kinds.at(i + 1) >= firstValidKind && _use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");4531}4532for (i = 0; i < result->_use_pos_and_kinds.length(); i += 2) {4533assert(result->_use_pos_and_kinds.at(i) >= split_pos, "must be");4534assert(result->_use_pos_and_kinds.at(i + 1) >= firstValidKind && result->_use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");4535}4536#endif45374538return result;4539}45404541// split this interval at the specified position and return4542// the head as a new interval (the original interval is the tail)4543//4544// Currently, only the first range can be split, and the new interval4545// must not have split positions4546Interval* Interval::split_from_start(int split_pos) {4547assert(LinearScan::is_virtual_interval(this), "cannot split fixed intervals");4548assert(split_pos > from() && split_pos < to(), "can only split inside interval");4549assert(split_pos > _first->from() && split_pos <= _first->to(), "can only split inside first range");4550assert(first_usage(noUse) > split_pos, "can not split when use positions are present");45514552// allocate new interval4553Interval* result = new_split_child();45544555// the new created interval has only one range (checked by assertion above),4556// so the splitting of the ranges is very simple4557result->add_range(_first->from(), split_pos);45584559if (split_pos == _first->to()) {4560assert(_first->next() != Range::end(), "must not be at end");4561_first = _first->next();4562} else {4563_first->set_from(split_pos);4564}45654566return result;4567}456845694570// returns true if the op_id is inside the interval4571bool Interval::covers(int op_id, LIR_OpVisitState::OprMode mode) const {4572Range* cur = _first;45734574while (cur != Range::end() && cur->to() < op_id) {4575cur = cur->next();4576}4577if (cur != Range::end()) {4578assert(cur->to() != cur->next()->from(), "ranges not separated");45794580if (mode == LIR_OpVisitState::outputMode) {4581return cur->from() <= op_id && op_id < cur->to();4582} else {4583return cur->from() <= op_id && op_id <= cur->to();4584}4585}4586return false;4587}45884589// returns true if the interval has any hole between hole_from and hole_to4590// (even if the hole has only the length 1)4591bool Interval::has_hole_between(int hole_from, int hole_to) {4592assert(hole_from < hole_to, "check");4593assert(from() <= hole_from && hole_to <= to(), "index out of interval");45944595Range* cur = _first;4596while (cur != Range::end()) {4597assert(cur->to() < cur->next()->from(), "no space between ranges");45984599// hole-range starts before this range -> hole4600if (hole_from < cur->from()) {4601return true;46024603// hole-range completely inside this range -> no hole4604} else if (hole_to <= cur->to()) {4605return false;46064607// overlapping of hole-range with this range -> hole4608} else if (hole_from <= cur->to()) {4609return true;4610}46114612cur = cur->next();4613}46144615return false;4616}46174618// Check if there is an intersection with any of the split children of 'interval'4619bool Interval::intersects_any_children_of(Interval* interval) const {4620if (interval->_split_children != NULL) {4621for (int i = 0; i < interval->_split_children->length(); i++) {4622if (intersects(interval->_split_children->at(i))) {4623return true;4624}4625}4626}4627return false;4628}462946304631#ifndef PRODUCT4632void Interval::print_on(outputStream* out, bool is_cfg_printer) const {4633const char* SpillState2Name[] = { "no definition", "no spill store", "one spill store", "store at definition", "start in memory", "no optimization" };4634const char* UseKind2Name[] = { "N", "L", "S", "M" };46354636const char* type_name;4637if (reg_num() < LIR_OprDesc::vreg_base) {4638type_name = "fixed";4639} else {4640type_name = type2name(type());4641}4642out->print("%d %s ", reg_num(), type_name);46434644if (is_cfg_printer) {4645// Special version for compatibility with C1 Visualizer.4646LIR_Opr opr = LinearScan::get_operand(reg_num());4647if (opr->is_valid()) {4648out->print("\"");4649opr->print(out);4650out->print("\" ");4651}4652} else {4653// Improved output for normal debugging.4654if (reg_num() < LIR_OprDesc::vreg_base) {4655LinearScan::print_reg_num(out, assigned_reg());4656} else if (assigned_reg() != -1 && (LinearScan::num_physical_regs(type()) == 1 || assigned_regHi() != -1)) {4657LinearScan::calc_operand_for_interval(this)->print(out);4658} else {4659// Virtual register that has no assigned register yet.4660out->print("[ANY]");4661}4662out->print(" ");4663}4664out->print("%d %d ", split_parent()->reg_num(), (register_hint(false) != NULL ? register_hint(false)->reg_num() : -1));46654666// print ranges4667Range* cur = _first;4668while (cur != Range::end()) {4669cur->print(out);4670cur = cur->next();4671assert(cur != NULL, "range list not closed with range sentinel");4672}46734674// print use positions4675int prev = 0;4676assert(_use_pos_and_kinds.length() % 2 == 0, "must be");4677for (int i =_use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {4678assert(_use_pos_and_kinds.at(i + 1) >= firstValidKind && _use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");4679assert(prev < _use_pos_and_kinds.at(i), "use positions not sorted");46804681out->print("%d %s ", _use_pos_and_kinds.at(i), UseKind2Name[_use_pos_and_kinds.at(i + 1)]);4682prev = _use_pos_and_kinds.at(i);4683}46844685out->print(" \"%s\"", SpillState2Name[spill_state()]);4686out->cr();4687}46884689void Interval::print_parent() const {4690if (_split_parent != this) {4691_split_parent->print_on(tty);4692} else {4693tty->print_cr("Parent: this");4694}4695}46964697void Interval::print_children() const {4698if (_split_children == NULL) {4699tty->print_cr("Children: []");4700} else {4701tty->print_cr("Children:");4702for (int i = 0; i < _split_children->length(); i++) {4703tty->print("%d: ", i);4704_split_children->at(i)->print_on(tty);4705}4706}4707}4708#endif // NOT PRODUCT47094710471147124713// **** Implementation of IntervalWalker ****************************47144715IntervalWalker::IntervalWalker(LinearScan* allocator, Interval* unhandled_fixed_first, Interval* unhandled_any_first)4716: _compilation(allocator->compilation())4717, _allocator(allocator)4718{4719_unhandled_first[fixedKind] = unhandled_fixed_first;4720_unhandled_first[anyKind] = unhandled_any_first;4721_active_first[fixedKind] = Interval::end();4722_inactive_first[fixedKind] = Interval::end();4723_active_first[anyKind] = Interval::end();4724_inactive_first[anyKind] = Interval::end();4725_current_position = -1;4726_current = NULL;4727next_interval();4728}472947304731// append interval in order of current range from()4732void IntervalWalker::append_sorted(Interval** list, Interval* interval) {4733Interval* prev = NULL;4734Interval* cur = *list;4735while (cur->current_from() < interval->current_from()) {4736prev = cur; cur = cur->next();4737}4738if (prev == NULL) {4739*list = interval;4740} else {4741prev->set_next(interval);4742}4743interval->set_next(cur);4744}47454746void IntervalWalker::append_to_unhandled(Interval** list, Interval* interval) {4747assert(interval->from() >= current()->current_from(), "cannot append new interval before current walk position");47484749Interval* prev = NULL;4750Interval* cur = *list;4751while (cur->from() < interval->from() || (cur->from() == interval->from() && cur->first_usage(noUse) < interval->first_usage(noUse))) {4752prev = cur; cur = cur->next();4753}4754if (prev == NULL) {4755*list = interval;4756} else {4757prev->set_next(interval);4758}4759interval->set_next(cur);4760}476147624763inline bool IntervalWalker::remove_from_list(Interval** list, Interval* i) {4764while (*list != Interval::end() && *list != i) {4765list = (*list)->next_addr();4766}4767if (*list != Interval::end()) {4768assert(*list == i, "check");4769*list = (*list)->next();4770return true;4771} else {4772return false;4773}4774}47754776void IntervalWalker::remove_from_list(Interval* i) {4777bool deleted;47784779if (i->state() == activeState) {4780deleted = remove_from_list(active_first_addr(anyKind), i);4781} else {4782assert(i->state() == inactiveState, "invalid state");4783deleted = remove_from_list(inactive_first_addr(anyKind), i);4784}47854786assert(deleted, "interval has not been found in list");4787}478847894790void IntervalWalker::walk_to(IntervalState state, int from) {4791assert (state == activeState || state == inactiveState, "wrong state");4792for_each_interval_kind(kind) {4793Interval** prev = state == activeState ? active_first_addr(kind) : inactive_first_addr(kind);4794Interval* next = *prev;4795while (next->current_from() <= from) {4796Interval* cur = next;4797next = cur->next();47984799bool range_has_changed = false;4800while (cur->current_to() <= from) {4801cur->next_range();4802range_has_changed = true;4803}48044805// also handle move from inactive list to active list4806range_has_changed = range_has_changed || (state == inactiveState && cur->current_from() <= from);48074808if (range_has_changed) {4809// remove cur from list4810*prev = next;4811if (cur->current_at_end()) {4812// move to handled state (not maintained as a list)4813cur->set_state(handledState);4814DEBUG_ONLY(interval_moved(cur, kind, state, handledState);)4815} else if (cur->current_from() <= from){4816// sort into active list4817append_sorted(active_first_addr(kind), cur);4818cur->set_state(activeState);4819if (*prev == cur) {4820assert(state == activeState, "check");4821prev = cur->next_addr();4822}4823DEBUG_ONLY(interval_moved(cur, kind, state, activeState);)4824} else {4825// sort into inactive list4826append_sorted(inactive_first_addr(kind), cur);4827cur->set_state(inactiveState);4828if (*prev == cur) {4829assert(state == inactiveState, "check");4830prev = cur->next_addr();4831}4832DEBUG_ONLY(interval_moved(cur, kind, state, inactiveState);)4833}4834} else {4835prev = cur->next_addr();4836continue;4837}4838}4839}4840}484148424843void IntervalWalker::next_interval() {4844IntervalKind kind;4845Interval* any = _unhandled_first[anyKind];4846Interval* fixed = _unhandled_first[fixedKind];48474848if (any != Interval::end()) {4849// intervals may start at same position -> prefer fixed interval4850kind = fixed != Interval::end() && fixed->from() <= any->from() ? fixedKind : anyKind;48514852assert (kind == fixedKind && fixed->from() <= any->from() ||4853kind == anyKind && any->from() <= fixed->from(), "wrong interval!!!");4854assert(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");48554856} else if (fixed != Interval::end()) {4857kind = fixedKind;4858} else {4859_current = NULL; return;4860}4861_current_kind = kind;4862_current = _unhandled_first[kind];4863_unhandled_first[kind] = _current->next();4864_current->set_next(Interval::end());4865_current->rewind_range();4866}486748684869void IntervalWalker::walk_to(int lir_op_id) {4870assert(_current_position <= lir_op_id, "can not walk backwards");4871while (current() != NULL) {4872bool is_active = current()->from() <= lir_op_id;4873int id = is_active ? current()->from() : lir_op_id;48744875TRACE_LINEAR_SCAN(2, if (_current_position < id) { tty->cr(); tty->print_cr("walk_to(%d) **************************************************************", id); })48764877// set _current_position prior to call of walk_to4878_current_position = id;48794880// call walk_to even if _current_position == id4881walk_to(activeState, id);4882walk_to(inactiveState, id);48834884if (is_active) {4885current()->set_state(activeState);4886if (activate_current()) {4887append_sorted(active_first_addr(current_kind()), current());4888DEBUG_ONLY(interval_moved(current(), current_kind(), unhandledState, activeState);)4889}48904891next_interval();4892} else {4893return;4894}4895}4896}48974898#ifdef ASSERT4899void IntervalWalker::interval_moved(Interval* interval, IntervalKind kind, IntervalState from, IntervalState to) {4900if (TraceLinearScanLevel >= 4) {4901#define print_state(state) \4902switch(state) {\4903case unhandledState: tty->print("unhandled"); break;\4904case activeState: tty->print("active"); break;\4905case inactiveState: tty->print("inactive"); break;\4906case handledState: tty->print("handled"); break;\4907default: ShouldNotReachHere(); \4908}49094910print_state(from); tty->print(" to "); print_state(to);4911tty->fill_to(23);4912interval->print();49134914#undef print_state4915}4916}4917#endif // ASSERT49184919// **** Implementation of LinearScanWalker **************************49204921LinearScanWalker::LinearScanWalker(LinearScan* allocator, Interval* unhandled_fixed_first, Interval* unhandled_any_first)4922: IntervalWalker(allocator, unhandled_fixed_first, unhandled_any_first)4923, _move_resolver(allocator)4924{4925for (int i = 0; i < LinearScan::nof_regs; i++) {4926_spill_intervals[i] = new IntervalList(2);4927}4928}492949304931inline void LinearScanWalker::init_use_lists(bool only_process_use_pos) {4932for (int i = _first_reg; i <= _last_reg; i++) {4933_use_pos[i] = max_jint;49344935if (!only_process_use_pos) {4936_block_pos[i] = max_jint;4937_spill_intervals[i]->clear();4938}4939}4940}49414942inline void LinearScanWalker::exclude_from_use(int reg) {4943assert(reg < LinearScan::nof_regs, "interval must have a register assigned (stack slots not allowed)");4944if (reg >= _first_reg && reg <= _last_reg) {4945_use_pos[reg] = 0;4946}4947}4948inline void LinearScanWalker::exclude_from_use(Interval* i) {4949assert(i->assigned_reg() != any_reg, "interval has no register assigned");49504951exclude_from_use(i->assigned_reg());4952exclude_from_use(i->assigned_regHi());4953}49544955inline void LinearScanWalker::set_use_pos(int reg, Interval* i, int use_pos, bool only_process_use_pos) {4956assert(use_pos != 0, "must use exclude_from_use to set use_pos to 0");49574958if (reg >= _first_reg && reg <= _last_reg) {4959if (_use_pos[reg] > use_pos) {4960_use_pos[reg] = use_pos;4961}4962if (!only_process_use_pos) {4963_spill_intervals[reg]->append(i);4964}4965}4966}4967inline void LinearScanWalker::set_use_pos(Interval* i, int use_pos, bool only_process_use_pos) {4968assert(i->assigned_reg() != any_reg, "interval has no register assigned");4969if (use_pos != -1) {4970set_use_pos(i->assigned_reg(), i, use_pos, only_process_use_pos);4971set_use_pos(i->assigned_regHi(), i, use_pos, only_process_use_pos);4972}4973}49744975inline void LinearScanWalker::set_block_pos(int reg, Interval* i, int block_pos) {4976if (reg >= _first_reg && reg <= _last_reg) {4977if (_block_pos[reg] > block_pos) {4978_block_pos[reg] = block_pos;4979}4980if (_use_pos[reg] > block_pos) {4981_use_pos[reg] = block_pos;4982}4983}4984}4985inline void LinearScanWalker::set_block_pos(Interval* i, int block_pos) {4986assert(i->assigned_reg() != any_reg, "interval has no register assigned");4987if (block_pos != -1) {4988set_block_pos(i->assigned_reg(), i, block_pos);4989set_block_pos(i->assigned_regHi(), i, block_pos);4990}4991}499249934994void LinearScanWalker::free_exclude_active_fixed() {4995Interval* list = active_first(fixedKind);4996while (list != Interval::end()) {4997assert(list->assigned_reg() < LinearScan::nof_regs, "active interval must have a register assigned");4998exclude_from_use(list);4999list = list->next();5000}5001}50025003void LinearScanWalker::free_exclude_active_any() {5004Interval* list = active_first(anyKind);5005while (list != Interval::end()) {5006exclude_from_use(list);5007list = list->next();5008}5009}50105011void LinearScanWalker::free_collect_inactive_fixed(Interval* cur) {5012Interval* list = inactive_first(fixedKind);5013while (list != Interval::end()) {5014if (cur->to() <= list->current_from()) {5015assert(list->current_intersects_at(cur) == -1, "must not intersect");5016set_use_pos(list, list->current_from(), true);5017} else {5018set_use_pos(list, list->current_intersects_at(cur), true);5019}5020list = list->next();5021}5022}50235024void LinearScanWalker::free_collect_inactive_any(Interval* cur) {5025Interval* list = inactive_first(anyKind);5026while (list != Interval::end()) {5027set_use_pos(list, list->current_intersects_at(cur), true);5028list = list->next();5029}5030}50315032void LinearScanWalker::spill_exclude_active_fixed() {5033Interval* list = active_first(fixedKind);5034while (list != Interval::end()) {5035exclude_from_use(list);5036list = list->next();5037}5038}50395040void LinearScanWalker::spill_block_inactive_fixed(Interval* cur) {5041Interval* list = inactive_first(fixedKind);5042while (list != Interval::end()) {5043if (cur->to() > list->current_from()) {5044set_block_pos(list, list->current_intersects_at(cur));5045} else {5046assert(list->current_intersects_at(cur) == -1, "invalid optimization: intervals intersect");5047}50485049list = list->next();5050}5051}50525053void LinearScanWalker::spill_collect_active_any() {5054Interval* list = active_first(anyKind);5055while (list != Interval::end()) {5056set_use_pos(list, MIN2(list->next_usage(loopEndMarker, _current_position), list->to()), false);5057list = list->next();5058}5059}50605061void LinearScanWalker::spill_collect_inactive_any(Interval* cur) {5062Interval* list = inactive_first(anyKind);5063while (list != Interval::end()) {5064if (list->current_intersects(cur)) {5065set_use_pos(list, MIN2(list->next_usage(loopEndMarker, _current_position), list->to()), false);5066}5067list = list->next();5068}5069}507050715072void LinearScanWalker::insert_move(int op_id, Interval* src_it, Interval* dst_it) {5073// output all moves here. When source and target are equal, the move is5074// optimized away later in assign_reg_nums50755076op_id = (op_id + 1) & ~1;5077BlockBegin* op_block = allocator()->block_of_op_with_id(op_id);5078assert(op_id > 0 && allocator()->block_of_op_with_id(op_id - 2) == op_block, "cannot insert move at block boundary");50795080// calculate index of instruction inside instruction list of current block5081// the minimal index (for a block with no spill moves) can be calculated because the5082// numbering of instructions is known.5083// When the block already contains spill moves, the index must be increased until the5084// correct index is reached.5085LIR_OpList* list = op_block->lir()->instructions_list();5086int index = (op_id - list->at(0)->id()) / 2;5087assert(list->at(index)->id() <= op_id, "error in calculation");50885089while (list->at(index)->id() != op_id) {5090index++;5091assert(0 <= index && index < list->length(), "index out of bounds");5092}5093assert(1 <= index && index < list->length(), "index out of bounds");5094assert(list->at(index)->id() == op_id, "error in calculation");50955096// insert new instruction before instruction at position index5097_move_resolver.move_insert_position(op_block->lir(), index - 1);5098_move_resolver.add_mapping(src_it, dst_it);5099}510051015102int LinearScanWalker::find_optimal_split_pos(BlockBegin* min_block, BlockBegin* max_block, int max_split_pos) {5103int from_block_nr = min_block->linear_scan_number();5104int to_block_nr = max_block->linear_scan_number();51055106assert(0 <= from_block_nr && from_block_nr < block_count(), "out of range");5107assert(0 <= to_block_nr && to_block_nr < block_count(), "out of range");5108assert(from_block_nr < to_block_nr, "must cross block boundary");51095110// Try to split at end of max_block. If this would be after5111// max_split_pos, then use the begin of max_block5112int optimal_split_pos = max_block->last_lir_instruction_id() + 2;5113if (optimal_split_pos > max_split_pos) {5114optimal_split_pos = max_block->first_lir_instruction_id();5115}51165117int min_loop_depth = max_block->loop_depth();5118for (int i = to_block_nr - 1; i >= from_block_nr; i--) {5119BlockBegin* cur = block_at(i);51205121if (cur->loop_depth() < min_loop_depth) {5122// block with lower loop-depth found -> split at the end of this block5123min_loop_depth = cur->loop_depth();5124optimal_split_pos = cur->last_lir_instruction_id() + 2;5125}5126}5127assert(optimal_split_pos > allocator()->max_lir_op_id() || allocator()->is_block_begin(optimal_split_pos), "algorithm must move split pos to block boundary");51285129return optimal_split_pos;5130}513151325133int LinearScanWalker::find_optimal_split_pos(Interval* it, int min_split_pos, int max_split_pos, bool do_loop_optimization) {5134int optimal_split_pos = -1;5135if (min_split_pos == max_split_pos) {5136// trivial case, no optimization of split position possible5137TRACE_LINEAR_SCAN(4, tty->print_cr(" min-pos and max-pos are equal, no optimization possible"));5138optimal_split_pos = min_split_pos;51395140} else {5141assert(min_split_pos < max_split_pos, "must be true then");5142assert(min_split_pos > 0, "cannot access min_split_pos - 1 otherwise");51435144// reason for using min_split_pos - 1: when the minimal split pos is exactly at the5145// beginning of a block, then min_split_pos is also a possible split position.5146// Use the block before as min_block, because then min_block->last_lir_instruction_id() + 2 == min_split_pos5147BlockBegin* min_block = allocator()->block_of_op_with_id(min_split_pos - 1);51485149// reason for using max_split_pos - 1: otherwise there would be an assertion failure5150// when an interval ends at the end of the last block of the method5151// (in this case, max_split_pos == allocator()->max_lir_op_id() + 2, and there is no5152// block at this op_id)5153BlockBegin* max_block = allocator()->block_of_op_with_id(max_split_pos - 1);51545155assert(min_block->linear_scan_number() <= max_block->linear_scan_number(), "invalid order");5156if (min_block == max_block) {5157// split position cannot be moved to block boundary, so split as late as possible5158TRACE_LINEAR_SCAN(4, tty->print_cr(" cannot move split pos to block boundary because min_pos and max_pos are in same block"));5159optimal_split_pos = max_split_pos;51605161} else if (it->has_hole_between(max_split_pos - 1, max_split_pos) && !allocator()->is_block_begin(max_split_pos)) {5162// Do not move split position if the interval has a hole before max_split_pos.5163// Intervals resulting from Phi-Functions have more than one definition (marked5164// as mustHaveRegister) with a hole before each definition. When the register is needed5165// for the second definition, an earlier reloading is unnecessary.5166TRACE_LINEAR_SCAN(4, tty->print_cr(" interval has hole just before max_split_pos, so splitting at max_split_pos"));5167optimal_split_pos = max_split_pos;51685169} else {5170// seach optimal block boundary between min_split_pos and max_split_pos5171TRACE_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()));51725173if (do_loop_optimization) {5174// Loop optimization: if a loop-end marker is found between min- and max-position,5175// then split before this loop5176int loop_end_pos = it->next_usage_exact(loopEndMarker, min_block->last_lir_instruction_id() + 2);5177TRACE_LINEAR_SCAN(4, tty->print_cr(" loop optimization: loop end found at pos %d", loop_end_pos));51785179assert(loop_end_pos > min_split_pos, "invalid order");5180if (loop_end_pos < max_split_pos) {5181// loop-end marker found between min- and max-position5182// if it is not the end marker for the same loop as the min-position, then move5183// the max-position to this loop block.5184// Desired result: uses tagged as shouldHaveRegister inside a loop cause a reloading5185// of the interval (normally, only mustHaveRegister causes a reloading)5186BlockBegin* loop_block = allocator()->block_of_op_with_id(loop_end_pos);51875188TRACE_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()));5189assert(loop_block != min_block, "loop_block and min_block must be different because block boundary is needed between");51905191optimal_split_pos = find_optimal_split_pos(min_block, loop_block, loop_block->last_lir_instruction_id() + 2);5192if (optimal_split_pos == loop_block->last_lir_instruction_id() + 2) {5193optimal_split_pos = -1;5194TRACE_LINEAR_SCAN(4, tty->print_cr(" loop optimization not necessary"));5195} else {5196TRACE_LINEAR_SCAN(4, tty->print_cr(" loop optimization successful"));5197}5198}5199}52005201if (optimal_split_pos == -1) {5202// not calculated by loop optimization5203optimal_split_pos = find_optimal_split_pos(min_block, max_block, max_split_pos);5204}5205}5206}5207TRACE_LINEAR_SCAN(4, tty->print_cr(" optimal split position: %d", optimal_split_pos));52085209return optimal_split_pos;5210}521152125213/*5214split an interval at the optimal position between min_split_pos and5215max_split_pos in two parts:52161) the left part has already a location assigned52172) the right part is sorted into to the unhandled-list5218*/5219void LinearScanWalker::split_before_usage(Interval* it, int min_split_pos, int max_split_pos) {5220TRACE_LINEAR_SCAN(2, tty->print ("----- splitting interval: "); it->print());5221TRACE_LINEAR_SCAN(2, tty->print_cr(" between %d and %d", min_split_pos, max_split_pos));52225223assert(it->from() < min_split_pos, "cannot split at start of interval");5224assert(current_position() < min_split_pos, "cannot split before current position");5225assert(min_split_pos <= max_split_pos, "invalid order");5226assert(max_split_pos <= it->to(), "cannot split after end of interval");52275228int optimal_split_pos = find_optimal_split_pos(it, min_split_pos, max_split_pos, true);52295230assert(min_split_pos <= optimal_split_pos && optimal_split_pos <= max_split_pos, "out of range");5231assert(optimal_split_pos <= it->to(), "cannot split after end of interval");5232assert(optimal_split_pos > it->from(), "cannot split at start of interval");52335234if (optimal_split_pos == it->to() && it->next_usage(mustHaveRegister, min_split_pos) == max_jint) {5235// the split position would be just before the end of the interval5236// -> no split at all necessary5237TRACE_LINEAR_SCAN(4, tty->print_cr(" no split necessary because optimal split position is at end of interval"));5238return;5239}52405241// must calculate this before the actual split is performed and before split position is moved to odd op_id5242bool move_necessary = !allocator()->is_block_begin(optimal_split_pos) && !it->has_hole_between(optimal_split_pos - 1, optimal_split_pos);52435244if (!allocator()->is_block_begin(optimal_split_pos)) {5245// move position before actual instruction (odd op_id)5246optimal_split_pos = (optimal_split_pos - 1) | 1;5247}52485249TRACE_LINEAR_SCAN(4, tty->print_cr(" splitting at position %d", optimal_split_pos));5250assert(allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 1), "split pos must be odd when not on block boundary");5251assert(!allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 0), "split pos must be even on block boundary");52525253Interval* split_part = it->split(optimal_split_pos);52545255allocator()->append_interval(split_part);5256allocator()->copy_register_flags(it, split_part);5257split_part->set_insert_move_when_activated(move_necessary);5258append_to_unhandled(unhandled_first_addr(anyKind), split_part);52595260TRACE_LINEAR_SCAN(2, tty->print_cr(" split interval in two parts (insert_move_when_activated: %d)", move_necessary));5261TRACE_LINEAR_SCAN(2, tty->print (" "); it->print());5262TRACE_LINEAR_SCAN(2, tty->print (" "); split_part->print());5263}52645265/*5266split an interval at the optimal position between min_split_pos and5267max_split_pos in two parts:52681) the left part has already a location assigned52692) the right part is always on the stack and therefore ignored in further processing5270*/5271void LinearScanWalker::split_for_spilling(Interval* it) {5272// calculate allowed range of splitting position5273int max_split_pos = current_position();5274int min_split_pos = MAX2(it->previous_usage(shouldHaveRegister, max_split_pos) + 1, it->from());52755276TRACE_LINEAR_SCAN(2, tty->print ("----- splitting and spilling interval: "); it->print());5277TRACE_LINEAR_SCAN(2, tty->print_cr(" between %d and %d", min_split_pos, max_split_pos));52785279assert(it->state() == activeState, "why spill interval that is not active?");5280assert(it->from() <= min_split_pos, "cannot split before start of interval");5281assert(min_split_pos <= max_split_pos, "invalid order");5282assert(max_split_pos < it->to(), "cannot split at end end of interval");5283assert(current_position() < it->to(), "interval must not end before current position");52845285if (min_split_pos == it->from()) {5286// the whole interval is never used, so spill it entirely to memory5287TRACE_LINEAR_SCAN(2, tty->print_cr(" spilling entire interval because split pos is at beginning of interval"));5288assert(it->first_usage(shouldHaveRegister) > current_position(), "interval must not have use position before current_position");52895290allocator()->assign_spill_slot(it);5291allocator()->change_spill_state(it, min_split_pos);52925293// Also kick parent intervals out of register to memory when they have no use5294// position. This avoids short interval in register surrounded by intervals in5295// memory -> avoid useless moves from memory to register and back5296Interval* parent = it;5297while (parent != NULL && parent->is_split_child()) {5298parent = parent->split_child_before_op_id(parent->from());52995300if (parent->assigned_reg() < LinearScan::nof_regs) {5301if (parent->first_usage(shouldHaveRegister) == max_jint) {5302// parent is never used, so kick it out of its assigned register5303TRACE_LINEAR_SCAN(4, tty->print_cr(" kicking out interval %d out of its register because it is never used", parent->reg_num()));5304allocator()->assign_spill_slot(parent);5305} else {5306// do not go further back because the register is actually used by the interval5307parent = NULL;5308}5309}5310}53115312} else {5313// search optimal split pos, split interval and spill only the right hand part5314int optimal_split_pos = find_optimal_split_pos(it, min_split_pos, max_split_pos, false);53155316assert(min_split_pos <= optimal_split_pos && optimal_split_pos <= max_split_pos, "out of range");5317assert(optimal_split_pos < it->to(), "cannot split at end of interval");5318assert(optimal_split_pos >= it->from(), "cannot split before start of interval");53195320if (!allocator()->is_block_begin(optimal_split_pos)) {5321// move position before actual instruction (odd op_id)5322optimal_split_pos = (optimal_split_pos - 1) | 1;5323}53245325TRACE_LINEAR_SCAN(4, tty->print_cr(" splitting at position %d", optimal_split_pos));5326assert(allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 1), "split pos must be odd when not on block boundary");5327assert(!allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 0), "split pos must be even on block boundary");53285329Interval* spilled_part = it->split(optimal_split_pos);5330allocator()->append_interval(spilled_part);5331allocator()->assign_spill_slot(spilled_part);5332allocator()->change_spill_state(spilled_part, optimal_split_pos);53335334if (!allocator()->is_block_begin(optimal_split_pos)) {5335TRACE_LINEAR_SCAN(4, tty->print_cr(" inserting move from interval %d to %d", it->reg_num(), spilled_part->reg_num()));5336insert_move(optimal_split_pos, it, spilled_part);5337}53385339// the current_split_child is needed later when moves are inserted for reloading5340assert(spilled_part->current_split_child() == it, "overwriting wrong current_split_child");5341spilled_part->make_current_split_child();53425343TRACE_LINEAR_SCAN(2, tty->print_cr(" split interval in two parts"));5344TRACE_LINEAR_SCAN(2, tty->print (" "); it->print());5345TRACE_LINEAR_SCAN(2, tty->print (" "); spilled_part->print());5346}5347}534853495350void LinearScanWalker::split_stack_interval(Interval* it) {5351int min_split_pos = current_position() + 1;5352int max_split_pos = MIN2(it->first_usage(shouldHaveRegister), it->to());53535354split_before_usage(it, min_split_pos, max_split_pos);5355}53565357void LinearScanWalker::split_when_partial_register_available(Interval* it, int register_available_until) {5358int min_split_pos = MAX2(it->previous_usage(shouldHaveRegister, register_available_until), it->from() + 1);5359int max_split_pos = register_available_until;53605361split_before_usage(it, min_split_pos, max_split_pos);5362}53635364void LinearScanWalker::split_and_spill_interval(Interval* it) {5365assert(it->state() == activeState || it->state() == inactiveState, "other states not allowed");53665367int current_pos = current_position();5368if (it->state() == inactiveState) {5369// the interval is currently inactive, so no spill slot is needed for now.5370// when the split part is activated, the interval has a new chance to get a register,5371// so in the best case no stack slot is necessary5372assert(it->has_hole_between(current_pos - 1, current_pos + 1), "interval can not be inactive otherwise");5373split_before_usage(it, current_pos + 1, current_pos + 1);53745375} else {5376// search the position where the interval must have a register and split5377// at the optimal position before.5378// The new created part is added to the unhandled list and will get a register5379// when it is activated5380int min_split_pos = current_pos + 1;5381int max_split_pos = MIN2(it->next_usage(mustHaveRegister, min_split_pos), it->to());53825383split_before_usage(it, min_split_pos, max_split_pos);53845385assert(it->next_usage(mustHaveRegister, current_pos) == max_jint, "the remaining part is spilled to stack and therefore has no register");5386split_for_spilling(it);5387}5388}53895390int LinearScanWalker::find_free_reg(int reg_needed_until, int interval_to, int hint_reg, int ignore_reg, bool* need_split) {5391int min_full_reg = any_reg;5392int max_partial_reg = any_reg;53935394for (int i = _first_reg; i <= _last_reg; i++) {5395if (i == ignore_reg) {5396// this register must be ignored53975398} else if (_use_pos[i] >= interval_to) {5399// this register is free for the full interval5400if (min_full_reg == any_reg || i == hint_reg || (_use_pos[i] < _use_pos[min_full_reg] && min_full_reg != hint_reg)) {5401min_full_reg = i;5402}5403} else if (_use_pos[i] > reg_needed_until) {5404// this register is at least free until reg_needed_until5405if (max_partial_reg == any_reg || i == hint_reg || (_use_pos[i] > _use_pos[max_partial_reg] && max_partial_reg != hint_reg)) {5406max_partial_reg = i;5407}5408}5409}54105411if (min_full_reg != any_reg) {5412return min_full_reg;5413} else if (max_partial_reg != any_reg) {5414*need_split = true;5415return max_partial_reg;5416} else {5417return any_reg;5418}5419}54205421int LinearScanWalker::find_free_double_reg(int reg_needed_until, int interval_to, int hint_reg, bool* need_split) {5422assert((_last_reg - _first_reg + 1) % 2 == 0, "adjust algorithm");54235424int min_full_reg = any_reg;5425int max_partial_reg = any_reg;54265427for (int i = _first_reg; i < _last_reg; i+=2) {5428if (_use_pos[i] >= interval_to && _use_pos[i + 1] >= interval_to) {5429// this register is free for the full interval5430if (min_full_reg == any_reg || i == hint_reg || (_use_pos[i] < _use_pos[min_full_reg] && min_full_reg != hint_reg)) {5431min_full_reg = i;5432}5433} else if (_use_pos[i] > reg_needed_until && _use_pos[i + 1] > reg_needed_until) {5434// this register is at least free until reg_needed_until5435if (max_partial_reg == any_reg || i == hint_reg || (_use_pos[i] > _use_pos[max_partial_reg] && max_partial_reg != hint_reg)) {5436max_partial_reg = i;5437}5438}5439}54405441if (min_full_reg != any_reg) {5442return min_full_reg;5443} else if (max_partial_reg != any_reg) {5444*need_split = true;5445return max_partial_reg;5446} else {5447return any_reg;5448}5449}54505451bool LinearScanWalker::alloc_free_reg(Interval* cur) {5452TRACE_LINEAR_SCAN(2, tty->print("trying to find free register for "); cur->print());54535454init_use_lists(true);5455free_exclude_active_fixed();5456free_exclude_active_any();5457free_collect_inactive_fixed(cur);5458free_collect_inactive_any(cur);5459assert(unhandled_first(fixedKind) == Interval::end(), "must not have unhandled fixed intervals because all fixed intervals have a use at position 0");54605461// _use_pos contains the start of the next interval that has this register assigned5462// (either as a fixed register or a normal allocated register in the past)5463// only intervals overlapping with cur are processed, non-overlapping invervals can be ignored safely5464#ifdef ASSERT5465if (TraceLinearScanLevel >= 4) {5466tty->print_cr(" state of registers:");5467for (int i = _first_reg; i <= _last_reg; i++) {5468tty->print(" reg %d (", i);5469LinearScan::print_reg_num(i);5470tty->print_cr("): use_pos: %d", _use_pos[i]);5471}5472}5473#endif54745475int hint_reg, hint_regHi;5476Interval* register_hint = cur->register_hint();5477if (register_hint != NULL) {5478hint_reg = register_hint->assigned_reg();5479hint_regHi = register_hint->assigned_regHi();54805481if (_num_phys_regs == 2 && allocator()->is_precolored_cpu_interval(register_hint)) {5482assert(hint_reg != any_reg && hint_regHi == any_reg, "must be for fixed intervals");5483hint_regHi = hint_reg + 1; // connect e.g. eax-edx5484}5485#ifdef ASSERT5486if (TraceLinearScanLevel >= 4) {5487tty->print(" hint registers %d (", hint_reg);5488LinearScan::print_reg_num(hint_reg);5489tty->print("), %d (", hint_regHi);5490LinearScan::print_reg_num(hint_regHi);5491tty->print(") from interval ");5492register_hint->print();5493}5494#endif5495} else {5496hint_reg = any_reg;5497hint_regHi = any_reg;5498}5499assert(hint_reg == any_reg || hint_reg != hint_regHi, "hint reg and regHi equal");5500assert(cur->assigned_reg() == any_reg && cur->assigned_regHi() == any_reg, "register already assigned to interval");55015502// the register must be free at least until this position5503int reg_needed_until = cur->from() + 1;5504int interval_to = cur->to();55055506bool need_split = false;5507int split_pos;5508int reg;5509int regHi = any_reg;55105511if (_adjacent_regs) {5512reg = find_free_double_reg(reg_needed_until, interval_to, hint_reg, &need_split);5513regHi = reg + 1;5514if (reg == any_reg) {5515return false;5516}5517split_pos = MIN2(_use_pos[reg], _use_pos[regHi]);55185519} else {5520reg = find_free_reg(reg_needed_until, interval_to, hint_reg, any_reg, &need_split);5521if (reg == any_reg) {5522return false;5523}5524split_pos = _use_pos[reg];55255526if (_num_phys_regs == 2) {5527regHi = find_free_reg(reg_needed_until, interval_to, hint_regHi, reg, &need_split);55285529if (_use_pos[reg] < interval_to && regHi == any_reg) {5530// do not split interval if only one register can be assigned until the split pos5531// (when one register is found for the whole interval, split&spill is only5532// performed for the hi register)5533return false;55345535} else if (regHi != any_reg) {5536split_pos = MIN2(split_pos, _use_pos[regHi]);55375538// sort register numbers to prevent e.g. a move from eax,ebx to ebx,eax5539if (reg > regHi) {5540int temp = reg;5541reg = regHi;5542regHi = temp;5543}5544}5545}5546}55475548cur->assign_reg(reg, regHi);5549#ifdef ASSERT5550if (TraceLinearScanLevel >= 2) {5551tty->print(" selected registers %d (", reg);5552LinearScan::print_reg_num(reg);5553tty->print("), %d (", regHi);5554LinearScan::print_reg_num(regHi);5555tty->print_cr(")");5556}5557#endif5558assert(split_pos > 0, "invalid split_pos");5559if (need_split) {5560// register not available for full interval, so split it5561split_when_partial_register_available(cur, split_pos);5562}55635564// only return true if interval is completely assigned5565return _num_phys_regs == 1 || regHi != any_reg;5566}556755685569int LinearScanWalker::find_locked_reg(int reg_needed_until, int interval_to, int ignore_reg, bool* need_split) {5570int max_reg = any_reg;55715572for (int i = _first_reg; i <= _last_reg; i++) {5573if (i == ignore_reg) {5574// this register must be ignored55755576} else if (_use_pos[i] > reg_needed_until) {5577if (max_reg == any_reg || _use_pos[i] > _use_pos[max_reg]) {5578max_reg = i;5579}5580}5581}55825583if (max_reg != any_reg && _block_pos[max_reg] <= interval_to) {5584*need_split = true;5585}55865587return max_reg;5588}55895590int LinearScanWalker::find_locked_double_reg(int reg_needed_until, int interval_to, bool* need_split) {5591assert((_last_reg - _first_reg + 1) % 2 == 0, "adjust algorithm");55925593int max_reg = any_reg;55945595for (int i = _first_reg; i < _last_reg; i+=2) {5596if (_use_pos[i] > reg_needed_until && _use_pos[i + 1] > reg_needed_until) {5597if (max_reg == any_reg || _use_pos[i] > _use_pos[max_reg]) {5598max_reg = i;5599}5600}5601}56025603if (max_reg != any_reg &&5604(_block_pos[max_reg] <= interval_to || _block_pos[max_reg + 1] <= interval_to)) {5605*need_split = true;5606}56075608return max_reg;5609}56105611void LinearScanWalker::split_and_spill_intersecting_intervals(int reg, int regHi) {5612assert(reg != any_reg, "no register assigned");56135614for (int i = 0; i < _spill_intervals[reg]->length(); i++) {5615Interval* it = _spill_intervals[reg]->at(i);5616remove_from_list(it);5617split_and_spill_interval(it);5618}56195620if (regHi != any_reg) {5621IntervalList* processed = _spill_intervals[reg];5622for (int i = 0; i < _spill_intervals[regHi]->length(); i++) {5623Interval* it = _spill_intervals[regHi]->at(i);5624if (processed->find(it) == -1) {5625remove_from_list(it);5626split_and_spill_interval(it);5627}5628}5629}5630}563156325633// Split an Interval and spill it to memory so that cur can be placed in a register5634void LinearScanWalker::alloc_locked_reg(Interval* cur) {5635TRACE_LINEAR_SCAN(2, tty->print("need to split and spill to get register for "); cur->print());56365637// collect current usage of registers5638init_use_lists(false);5639spill_exclude_active_fixed();5640assert(unhandled_first(fixedKind) == Interval::end(), "must not have unhandled fixed intervals because all fixed intervals have a use at position 0");5641spill_block_inactive_fixed(cur);5642spill_collect_active_any();5643spill_collect_inactive_any(cur);56445645#ifdef ASSERT5646if (TraceLinearScanLevel >= 4) {5647tty->print_cr(" state of registers:");5648for (int i = _first_reg; i <= _last_reg; i++) {5649tty->print(" reg %d(", i);5650LinearScan::print_reg_num(i);5651tty->print("): use_pos: %d, block_pos: %d, intervals: ", _use_pos[i], _block_pos[i]);5652for (int j = 0; j < _spill_intervals[i]->length(); j++) {5653tty->print("%d ", _spill_intervals[i]->at(j)->reg_num());5654}5655tty->cr();5656}5657}5658#endif56595660// the register must be free at least until this position5661int reg_needed_until = MIN2(cur->first_usage(mustHaveRegister), cur->from() + 1);5662int interval_to = cur->to();5663assert (reg_needed_until > 0 && reg_needed_until < max_jint, "interval has no use");56645665int split_pos = 0;5666int use_pos = 0;5667bool need_split = false;5668int reg, regHi;56695670if (_adjacent_regs) {5671reg = find_locked_double_reg(reg_needed_until, interval_to, &need_split);5672regHi = reg + 1;56735674if (reg != any_reg) {5675use_pos = MIN2(_use_pos[reg], _use_pos[regHi]);5676split_pos = MIN2(_block_pos[reg], _block_pos[regHi]);5677}5678} else {5679reg = find_locked_reg(reg_needed_until, interval_to, cur->assigned_reg(), &need_split);5680regHi = any_reg;56815682if (reg != any_reg) {5683use_pos = _use_pos[reg];5684split_pos = _block_pos[reg];56855686if (_num_phys_regs == 2) {5687if (cur->assigned_reg() != any_reg) {5688regHi = reg;5689reg = cur->assigned_reg();5690} else {5691regHi = find_locked_reg(reg_needed_until, interval_to, reg, &need_split);5692if (regHi != any_reg) {5693use_pos = MIN2(use_pos, _use_pos[regHi]);5694split_pos = MIN2(split_pos, _block_pos[regHi]);5695}5696}56975698if (regHi != any_reg && reg > regHi) {5699// sort register numbers to prevent e.g. a move from eax,ebx to ebx,eax5700int temp = reg;5701reg = regHi;5702regHi = temp;5703}5704}5705}5706}57075708if (reg == any_reg || (_num_phys_regs == 2 && regHi == any_reg) || use_pos <= cur->first_usage(mustHaveRegister)) {5709// the first use of cur is later than the spilling position -> spill cur5710TRACE_LINEAR_SCAN(4, tty->print_cr("able to spill current interval. first_usage(register): %d, use_pos: %d", cur->first_usage(mustHaveRegister), use_pos));57115712if (cur->first_usage(mustHaveRegister) <= cur->from() + 1) {5713assert(false, "cannot spill interval that is used in first instruction (possible reason: no register found)");5714// assign a reasonable register and do a bailout in product mode to avoid errors5715allocator()->assign_spill_slot(cur);5716BAILOUT("LinearScan: no register found");5717}57185719split_and_spill_interval(cur);5720} else {5721#ifdef ASSERT5722if (TraceLinearScanLevel >= 4) {5723tty->print("decided to use register %d (", reg);5724LinearScan::print_reg_num(reg);5725tty->print("), %d (", regHi);5726LinearScan::print_reg_num(regHi);5727tty->print_cr(")");5728}5729#endif5730assert(reg != any_reg && (_num_phys_regs == 1 || regHi != any_reg), "no register found");5731assert(split_pos > 0, "invalid split_pos");5732assert(need_split == false || split_pos > cur->from(), "splitting interval at from");57335734cur->assign_reg(reg, regHi);5735if (need_split) {5736// register not available for full interval, so split it5737split_when_partial_register_available(cur, split_pos);5738}57395740// perform splitting and spilling for all affected intervalls5741split_and_spill_intersecting_intervals(reg, regHi);5742}5743}57445745bool LinearScanWalker::no_allocation_possible(Interval* cur) {5746#ifdef X865747// fast calculation of intervals that can never get a register because the5748// the next instruction is a call that blocks all registers5749// Note: this does not work if callee-saved registers are available (e.g. on Sparc)57505751// check if this interval is the result of a split operation5752// (an interval got a register until this position)5753int pos = cur->from();5754if ((pos & 1) == 1) {5755// the current instruction is a call that blocks all registers5756if (pos < allocator()->max_lir_op_id() && allocator()->has_call(pos + 1)) {5757TRACE_LINEAR_SCAN(4, tty->print_cr(" free register cannot be available because all registers blocked by following call"));57585759// safety check that there is really no register available5760assert(alloc_free_reg(cur) == false, "found a register for this interval");5761return true;5762}57635764}5765#endif5766return false;5767}57685769void LinearScanWalker::init_vars_for_alloc(Interval* cur) {5770BasicType type = cur->type();5771_num_phys_regs = LinearScan::num_physical_regs(type);5772_adjacent_regs = LinearScan::requires_adjacent_regs(type);57735774if (pd_init_regs_for_alloc(cur)) {5775// the appropriate register range was selected.5776} else if (type == T_FLOAT || type == T_DOUBLE) {5777_first_reg = pd_first_fpu_reg;5778_last_reg = pd_last_fpu_reg;5779} else {5780_first_reg = pd_first_cpu_reg;5781_last_reg = FrameMap::last_cpu_reg();5782}57835784assert(0 <= _first_reg && _first_reg < LinearScan::nof_regs, "out of range");5785assert(0 <= _last_reg && _last_reg < LinearScan::nof_regs, "out of range");5786}578757885789bool LinearScanWalker::is_move(LIR_Op* op, Interval* from, Interval* to) {5790if (op->code() != lir_move) {5791return false;5792}5793assert(op->as_Op1() != NULL, "move must be LIR_Op1");57945795LIR_Opr in = ((LIR_Op1*)op)->in_opr();5796LIR_Opr res = ((LIR_Op1*)op)->result_opr();5797return in->is_virtual() && res->is_virtual() && in->vreg_number() == from->reg_num() && res->vreg_number() == to->reg_num();5798}57995800// optimization (especially for phi functions of nested loops):5801// assign same spill slot to non-intersecting intervals5802void LinearScanWalker::combine_spilled_intervals(Interval* cur) {5803if (cur->is_split_child()) {5804// optimization is only suitable for split parents5805return;5806}58075808Interval* register_hint = cur->register_hint(false);5809if (register_hint == NULL) {5810// cur is not the target of a move, otherwise register_hint would be set5811return;5812}5813assert(register_hint->is_split_parent(), "register hint must be split parent");58145815if (cur->spill_state() != noOptimization || register_hint->spill_state() != noOptimization) {5816// combining the stack slots for intervals where spill move optimization is applied5817// is not benefitial and would cause problems5818return;5819}58205821int begin_pos = cur->from();5822int end_pos = cur->to();5823if (end_pos > allocator()->max_lir_op_id() || (begin_pos & 1) != 0 || (end_pos & 1) != 0) {5824// safety check that lir_op_with_id is allowed5825return;5826}58275828if (!is_move(allocator()->lir_op_with_id(begin_pos), register_hint, cur) || !is_move(allocator()->lir_op_with_id(end_pos), cur, register_hint)) {5829// cur and register_hint are not connected with two moves5830return;5831}58325833Interval* begin_hint = register_hint->split_child_at_op_id(begin_pos, LIR_OpVisitState::inputMode);5834Interval* end_hint = register_hint->split_child_at_op_id(end_pos, LIR_OpVisitState::outputMode);5835if (begin_hint == end_hint || begin_hint->to() != begin_pos || end_hint->from() != end_pos) {5836// register_hint must be split, otherwise the re-writing of use positions does not work5837return;5838}58395840assert(begin_hint->assigned_reg() != any_reg, "must have register assigned");5841assert(end_hint->assigned_reg() == any_reg, "must not have register assigned");5842assert(cur->first_usage(mustHaveRegister) == begin_pos, "must have use position at begin of interval because of move");5843assert(end_hint->first_usage(mustHaveRegister) == end_pos, "must have use position at begin of interval because of move");58445845if (begin_hint->assigned_reg() < LinearScan::nof_regs) {5846// register_hint is not spilled at begin_pos, so it would not be benefitial to immediately spill cur5847return;5848}5849assert(register_hint->canonical_spill_slot() != -1, "must be set when part of interval was spilled");5850assert(!cur->intersects(register_hint), "cur should not intersect register_hint");58515852if (cur->intersects_any_children_of(register_hint)) {5853// 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 with5854// 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.5855return;5856}58575858// modify intervals such that cur gets the same stack slot as register_hint5859// delete use positions to prevent the intervals to get a register at beginning5860cur->set_canonical_spill_slot(register_hint->canonical_spill_slot());5861cur->remove_first_use_pos();5862end_hint->remove_first_use_pos();5863}586458655866// allocate a physical register or memory location to an interval5867bool LinearScanWalker::activate_current() {5868Interval* cur = current();5869bool result = true;58705871TRACE_LINEAR_SCAN(2, tty->print ("+++++ activating interval "); cur->print());5872TRACE_LINEAR_SCAN(4, tty->print_cr(" split_parent: %d, insert_move_when_activated: %d", cur->split_parent()->reg_num(), cur->insert_move_when_activated()));58735874if (cur->assigned_reg() >= LinearScan::nof_regs) {5875// activating an interval that has a stack slot assigned -> split it at first use position5876// used for method parameters5877TRACE_LINEAR_SCAN(4, tty->print_cr(" interval has spill slot assigned (method parameter) -> split it before first use"));58785879split_stack_interval(cur);5880result = false;58815882} else if (allocator()->gen()->is_vreg_flag_set(cur->reg_num(), LIRGenerator::must_start_in_memory)) {5883// activating an interval that must start in a stack slot, but may get a register later5884// used for lir_roundfp: rounding is done by store to stack and reload later5885TRACE_LINEAR_SCAN(4, tty->print_cr(" interval must start in stack slot -> split it before first use"));5886assert(cur->assigned_reg() == any_reg && cur->assigned_regHi() == any_reg, "register already assigned");58875888allocator()->assign_spill_slot(cur);5889split_stack_interval(cur);5890result = false;58915892} else if (cur->assigned_reg() == any_reg) {5893// interval has not assigned register -> normal allocation5894// (this is the normal case for most intervals)5895TRACE_LINEAR_SCAN(4, tty->print_cr(" normal allocation of register"));58965897// assign same spill slot to non-intersecting intervals5898combine_spilled_intervals(cur);58995900init_vars_for_alloc(cur);5901if (no_allocation_possible(cur) || !alloc_free_reg(cur)) {5902// no empty register available.5903// split and spill another interval so that this interval gets a register5904alloc_locked_reg(cur);5905}59065907// spilled intervals need not be move to active-list5908if (cur->assigned_reg() >= LinearScan::nof_regs) {5909result = false;5910}5911}59125913// load spilled values that become active from stack slot to register5914if (cur->insert_move_when_activated()) {5915assert(cur->is_split_child(), "must be");5916assert(cur->current_split_child() != NULL, "must be");5917assert(cur->current_split_child()->reg_num() != cur->reg_num(), "cannot insert move between same interval");5918TRACE_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()));59195920insert_move(cur->from(), cur->current_split_child(), cur);5921}5922cur->make_current_split_child();59235924return result; // true = interval is moved to active list5925}592659275928// Implementation of EdgeMoveOptimizer59295930EdgeMoveOptimizer::EdgeMoveOptimizer() :5931_edge_instructions(4),5932_edge_instructions_idx(4)5933{5934}59355936void EdgeMoveOptimizer::optimize(BlockList* code) {5937EdgeMoveOptimizer optimizer = EdgeMoveOptimizer();59385939// ignore the first block in the list (index 0 is not processed)5940for (int i = code->length() - 1; i >= 1; i--) {5941BlockBegin* block = code->at(i);59425943if (block->number_of_preds() > 1 && !block->is_set(BlockBegin::exception_entry_flag)) {5944optimizer.optimize_moves_at_block_end(block);5945}5946if (block->number_of_sux() == 2) {5947optimizer.optimize_moves_at_block_begin(block);5948}5949}5950}595159525953// clear all internal data structures5954void EdgeMoveOptimizer::init_instructions() {5955_edge_instructions.clear();5956_edge_instructions_idx.clear();5957}59585959// append a lir-instruction-list and the index of the current operation in to the list5960void EdgeMoveOptimizer::append_instructions(LIR_OpList* instructions, int instructions_idx) {5961_edge_instructions.append(instructions);5962_edge_instructions_idx.append(instructions_idx);5963}59645965// return the current operation of the given edge (predecessor or successor)5966LIR_Op* EdgeMoveOptimizer::instruction_at(int edge) {5967LIR_OpList* instructions = _edge_instructions.at(edge);5968int idx = _edge_instructions_idx.at(edge);59695970if (idx < instructions->length()) {5971return instructions->at(idx);5972} else {5973return NULL;5974}5975}59765977// removes the current operation of the given edge (predecessor or successor)5978void EdgeMoveOptimizer::remove_cur_instruction(int edge, bool decrement_index) {5979LIR_OpList* instructions = _edge_instructions.at(edge);5980int idx = _edge_instructions_idx.at(edge);5981instructions->remove_at(idx);59825983if (decrement_index) {5984_edge_instructions_idx.at_put(edge, idx - 1);5985}5986}598759885989bool EdgeMoveOptimizer::operations_different(LIR_Op* op1, LIR_Op* op2) {5990if (op1 == NULL || op2 == NULL) {5991// at least one block is already empty -> no optimization possible5992return true;5993}59945995if (op1->code() == lir_move && op2->code() == lir_move) {5996assert(op1->as_Op1() != NULL, "move must be LIR_Op1");5997assert(op2->as_Op1() != NULL, "move must be LIR_Op1");5998LIR_Op1* move1 = (LIR_Op1*)op1;5999LIR_Op1* move2 = (LIR_Op1*)op2;6000if (move1->info() == move2->info() && move1->in_opr() == move2->in_opr() && move1->result_opr() == move2->result_opr()) {6001// these moves are exactly equal and can be optimized6002return false;6003}60046005} else if (op1->code() == lir_fxch && op2->code() == lir_fxch) {6006assert(op1->as_Op1() != NULL, "fxch must be LIR_Op1");6007assert(op2->as_Op1() != NULL, "fxch must be LIR_Op1");6008LIR_Op1* fxch1 = (LIR_Op1*)op1;6009LIR_Op1* fxch2 = (LIR_Op1*)op2;6010if (fxch1->in_opr()->as_jint() == fxch2->in_opr()->as_jint()) {6011// equal FPU stack operations can be optimized6012return false;6013}60146015} else if (op1->code() == lir_fpop_raw && op2->code() == lir_fpop_raw) {6016// equal FPU stack operations can be optimized6017return false;6018}60196020// no optimization possible6021return true;6022}60236024void EdgeMoveOptimizer::optimize_moves_at_block_end(BlockBegin* block) {6025TRACE_LINEAR_SCAN(4, tty->print_cr("optimizing moves at end of block B%d", block->block_id()));60266027if (block->is_predecessor(block)) {6028// currently we can't handle this correctly.6029return;6030}60316032init_instructions();6033int num_preds = block->number_of_preds();6034assert(num_preds > 1, "do not call otherwise");6035assert(!block->is_set(BlockBegin::exception_entry_flag), "exception handlers not allowed");60366037// setup a list with the lir-instructions of all predecessors6038int i;6039for (i = 0; i < num_preds; i++) {6040BlockBegin* pred = block->pred_at(i);6041LIR_OpList* pred_instructions = pred->lir()->instructions_list();60426043if (pred->number_of_sux() != 1) {6044// this can happen with switch-statements where multiple edges are between6045// the same blocks.6046return;6047}60486049assert(pred->number_of_sux() == 1, "can handle only one successor");6050assert(pred->sux_at(0) == block, "invalid control flow");6051assert(pred_instructions->last()->code() == lir_branch, "block with successor must end with branch");6052assert(pred_instructions->last()->as_OpBranch() != NULL, "branch must be LIR_OpBranch");6053assert(pred_instructions->last()->as_OpBranch()->cond() == lir_cond_always, "block must end with unconditional branch");60546055if (pred_instructions->last()->info() != NULL) {6056// can not optimize instructions when debug info is needed6057return;6058}60596060// ignore the unconditional branch at the end of the block6061append_instructions(pred_instructions, pred_instructions->length() - 2);6062}606360646065// process lir-instructions while all predecessors end with the same instruction6066while (true) {6067LIR_Op* op = instruction_at(0);6068for (i = 1; i < num_preds; i++) {6069if (operations_different(op, instruction_at(i))) {6070// these instructions are different and cannot be optimized ->6071// no further optimization possible6072return;6073}6074}60756076TRACE_LINEAR_SCAN(4, tty->print("found instruction that is equal in all %d predecessors: ", num_preds); op->print());60776078// insert the instruction at the beginning of the current block6079block->lir()->insert_before(1, op);60806081// delete the instruction at the end of all predecessors6082for (i = 0; i < num_preds; i++) {6083remove_cur_instruction(i, true);6084}6085}6086}608760886089void EdgeMoveOptimizer::optimize_moves_at_block_begin(BlockBegin* block) {6090TRACE_LINEAR_SCAN(4, tty->print_cr("optimization moves at begin of block B%d", block->block_id()));60916092init_instructions();6093int num_sux = block->number_of_sux();60946095LIR_OpList* cur_instructions = block->lir()->instructions_list();60966097assert(num_sux == 2, "method should not be called otherwise");6098assert(cur_instructions->last()->code() == lir_branch, "block with successor must end with branch");6099assert(cur_instructions->last()->as_OpBranch() != NULL, "branch must be LIR_OpBranch");6100assert(cur_instructions->last()->as_OpBranch()->cond() == lir_cond_always, "block must end with unconditional branch");61016102if (cur_instructions->last()->info() != NULL) {6103// can no optimize instructions when debug info is needed6104return;6105}61066107LIR_Op* branch = cur_instructions->at(cur_instructions->length() - 2);6108if (branch->info() != NULL || (branch->code() != lir_branch && branch->code() != lir_cond_float_branch)) {6109// not a valid case for optimization6110// currently, only blocks that end with two branches (conditional branch followed6111// by unconditional branch) are optimized6112return;6113}61146115// now it is guaranteed that the block ends with two branch instructions.6116// the instructions are inserted at the end of the block before these two branches6117int insert_idx = cur_instructions->length() - 2;61186119int i;6120#ifdef ASSERT6121for (i = insert_idx - 1; i >= 0; i--) {6122LIR_Op* op = cur_instructions->at(i);6123if ((op->code() == lir_branch || op->code() == lir_cond_float_branch) && ((LIR_OpBranch*)op)->block() != NULL) {6124assert(false, "block with two successors can have only two branch instructions");6125}6126}6127#endif61286129// setup a list with the lir-instructions of all successors6130for (i = 0; i < num_sux; i++) {6131BlockBegin* sux = block->sux_at(i);6132LIR_OpList* sux_instructions = sux->lir()->instructions_list();61336134assert(sux_instructions->at(0)->code() == lir_label, "block must start with label");61356136if (sux->number_of_preds() != 1) {6137// this can happen with switch-statements where multiple edges are between6138// the same blocks.6139return;6140}6141assert(sux->pred_at(0) == block, "invalid control flow");6142assert(!sux->is_set(BlockBegin::exception_entry_flag), "exception handlers not allowed");61436144// ignore the label at the beginning of the block6145append_instructions(sux_instructions, 1);6146}61476148// process lir-instructions while all successors begin with the same instruction6149while (true) {6150LIR_Op* op = instruction_at(0);6151for (i = 1; i < num_sux; i++) {6152if (operations_different(op, instruction_at(i))) {6153// these instructions are different and cannot be optimized ->6154// no further optimization possible6155return;6156}6157}61586159TRACE_LINEAR_SCAN(4, tty->print("----- found instruction that is equal in all %d successors: ", num_sux); op->print());61606161// insert instruction at end of current block6162block->lir()->insert_before(insert_idx, op);6163insert_idx++;61646165// delete the instructions at the beginning of all successors6166for (i = 0; i < num_sux; i++) {6167remove_cur_instruction(i, false);6168}6169}6170}617161726173// Implementation of ControlFlowOptimizer61746175ControlFlowOptimizer::ControlFlowOptimizer() :6176_original_preds(4)6177{6178}61796180void ControlFlowOptimizer::optimize(BlockList* code) {6181ControlFlowOptimizer optimizer = ControlFlowOptimizer();61826183// push the OSR entry block to the end so that we're not jumping over it.6184BlockBegin* osr_entry = code->at(0)->end()->as_Base()->osr_entry();6185if (osr_entry) {6186int index = osr_entry->linear_scan_number();6187assert(code->at(index) == osr_entry, "wrong index");6188code->remove_at(index);6189code->append(osr_entry);6190}61916192optimizer.reorder_short_loops(code);6193optimizer.delete_empty_blocks(code);6194optimizer.delete_unnecessary_jumps(code);6195optimizer.delete_jumps_to_return(code);6196}61976198void ControlFlowOptimizer::reorder_short_loop(BlockList* code, BlockBegin* header_block, int header_idx) {6199int i = header_idx + 1;6200int max_end = MIN2(header_idx + ShortLoopSize, code->length());6201while (i < max_end && code->at(i)->loop_depth() >= header_block->loop_depth()) {6202i++;6203}62046205if (i == code->length() || code->at(i)->loop_depth() < header_block->loop_depth()) {6206int end_idx = i - 1;6207BlockBegin* end_block = code->at(end_idx);62086209if (end_block->number_of_sux() == 1 && end_block->sux_at(0) == header_block) {6210// short loop from header_idx to end_idx found -> reorder blocks such that6211// the header_block is the last block instead of the first block of the loop6212TRACE_LINEAR_SCAN(1, tty->print_cr("Reordering short loop: length %d, header B%d, end B%d",6213end_idx - header_idx + 1,6214header_block->block_id(), end_block->block_id()));62156216for (int j = header_idx; j < end_idx; j++) {6217code->at_put(j, code->at(j + 1));6218}6219code->at_put(end_idx, header_block);62206221// correct the flags so that any loop alignment occurs in the right place.6222assert(code->at(end_idx)->is_set(BlockBegin::backward_branch_target_flag), "must be backward branch target");6223code->at(end_idx)->clear(BlockBegin::backward_branch_target_flag);6224code->at(header_idx)->set(BlockBegin::backward_branch_target_flag);6225}6226}6227}62286229void ControlFlowOptimizer::reorder_short_loops(BlockList* code) {6230for (int i = code->length() - 1; i >= 0; i--) {6231BlockBegin* block = code->at(i);62326233if (block->is_set(BlockBegin::linear_scan_loop_header_flag)) {6234reorder_short_loop(code, block, i);6235}6236}62376238DEBUG_ONLY(verify(code));6239}62406241// only blocks with exactly one successor can be deleted. Such blocks6242// must always end with an unconditional branch to this successor6243bool ControlFlowOptimizer::can_delete_block(BlockBegin* block) {6244if (block->number_of_sux() != 1 || block->number_of_exception_handlers() != 0 || block->is_entry_block()) {6245return false;6246}62476248LIR_OpList* instructions = block->lir()->instructions_list();62496250assert(instructions->length() >= 2, "block must have label and branch");6251assert(instructions->at(0)->code() == lir_label, "first instruction must always be a label");6252assert(instructions->last()->as_OpBranch() != NULL, "last instrcution must always be a branch");6253assert(instructions->last()->as_OpBranch()->cond() == lir_cond_always, "branch must be unconditional");6254assert(instructions->last()->as_OpBranch()->block() == block->sux_at(0), "branch target must be the successor");62556256// block must have exactly one successor62576258if (instructions->length() == 2 && instructions->last()->info() == NULL) {6259return true;6260}6261return false;6262}62636264// substitute branch targets in all branch-instructions of this blocks6265void ControlFlowOptimizer::substitute_branch_target(BlockBegin* block, BlockBegin* target_from, BlockBegin* target_to) {6266TRACE_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()));62676268LIR_OpList* instructions = block->lir()->instructions_list();62696270assert(instructions->at(0)->code() == lir_label, "first instruction must always be a label");6271for (int i = instructions->length() - 1; i >= 1; i--) {6272LIR_Op* op = instructions->at(i);62736274if (op->code() == lir_branch || op->code() == lir_cond_float_branch) {6275assert(op->as_OpBranch() != NULL, "branch must be of type LIR_OpBranch");6276LIR_OpBranch* branch = (LIR_OpBranch*)op;62776278if (branch->block() == target_from) {6279branch->change_block(target_to);6280}6281if (branch->ublock() == target_from) {6282branch->change_ublock(target_to);6283}6284}6285}6286}62876288void ControlFlowOptimizer::delete_empty_blocks(BlockList* code) {6289int old_pos = 0;6290int new_pos = 0;6291int num_blocks = code->length();62926293while (old_pos < num_blocks) {6294BlockBegin* block = code->at(old_pos);62956296if (can_delete_block(block)) {6297BlockBegin* new_target = block->sux_at(0);62986299// propagate backward branch target flag for correct code alignment6300if (block->is_set(BlockBegin::backward_branch_target_flag)) {6301new_target->set(BlockBegin::backward_branch_target_flag);6302}63036304// collect a list with all predecessors that contains each predecessor only once6305// the predecessors of cur are changed during the substitution, so a copy of the6306// predecessor list is necessary6307int j;6308_original_preds.clear();6309for (j = block->number_of_preds() - 1; j >= 0; j--) {6310BlockBegin* pred = block->pred_at(j);6311if (_original_preds.find(pred) == -1) {6312_original_preds.append(pred);6313}6314}63156316for (j = _original_preds.length() - 1; j >= 0; j--) {6317BlockBegin* pred = _original_preds.at(j);6318substitute_branch_target(pred, block, new_target);6319pred->substitute_sux(block, new_target);6320}6321} else {6322// adjust position of this block in the block list if blocks before6323// have been deleted6324if (new_pos != old_pos) {6325code->at_put(new_pos, code->at(old_pos));6326}6327new_pos++;6328}6329old_pos++;6330}6331code->trunc_to(new_pos);63326333DEBUG_ONLY(verify(code));6334}63356336void ControlFlowOptimizer::delete_unnecessary_jumps(BlockList* code) {6337// skip the last block because there a branch is always necessary6338for (int i = code->length() - 2; i >= 0; i--) {6339BlockBegin* block = code->at(i);6340LIR_OpList* instructions = block->lir()->instructions_list();63416342LIR_Op* last_op = instructions->last();6343if (last_op->code() == lir_branch) {6344assert(last_op->as_OpBranch() != NULL, "branch must be of type LIR_OpBranch");6345LIR_OpBranch* last_branch = (LIR_OpBranch*)last_op;63466347assert(last_branch->block() != NULL, "last branch must always have a block as target");6348assert(last_branch->label() == last_branch->block()->label(), "must be equal");63496350if (last_branch->info() == NULL) {6351if (last_branch->block() == code->at(i + 1)) {63526353TRACE_LINEAR_SCAN(3, tty->print_cr("Deleting unconditional branch at end of block B%d", block->block_id()));63546355// delete last branch instruction6356instructions->trunc_to(instructions->length() - 1);63576358} else {6359LIR_Op* prev_op = instructions->at(instructions->length() - 2);6360if (prev_op->code() == lir_branch || prev_op->code() == lir_cond_float_branch) {6361assert(prev_op->as_OpBranch() != NULL, "branch must be of type LIR_OpBranch");6362LIR_OpBranch* prev_branch = (LIR_OpBranch*)prev_op;63636364if (prev_branch->stub() == NULL) {63656366LIR_Op2* prev_cmp = NULL;6367// There might be a cmove inserted for profiling which depends on the same6368// compare. If we change the condition of the respective compare, we have6369// to take care of this cmove as well.6370LIR_Op2* prev_cmove = NULL;63716372for(int j = instructions->length() - 3; j >= 0 && prev_cmp == NULL; j--) {6373prev_op = instructions->at(j);6374// check for the cmove6375if (prev_op->code() == lir_cmove) {6376assert(prev_op->as_Op2() != NULL, "cmove must be of type LIR_Op2");6377prev_cmove = (LIR_Op2*)prev_op;6378assert(prev_branch->cond() == prev_cmove->condition(), "should be the same");6379}6380if (prev_op->code() == lir_cmp) {6381assert(prev_op->as_Op2() != NULL, "branch must be of type LIR_Op2");6382prev_cmp = (LIR_Op2*)prev_op;6383assert(prev_branch->cond() == prev_cmp->condition(), "should be the same");6384}6385}6386// Guarantee because it is dereferenced below.6387guarantee(prev_cmp != NULL, "should have found comp instruction for branch");6388if (prev_branch->block() == code->at(i + 1) && prev_branch->info() == NULL) {63896390TRACE_LINEAR_SCAN(3, tty->print_cr("Negating conditional branch and deleting unconditional branch at end of block B%d", block->block_id()));63916392// eliminate a conditional branch to the immediate successor6393prev_branch->change_block(last_branch->block());6394prev_branch->negate_cond();6395prev_cmp->set_condition(prev_branch->cond());6396instructions->trunc_to(instructions->length() - 1);6397// if we do change the condition, we have to change the cmove as well6398if (prev_cmove != NULL) {6399prev_cmove->set_condition(prev_branch->cond());6400LIR_Opr t = prev_cmove->in_opr1();6401prev_cmove->set_in_opr1(prev_cmove->in_opr2());6402prev_cmove->set_in_opr2(t);6403}6404}6405}6406}6407}6408}6409}6410}64116412DEBUG_ONLY(verify(code));6413}64146415void ControlFlowOptimizer::delete_jumps_to_return(BlockList* code) {6416#ifdef ASSERT6417ResourceBitMap return_converted(BlockBegin::number_of_blocks());6418#endif64196420for (int i = code->length() - 1; i >= 0; i--) {6421BlockBegin* block = code->at(i);6422LIR_OpList* cur_instructions = block->lir()->instructions_list();6423LIR_Op* cur_last_op = cur_instructions->last();64246425assert(cur_instructions->at(0)->code() == lir_label, "first instruction must always be a label");6426if (cur_instructions->length() == 2 && cur_last_op->code() == lir_return) {6427// the block contains only a label and a return6428// if a predecessor ends with an unconditional jump to this block, then the jump6429// can be replaced with a return instruction6430//6431// Note: the original block with only a return statement cannot be deleted completely6432// because the predecessors might have other (conditional) jumps to this block6433// -> this may lead to unnecesary return instructions in the final code64346435assert(cur_last_op->info() == NULL, "return instructions do not have debug information");6436assert(block->number_of_sux() == 0 ||6437(return_converted.at(block->block_id()) && block->number_of_sux() == 1),6438"blocks that end with return must not have successors");64396440assert(cur_last_op->as_Op1() != NULL, "return must be LIR_Op1");6441LIR_Opr return_opr = ((LIR_Op1*)cur_last_op)->in_opr();64426443for (int j = block->number_of_preds() - 1; j >= 0; j--) {6444BlockBegin* pred = block->pred_at(j);6445LIR_OpList* pred_instructions = pred->lir()->instructions_list();6446LIR_Op* pred_last_op = pred_instructions->last();64476448if (pred_last_op->code() == lir_branch) {6449assert(pred_last_op->as_OpBranch() != NULL, "branch must be LIR_OpBranch");6450LIR_OpBranch* pred_last_branch = (LIR_OpBranch*)pred_last_op;64516452if (pred_last_branch->block() == block && pred_last_branch->cond() == lir_cond_always && pred_last_branch->info() == NULL) {6453// replace the jump to a return with a direct return6454// Note: currently the edge between the blocks is not deleted6455pred_instructions->at_put(pred_instructions->length() - 1, new LIR_OpReturn(return_opr));6456#ifdef ASSERT6457return_converted.set_bit(pred->block_id());6458#endif6459}6460}6461}6462}6463}6464}646564666467#ifdef ASSERT6468void ControlFlowOptimizer::verify(BlockList* code) {6469for (int i = 0; i < code->length(); i++) {6470BlockBegin* block = code->at(i);6471LIR_OpList* instructions = block->lir()->instructions_list();64726473int j;6474for (j = 0; j < instructions->length(); j++) {6475LIR_OpBranch* op_branch = instructions->at(j)->as_OpBranch();64766477if (op_branch != NULL) {6478assert(op_branch->block() == NULL || code->find(op_branch->block()) != -1, "branch target not valid");6479assert(op_branch->ublock() == NULL || code->find(op_branch->ublock()) != -1, "branch target not valid");6480}6481}64826483for (j = 0; j < block->number_of_sux() - 1; j++) {6484BlockBegin* sux = block->sux_at(j);6485assert(code->find(sux) != -1, "successor not valid");6486}64876488for (j = 0; j < block->number_of_preds() - 1; j++) {6489BlockBegin* pred = block->pred_at(j);6490assert(code->find(pred) != -1, "successor not valid");6491}6492}6493}6494#endif649564966497#ifndef PRODUCT64986499// Implementation of LinearStatistic65006501const char* LinearScanStatistic::counter_name(int counter_idx) {6502switch (counter_idx) {6503case counter_method: return "compiled methods";6504case counter_fpu_method: return "methods using fpu";6505case counter_loop_method: return "methods with loops";6506case counter_exception_method:return "methods with xhandler";65076508case counter_loop: return "loops";6509case counter_block: return "blocks";6510case counter_loop_block: return "blocks inside loop";6511case counter_exception_block: return "exception handler entries";6512case counter_interval: return "intervals";6513case counter_fixed_interval: return "fixed intervals";6514case counter_range: return "ranges";6515case counter_fixed_range: return "fixed ranges";6516case counter_use_pos: return "use positions";6517case counter_fixed_use_pos: return "fixed use positions";6518case counter_spill_slots: return "spill slots";65196520// counter for classes of lir instructions6521case counter_instruction: return "total instructions";6522case counter_label: return "labels";6523case counter_entry: return "method entries";6524case counter_return: return "method returns";6525case counter_call: return "method calls";6526case counter_move: return "moves";6527case counter_cmp: return "compare";6528case counter_cond_branch: return "conditional branches";6529case counter_uncond_branch: return "unconditional branches";6530case counter_stub_branch: return "branches to stub";6531case counter_alu: return "artithmetic + logic";6532case counter_alloc: return "allocations";6533case counter_sync: return "synchronisation";6534case counter_throw: return "throw";6535case counter_unwind: return "unwind";6536case counter_typecheck: return "type+null-checks";6537case counter_fpu_stack: return "fpu-stack";6538case counter_misc_inst: return "other instructions";6539case counter_other_inst: return "misc. instructions";65406541// counter for different types of moves6542case counter_move_total: return "total moves";6543case counter_move_reg_reg: return "register->register";6544case counter_move_reg_stack: return "register->stack";6545case counter_move_stack_reg: return "stack->register";6546case counter_move_stack_stack:return "stack->stack";6547case counter_move_reg_mem: return "register->memory";6548case counter_move_mem_reg: return "memory->register";6549case counter_move_const_any: return "constant->any";65506551case blank_line_1: return "";6552case blank_line_2: return "";65536554default: ShouldNotReachHere(); return "";6555}6556}65576558LinearScanStatistic::Counter LinearScanStatistic::base_counter(int counter_idx) {6559if (counter_idx == counter_fpu_method || counter_idx == counter_loop_method || counter_idx == counter_exception_method) {6560return counter_method;6561} else if (counter_idx == counter_loop_block || counter_idx == counter_exception_block) {6562return counter_block;6563} else if (counter_idx >= counter_instruction && counter_idx <= counter_other_inst) {6564return counter_instruction;6565} else if (counter_idx >= counter_move_total && counter_idx <= counter_move_const_any) {6566return counter_move_total;6567}6568return invalid_counter;6569}65706571LinearScanStatistic::LinearScanStatistic() {6572for (int i = 0; i < number_of_counters; i++) {6573_counters_sum[i] = 0;6574_counters_max[i] = -1;6575}65766577}65786579// add the method-local numbers to the total sum6580void LinearScanStatistic::sum_up(LinearScanStatistic &method_statistic) {6581for (int i = 0; i < number_of_counters; i++) {6582_counters_sum[i] += method_statistic._counters_sum[i];6583_counters_max[i] = MAX2(_counters_max[i], method_statistic._counters_sum[i]);6584}6585}65866587void LinearScanStatistic::print(const char* title) {6588if (CountLinearScan || TraceLinearScanLevel > 0) {6589tty->cr();6590tty->print_cr("***** LinearScan statistic - %s *****", title);65916592for (int i = 0; i < number_of_counters; i++) {6593if (_counters_sum[i] > 0 || _counters_max[i] >= 0) {6594tty->print("%25s: %8d", counter_name(i), _counters_sum[i]);65956596LinearScanStatistic::Counter cntr = base_counter(i);6597if (cntr != invalid_counter) {6598tty->print(" (%5.1f%%) ", _counters_sum[i] * 100.0 / _counters_sum[cntr]);6599} else {6600tty->print(" ");6601}66026603if (_counters_max[i] >= 0) {6604tty->print("%8d", _counters_max[i]);6605}6606}6607tty->cr();6608}6609}6610}66116612void LinearScanStatistic::collect(LinearScan* allocator) {6613inc_counter(counter_method);6614if (allocator->has_fpu_registers()) {6615inc_counter(counter_fpu_method);6616}6617if (allocator->num_loops() > 0) {6618inc_counter(counter_loop_method);6619}6620inc_counter(counter_loop, allocator->num_loops());6621inc_counter(counter_spill_slots, allocator->max_spills());66226623int i;6624for (i = 0; i < allocator->interval_count(); i++) {6625Interval* cur = allocator->interval_at(i);66266627if (cur != NULL) {6628inc_counter(counter_interval);6629inc_counter(counter_use_pos, cur->num_use_positions());6630if (LinearScan::is_precolored_interval(cur)) {6631inc_counter(counter_fixed_interval);6632inc_counter(counter_fixed_use_pos, cur->num_use_positions());6633}66346635Range* range = cur->first();6636while (range != Range::end()) {6637inc_counter(counter_range);6638if (LinearScan::is_precolored_interval(cur)) {6639inc_counter(counter_fixed_range);6640}6641range = range->next();6642}6643}6644}66456646bool has_xhandlers = false;6647// Note: only count blocks that are in code-emit order6648for (i = 0; i < allocator->ir()->code()->length(); i++) {6649BlockBegin* cur = allocator->ir()->code()->at(i);66506651inc_counter(counter_block);6652if (cur->loop_depth() > 0) {6653inc_counter(counter_loop_block);6654}6655if (cur->is_set(BlockBegin::exception_entry_flag)) {6656inc_counter(counter_exception_block);6657has_xhandlers = true;6658}66596660LIR_OpList* instructions = cur->lir()->instructions_list();6661for (int j = 0; j < instructions->length(); j++) {6662LIR_Op* op = instructions->at(j);66636664inc_counter(counter_instruction);66656666switch (op->code()) {6667case lir_label: inc_counter(counter_label); break;6668case lir_std_entry:6669case lir_osr_entry: inc_counter(counter_entry); break;6670case lir_return: inc_counter(counter_return); break;66716672case lir_rtcall:6673case lir_static_call:6674case lir_optvirtual_call: inc_counter(counter_call); break;66756676case lir_move: {6677inc_counter(counter_move);6678inc_counter(counter_move_total);66796680LIR_Opr in = op->as_Op1()->in_opr();6681LIR_Opr res = op->as_Op1()->result_opr();6682if (in->is_register()) {6683if (res->is_register()) {6684inc_counter(counter_move_reg_reg);6685} else if (res->is_stack()) {6686inc_counter(counter_move_reg_stack);6687} else if (res->is_address()) {6688inc_counter(counter_move_reg_mem);6689} else {6690ShouldNotReachHere();6691}6692} else if (in->is_stack()) {6693if (res->is_register()) {6694inc_counter(counter_move_stack_reg);6695} else {6696inc_counter(counter_move_stack_stack);6697}6698} else if (in->is_address()) {6699assert(res->is_register(), "must be");6700inc_counter(counter_move_mem_reg);6701} else if (in->is_constant()) {6702inc_counter(counter_move_const_any);6703} else {6704ShouldNotReachHere();6705}6706break;6707}67086709case lir_cmp: inc_counter(counter_cmp); break;67106711case lir_branch:6712case lir_cond_float_branch: {6713LIR_OpBranch* branch = op->as_OpBranch();6714if (branch->block() == NULL) {6715inc_counter(counter_stub_branch);6716} else if (branch->cond() == lir_cond_always) {6717inc_counter(counter_uncond_branch);6718} else {6719inc_counter(counter_cond_branch);6720}6721break;6722}67236724case lir_neg:6725case lir_add:6726case lir_sub:6727case lir_mul:6728case lir_div:6729case lir_rem:6730case lir_sqrt:6731case lir_abs:6732case lir_log10:6733case lir_logic_and:6734case lir_logic_or:6735case lir_logic_xor:6736case lir_shl:6737case lir_shr:6738case lir_ushr: inc_counter(counter_alu); break;67396740case lir_alloc_object:6741case lir_alloc_array: inc_counter(counter_alloc); break;67426743case lir_monaddr:6744case lir_lock:6745case lir_unlock: inc_counter(counter_sync); break;67466747case lir_throw: inc_counter(counter_throw); break;67486749case lir_unwind: inc_counter(counter_unwind); break;67506751case lir_null_check:6752case lir_leal:6753case lir_instanceof:6754case lir_checkcast:6755case lir_store_check: inc_counter(counter_typecheck); break;67566757case lir_fpop_raw:6758case lir_fxch:6759case lir_fld: inc_counter(counter_fpu_stack); break;67606761case lir_nop:6762case lir_push:6763case lir_pop:6764case lir_convert:6765case lir_roundfp:6766case lir_cmove: inc_counter(counter_misc_inst); break;67676768default: inc_counter(counter_other_inst); break;6769}6770}6771}67726773if (has_xhandlers) {6774inc_counter(counter_exception_method);6775}6776}67776778void LinearScanStatistic::compute(LinearScan* allocator, LinearScanStatistic &global_statistic) {6779if (CountLinearScan || TraceLinearScanLevel > 0) {67806781LinearScanStatistic local_statistic = LinearScanStatistic();67826783local_statistic.collect(allocator);6784global_statistic.sum_up(local_statistic);67856786if (TraceLinearScanLevel > 2) {6787local_statistic.print("current local statistic");6788}6789}6790}679167926793// Implementation of LinearTimers67946795LinearScanTimers::LinearScanTimers() {6796for (int i = 0; i < number_of_timers; i++) {6797timer(i)->reset();6798}6799}68006801const char* LinearScanTimers::timer_name(int idx) {6802switch (idx) {6803case timer_do_nothing: return "Nothing (Time Check)";6804case timer_number_instructions: return "Number Instructions";6805case timer_compute_local_live_sets: return "Local Live Sets";6806case timer_compute_global_live_sets: return "Global Live Sets";6807case timer_build_intervals: return "Build Intervals";6808case timer_sort_intervals_before: return "Sort Intervals Before";6809case timer_allocate_registers: return "Allocate Registers";6810case timer_resolve_data_flow: return "Resolve Data Flow";6811case timer_sort_intervals_after: return "Sort Intervals After";6812case timer_eliminate_spill_moves: return "Spill optimization";6813case timer_assign_reg_num: return "Assign Reg Num";6814case timer_allocate_fpu_stack: return "Allocate FPU Stack";6815case timer_optimize_lir: return "Optimize LIR";6816default: ShouldNotReachHere(); return "";6817}6818}68196820void LinearScanTimers::begin_method() {6821if (TimeEachLinearScan) {6822// reset all timers to measure only current method6823for (int i = 0; i < number_of_timers; i++) {6824timer(i)->reset();6825}6826}6827}68286829void LinearScanTimers::end_method(LinearScan* allocator) {6830if (TimeEachLinearScan) {68316832double c = timer(timer_do_nothing)->seconds();6833double total = 0;6834for (int i = 1; i < number_of_timers; i++) {6835total += timer(i)->seconds() - c;6836}68376838if (total >= 0.0005) {6839// print all information in one line for automatic processing6840tty->print("@"); allocator->compilation()->method()->print_name();68416842tty->print("@ %d ", allocator->compilation()->method()->code_size());6843tty->print("@ %d ", allocator->block_at(allocator->block_count() - 1)->last_lir_instruction_id() / 2);6844tty->print("@ %d ", allocator->block_count());6845tty->print("@ %d ", allocator->num_virtual_regs());6846tty->print("@ %d ", allocator->interval_count());6847tty->print("@ %d ", allocator->_num_calls);6848tty->print("@ %d ", allocator->num_loops());68496850tty->print("@ %6.6f ", total);6851for (int i = 1; i < number_of_timers; i++) {6852tty->print("@ %4.1f ", ((timer(i)->seconds() - c) / total) * 100);6853}6854tty->cr();6855}6856}6857}68586859void LinearScanTimers::print(double total_time) {6860if (TimeLinearScan) {6861// correction value: sum of dummy-timer that only measures the time that6862// is necesary to start and stop itself6863double c = timer(timer_do_nothing)->seconds();68646865for (int i = 0; i < number_of_timers; i++) {6866double t = timer(i)->seconds();6867tty->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);6868}6869}6870}68716872#endif // #ifndef PRODUCT687368746875