Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/opto/callGenerator.cpp
32285 views
/*1* Copyright (c) 2000, 2013, 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 "ci/bcEscapeAnalyzer.hpp"26#include "ci/ciCallSite.hpp"27#include "ci/ciObjArray.hpp"28#include "ci/ciMemberName.hpp"29#include "ci/ciMethodHandle.hpp"30#include "classfile/javaClasses.hpp"31#include "compiler/compileLog.hpp"32#include "opto/addnode.hpp"33#include "opto/callGenerator.hpp"34#include "opto/callnode.hpp"35#include "opto/cfgnode.hpp"36#include "opto/connode.hpp"37#include "opto/parse.hpp"38#include "opto/rootnode.hpp"39#include "opto/runtime.hpp"40#include "opto/subnode.hpp"414243// Utility function.44const TypeFunc* CallGenerator::tf() const {45return TypeFunc::make(method());46}4748//-----------------------------ParseGenerator---------------------------------49// Internal class which handles all direct bytecode traversal.50class ParseGenerator : public InlineCallGenerator {51private:52bool _is_osr;53float _expected_uses;5455public:56ParseGenerator(ciMethod* method, float expected_uses, bool is_osr = false)57: InlineCallGenerator(method)58{59_is_osr = is_osr;60_expected_uses = expected_uses;61assert(InlineTree::check_can_parse(method) == NULL, "parse must be possible");62}6364virtual bool is_parse() const { return true; }65virtual JVMState* generate(JVMState* jvms);66int is_osr() { return _is_osr; }6768};6970JVMState* ParseGenerator::generate(JVMState* jvms) {71Compile* C = Compile::current();7273if (is_osr()) {74// The JVMS for a OSR has a single argument (see its TypeFunc).75assert(jvms->depth() == 1, "no inline OSR");76}7778if (C->failing()) {79return NULL; // bailing out of the compile; do not try to parse80}8182Parse parser(jvms, method(), _expected_uses);83// Grab signature for matching/allocation84#ifdef ASSERT85if (parser.tf() != (parser.depth() == 1 ? C->tf() : tf())) {86MutexLockerEx ml(Compile_lock, Mutex::_no_safepoint_check_flag);87assert(C->env()->system_dictionary_modification_counter_changed(),88"Must invalidate if TypeFuncs differ");89}90#endif9192GraphKit& exits = parser.exits();9394if (C->failing()) {95while (exits.pop_exception_state() != NULL) ;96return NULL;97}9899assert(exits.jvms()->same_calls_as(jvms), "sanity");100101// Simply return the exit state of the parser,102// augmented by any exceptional states.103return exits.transfer_exceptions_into_jvms();104}105106//---------------------------DirectCallGenerator------------------------------107// Internal class which handles all out-of-line calls w/o receiver type checks.108class DirectCallGenerator : public CallGenerator {109private:110CallStaticJavaNode* _call_node;111// Force separate memory and I/O projections for the exceptional112// paths to facilitate late inlinig.113bool _separate_io_proj;114115public:116DirectCallGenerator(ciMethod* method, bool separate_io_proj)117: CallGenerator(method),118_separate_io_proj(separate_io_proj)119{120}121virtual JVMState* generate(JVMState* jvms);122123CallStaticJavaNode* call_node() const { return _call_node; }124};125126JVMState* DirectCallGenerator::generate(JVMState* jvms) {127GraphKit kit(jvms);128bool is_static = method()->is_static();129address target = is_static ? SharedRuntime::get_resolve_static_call_stub()130: SharedRuntime::get_resolve_opt_virtual_call_stub();131132if (kit.C->log() != NULL) {133kit.C->log()->elem("direct_call bci='%d'", jvms->bci());134}135136CallStaticJavaNode *call = new (kit.C) CallStaticJavaNode(kit.C, tf(), target, method(), kit.bci());137_call_node = call; // Save the call node in case we need it later138if (!is_static) {139// Make an explicit receiver null_check as part of this call.140// Since we share a map with the caller, his JVMS gets adjusted.141kit.null_check_receiver_before_call(method());142if (kit.stopped()) {143// And dump it back to the caller, decorated with any exceptions:144return kit.transfer_exceptions_into_jvms();145}146// Mark the call node as virtual, sort of:147call->set_optimized_virtual(true);148if (method()->is_method_handle_intrinsic() ||149method()->is_compiled_lambda_form()) {150call->set_method_handle_invoke(true);151}152}153kit.set_arguments_for_java_call(call);154kit.set_edges_for_java_call(call, false, _separate_io_proj);155Node* ret = kit.set_results_for_java_call(call, _separate_io_proj);156kit.push_node(method()->return_type()->basic_type(), ret);157return kit.transfer_exceptions_into_jvms();158}159160//--------------------------VirtualCallGenerator------------------------------161// Internal class which handles all out-of-line calls checking receiver type.162class VirtualCallGenerator : public CallGenerator {163private:164int _vtable_index;165public:166VirtualCallGenerator(ciMethod* method, int vtable_index)167: CallGenerator(method), _vtable_index(vtable_index)168{169assert(vtable_index == Method::invalid_vtable_index ||170vtable_index >= 0, "either invalid or usable");171}172virtual bool is_virtual() const { return true; }173virtual JVMState* generate(JVMState* jvms);174};175176JVMState* VirtualCallGenerator::generate(JVMState* jvms) {177GraphKit kit(jvms);178Node* receiver = kit.argument(0);179180if (kit.C->log() != NULL) {181kit.C->log()->elem("virtual_call bci='%d'", jvms->bci());182}183184// If the receiver is a constant null, do not torture the system185// by attempting to call through it. The compile will proceed186// correctly, but may bail out in final_graph_reshaping, because187// the call instruction will have a seemingly deficient out-count.188// (The bailout says something misleading about an "infinite loop".)189if (kit.gvn().type(receiver)->higher_equal(TypePtr::NULL_PTR)) {190assert(Bytecodes::is_invoke(kit.java_bc()), err_msg("%d: %s", kit.java_bc(), Bytecodes::name(kit.java_bc())));191ciMethod* declared_method = kit.method()->get_method_at_bci(kit.bci());192int arg_size = declared_method->signature()->arg_size_for_bc(kit.java_bc());193kit.inc_sp(arg_size); // restore arguments194kit.uncommon_trap(Deoptimization::Reason_null_check,195Deoptimization::Action_none,196NULL, "null receiver");197return kit.transfer_exceptions_into_jvms();198}199200// Ideally we would unconditionally do a null check here and let it201// be converted to an implicit check based on profile information.202// However currently the conversion to implicit null checks in203// Block::implicit_null_check() only looks for loads and stores, not calls.204ciMethod *caller = kit.method();205ciMethodData *caller_md = (caller == NULL) ? NULL : caller->method_data();206if (!UseInlineCaches || !ImplicitNullChecks || !os::zero_page_read_protected() ||207((ImplicitNullCheckThreshold > 0) && caller_md &&208(caller_md->trap_count(Deoptimization::Reason_null_check)209>= (uint)ImplicitNullCheckThreshold))) {210// Make an explicit receiver null_check as part of this call.211// Since we share a map with the caller, his JVMS gets adjusted.212receiver = kit.null_check_receiver_before_call(method());213if (kit.stopped()) {214// And dump it back to the caller, decorated with any exceptions:215return kit.transfer_exceptions_into_jvms();216}217}218219assert(!method()->is_static(), "virtual call must not be to static");220assert(!method()->is_final(), "virtual call should not be to final");221assert(!method()->is_private(), "virtual call should not be to private");222assert(_vtable_index == Method::invalid_vtable_index || !UseInlineCaches,223"no vtable calls if +UseInlineCaches ");224address target = SharedRuntime::get_resolve_virtual_call_stub();225// Normal inline cache used for call226CallDynamicJavaNode *call = new (kit.C) CallDynamicJavaNode(tf(), target, method(), _vtable_index, kit.bci());227kit.set_arguments_for_java_call(call);228kit.set_edges_for_java_call(call);229Node* ret = kit.set_results_for_java_call(call);230kit.push_node(method()->return_type()->basic_type(), ret);231232// Represent the effect of an implicit receiver null_check233// as part of this call. Since we share a map with the caller,234// his JVMS gets adjusted.235kit.cast_not_null(receiver);236return kit.transfer_exceptions_into_jvms();237}238239CallGenerator* CallGenerator::for_inline(ciMethod* m, float expected_uses) {240if (InlineTree::check_can_parse(m) != NULL) return NULL;241return new ParseGenerator(m, expected_uses);242}243244// As a special case, the JVMS passed to this CallGenerator is245// for the method execution already in progress, not just the JVMS246// of the caller. Thus, this CallGenerator cannot be mixed with others!247CallGenerator* CallGenerator::for_osr(ciMethod* m, int osr_bci) {248if (InlineTree::check_can_parse(m) != NULL) return NULL;249float past_uses = m->interpreter_invocation_count();250float expected_uses = past_uses;251return new ParseGenerator(m, expected_uses, true);252}253254CallGenerator* CallGenerator::for_direct_call(ciMethod* m, bool separate_io_proj) {255assert(!m->is_abstract(), "for_direct_call mismatch");256return new DirectCallGenerator(m, separate_io_proj);257}258259CallGenerator* CallGenerator::for_virtual_call(ciMethod* m, int vtable_index) {260assert(!m->is_static(), "for_virtual_call mismatch");261assert(!m->is_method_handle_intrinsic(), "should be a direct call");262return new VirtualCallGenerator(m, vtable_index);263}264265// Allow inlining decisions to be delayed266class LateInlineCallGenerator : public DirectCallGenerator {267protected:268CallGenerator* _inline_cg;269270virtual bool do_late_inline_check(JVMState* jvms) { return true; }271272public:273LateInlineCallGenerator(ciMethod* method, CallGenerator* inline_cg) :274DirectCallGenerator(method, true), _inline_cg(inline_cg) {}275276virtual bool is_late_inline() const { return true; }277278// Convert the CallStaticJava into an inline279virtual void do_late_inline();280281virtual JVMState* generate(JVMState* jvms) {282Compile *C = Compile::current();283C->print_inlining_skip(this);284285// Record that this call site should be revisited once the main286// parse is finished.287if (!is_mh_late_inline()) {288C->add_late_inline(this);289}290291// Emit the CallStaticJava and request separate projections so292// that the late inlining logic can distinguish between fall293// through and exceptional uses of the memory and io projections294// as is done for allocations and macro expansion.295return DirectCallGenerator::generate(jvms);296}297298virtual void print_inlining_late(const char* msg) {299CallNode* call = call_node();300Compile* C = Compile::current();301C->print_inlining_insert(this);302C->print_inlining(method(), call->jvms()->depth()-1, call->jvms()->bci(), msg);303}304305};306307void LateInlineCallGenerator::do_late_inline() {308// Can't inline it309CallStaticJavaNode* call = call_node();310if (call == NULL || call->outcnt() == 0 ||311call->in(0) == NULL || call->in(0)->is_top()) {312return;313}314315const TypeTuple *r = call->tf()->domain();316for (int i1 = 0; i1 < method()->arg_size(); i1++) {317if (call->in(TypeFunc::Parms + i1)->is_top() && r->field_at(TypeFunc::Parms + i1) != Type::HALF) {318assert(Compile::current()->inlining_incrementally(), "shouldn't happen during parsing");319return;320}321}322323if (call->in(TypeFunc::Memory)->is_top()) {324assert(Compile::current()->inlining_incrementally(), "shouldn't happen during parsing");325return;326}327328Compile* C = Compile::current();329// Remove inlined methods from Compiler's lists.330if (call->is_macro()) {331C->remove_macro_node(call);332}333334// Make a clone of the JVMState that appropriate to use for driving a parse335JVMState* old_jvms = call->jvms();336JVMState* jvms = old_jvms->clone_shallow(C);337uint size = call->req();338SafePointNode* map = new (C) SafePointNode(size, jvms);339for (uint i1 = 0; i1 < size; i1++) {340map->init_req(i1, call->in(i1));341}342343// Make sure the state is a MergeMem for parsing.344if (!map->in(TypeFunc::Memory)->is_MergeMem()) {345Node* mem = MergeMemNode::make(C, map->in(TypeFunc::Memory));346C->initial_gvn()->set_type_bottom(mem);347map->set_req(TypeFunc::Memory, mem);348}349350uint nargs = method()->arg_size();351// blow away old call arguments352Node* top = C->top();353for (uint i1 = 0; i1 < nargs; i1++) {354map->set_req(TypeFunc::Parms + i1, top);355}356jvms->set_map(map);357358// Make enough space in the expression stack to transfer359// the incoming arguments and return value.360map->ensure_stack(jvms, jvms->method()->max_stack());361for (uint i1 = 0; i1 < nargs; i1++) {362map->set_argument(jvms, i1, call->in(TypeFunc::Parms + i1));363}364365// This check is done here because for_method_handle_inline() method366// needs jvms for inlined state.367if (!do_late_inline_check(jvms)) {368map->disconnect_inputs(NULL, C);369return;370}371372C->print_inlining_insert(this);373374CompileLog* log = C->log();375if (log != NULL) {376log->head("late_inline method='%d'", log->identify(method()));377JVMState* p = jvms;378while (p != NULL) {379log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));380p = p->caller();381}382log->tail("late_inline");383}384385// Setup default node notes to be picked up by the inlining386Node_Notes* old_nn = C->node_notes_at(call->_idx);387if (old_nn != NULL) {388Node_Notes* entry_nn = old_nn->clone(C);389entry_nn->set_jvms(jvms);390C->set_default_node_notes(entry_nn);391}392393// Now perform the inling using the synthesized JVMState394JVMState* new_jvms = _inline_cg->generate(jvms);395if (new_jvms == NULL) return; // no change396if (C->failing()) return;397398// Capture any exceptional control flow399GraphKit kit(new_jvms);400401// Find the result object402Node* result = C->top();403int result_size = method()->return_type()->size();404if (result_size != 0 && !kit.stopped()) {405result = (result_size == 1) ? kit.pop() : kit.pop_pair();406}407408C->set_has_loops(C->has_loops() || _inline_cg->method()->has_loops());409C->env()->notice_inlined_method(_inline_cg->method());410C->set_inlining_progress(true);411412kit.replace_call(call, result, true);413}414415416CallGenerator* CallGenerator::for_late_inline(ciMethod* method, CallGenerator* inline_cg) {417return new LateInlineCallGenerator(method, inline_cg);418}419420class LateInlineMHCallGenerator : public LateInlineCallGenerator {421ciMethod* _caller;422int _attempt;423bool _input_not_const;424425virtual bool do_late_inline_check(JVMState* jvms);426virtual bool already_attempted() const { return _attempt > 0; }427428public:429LateInlineMHCallGenerator(ciMethod* caller, ciMethod* callee, bool input_not_const) :430LateInlineCallGenerator(callee, NULL), _caller(caller), _attempt(0), _input_not_const(input_not_const) {}431432virtual bool is_mh_late_inline() const { return true; }433434virtual JVMState* generate(JVMState* jvms) {435JVMState* new_jvms = LateInlineCallGenerator::generate(jvms);436if (_input_not_const) {437// inlining won't be possible so no need to enqueue right now.438call_node()->set_generator(this);439} else {440Compile::current()->add_late_inline(this);441}442return new_jvms;443}444445virtual void print_inlining_late(const char* msg) {446if (!_input_not_const) return;447LateInlineCallGenerator::print_inlining_late(msg);448}449};450451bool LateInlineMHCallGenerator::do_late_inline_check(JVMState* jvms) {452453CallGenerator* cg = for_method_handle_inline(jvms, _caller, method(), _input_not_const);454455if (!_input_not_const) {456_attempt++;457}458459if (cg != NULL) {460assert(!cg->is_late_inline() && cg->is_inline(), "we're doing late inlining");461_inline_cg = cg;462Compile::current()->dec_number_of_mh_late_inlines();463return true;464}465466call_node()->set_generator(this);467return false;468}469470CallGenerator* CallGenerator::for_mh_late_inline(ciMethod* caller, ciMethod* callee, bool input_not_const) {471Compile::current()->inc_number_of_mh_late_inlines();472CallGenerator* cg = new LateInlineMHCallGenerator(caller, callee, input_not_const);473return cg;474}475476class LateInlineStringCallGenerator : public LateInlineCallGenerator {477478public:479LateInlineStringCallGenerator(ciMethod* method, CallGenerator* inline_cg) :480LateInlineCallGenerator(method, inline_cg) {}481482virtual JVMState* generate(JVMState* jvms) {483Compile *C = Compile::current();484C->print_inlining_skip(this);485486C->add_string_late_inline(this);487488JVMState* new_jvms = DirectCallGenerator::generate(jvms);489return new_jvms;490}491492virtual bool is_string_late_inline() const { return true; }493};494495CallGenerator* CallGenerator::for_string_late_inline(ciMethod* method, CallGenerator* inline_cg) {496return new LateInlineStringCallGenerator(method, inline_cg);497}498499class LateInlineBoxingCallGenerator : public LateInlineCallGenerator {500501public:502LateInlineBoxingCallGenerator(ciMethod* method, CallGenerator* inline_cg) :503LateInlineCallGenerator(method, inline_cg) {}504505virtual JVMState* generate(JVMState* jvms) {506Compile *C = Compile::current();507C->print_inlining_skip(this);508509C->add_boxing_late_inline(this);510511JVMState* new_jvms = DirectCallGenerator::generate(jvms);512return new_jvms;513}514};515516CallGenerator* CallGenerator::for_boxing_late_inline(ciMethod* method, CallGenerator* inline_cg) {517return new LateInlineBoxingCallGenerator(method, inline_cg);518}519520//---------------------------WarmCallGenerator--------------------------------521// Internal class which handles initial deferral of inlining decisions.522class WarmCallGenerator : public CallGenerator {523WarmCallInfo* _call_info;524CallGenerator* _if_cold;525CallGenerator* _if_hot;526bool _is_virtual; // caches virtuality of if_cold527bool _is_inline; // caches inline-ness of if_hot528529public:530WarmCallGenerator(WarmCallInfo* ci,531CallGenerator* if_cold,532CallGenerator* if_hot)533: CallGenerator(if_cold->method())534{535assert(method() == if_hot->method(), "consistent choices");536_call_info = ci;537_if_cold = if_cold;538_if_hot = if_hot;539_is_virtual = if_cold->is_virtual();540_is_inline = if_hot->is_inline();541}542543virtual bool is_inline() const { return _is_inline; }544virtual bool is_virtual() const { return _is_virtual; }545virtual bool is_deferred() const { return true; }546547virtual JVMState* generate(JVMState* jvms);548};549550551CallGenerator* CallGenerator::for_warm_call(WarmCallInfo* ci,552CallGenerator* if_cold,553CallGenerator* if_hot) {554return new WarmCallGenerator(ci, if_cold, if_hot);555}556557JVMState* WarmCallGenerator::generate(JVMState* jvms) {558Compile* C = Compile::current();559if (C->log() != NULL) {560C->log()->elem("warm_call bci='%d'", jvms->bci());561}562jvms = _if_cold->generate(jvms);563if (jvms != NULL) {564Node* m = jvms->map()->control();565if (m->is_CatchProj()) m = m->in(0); else m = C->top();566if (m->is_Catch()) m = m->in(0); else m = C->top();567if (m->is_Proj()) m = m->in(0); else m = C->top();568if (m->is_CallJava()) {569_call_info->set_call(m->as_Call());570_call_info->set_hot_cg(_if_hot);571#ifndef PRODUCT572if (PrintOpto || PrintOptoInlining) {573tty->print_cr("Queueing for warm inlining at bci %d:", jvms->bci());574tty->print("WCI: ");575_call_info->print();576}577#endif578_call_info->set_heat(_call_info->compute_heat());579C->set_warm_calls(_call_info->insert_into(C->warm_calls()));580}581}582return jvms;583}584585void WarmCallInfo::make_hot() {586Unimplemented();587}588589void WarmCallInfo::make_cold() {590// No action: Just dequeue.591}592593594//------------------------PredictedCallGenerator------------------------------595// Internal class which handles all out-of-line calls checking receiver type.596class PredictedCallGenerator : public CallGenerator {597ciKlass* _predicted_receiver;598CallGenerator* _if_missed;599CallGenerator* _if_hit;600float _hit_prob;601602public:603PredictedCallGenerator(ciKlass* predicted_receiver,604CallGenerator* if_missed,605CallGenerator* if_hit, float hit_prob)606: CallGenerator(if_missed->method())607{608// The call profile data may predict the hit_prob as extreme as 0 or 1.609// Remove the extremes values from the range.610if (hit_prob > PROB_MAX) hit_prob = PROB_MAX;611if (hit_prob < PROB_MIN) hit_prob = PROB_MIN;612613_predicted_receiver = predicted_receiver;614_if_missed = if_missed;615_if_hit = if_hit;616_hit_prob = hit_prob;617}618619virtual bool is_virtual() const { return true; }620virtual bool is_inline() const { return _if_hit->is_inline(); }621virtual bool is_deferred() const { return _if_hit->is_deferred(); }622623virtual JVMState* generate(JVMState* jvms);624};625626627CallGenerator* CallGenerator::for_predicted_call(ciKlass* predicted_receiver,628CallGenerator* if_missed,629CallGenerator* if_hit,630float hit_prob) {631return new PredictedCallGenerator(predicted_receiver, if_missed, if_hit, hit_prob);632}633634635JVMState* PredictedCallGenerator::generate(JVMState* jvms) {636GraphKit kit(jvms);637PhaseGVN& gvn = kit.gvn();638// We need an explicit receiver null_check before checking its type.639// We share a map with the caller, so his JVMS gets adjusted.640Node* receiver = kit.argument(0);641642CompileLog* log = kit.C->log();643if (log != NULL) {644log->elem("predicted_call bci='%d' klass='%d'",645jvms->bci(), log->identify(_predicted_receiver));646}647648receiver = kit.null_check_receiver_before_call(method());649if (kit.stopped()) {650return kit.transfer_exceptions_into_jvms();651}652653// Make a copy of the replaced nodes in case we need to restore them654ReplacedNodes replaced_nodes = kit.map()->replaced_nodes();655replaced_nodes.clone();656657Node* exact_receiver = receiver; // will get updated in place...658Node* slow_ctl = kit.type_check_receiver(receiver,659_predicted_receiver, _hit_prob,660&exact_receiver);661662SafePointNode* slow_map = NULL;663JVMState* slow_jvms = NULL;664{ PreserveJVMState pjvms(&kit);665kit.set_control(slow_ctl);666if (!kit.stopped()) {667slow_jvms = _if_missed->generate(kit.sync_jvms());668if (kit.failing())669return NULL; // might happen because of NodeCountInliningCutoff670assert(slow_jvms != NULL, "must be");671kit.add_exception_states_from(slow_jvms);672kit.set_map(slow_jvms->map());673if (!kit.stopped())674slow_map = kit.stop();675}676}677678if (kit.stopped()) {679// Instance exactly does not matches the desired type.680kit.set_jvms(slow_jvms);681return kit.transfer_exceptions_into_jvms();682}683684// fall through if the instance exactly matches the desired type685kit.replace_in_map(receiver, exact_receiver);686687// Make the hot call:688JVMState* new_jvms = _if_hit->generate(kit.sync_jvms());689if (new_jvms == NULL) {690// Inline failed, so make a direct call.691assert(_if_hit->is_inline(), "must have been a failed inline");692CallGenerator* cg = CallGenerator::for_direct_call(_if_hit->method());693new_jvms = cg->generate(kit.sync_jvms());694}695kit.add_exception_states_from(new_jvms);696kit.set_jvms(new_jvms);697698// Need to merge slow and fast?699if (slow_map == NULL) {700// The fast path is the only path remaining.701return kit.transfer_exceptions_into_jvms();702}703704if (kit.stopped()) {705// Inlined method threw an exception, so it's just the slow path after all.706kit.set_jvms(slow_jvms);707return kit.transfer_exceptions_into_jvms();708}709710// There are 2 branches and the replaced nodes are only valid on711// one: restore the replaced nodes to what they were before the712// branch.713kit.map()->set_replaced_nodes(replaced_nodes);714715// Finish the diamond.716kit.C->set_has_split_ifs(true); // Has chance for split-if optimization717RegionNode* region = new (kit.C) RegionNode(3);718region->init_req(1, kit.control());719region->init_req(2, slow_map->control());720kit.set_control(gvn.transform(region));721Node* iophi = PhiNode::make(region, kit.i_o(), Type::ABIO);722iophi->set_req(2, slow_map->i_o());723kit.set_i_o(gvn.transform(iophi));724// Merge memory725kit.merge_memory(slow_map->merged_memory(), region, 2);726// Transform new memory Phis.727for (MergeMemStream mms(kit.merged_memory()); mms.next_non_empty();) {728Node* phi = mms.memory();729if (phi->is_Phi() && phi->in(0) == region) {730mms.set_memory(gvn.transform(phi));731}732}733uint tos = kit.jvms()->stkoff() + kit.sp();734uint limit = slow_map->req();735for (uint i = TypeFunc::Parms; i < limit; i++) {736// Skip unused stack slots; fast forward to monoff();737if (i == tos) {738i = kit.jvms()->monoff();739if( i >= limit ) break;740}741Node* m = kit.map()->in(i);742Node* n = slow_map->in(i);743if (m != n) {744const Type* t = gvn.type(m)->meet_speculative(gvn.type(n));745Node* phi = PhiNode::make(region, m, t);746phi->set_req(2, n);747kit.map()->set_req(i, gvn.transform(phi));748}749}750return kit.transfer_exceptions_into_jvms();751}752753754CallGenerator* CallGenerator::for_method_handle_call(JVMState* jvms, ciMethod* caller, ciMethod* callee, bool delayed_forbidden) {755assert(callee->is_method_handle_intrinsic() ||756callee->is_compiled_lambda_form(), "for_method_handle_call mismatch");757bool input_not_const;758CallGenerator* cg = CallGenerator::for_method_handle_inline(jvms, caller, callee, input_not_const);759Compile* C = Compile::current();760if (cg != NULL) {761if (!delayed_forbidden && AlwaysIncrementalInline) {762return CallGenerator::for_late_inline(callee, cg);763} else {764return cg;765}766}767int bci = jvms->bci();768ciCallProfile profile = caller->call_profile_at_bci(bci);769int call_site_count = caller->scale_count(profile.count());770771if (IncrementalInline && call_site_count > 0 &&772(input_not_const || !C->inlining_incrementally() || C->over_inlining_cutoff())) {773return CallGenerator::for_mh_late_inline(caller, callee, input_not_const);774} else {775// Out-of-line call.776return CallGenerator::for_direct_call(callee);777}778}779780CallGenerator* CallGenerator::for_method_handle_inline(JVMState* jvms, ciMethod* caller, ciMethod* callee, bool& input_not_const) {781GraphKit kit(jvms);782PhaseGVN& gvn = kit.gvn();783Compile* C = kit.C;784vmIntrinsics::ID iid = callee->intrinsic_id();785input_not_const = true;786switch (iid) {787case vmIntrinsics::_invokeBasic:788{789// Get MethodHandle receiver:790Node* receiver = kit.argument(0);791if (receiver->Opcode() == Op_ConP) {792input_not_const = false;793const TypeOopPtr* oop_ptr = receiver->bottom_type()->is_oopptr();794ciMethod* target = oop_ptr->const_oop()->as_method_handle()->get_vmtarget();795guarantee(!target->is_method_handle_intrinsic(), "should not happen"); // XXX remove796const int vtable_index = Method::invalid_vtable_index;797CallGenerator* cg = C->call_generator(target, vtable_index, false, jvms, true, PROB_ALWAYS, NULL, true, true);798assert(cg == NULL || !cg->is_late_inline() || cg->is_mh_late_inline(), "no late inline here");799if (cg != NULL && cg->is_inline())800return cg;801}802}803break;804805case vmIntrinsics::_linkToVirtual:806case vmIntrinsics::_linkToStatic:807case vmIntrinsics::_linkToSpecial:808case vmIntrinsics::_linkToInterface:809{810// Get MemberName argument:811Node* member_name = kit.argument(callee->arg_size() - 1);812if (member_name->Opcode() == Op_ConP) {813input_not_const = false;814const TypeOopPtr* oop_ptr = member_name->bottom_type()->is_oopptr();815ciMethod* target = oop_ptr->const_oop()->as_member_name()->get_vmtarget();816817// In lamda forms we erase signature types to avoid resolving issues818// involving class loaders. When we optimize a method handle invoke819// to a direct call we must cast the receiver and arguments to its820// actual types.821ciSignature* signature = target->signature();822const int receiver_skip = target->is_static() ? 0 : 1;823// Cast receiver to its type.824if (!target->is_static()) {825Node* arg = kit.argument(0);826const TypeOopPtr* arg_type = arg->bottom_type()->isa_oopptr();827const Type* sig_type = TypeOopPtr::make_from_klass(signature->accessing_klass());828if (arg_type != NULL && !arg_type->higher_equal(sig_type)) {829Node* cast_obj = gvn.transform(new (C) CheckCastPPNode(kit.control(), arg, sig_type));830kit.set_argument(0, cast_obj);831}832}833// Cast reference arguments to its type.834for (int i = 0, j = 0; i < signature->count(); i++) {835ciType* t = signature->type_at(i);836if (t->is_klass()) {837Node* arg = kit.argument(receiver_skip + j);838const TypeOopPtr* arg_type = arg->bottom_type()->isa_oopptr();839const Type* sig_type = TypeOopPtr::make_from_klass(t->as_klass());840if (arg_type != NULL && !arg_type->higher_equal(sig_type)) {841Node* cast_obj = gvn.transform(new (C) CheckCastPPNode(kit.control(), arg, sig_type));842kit.set_argument(receiver_skip + j, cast_obj);843}844}845j += t->size(); // long and double take two slots846}847848// Try to get the most accurate receiver type849const bool is_virtual = (iid == vmIntrinsics::_linkToVirtual);850const bool is_virtual_or_interface = (is_virtual || iid == vmIntrinsics::_linkToInterface);851int vtable_index = Method::invalid_vtable_index;852bool call_does_dispatch = false;853854ciKlass* speculative_receiver_type = NULL;855if (is_virtual_or_interface) {856ciInstanceKlass* klass = target->holder();857Node* receiver_node = kit.argument(0);858const TypeOopPtr* receiver_type = gvn.type(receiver_node)->isa_oopptr();859// call_does_dispatch and vtable_index are out-parameters. They might be changed.860// optimize_virtual_call() takes 2 different holder861// arguments for a corner case that doesn't apply here (see862// Parse::do_call())863target = C->optimize_virtual_call(caller, jvms->bci(), klass, klass,864target, receiver_type, is_virtual,865call_does_dispatch, vtable_index, // out-parameters866/*check_access=*/false);867// We lack profiling at this call but type speculation may868// provide us with a type869speculative_receiver_type = (receiver_type != NULL) ? receiver_type->speculative_type() : NULL;870}871872CallGenerator* cg = C->call_generator(target, vtable_index, call_does_dispatch, jvms, true, PROB_ALWAYS, speculative_receiver_type, true, true);873assert(cg == NULL || !cg->is_late_inline() || cg->is_mh_late_inline(), "no late inline here");874if (cg != NULL && cg->is_inline())875return cg;876}877}878break;879880default:881fatal(err_msg_res("unexpected intrinsic %d: %s", iid, vmIntrinsics::name_at(iid)));882break;883}884return NULL;885}886887888//------------------------PredicatedIntrinsicGenerator------------------------------889// Internal class which handles all predicated Intrinsic calls.890class PredicatedIntrinsicGenerator : public CallGenerator {891CallGenerator* _intrinsic;892CallGenerator* _cg;893894public:895PredicatedIntrinsicGenerator(CallGenerator* intrinsic,896CallGenerator* cg)897: CallGenerator(cg->method())898{899_intrinsic = intrinsic;900_cg = cg;901}902903virtual bool is_virtual() const { return true; }904virtual bool is_inlined() const { return true; }905virtual bool is_intrinsic() const { return true; }906907virtual JVMState* generate(JVMState* jvms);908};909910911CallGenerator* CallGenerator::for_predicated_intrinsic(CallGenerator* intrinsic,912CallGenerator* cg) {913return new PredicatedIntrinsicGenerator(intrinsic, cg);914}915916917JVMState* PredicatedIntrinsicGenerator::generate(JVMState* jvms) {918// The code we want to generate here is:919// if (receiver == NULL)920// uncommon_Trap921// if (predicate(0))922// do_intrinsic(0)923// else924// if (predicate(1))925// do_intrinsic(1)926// ...927// else928// do_java_comp929930GraphKit kit(jvms);931PhaseGVN& gvn = kit.gvn();932933CompileLog* log = kit.C->log();934if (log != NULL) {935log->elem("predicated_intrinsic bci='%d' method='%d'",936jvms->bci(), log->identify(method()));937}938939if (!method()->is_static()) {940// We need an explicit receiver null_check before checking its type in predicate.941// We share a map with the caller, so his JVMS gets adjusted.942Node* receiver = kit.null_check_receiver_before_call(method());943if (kit.stopped()) {944return kit.transfer_exceptions_into_jvms();945}946}947948int n_predicates = _intrinsic->predicates_count();949assert(n_predicates > 0, "sanity");950951JVMState** result_jvms = NEW_RESOURCE_ARRAY(JVMState*, (n_predicates+1));952953// Region for normal compilation code if intrinsic failed.954Node* slow_region = new (kit.C) RegionNode(1);955956int results = 0;957for (int predicate = 0; (predicate < n_predicates) && !kit.stopped(); predicate++) {958#ifdef ASSERT959JVMState* old_jvms = kit.jvms();960SafePointNode* old_map = kit.map();961Node* old_io = old_map->i_o();962Node* old_mem = old_map->memory();963Node* old_exc = old_map->next_exception();964#endif965Node* else_ctrl = _intrinsic->generate_predicate(kit.sync_jvms(), predicate);966#ifdef ASSERT967// Assert(no_new_memory && no_new_io && no_new_exceptions) after generate_predicate.968assert(old_jvms == kit.jvms(), "generate_predicate should not change jvm state");969SafePointNode* new_map = kit.map();970assert(old_io == new_map->i_o(), "generate_predicate should not change i_o");971assert(old_mem == new_map->memory(), "generate_predicate should not change memory");972assert(old_exc == new_map->next_exception(), "generate_predicate should not add exceptions");973#endif974if (!kit.stopped()) {975PreserveJVMState pjvms(&kit);976// Generate intrinsic code:977JVMState* new_jvms = _intrinsic->generate(kit.sync_jvms());978if (new_jvms == NULL) {979// Intrinsic failed, use normal compilation path for this predicate.980slow_region->add_req(kit.control());981} else {982kit.add_exception_states_from(new_jvms);983kit.set_jvms(new_jvms);984if (!kit.stopped()) {985result_jvms[results++] = kit.jvms();986}987}988}989if (else_ctrl == NULL) {990else_ctrl = kit.C->top();991}992kit.set_control(else_ctrl);993}994if (!kit.stopped()) {995// Final 'else' after predicates.996slow_region->add_req(kit.control());997}998if (slow_region->req() > 1) {999PreserveJVMState pjvms(&kit);1000// Generate normal compilation code:1001kit.set_control(gvn.transform(slow_region));1002JVMState* new_jvms = _cg->generate(kit.sync_jvms());1003if (kit.failing())1004return NULL; // might happen because of NodeCountInliningCutoff1005assert(new_jvms != NULL, "must be");1006kit.add_exception_states_from(new_jvms);1007kit.set_jvms(new_jvms);1008if (!kit.stopped()) {1009result_jvms[results++] = kit.jvms();1010}1011}10121013if (results == 0) {1014// All paths ended in uncommon traps.1015(void) kit.stop();1016return kit.transfer_exceptions_into_jvms();1017}10181019if (results == 1) { // Only one path1020kit.set_jvms(result_jvms[0]);1021return kit.transfer_exceptions_into_jvms();1022}10231024// Merge all paths.1025kit.C->set_has_split_ifs(true); // Has chance for split-if optimization1026RegionNode* region = new (kit.C) RegionNode(results + 1);1027Node* iophi = PhiNode::make(region, kit.i_o(), Type::ABIO);1028for (int i = 0; i < results; i++) {1029JVMState* jvms = result_jvms[i];1030int path = i + 1;1031SafePointNode* map = jvms->map();1032region->init_req(path, map->control());1033iophi->set_req(path, map->i_o());1034if (i == 0) {1035kit.set_jvms(jvms);1036} else {1037kit.merge_memory(map->merged_memory(), region, path);1038}1039}1040kit.set_control(gvn.transform(region));1041kit.set_i_o(gvn.transform(iophi));1042// Transform new memory Phis.1043for (MergeMemStream mms(kit.merged_memory()); mms.next_non_empty();) {1044Node* phi = mms.memory();1045if (phi->is_Phi() && phi->in(0) == region) {1046mms.set_memory(gvn.transform(phi));1047}1048}10491050// Merge debug info.1051Node** ins = NEW_RESOURCE_ARRAY(Node*, results);1052uint tos = kit.jvms()->stkoff() + kit.sp();1053Node* map = kit.map();1054uint limit = map->req();1055for (uint i = TypeFunc::Parms; i < limit; i++) {1056// Skip unused stack slots; fast forward to monoff();1057if (i == tos) {1058i = kit.jvms()->monoff();1059if( i >= limit ) break;1060}1061Node* n = map->in(i);1062ins[0] = n;1063const Type* t = gvn.type(n);1064bool needs_phi = false;1065for (int j = 1; j < results; j++) {1066JVMState* jvms = result_jvms[j];1067Node* jmap = jvms->map();1068Node* m = NULL;1069if (jmap->req() > i) {1070m = jmap->in(i);1071if (m != n) {1072needs_phi = true;1073t = t->meet_speculative(gvn.type(m));1074}1075}1076ins[j] = m;1077}1078if (needs_phi) {1079Node* phi = PhiNode::make(region, n, t);1080for (int j = 1; j < results; j++) {1081phi->set_req(j + 1, ins[j]);1082}1083map->set_req(i, gvn.transform(phi));1084}1085}10861087return kit.transfer_exceptions_into_jvms();1088}10891090//-------------------------UncommonTrapCallGenerator-----------------------------1091// Internal class which handles all out-of-line calls checking receiver type.1092class UncommonTrapCallGenerator : public CallGenerator {1093Deoptimization::DeoptReason _reason;1094Deoptimization::DeoptAction _action;10951096public:1097UncommonTrapCallGenerator(ciMethod* m,1098Deoptimization::DeoptReason reason,1099Deoptimization::DeoptAction action)1100: CallGenerator(m)1101{1102_reason = reason;1103_action = action;1104}11051106virtual bool is_virtual() const { ShouldNotReachHere(); return false; }1107virtual bool is_trap() const { return true; }11081109virtual JVMState* generate(JVMState* jvms);1110};111111121113CallGenerator*1114CallGenerator::for_uncommon_trap(ciMethod* m,1115Deoptimization::DeoptReason reason,1116Deoptimization::DeoptAction action) {1117return new UncommonTrapCallGenerator(m, reason, action);1118}111911201121JVMState* UncommonTrapCallGenerator::generate(JVMState* jvms) {1122GraphKit kit(jvms);1123// Take the trap with arguments pushed on the stack. (Cf. null_check_receiver).1124// Callsite signature can be different from actual method being called (i.e _linkTo* sites).1125// Use callsite signature always.1126ciMethod* declared_method = kit.method()->get_method_at_bci(kit.bci());1127int nargs = declared_method->arg_size();1128kit.inc_sp(nargs);1129assert(nargs <= kit.sp() && kit.sp() <= jvms->stk_size(), "sane sp w/ args pushed");1130if (_reason == Deoptimization::Reason_class_check &&1131_action == Deoptimization::Action_maybe_recompile) {1132// Temp fix for 65298111133// Don't allow uncommon_trap to override our decision to recompile in the event1134// of a class cast failure for a monomorphic call as it will never let us convert1135// the call to either bi-morphic or megamorphic and can lead to unc-trap loops1136bool keep_exact_action = true;1137kit.uncommon_trap(_reason, _action, NULL, "monomorphic vcall checkcast", false, keep_exact_action);1138} else {1139kit.uncommon_trap(_reason, _action);1140}1141return kit.transfer_exceptions_into_jvms();1142}11431144// (Note: Moved hook_up_call to GraphKit::set_edges_for_java_call.)11451146// (Node: Merged hook_up_exits into ParseGenerator::generate.)11471148#define NODES_OVERHEAD_PER_METHOD (30.0)1149#define NODES_PER_BYTECODE (9.5)11501151void WarmCallInfo::init(JVMState* call_site, ciMethod* call_method, ciCallProfile& profile, float prof_factor) {1152int call_count = profile.count();1153int code_size = call_method->code_size();11541155// Expected execution count is based on the historical count:1156_count = call_count < 0 ? 1 : call_site->method()->scale_count(call_count, prof_factor);11571158// Expected profit from inlining, in units of simple call-overheads.1159_profit = 1.0;11601161// Expected work performed by the call in units of call-overheads.1162// %%% need an empirical curve fit for "work" (time in call)1163float bytecodes_per_call = 3;1164_work = 1.0 + code_size / bytecodes_per_call;11651166// Expected size of compilation graph:1167// -XX:+PrintParseStatistics once reported:1168// Methods seen: 9184 Methods parsed: 9184 Nodes created: 15823911169// Histogram of 144298 parsed bytecodes:1170// %%% Need an better predictor for graph size.1171_size = NODES_OVERHEAD_PER_METHOD + (NODES_PER_BYTECODE * code_size);1172}11731174// is_cold: Return true if the node should never be inlined.1175// This is true if any of the key metrics are extreme.1176bool WarmCallInfo::is_cold() const {1177if (count() < WarmCallMinCount) return true;1178if (profit() < WarmCallMinProfit) return true;1179if (work() > WarmCallMaxWork) return true;1180if (size() > WarmCallMaxSize) return true;1181return false;1182}11831184// is_hot: Return true if the node should be inlined immediately.1185// This is true if any of the key metrics are extreme.1186bool WarmCallInfo::is_hot() const {1187assert(!is_cold(), "eliminate is_cold cases before testing is_hot");1188if (count() >= HotCallCountThreshold) return true;1189if (profit() >= HotCallProfitThreshold) return true;1190if (work() <= HotCallTrivialWork) return true;1191if (size() <= HotCallTrivialSize) return true;1192return false;1193}11941195// compute_heat:1196float WarmCallInfo::compute_heat() const {1197assert(!is_cold(), "compute heat only on warm nodes");1198assert(!is_hot(), "compute heat only on warm nodes");1199int min_size = MAX2(0, (int)HotCallTrivialSize);1200int max_size = MIN2(500, (int)WarmCallMaxSize);1201float method_size = (size() - min_size) / MAX2(1, max_size - min_size);1202float size_factor;1203if (method_size < 0.05) size_factor = 4; // 2 sigmas better than avg.1204else if (method_size < 0.15) size_factor = 2; // 1 sigma better than avg.1205else if (method_size < 0.5) size_factor = 1; // better than avg.1206else size_factor = 0.5; // worse than avg.1207return (count() * profit() * size_factor);1208}12091210bool WarmCallInfo::warmer_than(WarmCallInfo* that) {1211assert(this != that, "compare only different WCIs");1212assert(this->heat() != 0 && that->heat() != 0, "call compute_heat 1st");1213if (this->heat() > that->heat()) return true;1214if (this->heat() < that->heat()) return false;1215assert(this->heat() == that->heat(), "no NaN heat allowed");1216// Equal heat. Break the tie some other way.1217if (!this->call() || !that->call()) return (address)this > (address)that;1218return this->call()->_idx > that->call()->_idx;1219}12201221//#define UNINIT_NEXT ((WarmCallInfo*)badAddress)1222#define UNINIT_NEXT ((WarmCallInfo*)NULL)12231224WarmCallInfo* WarmCallInfo::insert_into(WarmCallInfo* head) {1225assert(next() == UNINIT_NEXT, "not yet on any list");1226WarmCallInfo* prev_p = NULL;1227WarmCallInfo* next_p = head;1228while (next_p != NULL && next_p->warmer_than(this)) {1229prev_p = next_p;1230next_p = prev_p->next();1231}1232// Install this between prev_p and next_p.1233this->set_next(next_p);1234if (prev_p == NULL)1235head = this;1236else1237prev_p->set_next(this);1238return head;1239}12401241WarmCallInfo* WarmCallInfo::remove_from(WarmCallInfo* head) {1242WarmCallInfo* prev_p = NULL;1243WarmCallInfo* next_p = head;1244while (next_p != this) {1245assert(next_p != NULL, "this must be in the list somewhere");1246prev_p = next_p;1247next_p = prev_p->next();1248}1249next_p = this->next();1250debug_only(this->set_next(UNINIT_NEXT));1251// Remove this from between prev_p and next_p.1252if (prev_p == NULL)1253head = next_p;1254else1255prev_p->set_next(next_p);1256return head;1257}12581259WarmCallInfo WarmCallInfo::_always_hot(WarmCallInfo::MAX_VALUE(), WarmCallInfo::MAX_VALUE(),1260WarmCallInfo::MIN_VALUE(), WarmCallInfo::MIN_VALUE());1261WarmCallInfo WarmCallInfo::_always_cold(WarmCallInfo::MIN_VALUE(), WarmCallInfo::MIN_VALUE(),1262WarmCallInfo::MAX_VALUE(), WarmCallInfo::MAX_VALUE());12631264WarmCallInfo* WarmCallInfo::always_hot() {1265assert(_always_hot.is_hot(), "must always be hot");1266return &_always_hot;1267}12681269WarmCallInfo* WarmCallInfo::always_cold() {1270assert(_always_cold.is_cold(), "must always be cold");1271return &_always_cold;1272}127312741275#ifndef PRODUCT12761277void WarmCallInfo::print() const {1278tty->print("%s : C=%6.1f P=%6.1f W=%6.1f S=%6.1f H=%6.1f -> %p",1279is_cold() ? "cold" : is_hot() ? "hot " : "warm",1280count(), profit(), work(), size(), compute_heat(), next());1281tty->cr();1282if (call() != NULL) call()->dump();1283}12841285void print_wci(WarmCallInfo* ci) {1286ci->print();1287}12881289void WarmCallInfo::print_all() const {1290for (const WarmCallInfo* p = this; p != NULL; p = p->next())1291p->print();1292}12931294int WarmCallInfo::count_all() const {1295int cnt = 0;1296for (const WarmCallInfo* p = this; p != NULL; p = p->next())1297cnt++;1298return cnt;1299}13001301#endif //PRODUCT130213031304