Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/shark/sharkTopLevelBlock.cpp
32285 views
/*1* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.2* Copyright 2008, 2009, 2010 Red Hat, Inc.3* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.4*5* This code is free software; you can redistribute it and/or modify it6* under the terms of the GNU General Public License version 2 only, as7* published by the Free Software Foundation.8*9* This code is distributed in the hope that it will be useful, but WITHOUT10* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or11* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License12* version 2 for more details (a copy is included in the LICENSE file that13* accompanied this code).14*15* You should have received a copy of the GNU General Public License version16* 2 along with this work; if not, write to the Free Software Foundation,17* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.18*19* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA20* or visit www.oracle.com if you need additional information or have any21* questions.22*23*/2425#include "precompiled.hpp"26#include "ci/ciField.hpp"27#include "ci/ciInstance.hpp"28#include "ci/ciObjArrayKlass.hpp"29#include "ci/ciStreams.hpp"30#include "ci/ciType.hpp"31#include "ci/ciTypeFlow.hpp"32#include "interpreter/bytecodes.hpp"33#include "memory/allocation.hpp"34#include "runtime/deoptimization.hpp"35#include "shark/llvmHeaders.hpp"36#include "shark/llvmValue.hpp"37#include "shark/sharkBuilder.hpp"38#include "shark/sharkCacheDecache.hpp"39#include "shark/sharkConstant.hpp"40#include "shark/sharkInliner.hpp"41#include "shark/sharkState.hpp"42#include "shark/sharkTopLevelBlock.hpp"43#include "shark/sharkValue.hpp"44#include "shark/shark_globals.hpp"45#include "utilities/debug.hpp"4647using namespace llvm;4849void SharkTopLevelBlock::scan_for_traps() {50// If typeflow found a trap then don't scan past it51int limit_bci = ciblock()->has_trap() ? ciblock()->trap_bci() : limit();5253// Scan the bytecode for traps that are always hit54iter()->reset_to_bci(start());55while (iter()->next_bci() < limit_bci) {56iter()->next();5758ciField *field;59ciMethod *method;60ciInstanceKlass *klass;61bool will_link;62bool is_field;6364switch (bc()) {65case Bytecodes::_ldc:66case Bytecodes::_ldc_w:67case Bytecodes::_ldc2_w:68if (!SharkConstant::for_ldc(iter())->is_loaded()) {69set_trap(70Deoptimization::make_trap_request(71Deoptimization::Reason_uninitialized,72Deoptimization::Action_reinterpret), bci());73return;74}75break;7677case Bytecodes::_getfield:78case Bytecodes::_getstatic:79case Bytecodes::_putfield:80case Bytecodes::_putstatic:81field = iter()->get_field(will_link);82assert(will_link, "typeflow responsibility");83is_field = (bc() == Bytecodes::_getfield || bc() == Bytecodes::_putfield);8485// If the bytecode does not match the field then bail out to86// the interpreter to throw an IncompatibleClassChangeError87if (is_field == field->is_static()) {88set_trap(89Deoptimization::make_trap_request(90Deoptimization::Reason_unhandled,91Deoptimization::Action_none), bci());92return;93}9495// Bail out if we are trying to access a static variable96// before the class initializer has completed.97if (!is_field && !field->holder()->is_initialized()) {98if (!static_field_ok_in_clinit(field)) {99set_trap(100Deoptimization::make_trap_request(101Deoptimization::Reason_uninitialized,102Deoptimization::Action_reinterpret), bci());103return;104}105}106break;107108case Bytecodes::_invokestatic:109case Bytecodes::_invokespecial:110case Bytecodes::_invokevirtual:111case Bytecodes::_invokeinterface:112ciSignature* sig;113method = iter()->get_method(will_link, &sig);114assert(will_link, "typeflow responsibility");115// We can't compile calls to method handle intrinsics, because we use116// the interpreter entry points and they expect the top frame to be an117// interpreter frame. We need to implement the intrinsics for Shark.118if (method->is_method_handle_intrinsic() || method->is_compiled_lambda_form()) {119if (SharkPerformanceWarnings) {120warning("JSR292 optimization not yet implemented in Shark");121}122set_trap(123Deoptimization::make_trap_request(124Deoptimization::Reason_unhandled,125Deoptimization::Action_make_not_compilable), bci());126return;127}128if (!method->holder()->is_linked()) {129set_trap(130Deoptimization::make_trap_request(131Deoptimization::Reason_uninitialized,132Deoptimization::Action_reinterpret), bci());133return;134}135136if (bc() == Bytecodes::_invokevirtual) {137klass = ciEnv::get_instance_klass_for_declared_method_holder(138iter()->get_declared_method_holder());139if (!klass->is_linked()) {140set_trap(141Deoptimization::make_trap_request(142Deoptimization::Reason_uninitialized,143Deoptimization::Action_reinterpret), bci());144return;145}146}147break;148149case Bytecodes::_new:150klass = iter()->get_klass(will_link)->as_instance_klass();151assert(will_link, "typeflow responsibility");152153// Bail out if the class is unloaded154if (iter()->is_unresolved_klass() || !klass->is_initialized()) {155set_trap(156Deoptimization::make_trap_request(157Deoptimization::Reason_uninitialized,158Deoptimization::Action_reinterpret), bci());159return;160}161162// Bail out if the class cannot be instantiated163if (klass->is_abstract() || klass->is_interface() ||164klass->name() == ciSymbol::java_lang_Class()) {165set_trap(166Deoptimization::make_trap_request(167Deoptimization::Reason_unhandled,168Deoptimization::Action_reinterpret), bci());169return;170}171break;172case Bytecodes::_invokedynamic:173case Bytecodes::_invokehandle:174if (SharkPerformanceWarnings) {175warning("JSR292 optimization not yet implemented in Shark");176}177set_trap(178Deoptimization::make_trap_request(179Deoptimization::Reason_unhandled,180Deoptimization::Action_make_not_compilable), bci());181return;182}183}184185// Trap if typeflow trapped (and we didn't before)186if (ciblock()->has_trap()) {187set_trap(188Deoptimization::make_trap_request(189Deoptimization::Reason_unloaded,190Deoptimization::Action_reinterpret,191ciblock()->trap_index()), ciblock()->trap_bci());192return;193}194}195196bool SharkTopLevelBlock::static_field_ok_in_clinit(ciField* field) {197assert(field->is_static(), "should be");198199// This code is lifted pretty much verbatim from C2's200// Parse::static_field_ok_in_clinit() in parse3.cpp.201bool access_OK = false;202if (target()->holder()->is_subclass_of(field->holder())) {203if (target()->is_static()) {204if (target()->name() == ciSymbol::class_initializer_name()) {205// It's OK to access static fields from the class initializer206access_OK = true;207}208}209else {210if (target()->name() == ciSymbol::object_initializer_name()) {211// It's also OK to access static fields inside a constructor,212// because any thread calling the constructor must first have213// synchronized on the class by executing a "new" bytecode.214access_OK = true;215}216}217}218return access_OK;219}220221SharkState* SharkTopLevelBlock::entry_state() {222if (_entry_state == NULL) {223assert(needs_phis(), "should do");224_entry_state = new SharkPHIState(this);225}226return _entry_state;227}228229void SharkTopLevelBlock::add_incoming(SharkState* incoming_state) {230if (needs_phis()) {231((SharkPHIState *) entry_state())->add_incoming(incoming_state);232}233else if (_entry_state == NULL) {234_entry_state = incoming_state;235}236else {237assert(entry_state()->equal_to(incoming_state), "should be");238}239}240241void SharkTopLevelBlock::enter(SharkTopLevelBlock* predecessor,242bool is_exception) {243// This block requires phis:244// - if it is entered more than once245// - if it is an exception handler, because in which246// case we assume it's entered more than once.247// - if the predecessor will be compiled after this248// block, in which case we can't simple propagate249// the state forward.250if (!needs_phis() &&251(entered() ||252is_exception ||253(predecessor && predecessor->index() >= index())))254_needs_phis = true;255256// Recurse into the tree257if (!entered()) {258_entered = true;259260scan_for_traps();261if (!has_trap()) {262for (int i = 0; i < num_successors(); i++) {263successor(i)->enter(this, false);264}265}266compute_exceptions();267for (int i = 0; i < num_exceptions(); i++) {268SharkTopLevelBlock *handler = exception(i);269if (handler)270handler->enter(this, true);271}272}273}274275void SharkTopLevelBlock::initialize() {276char name[28];277snprintf(name, sizeof(name),278"bci_%d%s",279start(), is_backedge_copy() ? "_backedge_copy" : "");280_entry_block = function()->CreateBlock(name);281}282283void SharkTopLevelBlock::decache_for_Java_call(ciMethod *callee) {284SharkJavaCallDecacher(function(), bci(), callee).scan(current_state());285for (int i = 0; i < callee->arg_size(); i++)286xpop();287}288289void SharkTopLevelBlock::cache_after_Java_call(ciMethod *callee) {290if (callee->return_type()->size()) {291ciType *type;292switch (callee->return_type()->basic_type()) {293case T_BOOLEAN:294case T_BYTE:295case T_CHAR:296case T_SHORT:297type = ciType::make(T_INT);298break;299300default:301type = callee->return_type();302}303304push(SharkValue::create_generic(type, NULL, false));305}306SharkJavaCallCacher(function(), callee).scan(current_state());307}308309void SharkTopLevelBlock::decache_for_VM_call() {310SharkVMCallDecacher(function(), bci()).scan(current_state());311}312313void SharkTopLevelBlock::cache_after_VM_call() {314SharkVMCallCacher(function()).scan(current_state());315}316317void SharkTopLevelBlock::decache_for_trap() {318SharkTrapDecacher(function(), bci()).scan(current_state());319}320321void SharkTopLevelBlock::emit_IR() {322builder()->SetInsertPoint(entry_block());323324// Parse the bytecode325parse_bytecode(start(), limit());326327// If this block falls through to the next then it won't have been328// terminated by a bytecode and we have to add the branch ourselves329if (falls_through() && !has_trap())330do_branch(ciTypeFlow::FALL_THROUGH);331}332333SharkTopLevelBlock* SharkTopLevelBlock::bci_successor(int bci) const {334// XXX now with Linear Search Technology (tm)335for (int i = 0; i < num_successors(); i++) {336ciTypeFlow::Block *successor = ciblock()->successors()->at(i);337if (successor->start() == bci)338return function()->block(successor->pre_order());339}340ShouldNotReachHere();341}342343void SharkTopLevelBlock::do_zero_check(SharkValue *value) {344if (value->is_phi() && value->as_phi()->all_incomers_zero_checked()) {345function()->add_deferred_zero_check(this, value);346}347else {348BasicBlock *continue_block = function()->CreateBlock("not_zero");349SharkState *saved_state = current_state();350set_current_state(saved_state->copy());351zero_check_value(value, continue_block);352builder()->SetInsertPoint(continue_block);353set_current_state(saved_state);354}355356value->set_zero_checked(true);357}358359void SharkTopLevelBlock::do_deferred_zero_check(SharkValue* value,360int bci,361SharkState* saved_state,362BasicBlock* continue_block) {363if (value->as_phi()->all_incomers_zero_checked()) {364builder()->CreateBr(continue_block);365}366else {367iter()->force_bci(start());368set_current_state(saved_state);369zero_check_value(value, continue_block);370}371}372373void SharkTopLevelBlock::zero_check_value(SharkValue* value,374BasicBlock* continue_block) {375BasicBlock *zero_block = builder()->CreateBlock(continue_block, "zero");376377Value *a, *b;378switch (value->basic_type()) {379case T_BYTE:380case T_CHAR:381case T_SHORT:382case T_INT:383a = value->jint_value();384b = LLVMValue::jint_constant(0);385break;386case T_LONG:387a = value->jlong_value();388b = LLVMValue::jlong_constant(0);389break;390case T_OBJECT:391case T_ARRAY:392a = value->jobject_value();393b = LLVMValue::LLVMValue::null();394break;395default:396tty->print_cr("Unhandled type %s", type2name(value->basic_type()));397ShouldNotReachHere();398}399400builder()->CreateCondBr(401builder()->CreateICmpNE(a, b), continue_block, zero_block);402403builder()->SetInsertPoint(zero_block);404if (value->is_jobject()) {405call_vm(406builder()->throw_NullPointerException(),407builder()->CreateIntToPtr(408LLVMValue::intptr_constant((intptr_t) __FILE__),409PointerType::getUnqual(SharkType::jbyte_type())),410LLVMValue::jint_constant(__LINE__),411EX_CHECK_NONE);412}413else {414call_vm(415builder()->throw_ArithmeticException(),416builder()->CreateIntToPtr(417LLVMValue::intptr_constant((intptr_t) __FILE__),418PointerType::getUnqual(SharkType::jbyte_type())),419LLVMValue::jint_constant(__LINE__),420EX_CHECK_NONE);421}422423Value *pending_exception = get_pending_exception();424clear_pending_exception();425handle_exception(pending_exception, EX_CHECK_FULL);426}427428void SharkTopLevelBlock::check_bounds(SharkValue* array, SharkValue* index) {429BasicBlock *out_of_bounds = function()->CreateBlock("out_of_bounds");430BasicBlock *in_bounds = function()->CreateBlock("in_bounds");431432Value *length = builder()->CreateArrayLength(array->jarray_value());433// we use an unsigned comparison to catch negative values434builder()->CreateCondBr(435builder()->CreateICmpULT(index->jint_value(), length),436in_bounds, out_of_bounds);437438builder()->SetInsertPoint(out_of_bounds);439SharkState *saved_state = current_state()->copy();440441call_vm(442builder()->throw_ArrayIndexOutOfBoundsException(),443builder()->CreateIntToPtr(444LLVMValue::intptr_constant((intptr_t) __FILE__),445PointerType::getUnqual(SharkType::jbyte_type())),446LLVMValue::jint_constant(__LINE__),447index->jint_value(),448EX_CHECK_NONE);449450Value *pending_exception = get_pending_exception();451clear_pending_exception();452handle_exception(pending_exception, EX_CHECK_FULL);453454set_current_state(saved_state);455456builder()->SetInsertPoint(in_bounds);457}458459void SharkTopLevelBlock::check_pending_exception(int action) {460assert(action & EAM_CHECK, "should be");461462BasicBlock *exception = function()->CreateBlock("exception");463BasicBlock *no_exception = function()->CreateBlock("no_exception");464465Value *pending_exception = get_pending_exception();466builder()->CreateCondBr(467builder()->CreateICmpEQ(pending_exception, LLVMValue::null()),468no_exception, exception);469470builder()->SetInsertPoint(exception);471SharkState *saved_state = current_state()->copy();472if (action & EAM_MONITOR_FUDGE) {473// The top monitor is marked live, but the exception was thrown474// while setting it up so we need to mark it dead before we enter475// any exception handlers as they will not expect it to be there.476set_num_monitors(num_monitors() - 1);477action ^= EAM_MONITOR_FUDGE;478}479clear_pending_exception();480handle_exception(pending_exception, action);481set_current_state(saved_state);482483builder()->SetInsertPoint(no_exception);484}485486void SharkTopLevelBlock::compute_exceptions() {487ciExceptionHandlerStream str(target(), start());488489int exc_count = str.count();490_exc_handlers = new GrowableArray<ciExceptionHandler*>(exc_count);491_exceptions = new GrowableArray<SharkTopLevelBlock*>(exc_count);492493int index = 0;494for (; !str.is_done(); str.next()) {495ciExceptionHandler *handler = str.handler();496if (handler->handler_bci() == -1)497break;498_exc_handlers->append(handler);499500// Try and get this exception's handler from typeflow. We should501// do it this way always, really, except that typeflow sometimes502// doesn't record exceptions, even loaded ones, and sometimes it503// returns them with a different handler bci. Why???504SharkTopLevelBlock *block = NULL;505ciInstanceKlass* klass;506if (handler->is_catch_all()) {507klass = java_lang_Throwable_klass();508}509else {510klass = handler->catch_klass();511}512for (int i = 0; i < ciblock()->exceptions()->length(); i++) {513if (klass == ciblock()->exc_klasses()->at(i)) {514block = function()->block(ciblock()->exceptions()->at(i)->pre_order());515if (block->start() == handler->handler_bci())516break;517else518block = NULL;519}520}521522// If typeflow let us down then try and figure it out ourselves523if (block == NULL) {524for (int i = 0; i < function()->block_count(); i++) {525SharkTopLevelBlock *candidate = function()->block(i);526if (candidate->start() == handler->handler_bci()) {527if (block != NULL) {528NOT_PRODUCT(warning("there may be trouble ahead"));529block = NULL;530break;531}532block = candidate;533}534}535}536_exceptions->append(block);537}538}539540void SharkTopLevelBlock::handle_exception(Value* exception, int action) {541if (action & EAM_HANDLE && num_exceptions() != 0) {542// Clear the stack and push the exception onto it543while (xstack_depth())544pop();545push(SharkValue::create_jobject(exception, true));546547// Work out how many options we have to check548bool has_catch_all = exc_handler(num_exceptions() - 1)->is_catch_all();549int num_options = num_exceptions();550if (has_catch_all)551num_options--;552553// Marshal any non-catch-all handlers554if (num_options > 0) {555bool all_loaded = true;556for (int i = 0; i < num_options; i++) {557if (!exc_handler(i)->catch_klass()->is_loaded()) {558all_loaded = false;559break;560}561}562563if (all_loaded)564marshal_exception_fast(num_options);565else566marshal_exception_slow(num_options);567}568569// Install the catch-all handler, if present570if (has_catch_all) {571SharkTopLevelBlock* handler = this->exception(num_options);572assert(handler != NULL, "catch-all handler cannot be unloaded");573574builder()->CreateBr(handler->entry_block());575handler->add_incoming(current_state());576return;577}578}579580// No exception handler was found; unwind and return581handle_return(T_VOID, exception);582}583584void SharkTopLevelBlock::marshal_exception_fast(int num_options) {585Value *exception_klass = builder()->CreateValueOfStructEntry(586xstack(0)->jobject_value(),587in_ByteSize(oopDesc::klass_offset_in_bytes()),588SharkType::klass_type(),589"exception_klass");590591for (int i = 0; i < num_options; i++) {592Value *check_klass =593builder()->CreateInlineMetadata(exc_handler(i)->catch_klass(), SharkType::klass_type());594595BasicBlock *not_exact = function()->CreateBlock("not_exact");596BasicBlock *not_subtype = function()->CreateBlock("not_subtype");597598builder()->CreateCondBr(599builder()->CreateICmpEQ(check_klass, exception_klass),600handler_for_exception(i), not_exact);601602builder()->SetInsertPoint(not_exact);603builder()->CreateCondBr(604builder()->CreateICmpNE(605builder()->CreateCall2(606builder()->is_subtype_of(), check_klass, exception_klass),607LLVMValue::jbyte_constant(0)),608handler_for_exception(i), not_subtype);609610builder()->SetInsertPoint(not_subtype);611}612}613614void SharkTopLevelBlock::marshal_exception_slow(int num_options) {615int *indexes = NEW_RESOURCE_ARRAY(int, num_options);616for (int i = 0; i < num_options; i++)617indexes[i] = exc_handler(i)->catch_klass_index();618619Value *index = call_vm(620builder()->find_exception_handler(),621builder()->CreateInlineData(622indexes,623num_options * sizeof(int),624PointerType::getUnqual(SharkType::jint_type())),625LLVMValue::jint_constant(num_options),626EX_CHECK_NO_CATCH);627628BasicBlock *no_handler = function()->CreateBlock("no_handler");629SwitchInst *switchinst = builder()->CreateSwitch(630index, no_handler, num_options);631632for (int i = 0; i < num_options; i++) {633switchinst->addCase(634LLVMValue::jint_constant(i),635handler_for_exception(i));636}637638builder()->SetInsertPoint(no_handler);639}640641BasicBlock* SharkTopLevelBlock::handler_for_exception(int index) {642SharkTopLevelBlock *successor = this->exception(index);643if (successor) {644successor->add_incoming(current_state());645return successor->entry_block();646}647else {648return make_trap(649exc_handler(index)->handler_bci(),650Deoptimization::make_trap_request(651Deoptimization::Reason_unhandled,652Deoptimization::Action_reinterpret));653}654}655656void SharkTopLevelBlock::maybe_add_safepoint() {657if (current_state()->has_safepointed())658return;659660BasicBlock *orig_block = builder()->GetInsertBlock();661SharkState *orig_state = current_state()->copy();662663BasicBlock *do_safepoint = function()->CreateBlock("do_safepoint");664BasicBlock *safepointed = function()->CreateBlock("safepointed");665666Value *state = builder()->CreateLoad(667builder()->CreateIntToPtr(668LLVMValue::intptr_constant(669(intptr_t) SafepointSynchronize::address_of_state()),670PointerType::getUnqual(SharkType::jint_type())),671"state");672673builder()->CreateCondBr(674builder()->CreateICmpEQ(675state,676LLVMValue::jint_constant(SafepointSynchronize::_synchronizing)),677do_safepoint, safepointed);678679builder()->SetInsertPoint(do_safepoint);680call_vm(builder()->safepoint(), EX_CHECK_FULL);681BasicBlock *safepointed_block = builder()->GetInsertBlock();682builder()->CreateBr(safepointed);683684builder()->SetInsertPoint(safepointed);685current_state()->merge(orig_state, orig_block, safepointed_block);686687current_state()->set_has_safepointed(true);688}689690void SharkTopLevelBlock::maybe_add_backedge_safepoint() {691if (current_state()->has_safepointed())692return;693694for (int i = 0; i < num_successors(); i++) {695if (successor(i)->can_reach(this)) {696maybe_add_safepoint();697break;698}699}700}701702bool SharkTopLevelBlock::can_reach(SharkTopLevelBlock* other) {703for (int i = 0; i < function()->block_count(); i++)704function()->block(i)->_can_reach_visited = false;705706return can_reach_helper(other);707}708709bool SharkTopLevelBlock::can_reach_helper(SharkTopLevelBlock* other) {710if (this == other)711return true;712713if (_can_reach_visited)714return false;715_can_reach_visited = true;716717if (!has_trap()) {718for (int i = 0; i < num_successors(); i++) {719if (successor(i)->can_reach_helper(other))720return true;721}722}723724for (int i = 0; i < num_exceptions(); i++) {725SharkTopLevelBlock *handler = exception(i);726if (handler && handler->can_reach_helper(other))727return true;728}729730return false;731}732733BasicBlock* SharkTopLevelBlock::make_trap(int trap_bci, int trap_request) {734BasicBlock *trap_block = function()->CreateBlock("trap");735BasicBlock *orig_block = builder()->GetInsertBlock();736builder()->SetInsertPoint(trap_block);737738int orig_bci = bci();739iter()->force_bci(trap_bci);740741do_trap(trap_request);742743builder()->SetInsertPoint(orig_block);744iter()->force_bci(orig_bci);745746return trap_block;747}748749void SharkTopLevelBlock::do_trap(int trap_request) {750decache_for_trap();751builder()->CreateRet(752builder()->CreateCall2(753builder()->uncommon_trap(),754thread(),755LLVMValue::jint_constant(trap_request)));756}757758void SharkTopLevelBlock::call_register_finalizer(Value *receiver) {759BasicBlock *orig_block = builder()->GetInsertBlock();760SharkState *orig_state = current_state()->copy();761762BasicBlock *do_call = function()->CreateBlock("has_finalizer");763BasicBlock *done = function()->CreateBlock("done");764765Value *klass = builder()->CreateValueOfStructEntry(766receiver,767in_ByteSize(oopDesc::klass_offset_in_bytes()),768SharkType::oop_type(),769"klass");770771Value *access_flags = builder()->CreateValueOfStructEntry(772klass,773Klass::access_flags_offset(),774SharkType::jint_type(),775"access_flags");776777builder()->CreateCondBr(778builder()->CreateICmpNE(779builder()->CreateAnd(780access_flags,781LLVMValue::jint_constant(JVM_ACC_HAS_FINALIZER)),782LLVMValue::jint_constant(0)),783do_call, done);784785builder()->SetInsertPoint(do_call);786call_vm(builder()->register_finalizer(), receiver, EX_CHECK_FULL);787BasicBlock *branch_block = builder()->GetInsertBlock();788builder()->CreateBr(done);789790builder()->SetInsertPoint(done);791current_state()->merge(orig_state, orig_block, branch_block);792}793794void SharkTopLevelBlock::handle_return(BasicType type, Value* exception) {795assert (exception == NULL || type == T_VOID, "exception OR result, please");796797if (num_monitors()) {798// Protect our exception across possible monitor release decaches799if (exception)800set_oop_tmp(exception);801802// We don't need to check for exceptions thrown here. If803// we're returning a value then we just carry on as normal:804// the caller will see the pending exception and handle it.805// If we're returning with an exception then that exception806// takes priority and the release_lock one will be ignored.807while (num_monitors())808release_lock(EX_CHECK_NONE);809810// Reload the exception we're throwing811if (exception)812exception = get_oop_tmp();813}814815if (exception) {816builder()->CreateStore(exception, pending_exception_address());817}818819Value *result_addr = stack()->CreatePopFrame(type2size[type]);820if (type != T_VOID) {821builder()->CreateStore(822pop_result(type)->generic_value(),823builder()->CreateIntToPtr(824result_addr,825PointerType::getUnqual(SharkType::to_stackType(type))));826}827828builder()->CreateRet(LLVMValue::jint_constant(0));829}830831void SharkTopLevelBlock::do_arraylength() {832SharkValue *array = pop();833check_null(array);834Value *length = builder()->CreateArrayLength(array->jarray_value());835push(SharkValue::create_jint(length, false));836}837838void SharkTopLevelBlock::do_aload(BasicType basic_type) {839SharkValue *index = pop();840SharkValue *array = pop();841842check_null(array);843check_bounds(array, index);844845Value *value = builder()->CreateLoad(846builder()->CreateArrayAddress(847array->jarray_value(), basic_type, index->jint_value()));848849Type *stack_type = SharkType::to_stackType(basic_type);850if (value->getType() != stack_type)851value = builder()->CreateIntCast(value, stack_type, basic_type != T_CHAR);852853switch (basic_type) {854case T_BYTE:855case T_CHAR:856case T_SHORT:857case T_INT:858push(SharkValue::create_jint(value, false));859break;860861case T_LONG:862push(SharkValue::create_jlong(value, false));863break;864865case T_FLOAT:866push(SharkValue::create_jfloat(value));867break;868869case T_DOUBLE:870push(SharkValue::create_jdouble(value));871break;872873case T_OBJECT:874// You might expect that array->type()->is_array_klass() would875// always be true, but it isn't. If ciTypeFlow detects that a876// value is always null then that value becomes an untyped null877// object. Shark doesn't presently support this, so a generic878// T_OBJECT is created. In this case we guess the type using879// the BasicType we were supplied. In reality the generated880// code will never be used, as the null value will be caught881// by the above null pointer check.882// http://icedtea.classpath.org/bugzilla/show_bug.cgi?id=324883push(884SharkValue::create_generic(885array->type()->is_array_klass() ?886((ciArrayKlass *) array->type())->element_type() :887ciType::make(basic_type),888value, false));889break;890891default:892tty->print_cr("Unhandled type %s", type2name(basic_type));893ShouldNotReachHere();894}895}896897void SharkTopLevelBlock::do_astore(BasicType basic_type) {898SharkValue *svalue = pop();899SharkValue *index = pop();900SharkValue *array = pop();901902check_null(array);903check_bounds(array, index);904905Value *value;906switch (basic_type) {907case T_BYTE:908case T_CHAR:909case T_SHORT:910case T_INT:911value = svalue->jint_value();912break;913914case T_LONG:915value = svalue->jlong_value();916break;917918case T_FLOAT:919value = svalue->jfloat_value();920break;921922case T_DOUBLE:923value = svalue->jdouble_value();924break;925926case T_OBJECT:927value = svalue->jobject_value();928// XXX assignability check929break;930931default:932tty->print_cr("Unhandled type %s", type2name(basic_type));933ShouldNotReachHere();934}935936Type *array_type = SharkType::to_arrayType(basic_type);937if (value->getType() != array_type)938value = builder()->CreateIntCast(value, array_type, basic_type != T_CHAR);939940Value *addr = builder()->CreateArrayAddress(941array->jarray_value(), basic_type, index->jint_value(), "addr");942943builder()->CreateStore(value, addr);944945if (basic_type == T_OBJECT) // XXX or T_ARRAY?946builder()->CreateUpdateBarrierSet(oopDesc::bs(), addr);947}948949void SharkTopLevelBlock::do_return(BasicType type) {950if (target()->intrinsic_id() == vmIntrinsics::_Object_init)951call_register_finalizer(local(0)->jobject_value());952maybe_add_safepoint();953handle_return(type, NULL);954}955956void SharkTopLevelBlock::do_athrow() {957SharkValue *exception = pop();958check_null(exception);959handle_exception(exception->jobject_value(), EX_CHECK_FULL);960}961962void SharkTopLevelBlock::do_goto() {963do_branch(ciTypeFlow::GOTO_TARGET);964}965966void SharkTopLevelBlock::do_jsr() {967push(SharkValue::address_constant(iter()->next_bci()));968do_branch(ciTypeFlow::GOTO_TARGET);969}970971void SharkTopLevelBlock::do_ret() {972assert(local(iter()->get_index())->address_value() ==973successor(ciTypeFlow::GOTO_TARGET)->start(), "should be");974do_branch(ciTypeFlow::GOTO_TARGET);975}976977// All propagation of state from one block to the next (via978// dest->add_incoming) is handled by these methods:979// do_branch980// do_if_helper981// do_switch982// handle_exception983984void SharkTopLevelBlock::do_branch(int successor_index) {985SharkTopLevelBlock *dest = successor(successor_index);986builder()->CreateBr(dest->entry_block());987dest->add_incoming(current_state());988}989990void SharkTopLevelBlock::do_if(ICmpInst::Predicate p,991SharkValue* b,992SharkValue* a) {993Value *llvm_a, *llvm_b;994if (a->is_jobject()) {995llvm_a = a->intptr_value(builder());996llvm_b = b->intptr_value(builder());997}998else {999llvm_a = a->jint_value();1000llvm_b = b->jint_value();1001}1002do_if_helper(p, llvm_b, llvm_a, current_state(), current_state());1003}10041005void SharkTopLevelBlock::do_if_helper(ICmpInst::Predicate p,1006Value* b,1007Value* a,1008SharkState* if_taken_state,1009SharkState* not_taken_state) {1010SharkTopLevelBlock *if_taken = successor(ciTypeFlow::IF_TAKEN);1011SharkTopLevelBlock *not_taken = successor(ciTypeFlow::IF_NOT_TAKEN);10121013builder()->CreateCondBr(1014builder()->CreateICmp(p, a, b),1015if_taken->entry_block(), not_taken->entry_block());10161017if_taken->add_incoming(if_taken_state);1018not_taken->add_incoming(not_taken_state);1019}10201021void SharkTopLevelBlock::do_switch() {1022int len = switch_table_length();10231024SharkTopLevelBlock *dest_block = successor(ciTypeFlow::SWITCH_DEFAULT);1025SwitchInst *switchinst = builder()->CreateSwitch(1026pop()->jint_value(), dest_block->entry_block(), len);1027dest_block->add_incoming(current_state());10281029for (int i = 0; i < len; i++) {1030int dest_bci = switch_dest(i);1031if (dest_bci != switch_default_dest()) {1032dest_block = bci_successor(dest_bci);1033switchinst->addCase(1034LLVMValue::jint_constant(switch_key(i)),1035dest_block->entry_block());1036dest_block->add_incoming(current_state());1037}1038}1039}10401041ciMethod* SharkTopLevelBlock::improve_virtual_call(ciMethod* caller,1042ciInstanceKlass* klass,1043ciMethod* dest_method,1044ciType* receiver_type) {1045// If the method is obviously final then we are already done1046if (dest_method->can_be_statically_bound())1047return dest_method;10481049// Array methods are all inherited from Object and are monomorphic1050if (receiver_type->is_array_klass() &&1051dest_method->holder() == java_lang_Object_klass())1052return dest_method;10531054// This code can replace a virtual call with a direct call if this1055// class is the only one in the entire set of loaded classes that1056// implements this method. This makes the compiled code dependent1057// on other classes that implement the method not being loaded, a1058// condition which is enforced by the dependency tracker. If the1059// dependency tracker determines a method has become invalid it1060// will mark it for recompilation, causing running copies to be1061// deoptimized. Shark currently can't deoptimize arbitrarily like1062// that, so this optimization cannot be used.1063// http://icedtea.classpath.org/bugzilla/show_bug.cgi?id=48110641065// All other interesting cases are instance classes1066if (!receiver_type->is_instance_klass())1067return NULL;10681069// Attempt to improve the receiver1070ciInstanceKlass* actual_receiver = klass;1071ciInstanceKlass *improved_receiver = receiver_type->as_instance_klass();1072if (improved_receiver->is_loaded() &&1073improved_receiver->is_initialized() &&1074!improved_receiver->is_interface() &&1075improved_receiver->is_subtype_of(actual_receiver)) {1076actual_receiver = improved_receiver;1077}10781079// Attempt to find a monomorphic target for this call using1080// class heirachy analysis.1081ciInstanceKlass *calling_klass = caller->holder();1082ciMethod* monomorphic_target =1083dest_method->find_monomorphic_target(calling_klass, klass, actual_receiver);1084if (monomorphic_target != NULL) {1085assert(!monomorphic_target->is_abstract(), "shouldn't be");10861087function()->dependencies()->assert_unique_concrete_method(actual_receiver, monomorphic_target);10881089// Opto has a bunch of type checking here that I don't1090// understand. It's to inhibit casting in one direction,1091// possibly because objects in Opto can have inexact1092// types, but I can't even tell which direction it1093// doesn't like. For now I'm going to block *any* cast.1094if (monomorphic_target != dest_method) {1095if (SharkPerformanceWarnings) {1096warning("found monomorphic target, but inhibited cast:");1097tty->print(" dest_method = ");1098dest_method->print_short_name(tty);1099tty->cr();1100tty->print(" monomorphic_target = ");1101monomorphic_target->print_short_name(tty);1102tty->cr();1103}1104monomorphic_target = NULL;1105}1106}11071108// Replace the virtual call with a direct one. This makes1109// us dependent on that target method not getting overridden1110// by dynamic class loading.1111if (monomorphic_target != NULL) {1112dependencies()->assert_unique_concrete_method(1113actual_receiver, monomorphic_target);1114return monomorphic_target;1115}11161117// Because Opto distinguishes exact types from inexact ones1118// it can perform a further optimization to replace calls1119// with non-monomorphic targets if the receiver has an exact1120// type. We don't mark types this way, so we can't do this.112111221123return NULL;1124}11251126Value *SharkTopLevelBlock::get_direct_callee(ciMethod* method) {1127return builder()->CreateBitCast(1128builder()->CreateInlineMetadata(method, SharkType::Method_type()),1129SharkType::Method_type(),1130"callee");1131}11321133Value *SharkTopLevelBlock::get_virtual_callee(SharkValue* receiver,1134int vtable_index) {1135Value *klass = builder()->CreateValueOfStructEntry(1136receiver->jobject_value(),1137in_ByteSize(oopDesc::klass_offset_in_bytes()),1138SharkType::oop_type(),1139"klass");11401141return builder()->CreateLoad(1142builder()->CreateArrayAddress(1143klass,1144SharkType::Method_type(),1145vtableEntry::size() * wordSize,1146in_ByteSize(InstanceKlass::vtable_start_offset() * wordSize),1147LLVMValue::intptr_constant(vtable_index)),1148"callee");1149}11501151Value* SharkTopLevelBlock::get_interface_callee(SharkValue *receiver,1152ciMethod* method) {1153BasicBlock *loop = function()->CreateBlock("loop");1154BasicBlock *got_null = function()->CreateBlock("got_null");1155BasicBlock *not_null = function()->CreateBlock("not_null");1156BasicBlock *next = function()->CreateBlock("next");1157BasicBlock *got_entry = function()->CreateBlock("got_entry");11581159// Locate the receiver's itable1160Value *object_klass = builder()->CreateValueOfStructEntry(1161receiver->jobject_value(), in_ByteSize(oopDesc::klass_offset_in_bytes()),1162SharkType::klass_type(),1163"object_klass");11641165Value *vtable_start = builder()->CreateAdd(1166builder()->CreatePtrToInt(object_klass, SharkType::intptr_type()),1167LLVMValue::intptr_constant(1168InstanceKlass::vtable_start_offset() * HeapWordSize),1169"vtable_start");11701171Value *vtable_length = builder()->CreateValueOfStructEntry(1172object_klass,1173in_ByteSize(InstanceKlass::vtable_length_offset() * HeapWordSize),1174SharkType::jint_type(),1175"vtable_length");1176vtable_length =1177builder()->CreateIntCast(vtable_length, SharkType::intptr_type(), false);11781179bool needs_aligning = HeapWordsPerLong > 1;1180Value *itable_start = builder()->CreateAdd(1181vtable_start,1182builder()->CreateShl(1183vtable_length,1184LLVMValue::intptr_constant(exact_log2(vtableEntry::size() * wordSize))),1185needs_aligning ? "" : "itable_start");1186if (needs_aligning) {1187itable_start = builder()->CreateAnd(1188builder()->CreateAdd(1189itable_start, LLVMValue::intptr_constant(BytesPerLong - 1)),1190LLVMValue::intptr_constant(~(BytesPerLong - 1)),1191"itable_start");1192}11931194// Locate this interface's entry in the table1195Value *iklass = builder()->CreateInlineMetadata(method->holder(), SharkType::klass_type());1196BasicBlock *loop_entry = builder()->GetInsertBlock();1197builder()->CreateBr(loop);1198builder()->SetInsertPoint(loop);1199PHINode *itable_entry_addr = builder()->CreatePHI(1200SharkType::intptr_type(), 0, "itable_entry_addr");1201itable_entry_addr->addIncoming(itable_start, loop_entry);12021203Value *itable_entry = builder()->CreateIntToPtr(1204itable_entry_addr, SharkType::itableOffsetEntry_type(), "itable_entry");12051206Value *itable_iklass = builder()->CreateValueOfStructEntry(1207itable_entry,1208in_ByteSize(itableOffsetEntry::interface_offset_in_bytes()),1209SharkType::klass_type(),1210"itable_iklass");12111212builder()->CreateCondBr(1213builder()->CreateICmpEQ(itable_iklass, LLVMValue::nullKlass()),1214got_null, not_null);12151216// A null entry means that the class doesn't implement the1217// interface, and wasn't the same as the class checked when1218// the interface was resolved.1219builder()->SetInsertPoint(got_null);1220builder()->CreateUnimplemented(__FILE__, __LINE__);1221builder()->CreateUnreachable();12221223builder()->SetInsertPoint(not_null);1224builder()->CreateCondBr(1225builder()->CreateICmpEQ(itable_iklass, iklass),1226got_entry, next);12271228builder()->SetInsertPoint(next);1229Value *next_entry = builder()->CreateAdd(1230itable_entry_addr,1231LLVMValue::intptr_constant(itableOffsetEntry::size() * wordSize));1232builder()->CreateBr(loop);1233itable_entry_addr->addIncoming(next_entry, next);12341235// Locate the method pointer1236builder()->SetInsertPoint(got_entry);1237Value *offset = builder()->CreateValueOfStructEntry(1238itable_entry,1239in_ByteSize(itableOffsetEntry::offset_offset_in_bytes()),1240SharkType::jint_type(),1241"offset");1242offset =1243builder()->CreateIntCast(offset, SharkType::intptr_type(), false);12441245return builder()->CreateLoad(1246builder()->CreateIntToPtr(1247builder()->CreateAdd(1248builder()->CreateAdd(1249builder()->CreateAdd(1250builder()->CreatePtrToInt(1251object_klass, SharkType::intptr_type()),1252offset),1253LLVMValue::intptr_constant(1254method->itable_index() * itableMethodEntry::size() * wordSize)),1255LLVMValue::intptr_constant(1256itableMethodEntry::method_offset_in_bytes())),1257PointerType::getUnqual(SharkType::Method_type())),1258"callee");1259}12601261void SharkTopLevelBlock::do_call() {1262// Set frequently used booleans1263bool is_static = bc() == Bytecodes::_invokestatic;1264bool is_virtual = bc() == Bytecodes::_invokevirtual;1265bool is_interface = bc() == Bytecodes::_invokeinterface;12661267// Find the method being called1268bool will_link;1269ciSignature* sig;1270ciMethod *dest_method = iter()->get_method(will_link, &sig);12711272assert(will_link, "typeflow responsibility");1273assert(dest_method->is_static() == is_static, "must match bc");12741275// Find the class of the method being called. Note1276// that the superclass check in the second assertion1277// is to cope with a hole in the spec that allows for1278// invokeinterface instructions where the resolved1279// method is a virtual method in java.lang.Object.1280// javac doesn't generate code like that, but there's1281// no reason a compliant Java compiler might not.1282ciInstanceKlass *holder_klass = dest_method->holder();1283assert(holder_klass->is_loaded(), "scan_for_traps responsibility");1284assert(holder_klass->is_interface() ||1285holder_klass->super() == NULL ||1286!is_interface, "must match bc");12871288bool is_forced_virtual = is_interface && holder_klass == java_lang_Object_klass();12891290ciKlass *holder = iter()->get_declared_method_holder();1291ciInstanceKlass *klass =1292ciEnv::get_instance_klass_for_declared_method_holder(holder);12931294if (is_forced_virtual) {1295klass = java_lang_Object_klass();1296}12971298// Find the receiver in the stack. We do this before1299// trying to inline because the inliner can only use1300// zero-checked values, not being able to perform the1301// check itself.1302SharkValue *receiver = NULL;1303if (!is_static) {1304receiver = xstack(dest_method->arg_size() - 1);1305check_null(receiver);1306}13071308// Try to improve non-direct calls1309bool call_is_virtual = is_virtual || is_interface;1310ciMethod *call_method = dest_method;1311if (call_is_virtual) {1312ciMethod *optimized_method = improve_virtual_call(1313target(), klass, dest_method, receiver->type());1314if (optimized_method) {1315call_method = optimized_method;1316call_is_virtual = false;1317}1318}13191320// Try to inline the call1321if (!call_is_virtual) {1322if (SharkInliner::attempt_inline(call_method, current_state())) {1323return;1324}1325}13261327// Find the method we are calling1328Value *callee;1329if (call_is_virtual) {1330if (is_virtual || is_forced_virtual) {1331assert(klass->is_linked(), "scan_for_traps responsibility");1332int vtable_index = call_method->resolve_vtable_index(1333target()->holder(), klass);1334assert(vtable_index >= 0, "should be");1335callee = get_virtual_callee(receiver, vtable_index);1336}1337else {1338assert(is_interface, "should be");1339callee = get_interface_callee(receiver, call_method);1340}1341}1342else {1343callee = get_direct_callee(call_method);1344}13451346// Load the SharkEntry from the callee1347Value *base_pc = builder()->CreateValueOfStructEntry(1348callee, Method::from_interpreted_offset(),1349SharkType::intptr_type(),1350"base_pc");13511352// Load the entry point from the SharkEntry1353Value *entry_point = builder()->CreateLoad(1354builder()->CreateIntToPtr(1355builder()->CreateAdd(1356base_pc,1357LLVMValue::intptr_constant(in_bytes(ZeroEntry::entry_point_offset()))),1358PointerType::getUnqual(1359PointerType::getUnqual(SharkType::entry_point_type()))),1360"entry_point");13611362// Make the call1363decache_for_Java_call(call_method);1364Value *deoptimized_frames = builder()->CreateCall3(1365entry_point, callee, base_pc, thread());13661367// If the callee got deoptimized then reexecute in the interpreter1368BasicBlock *reexecute = function()->CreateBlock("reexecute");1369BasicBlock *call_completed = function()->CreateBlock("call_completed");1370builder()->CreateCondBr(1371builder()->CreateICmpNE(deoptimized_frames, LLVMValue::jint_constant(0)),1372reexecute, call_completed);13731374builder()->SetInsertPoint(reexecute);1375builder()->CreateCall2(1376builder()->deoptimized_entry_point(),1377builder()->CreateSub(deoptimized_frames, LLVMValue::jint_constant(1)),1378thread());1379builder()->CreateBr(call_completed);13801381// Cache after the call1382builder()->SetInsertPoint(call_completed);1383cache_after_Java_call(call_method);13841385// Check for pending exceptions1386check_pending_exception(EX_CHECK_FULL);13871388// Mark that a safepoint check has occurred1389current_state()->set_has_safepointed(true);1390}13911392bool SharkTopLevelBlock::static_subtype_check(ciKlass* check_klass,1393ciKlass* object_klass) {1394// If the class we're checking against is java.lang.Object1395// then this is a no brainer. Apparently this can happen1396// in reflective code...1397if (check_klass == java_lang_Object_klass())1398return true;13991400// Perform a subtype check. NB in opto's code for this1401// (GraphKit::static_subtype_check) it says that static1402// interface types cannot be trusted, and if opto can't1403// trust them then I assume we can't either.1404if (object_klass->is_loaded() && !object_klass->is_interface()) {1405if (object_klass == check_klass)1406return true;14071408if (check_klass->is_loaded() && object_klass->is_subtype_of(check_klass))1409return true;1410}14111412return false;1413}14141415void SharkTopLevelBlock::do_instance_check() {1416// Get the class we're checking against1417bool will_link;1418ciKlass *check_klass = iter()->get_klass(will_link);14191420// Get the class of the object we're checking1421ciKlass *object_klass = xstack(0)->type()->as_klass();14221423// Can we optimize this check away?1424if (static_subtype_check(check_klass, object_klass)) {1425if (bc() == Bytecodes::_instanceof) {1426pop();1427push(SharkValue::jint_constant(1));1428}1429return;1430}14311432// Need to check this one at runtime1433if (will_link)1434do_full_instance_check(check_klass);1435else1436do_trapping_instance_check(check_klass);1437}14381439bool SharkTopLevelBlock::maybe_do_instanceof_if() {1440// Get the class we're checking against1441bool will_link;1442ciKlass *check_klass = iter()->get_klass(will_link);14431444// If the class is unloaded then the instanceof1445// cannot possibly succeed.1446if (!will_link)1447return false;14481449// Keep a copy of the object we're checking1450SharkValue *old_object = xstack(0);14511452// Get the class of the object we're checking1453ciKlass *object_klass = old_object->type()->as_klass();14541455// If the instanceof can be optimized away at compile time1456// then any subsequent checkcasts will be too so we handle1457// it normally.1458if (static_subtype_check(check_klass, object_klass))1459return false;14601461// Perform the instance check1462do_full_instance_check(check_klass);1463Value *result = pop()->jint_value();14641465// Create the casted object1466SharkValue *new_object = SharkValue::create_generic(1467check_klass, old_object->jobject_value(), old_object->zero_checked());14681469// Create two copies of the current state, one with the1470// original object and one with all instances of the1471// original object replaced with the new, casted object.1472SharkState *new_state = current_state();1473SharkState *old_state = new_state->copy();1474new_state->replace_all(old_object, new_object);14751476// Perform the check-and-branch1477switch (iter()->next_bc()) {1478case Bytecodes::_ifeq:1479// branch if not an instance1480do_if_helper(1481ICmpInst::ICMP_EQ,1482LLVMValue::jint_constant(0), result,1483old_state, new_state);1484break;14851486case Bytecodes::_ifne:1487// branch if an instance1488do_if_helper(1489ICmpInst::ICMP_NE,1490LLVMValue::jint_constant(0), result,1491new_state, old_state);1492break;14931494default:1495ShouldNotReachHere();1496}14971498return true;1499}15001501void SharkTopLevelBlock::do_full_instance_check(ciKlass* klass) {1502BasicBlock *not_null = function()->CreateBlock("not_null");1503BasicBlock *subtype_check = function()->CreateBlock("subtype_check");1504BasicBlock *is_instance = function()->CreateBlock("is_instance");1505BasicBlock *not_instance = function()->CreateBlock("not_instance");1506BasicBlock *merge1 = function()->CreateBlock("merge1");1507BasicBlock *merge2 = function()->CreateBlock("merge2");15081509enum InstanceCheckStates {1510IC_IS_NULL,1511IC_IS_INSTANCE,1512IC_NOT_INSTANCE,1513};15141515// Pop the object off the stack1516Value *object = pop()->jobject_value();15171518// Null objects aren't instances of anything1519builder()->CreateCondBr(1520builder()->CreateICmpEQ(object, LLVMValue::null()),1521merge2, not_null);1522BasicBlock *null_block = builder()->GetInsertBlock();15231524// Get the class we're checking against1525builder()->SetInsertPoint(not_null);1526Value *check_klass = builder()->CreateInlineMetadata(klass, SharkType::klass_type());15271528// Get the class of the object being tested1529Value *object_klass = builder()->CreateValueOfStructEntry(1530object, in_ByteSize(oopDesc::klass_offset_in_bytes()),1531SharkType::klass_type(),1532"object_klass");15331534// Perform the check1535builder()->CreateCondBr(1536builder()->CreateICmpEQ(check_klass, object_klass),1537is_instance, subtype_check);15381539builder()->SetInsertPoint(subtype_check);1540builder()->CreateCondBr(1541builder()->CreateICmpNE(1542builder()->CreateCall2(1543builder()->is_subtype_of(), check_klass, object_klass),1544LLVMValue::jbyte_constant(0)),1545is_instance, not_instance);15461547builder()->SetInsertPoint(is_instance);1548builder()->CreateBr(merge1);15491550builder()->SetInsertPoint(not_instance);1551builder()->CreateBr(merge1);15521553// First merge1554builder()->SetInsertPoint(merge1);1555PHINode *nonnull_result = builder()->CreatePHI(1556SharkType::jint_type(), 0, "nonnull_result");1557nonnull_result->addIncoming(1558LLVMValue::jint_constant(IC_IS_INSTANCE), is_instance);1559nonnull_result->addIncoming(1560LLVMValue::jint_constant(IC_NOT_INSTANCE), not_instance);1561BasicBlock *nonnull_block = builder()->GetInsertBlock();1562builder()->CreateBr(merge2);15631564// Second merge1565builder()->SetInsertPoint(merge2);1566PHINode *result = builder()->CreatePHI(1567SharkType::jint_type(), 0, "result");1568result->addIncoming(LLVMValue::jint_constant(IC_IS_NULL), null_block);1569result->addIncoming(nonnull_result, nonnull_block);15701571// Handle the result1572if (bc() == Bytecodes::_checkcast) {1573BasicBlock *failure = function()->CreateBlock("failure");1574BasicBlock *success = function()->CreateBlock("success");15751576builder()->CreateCondBr(1577builder()->CreateICmpNE(1578result, LLVMValue::jint_constant(IC_NOT_INSTANCE)),1579success, failure);15801581builder()->SetInsertPoint(failure);1582SharkState *saved_state = current_state()->copy();15831584call_vm(1585builder()->throw_ClassCastException(),1586builder()->CreateIntToPtr(1587LLVMValue::intptr_constant((intptr_t) __FILE__),1588PointerType::getUnqual(SharkType::jbyte_type())),1589LLVMValue::jint_constant(__LINE__),1590EX_CHECK_NONE);15911592Value *pending_exception = get_pending_exception();1593clear_pending_exception();1594handle_exception(pending_exception, EX_CHECK_FULL);15951596set_current_state(saved_state);1597builder()->SetInsertPoint(success);1598push(SharkValue::create_generic(klass, object, false));1599}1600else {1601push(1602SharkValue::create_jint(1603builder()->CreateIntCast(1604builder()->CreateICmpEQ(1605result, LLVMValue::jint_constant(IC_IS_INSTANCE)),1606SharkType::jint_type(), false), false));1607}1608}16091610void SharkTopLevelBlock::do_trapping_instance_check(ciKlass* klass) {1611BasicBlock *not_null = function()->CreateBlock("not_null");1612BasicBlock *is_null = function()->CreateBlock("null");16131614// Leave the object on the stack so it's there if we trap1615builder()->CreateCondBr(1616builder()->CreateICmpEQ(xstack(0)->jobject_value(), LLVMValue::null()),1617is_null, not_null);1618SharkState *saved_state = current_state()->copy();16191620// If it's not null then we need to trap1621builder()->SetInsertPoint(not_null);1622set_current_state(saved_state->copy());1623do_trap(1624Deoptimization::make_trap_request(1625Deoptimization::Reason_uninitialized,1626Deoptimization::Action_reinterpret));16271628// If it's null then we're ok1629builder()->SetInsertPoint(is_null);1630set_current_state(saved_state);1631if (bc() == Bytecodes::_checkcast) {1632push(SharkValue::create_generic(klass, pop()->jobject_value(), false));1633}1634else {1635pop();1636push(SharkValue::jint_constant(0));1637}1638}16391640void SharkTopLevelBlock::do_new() {1641bool will_link;1642ciInstanceKlass* klass = iter()->get_klass(will_link)->as_instance_klass();1643assert(will_link, "typeflow responsibility");16441645BasicBlock *got_tlab = NULL;1646BasicBlock *heap_alloc = NULL;1647BasicBlock *retry = NULL;1648BasicBlock *got_heap = NULL;1649BasicBlock *initialize = NULL;1650BasicBlock *got_fast = NULL;1651BasicBlock *slow_alloc_and_init = NULL;1652BasicBlock *got_slow = NULL;1653BasicBlock *push_object = NULL;16541655SharkState *fast_state = NULL;16561657Value *tlab_object = NULL;1658Value *heap_object = NULL;1659Value *fast_object = NULL;1660Value *slow_object = NULL;1661Value *object = NULL;16621663// The fast path1664if (!Klass::layout_helper_needs_slow_path(klass->layout_helper())) {1665if (UseTLAB) {1666got_tlab = function()->CreateBlock("got_tlab");1667heap_alloc = function()->CreateBlock("heap_alloc");1668}1669retry = function()->CreateBlock("retry");1670got_heap = function()->CreateBlock("got_heap");1671initialize = function()->CreateBlock("initialize");1672slow_alloc_and_init = function()->CreateBlock("slow_alloc_and_init");1673push_object = function()->CreateBlock("push_object");16741675size_t size_in_bytes = klass->size_helper() << LogHeapWordSize;16761677// Thread local allocation1678if (UseTLAB) {1679Value *top_addr = builder()->CreateAddressOfStructEntry(1680thread(), Thread::tlab_top_offset(),1681PointerType::getUnqual(SharkType::intptr_type()),1682"top_addr");16831684Value *end = builder()->CreateValueOfStructEntry(1685thread(), Thread::tlab_end_offset(),1686SharkType::intptr_type(),1687"end");16881689Value *old_top = builder()->CreateLoad(top_addr, "old_top");1690Value *new_top = builder()->CreateAdd(1691old_top, LLVMValue::intptr_constant(size_in_bytes));16921693builder()->CreateCondBr(1694builder()->CreateICmpULE(new_top, end),1695got_tlab, heap_alloc);16961697builder()->SetInsertPoint(got_tlab);1698tlab_object = builder()->CreateIntToPtr(1699old_top, SharkType::oop_type(), "tlab_object");17001701builder()->CreateStore(new_top, top_addr);1702builder()->CreateBr(initialize);17031704builder()->SetInsertPoint(heap_alloc);1705}17061707// Heap allocation1708Value *top_addr = builder()->CreateIntToPtr(1709LLVMValue::intptr_constant((intptr_t) Universe::heap()->top_addr()),1710PointerType::getUnqual(SharkType::intptr_type()),1711"top_addr");17121713Value *end = builder()->CreateLoad(1714builder()->CreateIntToPtr(1715LLVMValue::intptr_constant((intptr_t) Universe::heap()->end_addr()),1716PointerType::getUnqual(SharkType::intptr_type())),1717"end");17181719builder()->CreateBr(retry);1720builder()->SetInsertPoint(retry);17211722Value *old_top = builder()->CreateLoad(top_addr, "top");1723Value *new_top = builder()->CreateAdd(1724old_top, LLVMValue::intptr_constant(size_in_bytes));17251726builder()->CreateCondBr(1727builder()->CreateICmpULE(new_top, end),1728got_heap, slow_alloc_and_init);17291730builder()->SetInsertPoint(got_heap);1731heap_object = builder()->CreateIntToPtr(1732old_top, SharkType::oop_type(), "heap_object");17331734Value *check = builder()->CreateAtomicCmpXchg(top_addr, old_top, new_top, llvm::SequentiallyConsistent);1735builder()->CreateCondBr(1736builder()->CreateICmpEQ(old_top, check),1737initialize, retry);17381739// Initialize the object1740builder()->SetInsertPoint(initialize);1741if (tlab_object) {1742PHINode *phi = builder()->CreatePHI(1743SharkType::oop_type(), 0, "fast_object");1744phi->addIncoming(tlab_object, got_tlab);1745phi->addIncoming(heap_object, got_heap);1746fast_object = phi;1747}1748else {1749fast_object = heap_object;1750}17511752builder()->CreateMemset(1753builder()->CreateBitCast(1754fast_object, PointerType::getUnqual(SharkType::jbyte_type())),1755LLVMValue::jbyte_constant(0),1756LLVMValue::jint_constant(size_in_bytes),1757LLVMValue::jint_constant(HeapWordSize));17581759Value *mark_addr = builder()->CreateAddressOfStructEntry(1760fast_object, in_ByteSize(oopDesc::mark_offset_in_bytes()),1761PointerType::getUnqual(SharkType::intptr_type()),1762"mark_addr");17631764Value *klass_addr = builder()->CreateAddressOfStructEntry(1765fast_object, in_ByteSize(oopDesc::klass_offset_in_bytes()),1766PointerType::getUnqual(SharkType::klass_type()),1767"klass_addr");17681769// Set the mark1770intptr_t mark;1771if (UseBiasedLocking) {1772Unimplemented();1773}1774else {1775mark = (intptr_t) markOopDesc::prototype();1776}1777builder()->CreateStore(LLVMValue::intptr_constant(mark), mark_addr);17781779// Set the class1780Value *rtklass = builder()->CreateInlineMetadata(klass, SharkType::klass_type());1781builder()->CreateStore(rtklass, klass_addr);1782got_fast = builder()->GetInsertBlock();17831784builder()->CreateBr(push_object);1785builder()->SetInsertPoint(slow_alloc_and_init);1786fast_state = current_state()->copy();1787}17881789// The slow path1790call_vm(1791builder()->new_instance(),1792LLVMValue::jint_constant(iter()->get_klass_index()),1793EX_CHECK_FULL);1794slow_object = get_vm_result();1795got_slow = builder()->GetInsertBlock();17961797// Push the object1798if (push_object) {1799builder()->CreateBr(push_object);1800builder()->SetInsertPoint(push_object);1801}1802if (fast_object) {1803PHINode *phi = builder()->CreatePHI(SharkType::oop_type(), 0, "object");1804phi->addIncoming(fast_object, got_fast);1805phi->addIncoming(slow_object, got_slow);1806object = phi;1807current_state()->merge(fast_state, got_fast, got_slow);1808}1809else {1810object = slow_object;1811}18121813push(SharkValue::create_jobject(object, true));1814}18151816void SharkTopLevelBlock::do_newarray() {1817BasicType type = (BasicType) iter()->get_index();18181819call_vm(1820builder()->newarray(),1821LLVMValue::jint_constant(type),1822pop()->jint_value(),1823EX_CHECK_FULL);18241825ciArrayKlass *array_klass = ciArrayKlass::make(ciType::make(type));1826push(SharkValue::create_generic(array_klass, get_vm_result(), true));1827}18281829void SharkTopLevelBlock::do_anewarray() {1830bool will_link;1831ciKlass *klass = iter()->get_klass(will_link);1832assert(will_link, "typeflow responsibility");18331834ciObjArrayKlass *array_klass = ciObjArrayKlass::make(klass);1835if (!array_klass->is_loaded()) {1836Unimplemented();1837}18381839call_vm(1840builder()->anewarray(),1841LLVMValue::jint_constant(iter()->get_klass_index()),1842pop()->jint_value(),1843EX_CHECK_FULL);18441845push(SharkValue::create_generic(array_klass, get_vm_result(), true));1846}18471848void SharkTopLevelBlock::do_multianewarray() {1849bool will_link;1850ciArrayKlass *array_klass = iter()->get_klass(will_link)->as_array_klass();1851assert(will_link, "typeflow responsibility");18521853// The dimensions are stack values, so we use their slots for the1854// dimensions array. Note that we are storing them in the reverse1855// of normal stack order.1856int ndims = iter()->get_dimensions();18571858Value *dimensions = stack()->slot_addr(1859stack()->stack_slots_offset() + max_stack() - xstack_depth(),1860ArrayType::get(SharkType::jint_type(), ndims),1861"dimensions");18621863for (int i = 0; i < ndims; i++) {1864builder()->CreateStore(1865xstack(ndims - 1 - i)->jint_value(),1866builder()->CreateStructGEP(dimensions, i));1867}18681869call_vm(1870builder()->multianewarray(),1871LLVMValue::jint_constant(iter()->get_klass_index()),1872LLVMValue::jint_constant(ndims),1873builder()->CreateStructGEP(dimensions, 0),1874EX_CHECK_FULL);18751876// Now we can pop the dimensions off the stack1877for (int i = 0; i < ndims; i++)1878pop();18791880push(SharkValue::create_generic(array_klass, get_vm_result(), true));1881}18821883void SharkTopLevelBlock::acquire_method_lock() {1884Value *lockee;1885if (target()->is_static()) {1886lockee = builder()->CreateInlineOop(target()->holder()->java_mirror());1887}1888else1889lockee = local(0)->jobject_value();18901891iter()->force_bci(start()); // for the decache in acquire_lock1892acquire_lock(lockee, EX_CHECK_NO_CATCH);1893}18941895void SharkTopLevelBlock::do_monitorenter() {1896SharkValue *lockee = pop();1897check_null(lockee);1898acquire_lock(lockee->jobject_value(), EX_CHECK_FULL);1899}19001901void SharkTopLevelBlock::do_monitorexit() {1902pop(); // don't need this (monitors are block structured)1903release_lock(EX_CHECK_NO_CATCH);1904}19051906void SharkTopLevelBlock::acquire_lock(Value *lockee, int exception_action) {1907BasicBlock *try_recursive = function()->CreateBlock("try_recursive");1908BasicBlock *got_recursive = function()->CreateBlock("got_recursive");1909BasicBlock *not_recursive = function()->CreateBlock("not_recursive");1910BasicBlock *acquired_fast = function()->CreateBlock("acquired_fast");1911BasicBlock *lock_acquired = function()->CreateBlock("lock_acquired");19121913int monitor = num_monitors();1914Value *monitor_addr = stack()->monitor_addr(monitor);1915Value *monitor_object_addr = stack()->monitor_object_addr(monitor);1916Value *monitor_header_addr = stack()->monitor_header_addr(monitor);19171918// Store the object and mark the slot as live1919builder()->CreateStore(lockee, monitor_object_addr);1920set_num_monitors(monitor + 1);19211922// Try a simple lock1923Value *mark_addr = builder()->CreateAddressOfStructEntry(1924lockee, in_ByteSize(oopDesc::mark_offset_in_bytes()),1925PointerType::getUnqual(SharkType::intptr_type()),1926"mark_addr");19271928Value *mark = builder()->CreateLoad(mark_addr, "mark");1929Value *disp = builder()->CreateOr(1930mark, LLVMValue::intptr_constant(markOopDesc::unlocked_value), "disp");1931builder()->CreateStore(disp, monitor_header_addr);19321933Value *lock = builder()->CreatePtrToInt(1934monitor_header_addr, SharkType::intptr_type());1935Value *check = builder()->CreateAtomicCmpXchg(mark_addr, disp, lock, llvm::Acquire);1936builder()->CreateCondBr(1937builder()->CreateICmpEQ(disp, check),1938acquired_fast, try_recursive);19391940// Locking failed, but maybe this thread already owns it1941builder()->SetInsertPoint(try_recursive);1942Value *addr = builder()->CreateAnd(1943disp,1944LLVMValue::intptr_constant(~markOopDesc::lock_mask_in_place));19451946// NB we use the entire stack, but JavaThread::is_lock_owned()1947// uses a more limited range. I don't think it hurts though...1948Value *stack_limit = builder()->CreateValueOfStructEntry(1949thread(), Thread::stack_base_offset(),1950SharkType::intptr_type(),1951"stack_limit");19521953assert(sizeof(size_t) == sizeof(intptr_t), "should be");1954Value *stack_size = builder()->CreateValueOfStructEntry(1955thread(), Thread::stack_size_offset(),1956SharkType::intptr_type(),1957"stack_size");19581959Value *stack_start =1960builder()->CreateSub(stack_limit, stack_size, "stack_start");19611962builder()->CreateCondBr(1963builder()->CreateAnd(1964builder()->CreateICmpUGE(addr, stack_start),1965builder()->CreateICmpULT(addr, stack_limit)),1966got_recursive, not_recursive);19671968builder()->SetInsertPoint(got_recursive);1969builder()->CreateStore(LLVMValue::intptr_constant(0), monitor_header_addr);1970builder()->CreateBr(acquired_fast);19711972// Create an edge for the state merge1973builder()->SetInsertPoint(acquired_fast);1974SharkState *fast_state = current_state()->copy();1975builder()->CreateBr(lock_acquired);19761977// It's not a recursive case so we need to drop into the runtime1978builder()->SetInsertPoint(not_recursive);1979call_vm(1980builder()->monitorenter(), monitor_addr,1981exception_action | EAM_MONITOR_FUDGE);1982BasicBlock *acquired_slow = builder()->GetInsertBlock();1983builder()->CreateBr(lock_acquired);19841985// All done1986builder()->SetInsertPoint(lock_acquired);1987current_state()->merge(fast_state, acquired_fast, acquired_slow);1988}19891990void SharkTopLevelBlock::release_lock(int exception_action) {1991BasicBlock *not_recursive = function()->CreateBlock("not_recursive");1992BasicBlock *released_fast = function()->CreateBlock("released_fast");1993BasicBlock *slow_path = function()->CreateBlock("slow_path");1994BasicBlock *lock_released = function()->CreateBlock("lock_released");19951996int monitor = num_monitors() - 1;1997Value *monitor_addr = stack()->monitor_addr(monitor);1998Value *monitor_object_addr = stack()->monitor_object_addr(monitor);1999Value *monitor_header_addr = stack()->monitor_header_addr(monitor);20002001// If it is recursive then we're already done2002Value *disp = builder()->CreateLoad(monitor_header_addr);2003builder()->CreateCondBr(2004builder()->CreateICmpEQ(disp, LLVMValue::intptr_constant(0)),2005released_fast, not_recursive);20062007// Try a simple unlock2008builder()->SetInsertPoint(not_recursive);20092010Value *lock = builder()->CreatePtrToInt(2011monitor_header_addr, SharkType::intptr_type());20122013Value *lockee = builder()->CreateLoad(monitor_object_addr);20142015Value *mark_addr = builder()->CreateAddressOfStructEntry(2016lockee, in_ByteSize(oopDesc::mark_offset_in_bytes()),2017PointerType::getUnqual(SharkType::intptr_type()),2018"mark_addr");20192020Value *check = builder()->CreateAtomicCmpXchg(mark_addr, lock, disp, llvm::Release);2021builder()->CreateCondBr(2022builder()->CreateICmpEQ(lock, check),2023released_fast, slow_path);20242025// Create an edge for the state merge2026builder()->SetInsertPoint(released_fast);2027SharkState *fast_state = current_state()->copy();2028builder()->CreateBr(lock_released);20292030// Need to drop into the runtime to release this one2031builder()->SetInsertPoint(slow_path);2032call_vm(builder()->monitorexit(), monitor_addr, exception_action);2033BasicBlock *released_slow = builder()->GetInsertBlock();2034builder()->CreateBr(lock_released);20352036// All done2037builder()->SetInsertPoint(lock_released);2038current_state()->merge(fast_state, released_fast, released_slow);20392040// The object slot is now dead2041set_num_monitors(monitor);2042}204320442045