Path: blob/master/src/hotspot/share/opto/graphKit.cpp
64440 views
/*1* Copyright (c) 2001, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "ci/ciUtilities.hpp"26#include "classfile/javaClasses.hpp"27#include "ci/ciNativeEntryPoint.hpp"28#include "ci/ciObjArray.hpp"29#include "asm/register.hpp"30#include "compiler/compileLog.hpp"31#include "gc/shared/barrierSet.hpp"32#include "gc/shared/c2/barrierSetC2.hpp"33#include "interpreter/interpreter.hpp"34#include "memory/resourceArea.hpp"35#include "opto/addnode.hpp"36#include "opto/castnode.hpp"37#include "opto/convertnode.hpp"38#include "opto/graphKit.hpp"39#include "opto/idealKit.hpp"40#include "opto/intrinsicnode.hpp"41#include "opto/locknode.hpp"42#include "opto/machnode.hpp"43#include "opto/opaquenode.hpp"44#include "opto/parse.hpp"45#include "opto/rootnode.hpp"46#include "opto/runtime.hpp"47#include "opto/subtypenode.hpp"48#include "runtime/deoptimization.hpp"49#include "runtime/sharedRuntime.hpp"50#include "utilities/bitMap.inline.hpp"51#include "utilities/powerOfTwo.hpp"52#include "utilities/growableArray.hpp"5354//----------------------------GraphKit-----------------------------------------55// Main utility constructor.56GraphKit::GraphKit(JVMState* jvms)57: Phase(Phase::Parser),58_env(C->env()),59_gvn(*C->initial_gvn()),60_barrier_set(BarrierSet::barrier_set()->barrier_set_c2())61{62_exceptions = jvms->map()->next_exception();63if (_exceptions != NULL) jvms->map()->set_next_exception(NULL);64set_jvms(jvms);65}6667// Private constructor for parser.68GraphKit::GraphKit()69: Phase(Phase::Parser),70_env(C->env()),71_gvn(*C->initial_gvn()),72_barrier_set(BarrierSet::barrier_set()->barrier_set_c2())73{74_exceptions = NULL;75set_map(NULL);76debug_only(_sp = -99);77debug_only(set_bci(-99));78}79808182//---------------------------clean_stack---------------------------------------83// Clear away rubbish from the stack area of the JVM state.84// This destroys any arguments that may be waiting on the stack.85void GraphKit::clean_stack(int from_sp) {86SafePointNode* map = this->map();87JVMState* jvms = this->jvms();88int stk_size = jvms->stk_size();89int stkoff = jvms->stkoff();90Node* top = this->top();91for (int i = from_sp; i < stk_size; i++) {92if (map->in(stkoff + i) != top) {93map->set_req(stkoff + i, top);94}95}96}979899//--------------------------------sync_jvms-----------------------------------100// Make sure our current jvms agrees with our parse state.101JVMState* GraphKit::sync_jvms() const {102JVMState* jvms = this->jvms();103jvms->set_bci(bci()); // Record the new bci in the JVMState104jvms->set_sp(sp()); // Record the new sp in the JVMState105assert(jvms_in_sync(), "jvms is now in sync");106return jvms;107}108109//--------------------------------sync_jvms_for_reexecute---------------------110// Make sure our current jvms agrees with our parse state. This version111// uses the reexecute_sp for reexecuting bytecodes.112JVMState* GraphKit::sync_jvms_for_reexecute() {113JVMState* jvms = this->jvms();114jvms->set_bci(bci()); // Record the new bci in the JVMState115jvms->set_sp(reexecute_sp()); // Record the new sp in the JVMState116return jvms;117}118119#ifdef ASSERT120bool GraphKit::jvms_in_sync() const {121Parse* parse = is_Parse();122if (parse == NULL) {123if (bci() != jvms()->bci()) return false;124if (sp() != (int)jvms()->sp()) return false;125return true;126}127if (jvms()->method() != parse->method()) return false;128if (jvms()->bci() != parse->bci()) return false;129int jvms_sp = jvms()->sp();130if (jvms_sp != parse->sp()) return false;131int jvms_depth = jvms()->depth();132if (jvms_depth != parse->depth()) return false;133return true;134}135136// Local helper checks for special internal merge points137// used to accumulate and merge exception states.138// They are marked by the region's in(0) edge being the map itself.139// Such merge points must never "escape" into the parser at large,140// until they have been handed to gvn.transform.141static bool is_hidden_merge(Node* reg) {142if (reg == NULL) return false;143if (reg->is_Phi()) {144reg = reg->in(0);145if (reg == NULL) return false;146}147return reg->is_Region() && reg->in(0) != NULL && reg->in(0)->is_Root();148}149150void GraphKit::verify_map() const {151if (map() == NULL) return; // null map is OK152assert(map()->req() <= jvms()->endoff(), "no extra garbage on map");153assert(!map()->has_exceptions(), "call add_exception_states_from 1st");154assert(!is_hidden_merge(control()), "call use_exception_state, not set_map");155}156157void GraphKit::verify_exception_state(SafePointNode* ex_map) {158assert(ex_map->next_exception() == NULL, "not already part of a chain");159assert(has_saved_ex_oop(ex_map), "every exception state has an ex_oop");160}161#endif162163//---------------------------stop_and_kill_map---------------------------------164// Set _map to NULL, signalling a stop to further bytecode execution.165// First smash the current map's control to a constant, to mark it dead.166void GraphKit::stop_and_kill_map() {167SafePointNode* dead_map = stop();168if (dead_map != NULL) {169dead_map->disconnect_inputs(C); // Mark the map as killed.170assert(dead_map->is_killed(), "must be so marked");171}172}173174175//--------------------------------stopped--------------------------------------176// Tell if _map is NULL, or control is top.177bool GraphKit::stopped() {178if (map() == NULL) return true;179else if (control() == top()) return true;180else return false;181}182183184//-----------------------------has_ex_handler----------------------------------185// Tell if this method or any caller method has exception handlers.186bool GraphKit::has_ex_handler() {187for (JVMState* jvmsp = jvms(); jvmsp != NULL; jvmsp = jvmsp->caller()) {188if (jvmsp->has_method() && jvmsp->method()->has_exception_handlers()) {189return true;190}191}192return false;193}194195//------------------------------save_ex_oop------------------------------------196// Save an exception without blowing stack contents or other JVM state.197void GraphKit::set_saved_ex_oop(SafePointNode* ex_map, Node* ex_oop) {198assert(!has_saved_ex_oop(ex_map), "clear ex-oop before setting again");199ex_map->add_req(ex_oop);200debug_only(verify_exception_state(ex_map));201}202203inline static Node* common_saved_ex_oop(SafePointNode* ex_map, bool clear_it) {204assert(GraphKit::has_saved_ex_oop(ex_map), "ex_oop must be there");205Node* ex_oop = ex_map->in(ex_map->req()-1);206if (clear_it) ex_map->del_req(ex_map->req()-1);207return ex_oop;208}209210//-----------------------------saved_ex_oop------------------------------------211// Recover a saved exception from its map.212Node* GraphKit::saved_ex_oop(SafePointNode* ex_map) {213return common_saved_ex_oop(ex_map, false);214}215216//--------------------------clear_saved_ex_oop---------------------------------217// Erase a previously saved exception from its map.218Node* GraphKit::clear_saved_ex_oop(SafePointNode* ex_map) {219return common_saved_ex_oop(ex_map, true);220}221222#ifdef ASSERT223//---------------------------has_saved_ex_oop----------------------------------224// Erase a previously saved exception from its map.225bool GraphKit::has_saved_ex_oop(SafePointNode* ex_map) {226return ex_map->req() == ex_map->jvms()->endoff()+1;227}228#endif229230//-------------------------make_exception_state--------------------------------231// Turn the current JVM state into an exception state, appending the ex_oop.232SafePointNode* GraphKit::make_exception_state(Node* ex_oop) {233sync_jvms();234SafePointNode* ex_map = stop(); // do not manipulate this map any more235set_saved_ex_oop(ex_map, ex_oop);236return ex_map;237}238239240//--------------------------add_exception_state--------------------------------241// Add an exception to my list of exceptions.242void GraphKit::add_exception_state(SafePointNode* ex_map) {243if (ex_map == NULL || ex_map->control() == top()) {244return;245}246#ifdef ASSERT247verify_exception_state(ex_map);248if (has_exceptions()) {249assert(ex_map->jvms()->same_calls_as(_exceptions->jvms()), "all collected exceptions must come from the same place");250}251#endif252253// If there is already an exception of exactly this type, merge with it.254// In particular, null-checks and other low-level exceptions common up here.255Node* ex_oop = saved_ex_oop(ex_map);256const Type* ex_type = _gvn.type(ex_oop);257if (ex_oop == top()) {258// No action needed.259return;260}261assert(ex_type->isa_instptr(), "exception must be an instance");262for (SafePointNode* e2 = _exceptions; e2 != NULL; e2 = e2->next_exception()) {263const Type* ex_type2 = _gvn.type(saved_ex_oop(e2));264// We check sp also because call bytecodes can generate exceptions265// both before and after arguments are popped!266if (ex_type2 == ex_type267&& e2->_jvms->sp() == ex_map->_jvms->sp()) {268combine_exception_states(ex_map, e2);269return;270}271}272273// No pre-existing exception of the same type. Chain it on the list.274push_exception_state(ex_map);275}276277//-----------------------add_exception_states_from-----------------------------278void GraphKit::add_exception_states_from(JVMState* jvms) {279SafePointNode* ex_map = jvms->map()->next_exception();280if (ex_map != NULL) {281jvms->map()->set_next_exception(NULL);282for (SafePointNode* next_map; ex_map != NULL; ex_map = next_map) {283next_map = ex_map->next_exception();284ex_map->set_next_exception(NULL);285add_exception_state(ex_map);286}287}288}289290//-----------------------transfer_exceptions_into_jvms-------------------------291JVMState* GraphKit::transfer_exceptions_into_jvms() {292if (map() == NULL) {293// We need a JVMS to carry the exceptions, but the map has gone away.294// Create a scratch JVMS, cloned from any of the exception states...295if (has_exceptions()) {296_map = _exceptions;297_map = clone_map();298_map->set_next_exception(NULL);299clear_saved_ex_oop(_map);300debug_only(verify_map());301} else {302// ...or created from scratch303JVMState* jvms = new (C) JVMState(_method, NULL);304jvms->set_bci(_bci);305jvms->set_sp(_sp);306jvms->set_map(new SafePointNode(TypeFunc::Parms, jvms));307set_jvms(jvms);308for (uint i = 0; i < map()->req(); i++) map()->init_req(i, top());309set_all_memory(top());310while (map()->req() < jvms->endoff()) map()->add_req(top());311}312// (This is a kludge, in case you didn't notice.)313set_control(top());314}315JVMState* jvms = sync_jvms();316assert(!jvms->map()->has_exceptions(), "no exceptions on this map yet");317jvms->map()->set_next_exception(_exceptions);318_exceptions = NULL; // done with this set of exceptions319return jvms;320}321322static inline void add_n_reqs(Node* dstphi, Node* srcphi) {323assert(is_hidden_merge(dstphi), "must be a special merge node");324assert(is_hidden_merge(srcphi), "must be a special merge node");325uint limit = srcphi->req();326for (uint i = PhiNode::Input; i < limit; i++) {327dstphi->add_req(srcphi->in(i));328}329}330static inline void add_one_req(Node* dstphi, Node* src) {331assert(is_hidden_merge(dstphi), "must be a special merge node");332assert(!is_hidden_merge(src), "must not be a special merge node");333dstphi->add_req(src);334}335336//-----------------------combine_exception_states------------------------------337// This helper function combines exception states by building phis on a338// specially marked state-merging region. These regions and phis are339// untransformed, and can build up gradually. The region is marked by340// having a control input of its exception map, rather than NULL. Such341// regions do not appear except in this function, and in use_exception_state.342void GraphKit::combine_exception_states(SafePointNode* ex_map, SafePointNode* phi_map) {343if (failing()) return; // dying anyway...344JVMState* ex_jvms = ex_map->_jvms;345assert(ex_jvms->same_calls_as(phi_map->_jvms), "consistent call chains");346assert(ex_jvms->stkoff() == phi_map->_jvms->stkoff(), "matching locals");347assert(ex_jvms->sp() == phi_map->_jvms->sp(), "matching stack sizes");348assert(ex_jvms->monoff() == phi_map->_jvms->monoff(), "matching JVMS");349assert(ex_jvms->scloff() == phi_map->_jvms->scloff(), "matching scalar replaced objects");350assert(ex_map->req() == phi_map->req(), "matching maps");351uint tos = ex_jvms->stkoff() + ex_jvms->sp();352Node* hidden_merge_mark = root();353Node* region = phi_map->control();354MergeMemNode* phi_mem = phi_map->merged_memory();355MergeMemNode* ex_mem = ex_map->merged_memory();356if (region->in(0) != hidden_merge_mark) {357// The control input is not (yet) a specially-marked region in phi_map.358// Make it so, and build some phis.359region = new RegionNode(2);360_gvn.set_type(region, Type::CONTROL);361region->set_req(0, hidden_merge_mark); // marks an internal ex-state362region->init_req(1, phi_map->control());363phi_map->set_control(region);364Node* io_phi = PhiNode::make(region, phi_map->i_o(), Type::ABIO);365record_for_igvn(io_phi);366_gvn.set_type(io_phi, Type::ABIO);367phi_map->set_i_o(io_phi);368for (MergeMemStream mms(phi_mem); mms.next_non_empty(); ) {369Node* m = mms.memory();370Node* m_phi = PhiNode::make(region, m, Type::MEMORY, mms.adr_type(C));371record_for_igvn(m_phi);372_gvn.set_type(m_phi, Type::MEMORY);373mms.set_memory(m_phi);374}375}376377// Either or both of phi_map and ex_map might already be converted into phis.378Node* ex_control = ex_map->control();379// if there is special marking on ex_map also, we add multiple edges from src380bool add_multiple = (ex_control->in(0) == hidden_merge_mark);381// how wide was the destination phi_map, originally?382uint orig_width = region->req();383384if (add_multiple) {385add_n_reqs(region, ex_control);386add_n_reqs(phi_map->i_o(), ex_map->i_o());387} else {388// ex_map has no merges, so we just add single edges everywhere389add_one_req(region, ex_control);390add_one_req(phi_map->i_o(), ex_map->i_o());391}392for (MergeMemStream mms(phi_mem, ex_mem); mms.next_non_empty2(); ) {393if (mms.is_empty()) {394// get a copy of the base memory, and patch some inputs into it395const TypePtr* adr_type = mms.adr_type(C);396Node* phi = mms.force_memory()->as_Phi()->slice_memory(adr_type);397assert(phi->as_Phi()->region() == mms.base_memory()->in(0), "");398mms.set_memory(phi);399// Prepare to append interesting stuff onto the newly sliced phi:400while (phi->req() > orig_width) phi->del_req(phi->req()-1);401}402// Append stuff from ex_map:403if (add_multiple) {404add_n_reqs(mms.memory(), mms.memory2());405} else {406add_one_req(mms.memory(), mms.memory2());407}408}409uint limit = ex_map->req();410for (uint i = TypeFunc::Parms; i < limit; i++) {411// Skip everything in the JVMS after tos. (The ex_oop follows.)412if (i == tos) i = ex_jvms->monoff();413Node* src = ex_map->in(i);414Node* dst = phi_map->in(i);415if (src != dst) {416PhiNode* phi;417if (dst->in(0) != region) {418dst = phi = PhiNode::make(region, dst, _gvn.type(dst));419record_for_igvn(phi);420_gvn.set_type(phi, phi->type());421phi_map->set_req(i, dst);422// Prepare to append interesting stuff onto the new phi:423while (dst->req() > orig_width) dst->del_req(dst->req()-1);424} else {425assert(dst->is_Phi(), "nobody else uses a hidden region");426phi = dst->as_Phi();427}428if (add_multiple && src->in(0) == ex_control) {429// Both are phis.430add_n_reqs(dst, src);431} else {432while (dst->req() < region->req()) add_one_req(dst, src);433}434const Type* srctype = _gvn.type(src);435if (phi->type() != srctype) {436const Type* dsttype = phi->type()->meet_speculative(srctype);437if (phi->type() != dsttype) {438phi->set_type(dsttype);439_gvn.set_type(phi, dsttype);440}441}442}443}444phi_map->merge_replaced_nodes_with(ex_map);445}446447//--------------------------use_exception_state--------------------------------448Node* GraphKit::use_exception_state(SafePointNode* phi_map) {449if (failing()) { stop(); return top(); }450Node* region = phi_map->control();451Node* hidden_merge_mark = root();452assert(phi_map->jvms()->map() == phi_map, "sanity: 1-1 relation");453Node* ex_oop = clear_saved_ex_oop(phi_map);454if (region->in(0) == hidden_merge_mark) {455// Special marking for internal ex-states. Process the phis now.456region->set_req(0, region); // now it's an ordinary region457set_jvms(phi_map->jvms()); // ...so now we can use it as a map458// Note: Setting the jvms also sets the bci and sp.459set_control(_gvn.transform(region));460uint tos = jvms()->stkoff() + sp();461for (uint i = 1; i < tos; i++) {462Node* x = phi_map->in(i);463if (x->in(0) == region) {464assert(x->is_Phi(), "expected a special phi");465phi_map->set_req(i, _gvn.transform(x));466}467}468for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {469Node* x = mms.memory();470if (x->in(0) == region) {471assert(x->is_Phi(), "nobody else uses a hidden region");472mms.set_memory(_gvn.transform(x));473}474}475if (ex_oop->in(0) == region) {476assert(ex_oop->is_Phi(), "expected a special phi");477ex_oop = _gvn.transform(ex_oop);478}479} else {480set_jvms(phi_map->jvms());481}482483assert(!is_hidden_merge(phi_map->control()), "hidden ex. states cleared");484assert(!is_hidden_merge(phi_map->i_o()), "hidden ex. states cleared");485return ex_oop;486}487488//---------------------------------java_bc-------------------------------------489Bytecodes::Code GraphKit::java_bc() const {490ciMethod* method = this->method();491int bci = this->bci();492if (method != NULL && bci != InvocationEntryBci)493return method->java_code_at_bci(bci);494else495return Bytecodes::_illegal;496}497498void GraphKit::uncommon_trap_if_should_post_on_exceptions(Deoptimization::DeoptReason reason,499bool must_throw) {500// if the exception capability is set, then we will generate code501// to check the JavaThread.should_post_on_exceptions flag to see502// if we actually need to report exception events (for this503// thread). If we don't need to report exception events, we will504// take the normal fast path provided by add_exception_events. If505// exception event reporting is enabled for this thread, we will506// take the uncommon_trap in the BuildCutout below.507508// first must access the should_post_on_exceptions_flag in this thread's JavaThread509Node* jthread = _gvn.transform(new ThreadLocalNode());510Node* adr = basic_plus_adr(top(), jthread, in_bytes(JavaThread::should_post_on_exceptions_flag_offset()));511Node* should_post_flag = make_load(control(), adr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, MemNode::unordered);512513// Test the should_post_on_exceptions_flag vs. 0514Node* chk = _gvn.transform( new CmpINode(should_post_flag, intcon(0)) );515Node* tst = _gvn.transform( new BoolNode(chk, BoolTest::eq) );516517// Branch to slow_path if should_post_on_exceptions_flag was true518{ BuildCutout unless(this, tst, PROB_MAX);519// Do not try anything fancy if we're notifying the VM on every throw.520// Cf. case Bytecodes::_athrow in parse2.cpp.521uncommon_trap(reason, Deoptimization::Action_none,522(ciKlass*)NULL, (char*)NULL, must_throw);523}524525}526527//------------------------------builtin_throw----------------------------------528void GraphKit::builtin_throw(Deoptimization::DeoptReason reason, Node* arg) {529bool must_throw = true;530531// If this particular condition has not yet happened at this532// bytecode, then use the uncommon trap mechanism, and allow for533// a future recompilation if several traps occur here.534// If the throw is hot, try to use a more complicated inline mechanism535// which keeps execution inside the compiled code.536bool treat_throw_as_hot = false;537ciMethodData* md = method()->method_data();538539if (ProfileTraps) {540if (too_many_traps(reason)) {541treat_throw_as_hot = true;542}543// (If there is no MDO at all, assume it is early in544// execution, and that any deopts are part of the545// startup transient, and don't need to be remembered.)546547// Also, if there is a local exception handler, treat all throws548// as hot if there has been at least one in this method.549if (C->trap_count(reason) != 0550&& method()->method_data()->trap_count(reason) != 0551&& has_ex_handler()) {552treat_throw_as_hot = true;553}554}555556// If this throw happens frequently, an uncommon trap might cause557// a performance pothole. If there is a local exception handler,558// and if this particular bytecode appears to be deoptimizing often,559// let us handle the throw inline, with a preconstructed instance.560// Note: If the deopt count has blown up, the uncommon trap561// runtime is going to flush this nmethod, not matter what.562if (treat_throw_as_hot563&& (!StackTraceInThrowable || OmitStackTraceInFastThrow)) {564// If the throw is local, we use a pre-existing instance and565// punt on the backtrace. This would lead to a missing backtrace566// (a repeat of 4292742) if the backtrace object is ever asked567// for its backtrace.568// Fixing this remaining case of 4292742 requires some flavor of569// escape analysis. Leave that for the future.570ciInstance* ex_obj = NULL;571switch (reason) {572case Deoptimization::Reason_null_check:573ex_obj = env()->NullPointerException_instance();574break;575case Deoptimization::Reason_div0_check:576ex_obj = env()->ArithmeticException_instance();577break;578case Deoptimization::Reason_range_check:579ex_obj = env()->ArrayIndexOutOfBoundsException_instance();580break;581case Deoptimization::Reason_class_check:582if (java_bc() == Bytecodes::_aastore) {583ex_obj = env()->ArrayStoreException_instance();584} else {585ex_obj = env()->ClassCastException_instance();586}587break;588default:589break;590}591if (failing()) { stop(); return; } // exception allocation might fail592if (ex_obj != NULL) {593if (env()->jvmti_can_post_on_exceptions()) {594// check if we must post exception events, take uncommon trap if so595uncommon_trap_if_should_post_on_exceptions(reason, must_throw);596// here if should_post_on_exceptions is false597// continue on with the normal codegen598}599600// Cheat with a preallocated exception object.601if (C->log() != NULL)602C->log()->elem("hot_throw preallocated='1' reason='%s'",603Deoptimization::trap_reason_name(reason));604const TypeInstPtr* ex_con = TypeInstPtr::make(ex_obj);605Node* ex_node = _gvn.transform(ConNode::make(ex_con));606607// Clear the detail message of the preallocated exception object.608// Weblogic sometimes mutates the detail message of exceptions609// using reflection.610int offset = java_lang_Throwable::get_detailMessage_offset();611const TypePtr* adr_typ = ex_con->add_offset(offset);612613Node *adr = basic_plus_adr(ex_node, ex_node, offset);614const TypeOopPtr* val_type = TypeOopPtr::make_from_klass(env()->String_klass());615Node *store = access_store_at(ex_node, adr, adr_typ, null(), val_type, T_OBJECT, IN_HEAP);616617if (!method()->has_exception_handlers()) {618// We don't need to preserve the stack if there's no handler as the entire frame is going to be popped anyway.619// This prevents issues with exception handling and late inlining.620set_sp(0);621clean_stack(0);622}623624add_exception_state(make_exception_state(ex_node));625return;626}627}628629// %%% Maybe add entry to OptoRuntime which directly throws the exc.?630// It won't be much cheaper than bailing to the interp., since we'll631// have to pass up all the debug-info, and the runtime will have to632// create the stack trace.633634// Usual case: Bail to interpreter.635// Reserve the right to recompile if we haven't seen anything yet.636637ciMethod* m = Deoptimization::reason_is_speculate(reason) ? C->method() : NULL;638Deoptimization::DeoptAction action = Deoptimization::Action_maybe_recompile;639if (treat_throw_as_hot640&& (method()->method_data()->trap_recompiled_at(bci(), m)641|| C->too_many_traps(reason))) {642// We cannot afford to take more traps here. Suffer in the interpreter.643if (C->log() != NULL)644C->log()->elem("hot_throw preallocated='0' reason='%s' mcount='%d'",645Deoptimization::trap_reason_name(reason),646C->trap_count(reason));647action = Deoptimization::Action_none;648}649650// "must_throw" prunes the JVM state to include only the stack, if there651// are no local exception handlers. This should cut down on register652// allocation time and code size, by drastically reducing the number653// of in-edges on the call to the uncommon trap.654655uncommon_trap(reason, action, (ciKlass*)NULL, (char*)NULL, must_throw);656}657658659//----------------------------PreserveJVMState---------------------------------660PreserveJVMState::PreserveJVMState(GraphKit* kit, bool clone_map) {661debug_only(kit->verify_map());662_kit = kit;663_map = kit->map(); // preserve the map664_sp = kit->sp();665kit->set_map(clone_map ? kit->clone_map() : NULL);666#ifdef ASSERT667_bci = kit->bci();668Parse* parser = kit->is_Parse();669int block = (parser == NULL || parser->block() == NULL) ? -1 : parser->block()->rpo();670_block = block;671#endif672}673PreserveJVMState::~PreserveJVMState() {674GraphKit* kit = _kit;675#ifdef ASSERT676assert(kit->bci() == _bci, "bci must not shift");677Parse* parser = kit->is_Parse();678int block = (parser == NULL || parser->block() == NULL) ? -1 : parser->block()->rpo();679assert(block == _block, "block must not shift");680#endif681kit->set_map(_map);682kit->set_sp(_sp);683}684685686//-----------------------------BuildCutout-------------------------------------687BuildCutout::BuildCutout(GraphKit* kit, Node* p, float prob, float cnt)688: PreserveJVMState(kit)689{690assert(p->is_Con() || p->is_Bool(), "test must be a bool");691SafePointNode* outer_map = _map; // preserved map is caller's692SafePointNode* inner_map = kit->map();693IfNode* iff = kit->create_and_map_if(outer_map->control(), p, prob, cnt);694outer_map->set_control(kit->gvn().transform( new IfTrueNode(iff) ));695inner_map->set_control(kit->gvn().transform( new IfFalseNode(iff) ));696}697BuildCutout::~BuildCutout() {698GraphKit* kit = _kit;699assert(kit->stopped(), "cutout code must stop, throw, return, etc.");700}701702//---------------------------PreserveReexecuteState----------------------------703PreserveReexecuteState::PreserveReexecuteState(GraphKit* kit) {704assert(!kit->stopped(), "must call stopped() before");705_kit = kit;706_sp = kit->sp();707_reexecute = kit->jvms()->_reexecute;708}709PreserveReexecuteState::~PreserveReexecuteState() {710if (_kit->stopped()) return;711_kit->jvms()->_reexecute = _reexecute;712_kit->set_sp(_sp);713}714715//------------------------------clone_map--------------------------------------716// Implementation of PreserveJVMState717//718// Only clone_map(...) here. If this function is only used in the719// PreserveJVMState class we may want to get rid of this extra720// function eventually and do it all there.721722SafePointNode* GraphKit::clone_map() {723if (map() == NULL) return NULL;724725// Clone the memory edge first726Node* mem = MergeMemNode::make(map()->memory());727gvn().set_type_bottom(mem);728729SafePointNode *clonemap = (SafePointNode*)map()->clone();730JVMState* jvms = this->jvms();731JVMState* clonejvms = jvms->clone_shallow(C);732clonemap->set_memory(mem);733clonemap->set_jvms(clonejvms);734clonejvms->set_map(clonemap);735record_for_igvn(clonemap);736gvn().set_type_bottom(clonemap);737return clonemap;738}739740741//-----------------------------set_map_clone-----------------------------------742void GraphKit::set_map_clone(SafePointNode* m) {743_map = m;744_map = clone_map();745_map->set_next_exception(NULL);746debug_only(verify_map());747}748749750//----------------------------kill_dead_locals---------------------------------751// Detect any locals which are known to be dead, and force them to top.752void GraphKit::kill_dead_locals() {753// Consult the liveness information for the locals. If any754// of them are unused, then they can be replaced by top(). This755// should help register allocation time and cut down on the size756// of the deoptimization information.757758// This call is made from many of the bytecode handling759// subroutines called from the Big Switch in do_one_bytecode.760// Every bytecode which might include a slow path is responsible761// for killing its dead locals. The more consistent we762// are about killing deads, the fewer useless phis will be763// constructed for them at various merge points.764765// bci can be -1 (InvocationEntryBci). We return the entry766// liveness for the method.767768if (method() == NULL || method()->code_size() == 0) {769// We are building a graph for a call to a native method.770// All locals are live.771return;772}773774ResourceMark rm;775776// Consult the liveness information for the locals. If any777// of them are unused, then they can be replaced by top(). This778// should help register allocation time and cut down on the size779// of the deoptimization information.780MethodLivenessResult live_locals = method()->liveness_at_bci(bci());781782int len = (int)live_locals.size();783assert(len <= jvms()->loc_size(), "too many live locals");784for (int local = 0; local < len; local++) {785if (!live_locals.at(local)) {786set_local(local, top());787}788}789}790791#ifdef ASSERT792//-------------------------dead_locals_are_killed------------------------------793// Return true if all dead locals are set to top in the map.794// Used to assert "clean" debug info at various points.795bool GraphKit::dead_locals_are_killed() {796if (method() == NULL || method()->code_size() == 0) {797// No locals need to be dead, so all is as it should be.798return true;799}800801// Make sure somebody called kill_dead_locals upstream.802ResourceMark rm;803for (JVMState* jvms = this->jvms(); jvms != NULL; jvms = jvms->caller()) {804if (jvms->loc_size() == 0) continue; // no locals to consult805SafePointNode* map = jvms->map();806ciMethod* method = jvms->method();807int bci = jvms->bci();808if (jvms == this->jvms()) {809bci = this->bci(); // it might not yet be synched810}811MethodLivenessResult live_locals = method->liveness_at_bci(bci);812int len = (int)live_locals.size();813if (!live_locals.is_valid() || len == 0)814// This method is trivial, or is poisoned by a breakpoint.815return true;816assert(len == jvms->loc_size(), "live map consistent with locals map");817for (int local = 0; local < len; local++) {818if (!live_locals.at(local) && map->local(jvms, local) != top()) {819if (PrintMiscellaneous && (Verbose || WizardMode)) {820tty->print_cr("Zombie local %d: ", local);821jvms->dump();822}823return false;824}825}826}827return true;828}829830#endif //ASSERT831832// Helper function for enforcing certain bytecodes to reexecute if deoptimization happens.833static bool should_reexecute_implied_by_bytecode(JVMState *jvms, bool is_anewarray) {834ciMethod* cur_method = jvms->method();835int cur_bci = jvms->bci();836if (cur_method != NULL && cur_bci != InvocationEntryBci) {837Bytecodes::Code code = cur_method->java_code_at_bci(cur_bci);838return Interpreter::bytecode_should_reexecute(code) ||839(is_anewarray && code == Bytecodes::_multianewarray);840// Reexecute _multianewarray bytecode which was replaced with841// sequence of [a]newarray. See Parse::do_multianewarray().842//843// Note: interpreter should not have it set since this optimization844// is limited by dimensions and guarded by flag so in some cases845// multianewarray() runtime calls will be generated and846// the bytecode should not be reexecutes (stack will not be reset).847} else {848return false;849}850}851852// Helper function for adding JVMState and debug information to node853void GraphKit::add_safepoint_edges(SafePointNode* call, bool must_throw) {854// Add the safepoint edges to the call (or other safepoint).855856// Make sure dead locals are set to top. This857// should help register allocation time and cut down on the size858// of the deoptimization information.859assert(dead_locals_are_killed(), "garbage in debug info before safepoint");860861// Walk the inline list to fill in the correct set of JVMState's862// Also fill in the associated edges for each JVMState.863864// If the bytecode needs to be reexecuted we need to put865// the arguments back on the stack.866const bool should_reexecute = jvms()->should_reexecute();867JVMState* youngest_jvms = should_reexecute ? sync_jvms_for_reexecute() : sync_jvms();868869// NOTE: set_bci (called from sync_jvms) might reset the reexecute bit to870// undefined if the bci is different. This is normal for Parse but it871// should not happen for LibraryCallKit because only one bci is processed.872assert(!is_LibraryCallKit() || (jvms()->should_reexecute() == should_reexecute),873"in LibraryCallKit the reexecute bit should not change");874875// If we are guaranteed to throw, we can prune everything but the876// input to the current bytecode.877bool can_prune_locals = false;878uint stack_slots_not_pruned = 0;879int inputs = 0, depth = 0;880if (must_throw) {881assert(method() == youngest_jvms->method(), "sanity");882if (compute_stack_effects(inputs, depth)) {883can_prune_locals = true;884stack_slots_not_pruned = inputs;885}886}887888if (env()->should_retain_local_variables()) {889// At any safepoint, this method can get breakpointed, which would890// then require an immediate deoptimization.891can_prune_locals = false; // do not prune locals892stack_slots_not_pruned = 0;893}894895// do not scribble on the input jvms896JVMState* out_jvms = youngest_jvms->clone_deep(C);897call->set_jvms(out_jvms); // Start jvms list for call node898899// For a known set of bytecodes, the interpreter should reexecute them if900// deoptimization happens. We set the reexecute state for them here901if (out_jvms->is_reexecute_undefined() && //don't change if already specified902should_reexecute_implied_by_bytecode(out_jvms, call->is_AllocateArray())) {903#ifdef ASSERT904int inputs = 0, not_used; // initialized by GraphKit::compute_stack_effects()905assert(method() == youngest_jvms->method(), "sanity");906assert(compute_stack_effects(inputs, not_used), "unknown bytecode: %s", Bytecodes::name(java_bc()));907assert(out_jvms->sp() >= (uint)inputs, "not enough operands for reexecution");908#endif // ASSERT909out_jvms->set_should_reexecute(true); //NOTE: youngest_jvms not changed910}911912// Presize the call:913DEBUG_ONLY(uint non_debug_edges = call->req());914call->add_req_batch(top(), youngest_jvms->debug_depth());915assert(call->req() == non_debug_edges + youngest_jvms->debug_depth(), "");916917// Set up edges so that the call looks like this:918// Call [state:] ctl io mem fptr retadr919// [parms:] parm0 ... parmN920// [root:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN921// [...mid:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN [...]922// [young:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN923// Note that caller debug info precedes callee debug info.924925// Fill pointer walks backwards from "young:" to "root:" in the diagram above:926uint debug_ptr = call->req();927928// Loop over the map input edges associated with jvms, add them929// to the call node, & reset all offsets to match call node array.930for (JVMState* in_jvms = youngest_jvms; in_jvms != NULL; ) {931uint debug_end = debug_ptr;932uint debug_start = debug_ptr - in_jvms->debug_size();933debug_ptr = debug_start; // back up the ptr934935uint p = debug_start; // walks forward in [debug_start, debug_end)936uint j, k, l;937SafePointNode* in_map = in_jvms->map();938out_jvms->set_map(call);939940if (can_prune_locals) {941assert(in_jvms->method() == out_jvms->method(), "sanity");942// If the current throw can reach an exception handler in this JVMS,943// then we must keep everything live that can reach that handler.944// As a quick and dirty approximation, we look for any handlers at all.945if (in_jvms->method()->has_exception_handlers()) {946can_prune_locals = false;947}948}949950// Add the Locals951k = in_jvms->locoff();952l = in_jvms->loc_size();953out_jvms->set_locoff(p);954if (!can_prune_locals) {955for (j = 0; j < l; j++)956call->set_req(p++, in_map->in(k+j));957} else {958p += l; // already set to top above by add_req_batch959}960961// Add the Expression Stack962k = in_jvms->stkoff();963l = in_jvms->sp();964out_jvms->set_stkoff(p);965if (!can_prune_locals) {966for (j = 0; j < l; j++)967call->set_req(p++, in_map->in(k+j));968} else if (can_prune_locals && stack_slots_not_pruned != 0) {969// Divide stack into {S0,...,S1}, where S0 is set to top.970uint s1 = stack_slots_not_pruned;971stack_slots_not_pruned = 0; // for next iteration972if (s1 > l) s1 = l;973uint s0 = l - s1;974p += s0; // skip the tops preinstalled by add_req_batch975for (j = s0; j < l; j++)976call->set_req(p++, in_map->in(k+j));977} else {978p += l; // already set to top above by add_req_batch979}980981// Add the Monitors982k = in_jvms->monoff();983l = in_jvms->mon_size();984out_jvms->set_monoff(p);985for (j = 0; j < l; j++)986call->set_req(p++, in_map->in(k+j));987988// Copy any scalar object fields.989k = in_jvms->scloff();990l = in_jvms->scl_size();991out_jvms->set_scloff(p);992for (j = 0; j < l; j++)993call->set_req(p++, in_map->in(k+j));994995// Finish the new jvms.996out_jvms->set_endoff(p);997998assert(out_jvms->endoff() == debug_end, "fill ptr must match");999assert(out_jvms->depth() == in_jvms->depth(), "depth must match");1000assert(out_jvms->loc_size() == in_jvms->loc_size(), "size must match");1001assert(out_jvms->mon_size() == in_jvms->mon_size(), "size must match");1002assert(out_jvms->scl_size() == in_jvms->scl_size(), "size must match");1003assert(out_jvms->debug_size() == in_jvms->debug_size(), "size must match");10041005// Update the two tail pointers in parallel.1006out_jvms = out_jvms->caller();1007in_jvms = in_jvms->caller();1008}10091010assert(debug_ptr == non_debug_edges, "debug info must fit exactly");10111012// Test the correctness of JVMState::debug_xxx accessors:1013assert(call->jvms()->debug_start() == non_debug_edges, "");1014assert(call->jvms()->debug_end() == call->req(), "");1015assert(call->jvms()->debug_depth() == call->req() - non_debug_edges, "");1016}10171018bool GraphKit::compute_stack_effects(int& inputs, int& depth) {1019Bytecodes::Code code = java_bc();1020if (code == Bytecodes::_wide) {1021code = method()->java_code_at_bci(bci() + 1);1022}10231024BasicType rtype = T_ILLEGAL;1025int rsize = 0;10261027if (code != Bytecodes::_illegal) {1028depth = Bytecodes::depth(code); // checkcast=0, athrow=-11029rtype = Bytecodes::result_type(code); // checkcast=P, athrow=V1030if (rtype < T_CONFLICT)1031rsize = type2size[rtype];1032}10331034switch (code) {1035case Bytecodes::_illegal:1036return false;10371038case Bytecodes::_ldc:1039case Bytecodes::_ldc_w:1040case Bytecodes::_ldc2_w:1041inputs = 0;1042break;10431044case Bytecodes::_dup: inputs = 1; break;1045case Bytecodes::_dup_x1: inputs = 2; break;1046case Bytecodes::_dup_x2: inputs = 3; break;1047case Bytecodes::_dup2: inputs = 2; break;1048case Bytecodes::_dup2_x1: inputs = 3; break;1049case Bytecodes::_dup2_x2: inputs = 4; break;1050case Bytecodes::_swap: inputs = 2; break;1051case Bytecodes::_arraylength: inputs = 1; break;10521053case Bytecodes::_getstatic:1054case Bytecodes::_putstatic:1055case Bytecodes::_getfield:1056case Bytecodes::_putfield:1057{1058bool ignored_will_link;1059ciField* field = method()->get_field_at_bci(bci(), ignored_will_link);1060int size = field->type()->size();1061bool is_get = (depth >= 0), is_static = (depth & 1);1062inputs = (is_static ? 0 : 1);1063if (is_get) {1064depth = size - inputs;1065} else {1066inputs += size; // putxxx pops the value from the stack1067depth = - inputs;1068}1069}1070break;10711072case Bytecodes::_invokevirtual:1073case Bytecodes::_invokespecial:1074case Bytecodes::_invokestatic:1075case Bytecodes::_invokedynamic:1076case Bytecodes::_invokeinterface:1077{1078bool ignored_will_link;1079ciSignature* declared_signature = NULL;1080ciMethod* ignored_callee = method()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);1081assert(declared_signature != NULL, "cannot be null");1082inputs = declared_signature->arg_size_for_bc(code);1083int size = declared_signature->return_type()->size();1084depth = size - inputs;1085}1086break;10871088case Bytecodes::_multianewarray:1089{1090ciBytecodeStream iter(method());1091iter.reset_to_bci(bci());1092iter.next();1093inputs = iter.get_dimensions();1094assert(rsize == 1, "");1095depth = rsize - inputs;1096}1097break;10981099case Bytecodes::_ireturn:1100case Bytecodes::_lreturn:1101case Bytecodes::_freturn:1102case Bytecodes::_dreturn:1103case Bytecodes::_areturn:1104assert(rsize == -depth, "");1105inputs = rsize;1106break;11071108case Bytecodes::_jsr:1109case Bytecodes::_jsr_w:1110inputs = 0;1111depth = 1; // S.B. depth=1, not zero1112break;11131114default:1115// bytecode produces a typed result1116inputs = rsize - depth;1117assert(inputs >= 0, "");1118break;1119}11201121#ifdef ASSERT1122// spot check1123int outputs = depth + inputs;1124assert(outputs >= 0, "sanity");1125switch (code) {1126case Bytecodes::_checkcast: assert(inputs == 1 && outputs == 1, ""); break;1127case Bytecodes::_athrow: assert(inputs == 1 && outputs == 0, ""); break;1128case Bytecodes::_aload_0: assert(inputs == 0 && outputs == 1, ""); break;1129case Bytecodes::_return: assert(inputs == 0 && outputs == 0, ""); break;1130case Bytecodes::_drem: assert(inputs == 4 && outputs == 2, ""); break;1131default: break;1132}1133#endif //ASSERT11341135return true;1136}1137113811391140//------------------------------basic_plus_adr---------------------------------1141Node* GraphKit::basic_plus_adr(Node* base, Node* ptr, Node* offset) {1142// short-circuit a common case1143if (offset == intcon(0)) return ptr;1144return _gvn.transform( new AddPNode(base, ptr, offset) );1145}11461147Node* GraphKit::ConvI2L(Node* offset) {1148// short-circuit a common case1149jint offset_con = find_int_con(offset, Type::OffsetBot);1150if (offset_con != Type::OffsetBot) {1151return longcon((jlong) offset_con);1152}1153return _gvn.transform( new ConvI2LNode(offset));1154}11551156Node* GraphKit::ConvI2UL(Node* offset) {1157juint offset_con = (juint) find_int_con(offset, Type::OffsetBot);1158if (offset_con != (juint) Type::OffsetBot) {1159return longcon((julong) offset_con);1160}1161Node* conv = _gvn.transform( new ConvI2LNode(offset));1162Node* mask = _gvn.transform(ConLNode::make((julong) max_juint));1163return _gvn.transform( new AndLNode(conv, mask) );1164}11651166Node* GraphKit::ConvL2I(Node* offset) {1167// short-circuit a common case1168jlong offset_con = find_long_con(offset, (jlong)Type::OffsetBot);1169if (offset_con != (jlong)Type::OffsetBot) {1170return intcon((int) offset_con);1171}1172return _gvn.transform( new ConvL2INode(offset));1173}11741175//-------------------------load_object_klass-----------------------------------1176Node* GraphKit::load_object_klass(Node* obj) {1177// Special-case a fresh allocation to avoid building nodes:1178Node* akls = AllocateNode::Ideal_klass(obj, &_gvn);1179if (akls != NULL) return akls;1180Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());1181return _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), k_adr, TypeInstPtr::KLASS));1182}11831184//-------------------------load_array_length-----------------------------------1185Node* GraphKit::load_array_length(Node* array) {1186// Special-case a fresh allocation to avoid building nodes:1187AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(array, &_gvn);1188Node *alen;1189if (alloc == NULL) {1190Node *r_adr = basic_plus_adr(array, arrayOopDesc::length_offset_in_bytes());1191alen = _gvn.transform( new LoadRangeNode(0, immutable_memory(), r_adr, TypeInt::POS));1192} else {1193alen = array_ideal_length(alloc, _gvn.type(array)->is_oopptr(), false);1194}1195return alen;1196}11971198Node* GraphKit::array_ideal_length(AllocateArrayNode* alloc,1199const TypeOopPtr* oop_type,1200bool replace_length_in_map) {1201Node* length = alloc->Ideal_length();1202if (replace_length_in_map == false || map()->find_edge(length) >= 0) {1203Node* ccast = alloc->make_ideal_length(oop_type, &_gvn);1204if (ccast != length) {1205// do not transfrom ccast here, it might convert to top node for1206// negative array length and break assumptions in parsing stage.1207_gvn.set_type_bottom(ccast);1208record_for_igvn(ccast);1209if (replace_length_in_map) {1210replace_in_map(length, ccast);1211}1212return ccast;1213}1214}1215return length;1216}12171218//------------------------------do_null_check----------------------------------1219// Helper function to do a NULL pointer check. Returned value is1220// the incoming address with NULL casted away. You are allowed to use the1221// not-null value only if you are control dependent on the test.1222#ifndef PRODUCT1223extern int explicit_null_checks_inserted,1224explicit_null_checks_elided;1225#endif1226Node* GraphKit::null_check_common(Node* value, BasicType type,1227// optional arguments for variations:1228bool assert_null,1229Node* *null_control,1230bool speculative) {1231assert(!assert_null || null_control == NULL, "not both at once");1232if (stopped()) return top();1233NOT_PRODUCT(explicit_null_checks_inserted++);12341235// Construct NULL check1236Node *chk = NULL;1237switch(type) {1238case T_LONG : chk = new CmpLNode(value, _gvn.zerocon(T_LONG)); break;1239case T_INT : chk = new CmpINode(value, _gvn.intcon(0)); break;1240case T_ARRAY : // fall through1241type = T_OBJECT; // simplify further tests1242case T_OBJECT : {1243const Type *t = _gvn.type( value );12441245const TypeOopPtr* tp = t->isa_oopptr();1246if (tp != NULL && tp->klass() != NULL && !tp->klass()->is_loaded()1247// Only for do_null_check, not any of its siblings:1248&& !assert_null && null_control == NULL) {1249// Usually, any field access or invocation on an unloaded oop type1250// will simply fail to link, since the statically linked class is1251// likely also to be unloaded. However, in -Xcomp mode, sometimes1252// the static class is loaded but the sharper oop type is not.1253// Rather than checking for this obscure case in lots of places,1254// we simply observe that a null check on an unloaded class1255// will always be followed by a nonsense operation, so we1256// can just issue the uncommon trap here.1257// Our access to the unloaded class will only be correct1258// after it has been loaded and initialized, which requires1259// a trip through the interpreter.1260#ifndef PRODUCT1261if (WizardMode) { tty->print("Null check of unloaded "); tp->klass()->print(); tty->cr(); }1262#endif1263uncommon_trap(Deoptimization::Reason_unloaded,1264Deoptimization::Action_reinterpret,1265tp->klass(), "!loaded");1266return top();1267}12681269if (assert_null) {1270// See if the type is contained in NULL_PTR.1271// If so, then the value is already null.1272if (t->higher_equal(TypePtr::NULL_PTR)) {1273NOT_PRODUCT(explicit_null_checks_elided++);1274return value; // Elided null assert quickly!1275}1276} else {1277// See if mixing in the NULL pointer changes type.1278// If so, then the NULL pointer was not allowed in the original1279// type. In other words, "value" was not-null.1280if (t->meet(TypePtr::NULL_PTR) != t->remove_speculative()) {1281// same as: if (!TypePtr::NULL_PTR->higher_equal(t)) ...1282NOT_PRODUCT(explicit_null_checks_elided++);1283return value; // Elided null check quickly!1284}1285}1286chk = new CmpPNode( value, null() );1287break;1288}12891290default:1291fatal("unexpected type: %s", type2name(type));1292}1293assert(chk != NULL, "sanity check");1294chk = _gvn.transform(chk);12951296BoolTest::mask btest = assert_null ? BoolTest::eq : BoolTest::ne;1297BoolNode *btst = new BoolNode( chk, btest);1298Node *tst = _gvn.transform( btst );12991300//-----------1301// if peephole optimizations occurred, a prior test existed.1302// If a prior test existed, maybe it dominates as we can avoid this test.1303if (tst != btst && type == T_OBJECT) {1304// At this point we want to scan up the CFG to see if we can1305// find an identical test (and so avoid this test altogether).1306Node *cfg = control();1307int depth = 0;1308while( depth < 16 ) { // Limit search depth for speed1309if( cfg->Opcode() == Op_IfTrue &&1310cfg->in(0)->in(1) == tst ) {1311// Found prior test. Use "cast_not_null" to construct an identical1312// CastPP (and hence hash to) as already exists for the prior test.1313// Return that casted value.1314if (assert_null) {1315replace_in_map(value, null());1316return null(); // do not issue the redundant test1317}1318Node *oldcontrol = control();1319set_control(cfg);1320Node *res = cast_not_null(value);1321set_control(oldcontrol);1322NOT_PRODUCT(explicit_null_checks_elided++);1323return res;1324}1325cfg = IfNode::up_one_dom(cfg, /*linear_only=*/ true);1326if (cfg == NULL) break; // Quit at region nodes1327depth++;1328}1329}13301331//-----------1332// Branch to failure if null1333float ok_prob = PROB_MAX; // a priori estimate: nulls never happen1334Deoptimization::DeoptReason reason;1335if (assert_null) {1336reason = Deoptimization::reason_null_assert(speculative);1337} else if (type == T_OBJECT) {1338reason = Deoptimization::reason_null_check(speculative);1339} else {1340reason = Deoptimization::Reason_div0_check;1341}1342// %%% Since Reason_unhandled is not recorded on a per-bytecode basis,1343// ciMethodData::has_trap_at will return a conservative -1 if any1344// must-be-null assertion has failed. This could cause performance1345// problems for a method after its first do_null_assert failure.1346// Consider using 'Reason_class_check' instead?13471348// To cause an implicit null check, we set the not-null probability1349// to the maximum (PROB_MAX). For an explicit check the probability1350// is set to a smaller value.1351if (null_control != NULL || too_many_traps(reason)) {1352// probability is less likely1353ok_prob = PROB_LIKELY_MAG(3);1354} else if (!assert_null &&1355(ImplicitNullCheckThreshold > 0) &&1356method() != NULL &&1357(method()->method_data()->trap_count(reason)1358>= (uint)ImplicitNullCheckThreshold)) {1359ok_prob = PROB_LIKELY_MAG(3);1360}13611362if (null_control != NULL) {1363IfNode* iff = create_and_map_if(control(), tst, ok_prob, COUNT_UNKNOWN);1364Node* null_true = _gvn.transform( new IfFalseNode(iff));1365set_control( _gvn.transform( new IfTrueNode(iff)));1366#ifndef PRODUCT1367if (null_true == top()) {1368explicit_null_checks_elided++;1369}1370#endif1371(*null_control) = null_true;1372} else {1373BuildCutout unless(this, tst, ok_prob);1374// Check for optimizer eliding test at parse time1375if (stopped()) {1376// Failure not possible; do not bother making uncommon trap.1377NOT_PRODUCT(explicit_null_checks_elided++);1378} else if (assert_null) {1379uncommon_trap(reason,1380Deoptimization::Action_make_not_entrant,1381NULL, "assert_null");1382} else {1383replace_in_map(value, zerocon(type));1384builtin_throw(reason);1385}1386}13871388// Must throw exception, fall-thru not possible?1389if (stopped()) {1390return top(); // No result1391}13921393if (assert_null) {1394// Cast obj to null on this path.1395replace_in_map(value, zerocon(type));1396return zerocon(type);1397}13981399// Cast obj to not-null on this path, if there is no null_control.1400// (If there is a null_control, a non-null value may come back to haunt us.)1401if (type == T_OBJECT) {1402Node* cast = cast_not_null(value, false);1403if (null_control == NULL || (*null_control) == top())1404replace_in_map(value, cast);1405value = cast;1406}14071408return value;1409}141014111412//------------------------------cast_not_null----------------------------------1413// Cast obj to not-null on this path1414Node* GraphKit::cast_not_null(Node* obj, bool do_replace_in_map) {1415const Type *t = _gvn.type(obj);1416const Type *t_not_null = t->join_speculative(TypePtr::NOTNULL);1417// Object is already not-null?1418if( t == t_not_null ) return obj;14191420Node *cast = new CastPPNode(obj,t_not_null);1421cast->init_req(0, control());1422cast = _gvn.transform( cast );14231424// Scan for instances of 'obj' in the current JVM mapping.1425// These instances are known to be not-null after the test.1426if (do_replace_in_map)1427replace_in_map(obj, cast);14281429return cast; // Return casted value1430}14311432// Sometimes in intrinsics, we implicitly know an object is not null1433// (there's no actual null check) so we can cast it to not null. In1434// the course of optimizations, the input to the cast can become null.1435// In that case that data path will die and we need the control path1436// to become dead as well to keep the graph consistent. So we have to1437// add a check for null for which one branch can't be taken. It uses1438// an Opaque4 node that will cause the check to be removed after loop1439// opts so the test goes away and the compiled code doesn't execute a1440// useless check.1441Node* GraphKit::must_be_not_null(Node* value, bool do_replace_in_map) {1442if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(value))) {1443return value;1444}1445Node* chk = _gvn.transform(new CmpPNode(value, null()));1446Node *tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));1447Node* opaq = _gvn.transform(new Opaque4Node(C, tst, intcon(1)));1448IfNode *iff = new IfNode(control(), opaq, PROB_MAX, COUNT_UNKNOWN);1449_gvn.set_type(iff, iff->Value(&_gvn));1450Node *if_f = _gvn.transform(new IfFalseNode(iff));1451Node *frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));1452Node* halt = _gvn.transform(new HaltNode(if_f, frame, "unexpected null in intrinsic"));1453C->root()->add_req(halt);1454Node *if_t = _gvn.transform(new IfTrueNode(iff));1455set_control(if_t);1456return cast_not_null(value, do_replace_in_map);1457}145814591460//--------------------------replace_in_map-------------------------------------1461void GraphKit::replace_in_map(Node* old, Node* neww) {1462if (old == neww) {1463return;1464}14651466map()->replace_edge(old, neww);14671468// Note: This operation potentially replaces any edge1469// on the map. This includes locals, stack, and monitors1470// of the current (innermost) JVM state.14711472// don't let inconsistent types from profiling escape this1473// method14741475const Type* told = _gvn.type(old);1476const Type* tnew = _gvn.type(neww);14771478if (!tnew->higher_equal(told)) {1479return;1480}14811482map()->record_replaced_node(old, neww);1483}148414851486//=============================================================================1487//--------------------------------memory---------------------------------------1488Node* GraphKit::memory(uint alias_idx) {1489MergeMemNode* mem = merged_memory();1490Node* p = mem->memory_at(alias_idx);1491assert(p != mem->empty_memory(), "empty");1492_gvn.set_type(p, Type::MEMORY); // must be mapped1493return p;1494}14951496//-----------------------------reset_memory------------------------------------1497Node* GraphKit::reset_memory() {1498Node* mem = map()->memory();1499// do not use this node for any more parsing!1500debug_only( map()->set_memory((Node*)NULL) );1501return _gvn.transform( mem );1502}15031504//------------------------------set_all_memory---------------------------------1505void GraphKit::set_all_memory(Node* newmem) {1506Node* mergemem = MergeMemNode::make(newmem);1507gvn().set_type_bottom(mergemem);1508map()->set_memory(mergemem);1509}15101511//------------------------------set_all_memory_call----------------------------1512void GraphKit::set_all_memory_call(Node* call, bool separate_io_proj) {1513Node* newmem = _gvn.transform( new ProjNode(call, TypeFunc::Memory, separate_io_proj) );1514set_all_memory(newmem);1515}15161517//=============================================================================1518//1519// parser factory methods for MemNodes1520//1521// These are layered on top of the factory methods in LoadNode and StoreNode,1522// and integrate with the parser's memory state and _gvn engine.1523//15241525// factory methods in "int adr_idx"1526Node* GraphKit::make_load(Node* ctl, Node* adr, const Type* t, BasicType bt,1527int adr_idx,1528MemNode::MemOrd mo,1529LoadNode::ControlDependency control_dependency,1530bool require_atomic_access,1531bool unaligned,1532bool mismatched,1533bool unsafe,1534uint8_t barrier_data) {1535assert(adr_idx != Compile::AliasIdxTop, "use other make_load factory" );1536const TypePtr* adr_type = NULL; // debug-mode-only argument1537debug_only(adr_type = C->get_adr_type(adr_idx));1538Node* mem = memory(adr_idx);1539Node* ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo, control_dependency, require_atomic_access, unaligned, mismatched, unsafe, barrier_data);1540ld = _gvn.transform(ld);1541if (((bt == T_OBJECT) && C->do_escape_analysis()) || C->eliminate_boxing()) {1542// Improve graph before escape analysis and boxing elimination.1543record_for_igvn(ld);1544}1545return ld;1546}15471548Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt,1549int adr_idx,1550MemNode::MemOrd mo,1551bool require_atomic_access,1552bool unaligned,1553bool mismatched,1554bool unsafe) {1555assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );1556const TypePtr* adr_type = NULL;1557debug_only(adr_type = C->get_adr_type(adr_idx));1558Node *mem = memory(adr_idx);1559Node* st = StoreNode::make(_gvn, ctl, mem, adr, adr_type, val, bt, mo, require_atomic_access);1560if (unaligned) {1561st->as_Store()->set_unaligned_access();1562}1563if (mismatched) {1564st->as_Store()->set_mismatched_access();1565}1566if (unsafe) {1567st->as_Store()->set_unsafe_access();1568}1569st = _gvn.transform(st);1570set_memory(st, adr_idx);1571// Back-to-back stores can only remove intermediate store with DU info1572// so push on worklist for optimizer.1573if (mem->req() > MemNode::Address && adr == mem->in(MemNode::Address))1574record_for_igvn(st);15751576return st;1577}15781579Node* GraphKit::access_store_at(Node* obj,1580Node* adr,1581const TypePtr* adr_type,1582Node* val,1583const Type* val_type,1584BasicType bt,1585DecoratorSet decorators) {1586// Transformation of a value which could be NULL pointer (CastPP #NULL)1587// could be delayed during Parse (for example, in adjust_map_after_if()).1588// Execute transformation here to avoid barrier generation in such case.1589if (_gvn.type(val) == TypePtr::NULL_PTR) {1590val = _gvn.makecon(TypePtr::NULL_PTR);1591}15921593if (stopped()) {1594return top(); // Dead path ?1595}15961597assert(val != NULL, "not dead path");15981599C2AccessValuePtr addr(adr, adr_type);1600C2AccessValue value(val, val_type);1601C2ParseAccess access(this, decorators | C2_WRITE_ACCESS, bt, obj, addr);1602if (access.is_raw()) {1603return _barrier_set->BarrierSetC2::store_at(access, value);1604} else {1605return _barrier_set->store_at(access, value);1606}1607}16081609Node* GraphKit::access_load_at(Node* obj, // containing obj1610Node* adr, // actual adress to store val at1611const TypePtr* adr_type,1612const Type* val_type,1613BasicType bt,1614DecoratorSet decorators) {1615if (stopped()) {1616return top(); // Dead path ?1617}16181619C2AccessValuePtr addr(adr, adr_type);1620C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, obj, addr);1621if (access.is_raw()) {1622return _barrier_set->BarrierSetC2::load_at(access, val_type);1623} else {1624return _barrier_set->load_at(access, val_type);1625}1626}16271628Node* GraphKit::access_load(Node* adr, // actual adress to load val at1629const Type* val_type,1630BasicType bt,1631DecoratorSet decorators) {1632if (stopped()) {1633return top(); // Dead path ?1634}16351636C2AccessValuePtr addr(adr, adr->bottom_type()->is_ptr());1637C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, NULL, addr);1638if (access.is_raw()) {1639return _barrier_set->BarrierSetC2::load_at(access, val_type);1640} else {1641return _barrier_set->load_at(access, val_type);1642}1643}16441645Node* GraphKit::access_atomic_cmpxchg_val_at(Node* obj,1646Node* adr,1647const TypePtr* adr_type,1648int alias_idx,1649Node* expected_val,1650Node* new_val,1651const Type* value_type,1652BasicType bt,1653DecoratorSet decorators) {1654C2AccessValuePtr addr(adr, adr_type);1655C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS,1656bt, obj, addr, alias_idx);1657if (access.is_raw()) {1658return _barrier_set->BarrierSetC2::atomic_cmpxchg_val_at(access, expected_val, new_val, value_type);1659} else {1660return _barrier_set->atomic_cmpxchg_val_at(access, expected_val, new_val, value_type);1661}1662}16631664Node* GraphKit::access_atomic_cmpxchg_bool_at(Node* obj,1665Node* adr,1666const TypePtr* adr_type,1667int alias_idx,1668Node* expected_val,1669Node* new_val,1670const Type* value_type,1671BasicType bt,1672DecoratorSet decorators) {1673C2AccessValuePtr addr(adr, adr_type);1674C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS,1675bt, obj, addr, alias_idx);1676if (access.is_raw()) {1677return _barrier_set->BarrierSetC2::atomic_cmpxchg_bool_at(access, expected_val, new_val, value_type);1678} else {1679return _barrier_set->atomic_cmpxchg_bool_at(access, expected_val, new_val, value_type);1680}1681}16821683Node* GraphKit::access_atomic_xchg_at(Node* obj,1684Node* adr,1685const TypePtr* adr_type,1686int alias_idx,1687Node* new_val,1688const Type* value_type,1689BasicType bt,1690DecoratorSet decorators) {1691C2AccessValuePtr addr(adr, adr_type);1692C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS,1693bt, obj, addr, alias_idx);1694if (access.is_raw()) {1695return _barrier_set->BarrierSetC2::atomic_xchg_at(access, new_val, value_type);1696} else {1697return _barrier_set->atomic_xchg_at(access, new_val, value_type);1698}1699}17001701Node* GraphKit::access_atomic_add_at(Node* obj,1702Node* adr,1703const TypePtr* adr_type,1704int alias_idx,1705Node* new_val,1706const Type* value_type,1707BasicType bt,1708DecoratorSet decorators) {1709C2AccessValuePtr addr(adr, adr_type);1710C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS, bt, obj, addr, alias_idx);1711if (access.is_raw()) {1712return _barrier_set->BarrierSetC2::atomic_add_at(access, new_val, value_type);1713} else {1714return _barrier_set->atomic_add_at(access, new_val, value_type);1715}1716}17171718void GraphKit::access_clone(Node* src, Node* dst, Node* size, bool is_array) {1719return _barrier_set->clone(this, src, dst, size, is_array);1720}17211722//-------------------------array_element_address-------------------------1723Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt,1724const TypeInt* sizetype, Node* ctrl) {1725uint shift = exact_log2(type2aelembytes(elembt));1726uint header = arrayOopDesc::base_offset_in_bytes(elembt);17271728// short-circuit a common case (saves lots of confusing waste motion)1729jint idx_con = find_int_con(idx, -1);1730if (idx_con >= 0) {1731intptr_t offset = header + ((intptr_t)idx_con << shift);1732return basic_plus_adr(ary, offset);1733}17341735// must be correct type for alignment purposes1736Node* base = basic_plus_adr(ary, header);1737idx = Compile::conv_I2X_index(&_gvn, idx, sizetype, ctrl);1738Node* scale = _gvn.transform( new LShiftXNode(idx, intcon(shift)) );1739return basic_plus_adr(ary, base, scale);1740}17411742//-------------------------load_array_element-------------------------1743Node* GraphKit::load_array_element(Node* ary, Node* idx, const TypeAryPtr* arytype, bool set_ctrl) {1744const Type* elemtype = arytype->elem();1745BasicType elembt = elemtype->array_element_basic_type();1746Node* adr = array_element_address(ary, idx, elembt, arytype->size());1747if (elembt == T_NARROWOOP) {1748elembt = T_OBJECT; // To satisfy switch in LoadNode::make()1749}1750Node* ld = access_load_at(ary, adr, arytype, elemtype, elembt,1751IN_HEAP | IS_ARRAY | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0));1752return ld;1753}17541755//-------------------------set_arguments_for_java_call-------------------------1756// Arguments (pre-popped from the stack) are taken from the JVMS.1757void GraphKit::set_arguments_for_java_call(CallJavaNode* call) {1758// Add the call arguments:1759uint nargs = call->method()->arg_size();1760for (uint i = 0; i < nargs; i++) {1761Node* arg = argument(i);1762call->init_req(i + TypeFunc::Parms, arg);1763}1764}17651766//---------------------------set_edges_for_java_call---------------------------1767// Connect a newly created call into the current JVMS.1768// A return value node (if any) is returned from set_edges_for_java_call.1769void GraphKit::set_edges_for_java_call(CallJavaNode* call, bool must_throw, bool separate_io_proj) {17701771// Add the predefined inputs:1772call->init_req( TypeFunc::Control, control() );1773call->init_req( TypeFunc::I_O , i_o() );1774call->init_req( TypeFunc::Memory , reset_memory() );1775call->init_req( TypeFunc::FramePtr, frameptr() );1776call->init_req( TypeFunc::ReturnAdr, top() );17771778add_safepoint_edges(call, must_throw);17791780Node* xcall = _gvn.transform(call);17811782if (xcall == top()) {1783set_control(top());1784return;1785}1786assert(xcall == call, "call identity is stable");17871788// Re-use the current map to produce the result.17891790set_control(_gvn.transform(new ProjNode(call, TypeFunc::Control)));1791set_i_o( _gvn.transform(new ProjNode(call, TypeFunc::I_O , separate_io_proj)));1792set_all_memory_call(xcall, separate_io_proj);17931794//return xcall; // no need, caller already has it1795}17961797Node* GraphKit::set_results_for_java_call(CallJavaNode* call, bool separate_io_proj, bool deoptimize) {1798if (stopped()) return top(); // maybe the call folded up?17991800// Capture the return value, if any.1801Node* ret;1802if (call->method() == NULL ||1803call->method()->return_type()->basic_type() == T_VOID)1804ret = top();1805else ret = _gvn.transform(new ProjNode(call, TypeFunc::Parms));18061807// Note: Since any out-of-line call can produce an exception,1808// we always insert an I_O projection from the call into the result.18091810make_slow_call_ex(call, env()->Throwable_klass(), separate_io_proj, deoptimize);18111812if (separate_io_proj) {1813// The caller requested separate projections be used by the fall1814// through and exceptional paths, so replace the projections for1815// the fall through path.1816set_i_o(_gvn.transform( new ProjNode(call, TypeFunc::I_O) ));1817set_all_memory(_gvn.transform( new ProjNode(call, TypeFunc::Memory) ));1818}1819return ret;1820}18211822//--------------------set_predefined_input_for_runtime_call--------------------1823// Reading and setting the memory state is way conservative here.1824// The real problem is that I am not doing real Type analysis on memory,1825// so I cannot distinguish card mark stores from other stores. Across a GC1826// point the Store Barrier and the card mark memory has to agree. I cannot1827// have a card mark store and its barrier split across the GC point from1828// either above or below. Here I get that to happen by reading ALL of memory.1829// A better answer would be to separate out card marks from other memory.1830// For now, return the input memory state, so that it can be reused1831// after the call, if this call has restricted memory effects.1832Node* GraphKit::set_predefined_input_for_runtime_call(SafePointNode* call, Node* narrow_mem) {1833// Set fixed predefined input arguments1834Node* memory = reset_memory();1835Node* m = narrow_mem == NULL ? memory : narrow_mem;1836call->init_req( TypeFunc::Control, control() );1837call->init_req( TypeFunc::I_O, top() ); // does no i/o1838call->init_req( TypeFunc::Memory, m ); // may gc ptrs1839call->init_req( TypeFunc::FramePtr, frameptr() );1840call->init_req( TypeFunc::ReturnAdr, top() );1841return memory;1842}18431844//-------------------set_predefined_output_for_runtime_call--------------------1845// Set control and memory (not i_o) from the call.1846// If keep_mem is not NULL, use it for the output state,1847// except for the RawPtr output of the call, if hook_mem is TypeRawPtr::BOTTOM.1848// If hook_mem is NULL, this call produces no memory effects at all.1849// If hook_mem is a Java-visible memory slice (such as arraycopy operands),1850// then only that memory slice is taken from the call.1851// In the last case, we must put an appropriate memory barrier before1852// the call, so as to create the correct anti-dependencies on loads1853// preceding the call.1854void GraphKit::set_predefined_output_for_runtime_call(Node* call,1855Node* keep_mem,1856const TypePtr* hook_mem) {1857// no i/o1858set_control(_gvn.transform( new ProjNode(call,TypeFunc::Control) ));1859if (keep_mem) {1860// First clone the existing memory state1861set_all_memory(keep_mem);1862if (hook_mem != NULL) {1863// Make memory for the call1864Node* mem = _gvn.transform( new ProjNode(call, TypeFunc::Memory) );1865// Set the RawPtr memory state only. This covers all the heap top/GC stuff1866// We also use hook_mem to extract specific effects from arraycopy stubs.1867set_memory(mem, hook_mem);1868}1869// ...else the call has NO memory effects.18701871// Make sure the call advertises its memory effects precisely.1872// This lets us build accurate anti-dependences in gcm.cpp.1873assert(C->alias_type(call->adr_type()) == C->alias_type(hook_mem),1874"call node must be constructed correctly");1875} else {1876assert(hook_mem == NULL, "");1877// This is not a "slow path" call; all memory comes from the call.1878set_all_memory_call(call);1879}1880}18811882// Keep track of MergeMems feeding into other MergeMems1883static void add_mergemem_users_to_worklist(Unique_Node_List& wl, Node* mem) {1884if (!mem->is_MergeMem()) {1885return;1886}1887for (SimpleDUIterator i(mem); i.has_next(); i.next()) {1888Node* use = i.get();1889if (use->is_MergeMem()) {1890wl.push(use);1891}1892}1893}18941895// Replace the call with the current state of the kit.1896void GraphKit::replace_call(CallNode* call, Node* result, bool do_replaced_nodes) {1897JVMState* ejvms = NULL;1898if (has_exceptions()) {1899ejvms = transfer_exceptions_into_jvms();1900}19011902ReplacedNodes replaced_nodes = map()->replaced_nodes();1903ReplacedNodes replaced_nodes_exception;1904Node* ex_ctl = top();19051906SafePointNode* final_state = stop();19071908// Find all the needed outputs of this call1909CallProjections callprojs;1910call->extract_projections(&callprojs, true);19111912Unique_Node_List wl;1913Node* init_mem = call->in(TypeFunc::Memory);1914Node* final_mem = final_state->in(TypeFunc::Memory);1915Node* final_ctl = final_state->in(TypeFunc::Control);1916Node* final_io = final_state->in(TypeFunc::I_O);19171918// Replace all the old call edges with the edges from the inlining result1919if (callprojs.fallthrough_catchproj != NULL) {1920C->gvn_replace_by(callprojs.fallthrough_catchproj, final_ctl);1921}1922if (callprojs.fallthrough_memproj != NULL) {1923if (final_mem->is_MergeMem()) {1924// Parser's exits MergeMem was not transformed but may be optimized1925final_mem = _gvn.transform(final_mem);1926}1927C->gvn_replace_by(callprojs.fallthrough_memproj, final_mem);1928add_mergemem_users_to_worklist(wl, final_mem);1929}1930if (callprojs.fallthrough_ioproj != NULL) {1931C->gvn_replace_by(callprojs.fallthrough_ioproj, final_io);1932}19331934// Replace the result with the new result if it exists and is used1935if (callprojs.resproj != NULL && result != NULL) {1936C->gvn_replace_by(callprojs.resproj, result);1937}19381939if (ejvms == NULL) {1940// No exception edges to simply kill off those paths1941if (callprojs.catchall_catchproj != NULL) {1942C->gvn_replace_by(callprojs.catchall_catchproj, C->top());1943}1944if (callprojs.catchall_memproj != NULL) {1945C->gvn_replace_by(callprojs.catchall_memproj, C->top());1946}1947if (callprojs.catchall_ioproj != NULL) {1948C->gvn_replace_by(callprojs.catchall_ioproj, C->top());1949}1950// Replace the old exception object with top1951if (callprojs.exobj != NULL) {1952C->gvn_replace_by(callprojs.exobj, C->top());1953}1954} else {1955GraphKit ekit(ejvms);19561957// Load my combined exception state into the kit, with all phis transformed:1958SafePointNode* ex_map = ekit.combine_and_pop_all_exception_states();1959replaced_nodes_exception = ex_map->replaced_nodes();19601961Node* ex_oop = ekit.use_exception_state(ex_map);19621963if (callprojs.catchall_catchproj != NULL) {1964C->gvn_replace_by(callprojs.catchall_catchproj, ekit.control());1965ex_ctl = ekit.control();1966}1967if (callprojs.catchall_memproj != NULL) {1968Node* ex_mem = ekit.reset_memory();1969C->gvn_replace_by(callprojs.catchall_memproj, ex_mem);1970add_mergemem_users_to_worklist(wl, ex_mem);1971}1972if (callprojs.catchall_ioproj != NULL) {1973C->gvn_replace_by(callprojs.catchall_ioproj, ekit.i_o());1974}19751976// Replace the old exception object with the newly created one1977if (callprojs.exobj != NULL) {1978C->gvn_replace_by(callprojs.exobj, ex_oop);1979}1980}19811982// Disconnect the call from the graph1983call->disconnect_inputs(C);1984C->gvn_replace_by(call, C->top());19851986// Clean up any MergeMems that feed other MergeMems since the1987// optimizer doesn't like that.1988while (wl.size() > 0) {1989_gvn.transform(wl.pop());1990}19911992if (callprojs.fallthrough_catchproj != NULL && !final_ctl->is_top() && do_replaced_nodes) {1993replaced_nodes.apply(C, final_ctl);1994}1995if (!ex_ctl->is_top() && do_replaced_nodes) {1996replaced_nodes_exception.apply(C, ex_ctl);1997}1998}199920002001//------------------------------increment_counter------------------------------2002// for statistics: increment a VM counter by 120032004void GraphKit::increment_counter(address counter_addr) {2005Node* adr1 = makecon(TypeRawPtr::make(counter_addr));2006increment_counter(adr1);2007}20082009void GraphKit::increment_counter(Node* counter_addr) {2010int adr_type = Compile::AliasIdxRaw;2011Node* ctrl = control();2012Node* cnt = make_load(ctrl, counter_addr, TypeLong::LONG, T_LONG, adr_type, MemNode::unordered);2013Node* incr = _gvn.transform(new AddLNode(cnt, _gvn.longcon(1)));2014store_to_memory(ctrl, counter_addr, incr, T_LONG, adr_type, MemNode::unordered);2015}201620172018//------------------------------uncommon_trap----------------------------------2019// Bail out to the interpreter in mid-method. Implemented by calling the2020// uncommon_trap blob. This helper function inserts a runtime call with the2021// right debug info.2022void GraphKit::uncommon_trap(int trap_request,2023ciKlass* klass, const char* comment,2024bool must_throw,2025bool keep_exact_action) {2026if (failing()) stop();2027if (stopped()) return; // trap reachable?20282029// Note: If ProfileTraps is true, and if a deopt. actually2030// occurs here, the runtime will make sure an MDO exists. There is2031// no need to call method()->ensure_method_data() at this point.20322033// Set the stack pointer to the right value for reexecution:2034set_sp(reexecute_sp());20352036#ifdef ASSERT2037if (!must_throw) {2038// Make sure the stack has at least enough depth to execute2039// the current bytecode.2040int inputs, ignored_depth;2041if (compute_stack_effects(inputs, ignored_depth)) {2042assert(sp() >= inputs, "must have enough JVMS stack to execute %s: sp=%d, inputs=%d",2043Bytecodes::name(java_bc()), sp(), inputs);2044}2045}2046#endif20472048Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request);2049Deoptimization::DeoptAction action = Deoptimization::trap_request_action(trap_request);20502051switch (action) {2052case Deoptimization::Action_maybe_recompile:2053case Deoptimization::Action_reinterpret:2054// Temporary fix for 6529811 to allow virtual calls to be sure they2055// get the chance to go from mono->bi->mega2056if (!keep_exact_action &&2057Deoptimization::trap_request_index(trap_request) < 0 &&2058too_many_recompiles(reason)) {2059// This BCI is causing too many recompilations.2060if (C->log() != NULL) {2061C->log()->elem("observe that='trap_action_change' reason='%s' from='%s' to='none'",2062Deoptimization::trap_reason_name(reason),2063Deoptimization::trap_action_name(action));2064}2065action = Deoptimization::Action_none;2066trap_request = Deoptimization::make_trap_request(reason, action);2067} else {2068C->set_trap_can_recompile(true);2069}2070break;2071case Deoptimization::Action_make_not_entrant:2072C->set_trap_can_recompile(true);2073break;2074case Deoptimization::Action_none:2075case Deoptimization::Action_make_not_compilable:2076break;2077default:2078#ifdef ASSERT2079fatal("unknown action %d: %s", action, Deoptimization::trap_action_name(action));2080#endif2081break;2082}20832084if (TraceOptoParse) {2085char buf[100];2086tty->print_cr("Uncommon trap %s at bci:%d",2087Deoptimization::format_trap_request(buf, sizeof(buf),2088trap_request), bci());2089}20902091CompileLog* log = C->log();2092if (log != NULL) {2093int kid = (klass == NULL)? -1: log->identify(klass);2094log->begin_elem("uncommon_trap bci='%d'", bci());2095char buf[100];2096log->print(" %s", Deoptimization::format_trap_request(buf, sizeof(buf),2097trap_request));2098if (kid >= 0) log->print(" klass='%d'", kid);2099if (comment != NULL) log->print(" comment='%s'", comment);2100log->end_elem();2101}21022103// Make sure any guarding test views this path as very unlikely2104Node *i0 = control()->in(0);2105if (i0 != NULL && i0->is_If()) { // Found a guarding if test?2106IfNode *iff = i0->as_If();2107float f = iff->_prob; // Get prob2108if (control()->Opcode() == Op_IfTrue) {2109if (f > PROB_UNLIKELY_MAG(4))2110iff->_prob = PROB_MIN;2111} else {2112if (f < PROB_LIKELY_MAG(4))2113iff->_prob = PROB_MAX;2114}2115}21162117// Clear out dead values from the debug info.2118kill_dead_locals();21192120// Now insert the uncommon trap subroutine call2121address call_addr = SharedRuntime::uncommon_trap_blob()->entry_point();2122const TypePtr* no_memory_effects = NULL;2123// Pass the index of the class to be loaded2124Node* call = make_runtime_call(RC_NO_LEAF | RC_UNCOMMON |2125(must_throw ? RC_MUST_THROW : 0),2126OptoRuntime::uncommon_trap_Type(),2127call_addr, "uncommon_trap", no_memory_effects,2128intcon(trap_request));2129assert(call->as_CallStaticJava()->uncommon_trap_request() == trap_request,2130"must extract request correctly from the graph");2131assert(trap_request != 0, "zero value reserved by uncommon_trap_request");21322133call->set_req(TypeFunc::ReturnAdr, returnadr());2134// The debug info is the only real input to this call.21352136// Halt-and-catch fire here. The above call should never return!2137HaltNode* halt = new HaltNode(control(), frameptr(), "uncommon trap returned which should never happen"2138PRODUCT_ONLY(COMMA /*reachable*/false));2139_gvn.set_type_bottom(halt);2140root()->add_req(halt);21412142stop_and_kill_map();2143}214421452146//--------------------------just_allocated_object------------------------------2147// Report the object that was just allocated.2148// It must be the case that there are no intervening safepoints.2149// We use this to determine if an object is so "fresh" that2150// it does not require card marks.2151Node* GraphKit::just_allocated_object(Node* current_control) {2152Node* ctrl = current_control;2153// Object::<init> is invoked after allocation, most of invoke nodes2154// will be reduced, but a region node is kept in parse time, we check2155// the pattern and skip the region node if it degraded to a copy.2156if (ctrl != NULL && ctrl->is_Region() && ctrl->req() == 2 &&2157ctrl->as_Region()->is_copy()) {2158ctrl = ctrl->as_Region()->is_copy();2159}2160if (C->recent_alloc_ctl() == ctrl) {2161return C->recent_alloc_obj();2162}2163return NULL;2164}216521662167/**2168* Record profiling data exact_kls for Node n with the type system so2169* that it can propagate it (speculation)2170*2171* @param n node that the type applies to2172* @param exact_kls type from profiling2173* @param maybe_null did profiling see null?2174*2175* @return node with improved type2176*/2177Node* GraphKit::record_profile_for_speculation(Node* n, ciKlass* exact_kls, ProfilePtrKind ptr_kind) {2178const Type* current_type = _gvn.type(n);2179assert(UseTypeSpeculation, "type speculation must be on");21802181const TypePtr* speculative = current_type->speculative();21822183// Should the klass from the profile be recorded in the speculative type?2184if (current_type->would_improve_type(exact_kls, jvms()->depth())) {2185const TypeKlassPtr* tklass = TypeKlassPtr::make(exact_kls);2186const TypeOopPtr* xtype = tklass->as_instance_type();2187assert(xtype->klass_is_exact(), "Should be exact");2188// Any reason to believe n is not null (from this profiling or a previous one)?2189assert(ptr_kind != ProfileAlwaysNull, "impossible here");2190const TypePtr* ptr = (ptr_kind == ProfileMaybeNull && current_type->speculative_maybe_null()) ? TypePtr::BOTTOM : TypePtr::NOTNULL;2191// record the new speculative type's depth2192speculative = xtype->cast_to_ptr_type(ptr->ptr())->is_ptr();2193speculative = speculative->with_inline_depth(jvms()->depth());2194} else if (current_type->would_improve_ptr(ptr_kind)) {2195// Profiling report that null was never seen so we can change the2196// speculative type to non null ptr.2197if (ptr_kind == ProfileAlwaysNull) {2198speculative = TypePtr::NULL_PTR;2199} else {2200assert(ptr_kind == ProfileNeverNull, "nothing else is an improvement");2201const TypePtr* ptr = TypePtr::NOTNULL;2202if (speculative != NULL) {2203speculative = speculative->cast_to_ptr_type(ptr->ptr())->is_ptr();2204} else {2205speculative = ptr;2206}2207}2208}22092210if (speculative != current_type->speculative()) {2211// Build a type with a speculative type (what we think we know2212// about the type but will need a guard when we use it)2213const TypeOopPtr* spec_type = TypeOopPtr::make(TypePtr::BotPTR, Type::OffsetBot, TypeOopPtr::InstanceBot, speculative);2214// We're changing the type, we need a new CheckCast node to carry2215// the new type. The new type depends on the control: what2216// profiling tells us is only valid from here as far as we can2217// tell.2218Node* cast = new CheckCastPPNode(control(), n, current_type->remove_speculative()->join_speculative(spec_type));2219cast = _gvn.transform(cast);2220replace_in_map(n, cast);2221n = cast;2222}22232224return n;2225}22262227/**2228* Record profiling data from receiver profiling at an invoke with the2229* type system so that it can propagate it (speculation)2230*2231* @param n receiver node2232*2233* @return node with improved type2234*/2235Node* GraphKit::record_profiled_receiver_for_speculation(Node* n) {2236if (!UseTypeSpeculation) {2237return n;2238}2239ciKlass* exact_kls = profile_has_unique_klass();2240ProfilePtrKind ptr_kind = ProfileMaybeNull;2241if ((java_bc() == Bytecodes::_checkcast ||2242java_bc() == Bytecodes::_instanceof ||2243java_bc() == Bytecodes::_aastore) &&2244method()->method_data()->is_mature()) {2245ciProfileData* data = method()->method_data()->bci_to_data(bci());2246if (data != NULL) {2247if (!data->as_BitData()->null_seen()) {2248ptr_kind = ProfileNeverNull;2249} else {2250assert(data->is_ReceiverTypeData(), "bad profile data type");2251ciReceiverTypeData* call = (ciReceiverTypeData*)data->as_ReceiverTypeData();2252uint i = 0;2253for (; i < call->row_limit(); i++) {2254ciKlass* receiver = call->receiver(i);2255if (receiver != NULL) {2256break;2257}2258}2259ptr_kind = (i == call->row_limit()) ? ProfileAlwaysNull : ProfileMaybeNull;2260}2261}2262}2263return record_profile_for_speculation(n, exact_kls, ptr_kind);2264}22652266/**2267* Record profiling data from argument profiling at an invoke with the2268* type system so that it can propagate it (speculation)2269*2270* @param dest_method target method for the call2271* @param bc what invoke bytecode is this?2272*/2273void GraphKit::record_profiled_arguments_for_speculation(ciMethod* dest_method, Bytecodes::Code bc) {2274if (!UseTypeSpeculation) {2275return;2276}2277const TypeFunc* tf = TypeFunc::make(dest_method);2278int nargs = tf->domain()->cnt() - TypeFunc::Parms;2279int skip = Bytecodes::has_receiver(bc) ? 1 : 0;2280for (int j = skip, i = 0; j < nargs && i < TypeProfileArgsLimit; j++) {2281const Type *targ = tf->domain()->field_at(j + TypeFunc::Parms);2282if (is_reference_type(targ->basic_type())) {2283ProfilePtrKind ptr_kind = ProfileMaybeNull;2284ciKlass* better_type = NULL;2285if (method()->argument_profiled_type(bci(), i, better_type, ptr_kind)) {2286record_profile_for_speculation(argument(j), better_type, ptr_kind);2287}2288i++;2289}2290}2291}22922293/**2294* Record profiling data from parameter profiling at an invoke with2295* the type system so that it can propagate it (speculation)2296*/2297void GraphKit::record_profiled_parameters_for_speculation() {2298if (!UseTypeSpeculation) {2299return;2300}2301for (int i = 0, j = 0; i < method()->arg_size() ; i++) {2302if (_gvn.type(local(i))->isa_oopptr()) {2303ProfilePtrKind ptr_kind = ProfileMaybeNull;2304ciKlass* better_type = NULL;2305if (method()->parameter_profiled_type(j, better_type, ptr_kind)) {2306record_profile_for_speculation(local(i), better_type, ptr_kind);2307}2308j++;2309}2310}2311}23122313/**2314* Record profiling data from return value profiling at an invoke with2315* the type system so that it can propagate it (speculation)2316*/2317void GraphKit::record_profiled_return_for_speculation() {2318if (!UseTypeSpeculation) {2319return;2320}2321ProfilePtrKind ptr_kind = ProfileMaybeNull;2322ciKlass* better_type = NULL;2323if (method()->return_profiled_type(bci(), better_type, ptr_kind)) {2324// If profiling reports a single type for the return value,2325// feed it to the type system so it can propagate it as a2326// speculative type2327record_profile_for_speculation(stack(sp()-1), better_type, ptr_kind);2328}2329}23302331void GraphKit::round_double_arguments(ciMethod* dest_method) {2332if (Matcher::strict_fp_requires_explicit_rounding) {2333// (Note: TypeFunc::make has a cache that makes this fast.)2334const TypeFunc* tf = TypeFunc::make(dest_method);2335int nargs = tf->domain()->cnt() - TypeFunc::Parms;2336for (int j = 0; j < nargs; j++) {2337const Type *targ = tf->domain()->field_at(j + TypeFunc::Parms);2338if (targ->basic_type() == T_DOUBLE) {2339// If any parameters are doubles, they must be rounded before2340// the call, dstore_rounding does gvn.transform2341Node *arg = argument(j);2342arg = dstore_rounding(arg);2343set_argument(j, arg);2344}2345}2346}2347}23482349// rounding for strict float precision conformance2350Node* GraphKit::precision_rounding(Node* n) {2351if (Matcher::strict_fp_requires_explicit_rounding) {2352#ifdef IA322353if (UseSSE == 0) {2354return _gvn.transform(new RoundFloatNode(0, n));2355}2356#else2357Unimplemented();2358#endif // IA322359}2360return n;2361}23622363// rounding for strict double precision conformance2364Node* GraphKit::dprecision_rounding(Node *n) {2365if (Matcher::strict_fp_requires_explicit_rounding) {2366#ifdef IA322367if (UseSSE < 2) {2368return _gvn.transform(new RoundDoubleNode(0, n));2369}2370#else2371Unimplemented();2372#endif // IA322373}2374return n;2375}23762377// rounding for non-strict double stores2378Node* GraphKit::dstore_rounding(Node* n) {2379if (Matcher::strict_fp_requires_explicit_rounding) {2380#ifdef IA322381if (UseSSE < 2) {2382return _gvn.transform(new RoundDoubleNode(0, n));2383}2384#else2385Unimplemented();2386#endif // IA322387}2388return n;2389}23902391//=============================================================================2392// Generate a fast path/slow path idiom. Graph looks like:2393// [foo] indicates that 'foo' is a parameter2394//2395// [in] NULL2396// \ /2397// CmpP2398// Bool ne2399// If2400// / \2401// True False-<2>2402// / |2403// / cast_not_null2404// Load | | ^2405// [fast_test] | |2406// gvn to opt_test | |2407// / \ | <1>2408// True False |2409// | \\ |2410// [slow_call] \[fast_result]2411// Ctl Val \ \2412// | \ \2413// Catch <1> \ \2414// / \ ^ \ \2415// Ex No_Ex | \ \2416// | \ \ | \ <2> \2417// ... \ [slow_res] | | \ [null_result]2418// \ \--+--+--- | |2419// \ | / \ | /2420// --------Region Phi2421//2422//=============================================================================2423// Code is structured as a series of driver functions all called 'do_XXX' that2424// call a set of helper functions. Helper functions first, then drivers.24252426//------------------------------null_check_oop---------------------------------2427// Null check oop. Set null-path control into Region in slot 3.2428// Make a cast-not-nullness use the other not-null control. Return cast.2429Node* GraphKit::null_check_oop(Node* value, Node* *null_control,2430bool never_see_null,2431bool safe_for_replace,2432bool speculative) {2433// Initial NULL check taken path2434(*null_control) = top();2435Node* cast = null_check_common(value, T_OBJECT, false, null_control, speculative);24362437// Generate uncommon_trap:2438if (never_see_null && (*null_control) != top()) {2439// If we see an unexpected null at a check-cast we record it and force a2440// recompile; the offending check-cast will be compiled to handle NULLs.2441// If we see more than one offending BCI, then all checkcasts in the2442// method will be compiled to handle NULLs.2443PreserveJVMState pjvms(this);2444set_control(*null_control);2445replace_in_map(value, null());2446Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculative);2447uncommon_trap(reason,2448Deoptimization::Action_make_not_entrant);2449(*null_control) = top(); // NULL path is dead2450}2451if ((*null_control) == top() && safe_for_replace) {2452replace_in_map(value, cast);2453}24542455// Cast away null-ness on the result2456return cast;2457}24582459//------------------------------opt_iff----------------------------------------2460// Optimize the fast-check IfNode. Set the fast-path region slot 2.2461// Return slow-path control.2462Node* GraphKit::opt_iff(Node* region, Node* iff) {2463IfNode *opt_iff = _gvn.transform(iff)->as_If();24642465// Fast path taken; set region slot 22466Node *fast_taken = _gvn.transform( new IfFalseNode(opt_iff) );2467region->init_req(2,fast_taken); // Capture fast-control24682469// Fast path not-taken, i.e. slow path2470Node *slow_taken = _gvn.transform( new IfTrueNode(opt_iff) );2471return slow_taken;2472}24732474//-----------------------------make_runtime_call-------------------------------2475Node* GraphKit::make_runtime_call(int flags,2476const TypeFunc* call_type, address call_addr,2477const char* call_name,2478const TypePtr* adr_type,2479// The following parms are all optional.2480// The first NULL ends the list.2481Node* parm0, Node* parm1,2482Node* parm2, Node* parm3,2483Node* parm4, Node* parm5,2484Node* parm6, Node* parm7) {2485assert(call_addr != NULL, "must not call NULL targets");24862487// Slow-path call2488bool is_leaf = !(flags & RC_NO_LEAF);2489bool has_io = (!is_leaf && !(flags & RC_NO_IO));2490if (call_name == NULL) {2491assert(!is_leaf, "must supply name for leaf");2492call_name = OptoRuntime::stub_name(call_addr);2493}2494CallNode* call;2495if (!is_leaf) {2496call = new CallStaticJavaNode(call_type, call_addr, call_name, adr_type);2497} else if (flags & RC_NO_FP) {2498call = new CallLeafNoFPNode(call_type, call_addr, call_name, adr_type);2499} else if (flags & RC_VECTOR){2500uint num_bits = call_type->range()->field_at(TypeFunc::Parms)->is_vect()->length_in_bytes() * BitsPerByte;2501call = new CallLeafVectorNode(call_type, call_addr, call_name, adr_type, num_bits);2502} else {2503call = new CallLeafNode(call_type, call_addr, call_name, adr_type);2504}25052506// The following is similar to set_edges_for_java_call,2507// except that the memory effects of the call are restricted to AliasIdxRaw.25082509// Slow path call has no side-effects, uses few values2510bool wide_in = !(flags & RC_NARROW_MEM);2511bool wide_out = (C->get_alias_index(adr_type) == Compile::AliasIdxBot);25122513Node* prev_mem = NULL;2514if (wide_in) {2515prev_mem = set_predefined_input_for_runtime_call(call);2516} else {2517assert(!wide_out, "narrow in => narrow out");2518Node* narrow_mem = memory(adr_type);2519prev_mem = set_predefined_input_for_runtime_call(call, narrow_mem);2520}25212522// Hook each parm in order. Stop looking at the first NULL.2523if (parm0 != NULL) { call->init_req(TypeFunc::Parms+0, parm0);2524if (parm1 != NULL) { call->init_req(TypeFunc::Parms+1, parm1);2525if (parm2 != NULL) { call->init_req(TypeFunc::Parms+2, parm2);2526if (parm3 != NULL) { call->init_req(TypeFunc::Parms+3, parm3);2527if (parm4 != NULL) { call->init_req(TypeFunc::Parms+4, parm4);2528if (parm5 != NULL) { call->init_req(TypeFunc::Parms+5, parm5);2529if (parm6 != NULL) { call->init_req(TypeFunc::Parms+6, parm6);2530if (parm7 != NULL) { call->init_req(TypeFunc::Parms+7, parm7);2531/* close each nested if ===> */ } } } } } } } }2532assert(call->in(call->req()-1) != NULL, "must initialize all parms");25332534if (!is_leaf) {2535// Non-leaves can block and take safepoints:2536add_safepoint_edges(call, ((flags & RC_MUST_THROW) != 0));2537}2538// Non-leaves can throw exceptions:2539if (has_io) {2540call->set_req(TypeFunc::I_O, i_o());2541}25422543if (flags & RC_UNCOMMON) {2544// Set the count to a tiny probability. Cf. Estimate_Block_Frequency.2545// (An "if" probability corresponds roughly to an unconditional count.2546// Sort of.)2547call->set_cnt(PROB_UNLIKELY_MAG(4));2548}25492550Node* c = _gvn.transform(call);2551assert(c == call, "cannot disappear");25522553if (wide_out) {2554// Slow path call has full side-effects.2555set_predefined_output_for_runtime_call(call);2556} else {2557// Slow path call has few side-effects, and/or sets few values.2558set_predefined_output_for_runtime_call(call, prev_mem, adr_type);2559}25602561if (has_io) {2562set_i_o(_gvn.transform(new ProjNode(call, TypeFunc::I_O)));2563}2564return call;25652566}25672568// i2b2569Node* GraphKit::sign_extend_byte(Node* in) {2570Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(24)));2571return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(24)));2572}25732574// i2s2575Node* GraphKit::sign_extend_short(Node* in) {2576Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(16)));2577return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(16)));2578}25792580//-----------------------------make_native_call-------------------------------2581Node* GraphKit::make_native_call(address call_addr, const TypeFunc* call_type, uint nargs, ciNativeEntryPoint* nep) {2582// Select just the actual call args to pass on2583// [MethodHandle fallback, long addr, HALF addr, ... args , NativeEntryPoint nep]2584// | |2585// V V2586// [ ... args ]2587uint n_filtered_args = nargs - 4; // -fallback, -addr (2), -nep;2588ResourceMark rm;2589Node** argument_nodes = NEW_RESOURCE_ARRAY(Node*, n_filtered_args);2590const Type** arg_types = TypeTuple::fields(n_filtered_args);2591GrowableArray<VMReg> arg_regs(C->comp_arena(), n_filtered_args, n_filtered_args, VMRegImpl::Bad());25922593VMReg* argRegs = nep->argMoves();2594{2595for (uint vm_arg_pos = 0, java_arg_read_pos = 0;2596vm_arg_pos < n_filtered_args; vm_arg_pos++) {2597uint vm_unfiltered_arg_pos = vm_arg_pos + 3; // +3 to skip fallback handle argument and addr (2 since long)2598Node* node = argument(vm_unfiltered_arg_pos);2599const Type* type = call_type->domain()->field_at(TypeFunc::Parms + vm_unfiltered_arg_pos);2600VMReg reg = type == Type::HALF2601? VMRegImpl::Bad()2602: argRegs[java_arg_read_pos++];26032604argument_nodes[vm_arg_pos] = node;2605arg_types[TypeFunc::Parms + vm_arg_pos] = type;2606arg_regs.at_put(vm_arg_pos, reg);2607}2608}26092610uint n_returns = call_type->range()->cnt() - TypeFunc::Parms;2611GrowableArray<VMReg> ret_regs(C->comp_arena(), n_returns, n_returns, VMRegImpl::Bad());2612const Type** ret_types = TypeTuple::fields(n_returns);26132614VMReg* retRegs = nep->returnMoves();2615{2616for (uint vm_ret_pos = 0, java_ret_read_pos = 0;2617vm_ret_pos < n_returns; vm_ret_pos++) { // 0 or 12618const Type* type = call_type->range()->field_at(TypeFunc::Parms + vm_ret_pos);2619VMReg reg = type == Type::HALF2620? VMRegImpl::Bad()2621: retRegs[java_ret_read_pos++];26222623ret_regs.at_put(vm_ret_pos, reg);2624ret_types[TypeFunc::Parms + vm_ret_pos] = type;2625}2626}26272628const TypeFunc* new_call_type = TypeFunc::make(2629TypeTuple::make(TypeFunc::Parms + n_filtered_args, arg_types),2630TypeTuple::make(TypeFunc::Parms + n_returns, ret_types)2631);26322633if (nep->need_transition()) {2634RuntimeStub* invoker = SharedRuntime::make_native_invoker(call_addr,2635nep->shadow_space(),2636arg_regs, ret_regs);2637if (invoker == NULL) {2638C->record_failure("native invoker not implemented on this platform");2639return NULL;2640}2641C->add_native_invoker(invoker);2642call_addr = invoker->code_begin();2643}2644assert(call_addr != NULL, "sanity");26452646CallNativeNode* call = new CallNativeNode(new_call_type, call_addr, nep->name(), TypePtr::BOTTOM,2647arg_regs,2648ret_regs,2649nep->shadow_space(),2650nep->need_transition());26512652if (call->_need_transition) {2653add_safepoint_edges(call);2654}26552656set_predefined_input_for_runtime_call(call);26572658for (uint i = 0; i < n_filtered_args; i++) {2659call->init_req(i + TypeFunc::Parms, argument_nodes[i]);2660}26612662Node* c = gvn().transform(call);2663assert(c == call, "cannot disappear");26642665set_predefined_output_for_runtime_call(call);26662667Node* ret;2668if (method() == NULL || method()->return_type()->basic_type() == T_VOID) {2669ret = top();2670} else {2671ret = gvn().transform(new ProjNode(call, TypeFunc::Parms));2672// Unpack native results if needed2673// Need this method type since it's unerased2674switch (nep->method_type()->rtype()->basic_type()) {2675case T_CHAR:2676ret = _gvn.transform(new AndINode(ret, _gvn.intcon(0xFFFF)));2677break;2678case T_BYTE:2679ret = sign_extend_byte(ret);2680break;2681case T_SHORT:2682ret = sign_extend_short(ret);2683break;2684default: // do nothing2685break;2686}2687}26882689push_node(method()->return_type()->basic_type(), ret);26902691return call;2692}26932694//------------------------------merge_memory-----------------------------------2695// Merge memory from one path into the current memory state.2696void GraphKit::merge_memory(Node* new_mem, Node* region, int new_path) {2697for (MergeMemStream mms(merged_memory(), new_mem->as_MergeMem()); mms.next_non_empty2(); ) {2698Node* old_slice = mms.force_memory();2699Node* new_slice = mms.memory2();2700if (old_slice != new_slice) {2701PhiNode* phi;2702if (old_slice->is_Phi() && old_slice->as_Phi()->region() == region) {2703if (mms.is_empty()) {2704// clone base memory Phi's inputs for this memory slice2705assert(old_slice == mms.base_memory(), "sanity");2706phi = PhiNode::make(region, NULL, Type::MEMORY, mms.adr_type(C));2707_gvn.set_type(phi, Type::MEMORY);2708for (uint i = 1; i < phi->req(); i++) {2709phi->init_req(i, old_slice->in(i));2710}2711} else {2712phi = old_slice->as_Phi(); // Phi was generated already2713}2714} else {2715phi = PhiNode::make(region, old_slice, Type::MEMORY, mms.adr_type(C));2716_gvn.set_type(phi, Type::MEMORY);2717}2718phi->set_req(new_path, new_slice);2719mms.set_memory(phi);2720}2721}2722}27232724//------------------------------make_slow_call_ex------------------------------2725// Make the exception handler hookups for the slow call2726void GraphKit::make_slow_call_ex(Node* call, ciInstanceKlass* ex_klass, bool separate_io_proj, bool deoptimize) {2727if (stopped()) return;27282729// Make a catch node with just two handlers: fall-through and catch-all2730Node* i_o = _gvn.transform( new ProjNode(call, TypeFunc::I_O, separate_io_proj) );2731Node* catc = _gvn.transform( new CatchNode(control(), i_o, 2) );2732Node* norm = new CatchProjNode(catc, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci);2733_gvn.set_type_bottom(norm);2734C->record_for_igvn(norm);2735Node* excp = _gvn.transform( new CatchProjNode(catc, CatchProjNode::catch_all_index, CatchProjNode::no_handler_bci) );27362737{ PreserveJVMState pjvms(this);2738set_control(excp);2739set_i_o(i_o);27402741if (excp != top()) {2742if (deoptimize) {2743// Deoptimize if an exception is caught. Don't construct exception state in this case.2744uncommon_trap(Deoptimization::Reason_unhandled,2745Deoptimization::Action_none);2746} else {2747// Create an exception state also.2748// Use an exact type if the caller has a specific exception.2749const Type* ex_type = TypeOopPtr::make_from_klass_unique(ex_klass)->cast_to_ptr_type(TypePtr::NotNull);2750Node* ex_oop = new CreateExNode(ex_type, control(), i_o);2751add_exception_state(make_exception_state(_gvn.transform(ex_oop)));2752}2753}2754}27552756// Get the no-exception control from the CatchNode.2757set_control(norm);2758}27592760static IfNode* gen_subtype_check_compare(Node* ctrl, Node* in1, Node* in2, BoolTest::mask test, float p, PhaseGVN& gvn, BasicType bt) {2761Node* cmp = NULL;2762switch(bt) {2763case T_INT: cmp = new CmpINode(in1, in2); break;2764case T_ADDRESS: cmp = new CmpPNode(in1, in2); break;2765default: fatal("unexpected comparison type %s", type2name(bt));2766}2767gvn.transform(cmp);2768Node* bol = gvn.transform(new BoolNode(cmp, test));2769IfNode* iff = new IfNode(ctrl, bol, p, COUNT_UNKNOWN);2770gvn.transform(iff);2771if (!bol->is_Con()) gvn.record_for_igvn(iff);2772return iff;2773}27742775//-------------------------------gen_subtype_check-----------------------------2776// Generate a subtyping check. Takes as input the subtype and supertype.2777// Returns 2 values: sets the default control() to the true path and returns2778// the false path. Only reads invariant memory; sets no (visible) memory.2779// The PartialSubtypeCheckNode sets the hidden 1-word cache in the encoding2780// but that's not exposed to the optimizer. This call also doesn't take in an2781// Object; if you wish to check an Object you need to load the Object's class2782// prior to coming here.2783Node* Phase::gen_subtype_check(Node* subklass, Node* superklass, Node** ctrl, Node* mem, PhaseGVN& gvn) {2784Compile* C = gvn.C;2785if ((*ctrl)->is_top()) {2786return C->top();2787}27882789// Fast check for identical types, perhaps identical constants.2790// The types can even be identical non-constants, in cases2791// involving Array.newInstance, Object.clone, etc.2792if (subklass == superklass)2793return C->top(); // false path is dead; no test needed.27942795if (gvn.type(superklass)->singleton()) {2796ciKlass* superk = gvn.type(superklass)->is_klassptr()->klass();2797ciKlass* subk = gvn.type(subklass)->is_klassptr()->klass();27982799// In the common case of an exact superklass, try to fold up the2800// test before generating code. You may ask, why not just generate2801// the code and then let it fold up? The answer is that the generated2802// code will necessarily include null checks, which do not always2803// completely fold away. If they are also needless, then they turn2804// into a performance loss. Example:2805// Foo[] fa = blah(); Foo x = fa[0]; fa[1] = x;2806// Here, the type of 'fa' is often exact, so the store check2807// of fa[1]=x will fold up, without testing the nullness of x.2808switch (C->static_subtype_check(superk, subk)) {2809case Compile::SSC_always_false:2810{2811Node* always_fail = *ctrl;2812*ctrl = gvn.C->top();2813return always_fail;2814}2815case Compile::SSC_always_true:2816return C->top();2817case Compile::SSC_easy_test:2818{2819// Just do a direct pointer compare and be done.2820IfNode* iff = gen_subtype_check_compare(*ctrl, subklass, superklass, BoolTest::eq, PROB_STATIC_FREQUENT, gvn, T_ADDRESS);2821*ctrl = gvn.transform(new IfTrueNode(iff));2822return gvn.transform(new IfFalseNode(iff));2823}2824case Compile::SSC_full_test:2825break;2826default:2827ShouldNotReachHere();2828}2829}28302831// %%% Possible further optimization: Even if the superklass is not exact,2832// if the subklass is the unique subtype of the superklass, the check2833// will always succeed. We could leave a dependency behind to ensure this.28342835// First load the super-klass's check-offset2836Node *p1 = gvn.transform(new AddPNode(superklass, superklass, gvn.MakeConX(in_bytes(Klass::super_check_offset_offset()))));2837Node* m = C->immutable_memory();2838Node *chk_off = gvn.transform(new LoadINode(NULL, m, p1, gvn.type(p1)->is_ptr(), TypeInt::INT, MemNode::unordered));2839int cacheoff_con = in_bytes(Klass::secondary_super_cache_offset());2840bool might_be_cache = (gvn.find_int_con(chk_off, cacheoff_con) == cacheoff_con);28412842// Load from the sub-klass's super-class display list, or a 1-word cache of2843// the secondary superclass list, or a failing value with a sentinel offset2844// if the super-klass is an interface or exceptionally deep in the Java2845// hierarchy and we have to scan the secondary superclass list the hard way.2846// Worst-case type is a little odd: NULL is allowed as a result (usually2847// klass loads can never produce a NULL).2848Node *chk_off_X = chk_off;2849#ifdef _LP642850chk_off_X = gvn.transform(new ConvI2LNode(chk_off_X));2851#endif2852Node *p2 = gvn.transform(new AddPNode(subklass,subklass,chk_off_X));2853// For some types like interfaces the following loadKlass is from a 1-word2854// cache which is mutable so can't use immutable memory. Other2855// types load from the super-class display table which is immutable.2856Node *kmem = C->immutable_memory();2857// secondary_super_cache is not immutable but can be treated as such because:2858// - no ideal node writes to it in a way that could cause an2859// incorrect/missed optimization of the following Load.2860// - it's a cache so, worse case, not reading the latest value2861// wouldn't cause incorrect execution2862if (might_be_cache && mem != NULL) {2863kmem = mem->is_MergeMem() ? mem->as_MergeMem()->memory_at(C->get_alias_index(gvn.type(p2)->is_ptr())) : mem;2864}2865Node *nkls = gvn.transform(LoadKlassNode::make(gvn, NULL, kmem, p2, gvn.type(p2)->is_ptr(), TypeKlassPtr::OBJECT_OR_NULL));28662867// Compile speed common case: ARE a subtype and we canNOT fail2868if( superklass == nkls )2869return C->top(); // false path is dead; no test needed.28702871// See if we get an immediate positive hit. Happens roughly 83% of the2872// time. Test to see if the value loaded just previously from the subklass2873// is exactly the superklass.2874IfNode *iff1 = gen_subtype_check_compare(*ctrl, superklass, nkls, BoolTest::eq, PROB_LIKELY(0.83f), gvn, T_ADDRESS);2875Node *iftrue1 = gvn.transform( new IfTrueNode (iff1));2876*ctrl = gvn.transform(new IfFalseNode(iff1));28772878// Compile speed common case: Check for being deterministic right now. If2879// chk_off is a constant and not equal to cacheoff then we are NOT a2880// subklass. In this case we need exactly the 1 test above and we can2881// return those results immediately.2882if (!might_be_cache) {2883Node* not_subtype_ctrl = *ctrl;2884*ctrl = iftrue1; // We need exactly the 1 test above2885return not_subtype_ctrl;2886}28872888// Gather the various success & failures here2889RegionNode *r_ok_subtype = new RegionNode(4);2890gvn.record_for_igvn(r_ok_subtype);2891RegionNode *r_not_subtype = new RegionNode(3);2892gvn.record_for_igvn(r_not_subtype);28932894r_ok_subtype->init_req(1, iftrue1);28952896// Check for immediate negative hit. Happens roughly 11% of the time (which2897// is roughly 63% of the remaining cases). Test to see if the loaded2898// check-offset points into the subklass display list or the 1-element2899// cache. If it points to the display (and NOT the cache) and the display2900// missed then it's not a subtype.2901Node *cacheoff = gvn.intcon(cacheoff_con);2902IfNode *iff2 = gen_subtype_check_compare(*ctrl, chk_off, cacheoff, BoolTest::ne, PROB_LIKELY(0.63f), gvn, T_INT);2903r_not_subtype->init_req(1, gvn.transform(new IfTrueNode (iff2)));2904*ctrl = gvn.transform(new IfFalseNode(iff2));29052906// Check for self. Very rare to get here, but it is taken 1/3 the time.2907// No performance impact (too rare) but allows sharing of secondary arrays2908// which has some footprint reduction.2909IfNode *iff3 = gen_subtype_check_compare(*ctrl, subklass, superklass, BoolTest::eq, PROB_LIKELY(0.36f), gvn, T_ADDRESS);2910r_ok_subtype->init_req(2, gvn.transform(new IfTrueNode(iff3)));2911*ctrl = gvn.transform(new IfFalseNode(iff3));29122913// -- Roads not taken here: --2914// We could also have chosen to perform the self-check at the beginning2915// of this code sequence, as the assembler does. This would not pay off2916// the same way, since the optimizer, unlike the assembler, can perform2917// static type analysis to fold away many successful self-checks.2918// Non-foldable self checks work better here in second position, because2919// the initial primary superclass check subsumes a self-check for most2920// types. An exception would be a secondary type like array-of-interface,2921// which does not appear in its own primary supertype display.2922// Finally, we could have chosen to move the self-check into the2923// PartialSubtypeCheckNode, and from there out-of-line in a platform2924// dependent manner. But it is worthwhile to have the check here,2925// where it can be perhaps be optimized. The cost in code space is2926// small (register compare, branch).29272928// Now do a linear scan of the secondary super-klass array. Again, no real2929// performance impact (too rare) but it's gotta be done.2930// Since the code is rarely used, there is no penalty for moving it2931// out of line, and it can only improve I-cache density.2932// The decision to inline or out-of-line this final check is platform2933// dependent, and is found in the AD file definition of PartialSubtypeCheck.2934Node* psc = gvn.transform(2935new PartialSubtypeCheckNode(*ctrl, subklass, superklass));29362937IfNode *iff4 = gen_subtype_check_compare(*ctrl, psc, gvn.zerocon(T_OBJECT), BoolTest::ne, PROB_FAIR, gvn, T_ADDRESS);2938r_not_subtype->init_req(2, gvn.transform(new IfTrueNode (iff4)));2939r_ok_subtype ->init_req(3, gvn.transform(new IfFalseNode(iff4)));29402941// Return false path; set default control to true path.2942*ctrl = gvn.transform(r_ok_subtype);2943return gvn.transform(r_not_subtype);2944}29452946Node* GraphKit::gen_subtype_check(Node* obj_or_subklass, Node* superklass) {2947bool expand_subtype_check = C->post_loop_opts_phase() || // macro node expansion is over2948ExpandSubTypeCheckAtParseTime; // forced expansion2949if (expand_subtype_check) {2950MergeMemNode* mem = merged_memory();2951Node* ctrl = control();2952Node* subklass = obj_or_subklass;2953if (!_gvn.type(obj_or_subklass)->isa_klassptr()) {2954subklass = load_object_klass(obj_or_subklass);2955}29562957Node* n = Phase::gen_subtype_check(subklass, superklass, &ctrl, mem, _gvn);2958set_control(ctrl);2959return n;2960}29612962Node* check = _gvn.transform(new SubTypeCheckNode(C, obj_or_subklass, superklass));2963Node* bol = _gvn.transform(new BoolNode(check, BoolTest::eq));2964IfNode* iff = create_and_xform_if(control(), bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);2965set_control(_gvn.transform(new IfTrueNode(iff)));2966return _gvn.transform(new IfFalseNode(iff));2967}29682969// Profile-driven exact type check:2970Node* GraphKit::type_check_receiver(Node* receiver, ciKlass* klass,2971float prob,2972Node* *casted_receiver) {2973assert(!klass->is_interface(), "no exact type check on interfaces");29742975const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);2976Node* recv_klass = load_object_klass(receiver);2977Node* want_klass = makecon(tklass);2978Node* cmp = _gvn.transform(new CmpPNode(recv_klass, want_klass));2979Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));2980IfNode* iff = create_and_xform_if(control(), bol, prob, COUNT_UNKNOWN);2981set_control( _gvn.transform(new IfTrueNode (iff)));2982Node* fail = _gvn.transform(new IfFalseNode(iff));29832984if (!stopped()) {2985const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();2986const TypeOopPtr* recvx_type = tklass->as_instance_type();2987assert(recvx_type->klass_is_exact(), "");29882989if (!receiver_type->higher_equal(recvx_type)) { // ignore redundant casts2990// Subsume downstream occurrences of receiver with a cast to2991// recv_xtype, since now we know what the type will be.2992Node* cast = new CheckCastPPNode(control(), receiver, recvx_type);2993(*casted_receiver) = _gvn.transform(cast);2994// (User must make the replace_in_map call.)2995}2996}29972998return fail;2999}30003001//------------------------------subtype_check_receiver-------------------------3002Node* GraphKit::subtype_check_receiver(Node* receiver, ciKlass* klass,3003Node** casted_receiver) {3004const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);3005Node* want_klass = makecon(tklass);30063007Node* slow_ctl = gen_subtype_check(receiver, want_klass);30083009// Ignore interface type information until interface types are properly tracked.3010if (!stopped() && !klass->is_interface()) {3011const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();3012const TypeOopPtr* recv_type = tklass->cast_to_exactness(false)->is_klassptr()->as_instance_type();3013if (!receiver_type->higher_equal(recv_type)) { // ignore redundant casts3014Node* cast = new CheckCastPPNode(control(), receiver, recv_type);3015(*casted_receiver) = _gvn.transform(cast);3016}3017}30183019return slow_ctl;3020}30213022//------------------------------seems_never_null-------------------------------3023// Use null_seen information if it is available from the profile.3024// If we see an unexpected null at a type check we record it and force a3025// recompile; the offending check will be recompiled to handle NULLs.3026// If we see several offending BCIs, then all checks in the3027// method will be recompiled.3028bool GraphKit::seems_never_null(Node* obj, ciProfileData* data, bool& speculating) {3029speculating = !_gvn.type(obj)->speculative_maybe_null();3030Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculating);3031if (UncommonNullCast // Cutout for this technique3032&& obj != null() // And not the -Xcomp stupid case?3033&& !too_many_traps(reason)3034) {3035if (speculating) {3036return true;3037}3038if (data == NULL)3039// Edge case: no mature data. Be optimistic here.3040return true;3041// If the profile has not seen a null, assume it won't happen.3042assert(java_bc() == Bytecodes::_checkcast ||3043java_bc() == Bytecodes::_instanceof ||3044java_bc() == Bytecodes::_aastore, "MDO must collect null_seen bit here");3045return !data->as_BitData()->null_seen();3046}3047speculating = false;3048return false;3049}30503051void GraphKit::guard_klass_being_initialized(Node* klass) {3052int init_state_off = in_bytes(InstanceKlass::init_state_offset());3053Node* adr = basic_plus_adr(top(), klass, init_state_off);3054Node* init_state = LoadNode::make(_gvn, NULL, immutable_memory(), adr,3055adr->bottom_type()->is_ptr(), TypeInt::BYTE,3056T_BYTE, MemNode::unordered);3057init_state = _gvn.transform(init_state);30583059Node* being_initialized_state = makecon(TypeInt::make(InstanceKlass::being_initialized));30603061Node* chk = _gvn.transform(new CmpINode(being_initialized_state, init_state));3062Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));30633064{ BuildCutout unless(this, tst, PROB_MAX);3065uncommon_trap(Deoptimization::Reason_initialized, Deoptimization::Action_reinterpret);3066}3067}30683069void GraphKit::guard_init_thread(Node* klass) {3070int init_thread_off = in_bytes(InstanceKlass::init_thread_offset());3071Node* adr = basic_plus_adr(top(), klass, init_thread_off);30723073Node* init_thread = LoadNode::make(_gvn, NULL, immutable_memory(), adr,3074adr->bottom_type()->is_ptr(), TypePtr::NOTNULL,3075T_ADDRESS, MemNode::unordered);3076init_thread = _gvn.transform(init_thread);30773078Node* cur_thread = _gvn.transform(new ThreadLocalNode());30793080Node* chk = _gvn.transform(new CmpPNode(cur_thread, init_thread));3081Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));30823083{ BuildCutout unless(this, tst, PROB_MAX);3084uncommon_trap(Deoptimization::Reason_uninitialized, Deoptimization::Action_none);3085}3086}30873088void GraphKit::clinit_barrier(ciInstanceKlass* ik, ciMethod* context) {3089if (ik->is_being_initialized()) {3090if (C->needs_clinit_barrier(ik, context)) {3091Node* klass = makecon(TypeKlassPtr::make(ik));3092guard_klass_being_initialized(klass);3093guard_init_thread(klass);3094insert_mem_bar(Op_MemBarCPUOrder);3095}3096} else if (ik->is_initialized()) {3097return; // no barrier needed3098} else {3099uncommon_trap(Deoptimization::Reason_uninitialized,3100Deoptimization::Action_reinterpret,3101NULL);3102}3103}31043105//------------------------maybe_cast_profiled_receiver-------------------------3106// If the profile has seen exactly one type, narrow to exactly that type.3107// Subsequent type checks will always fold up.3108Node* GraphKit::maybe_cast_profiled_receiver(Node* not_null_obj,3109ciKlass* require_klass,3110ciKlass* spec_klass,3111bool safe_for_replace) {3112if (!UseTypeProfile || !TypeProfileCasts) return NULL;31133114Deoptimization::DeoptReason reason = Deoptimization::reason_class_check(spec_klass != NULL);31153116// Make sure we haven't already deoptimized from this tactic.3117if (too_many_traps_or_recompiles(reason))3118return NULL;31193120// (No, this isn't a call, but it's enough like a virtual call3121// to use the same ciMethod accessor to get the profile info...)3122// If we have a speculative type use it instead of profiling (which3123// may not help us)3124ciKlass* exact_kls = spec_klass == NULL ? profile_has_unique_klass() : spec_klass;3125if (exact_kls != NULL) {// no cast failures here3126if (require_klass == NULL ||3127C->static_subtype_check(require_klass, exact_kls) == Compile::SSC_always_true) {3128// If we narrow the type to match what the type profile sees or3129// the speculative type, we can then remove the rest of the3130// cast.3131// This is a win, even if the exact_kls is very specific,3132// because downstream operations, such as method calls,3133// will often benefit from the sharper type.3134Node* exact_obj = not_null_obj; // will get updated in place...3135Node* slow_ctl = type_check_receiver(exact_obj, exact_kls, 1.0,3136&exact_obj);3137{ PreserveJVMState pjvms(this);3138set_control(slow_ctl);3139uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);3140}3141if (safe_for_replace) {3142replace_in_map(not_null_obj, exact_obj);3143}3144return exact_obj;3145}3146// assert(ssc == Compile::SSC_always_true)... except maybe the profile lied to us.3147}31483149return NULL;3150}31513152/**3153* Cast obj to type and emit guard unless we had too many traps here3154* already3155*3156* @param obj node being casted3157* @param type type to cast the node to3158* @param not_null true if we know node cannot be null3159*/3160Node* GraphKit::maybe_cast_profiled_obj(Node* obj,3161ciKlass* type,3162bool not_null) {3163if (stopped()) {3164return obj;3165}31663167// type == NULL if profiling tells us this object is always null3168if (type != NULL) {3169Deoptimization::DeoptReason class_reason = Deoptimization::Reason_speculate_class_check;3170Deoptimization::DeoptReason null_reason = Deoptimization::Reason_speculate_null_check;31713172if (!too_many_traps_or_recompiles(null_reason) &&3173!too_many_traps_or_recompiles(class_reason)) {3174Node* not_null_obj = NULL;3175// not_null is true if we know the object is not null and3176// there's no need for a null check3177if (!not_null) {3178Node* null_ctl = top();3179not_null_obj = null_check_oop(obj, &null_ctl, true, true, true);3180assert(null_ctl->is_top(), "no null control here");3181} else {3182not_null_obj = obj;3183}31843185Node* exact_obj = not_null_obj;3186ciKlass* exact_kls = type;3187Node* slow_ctl = type_check_receiver(exact_obj, exact_kls, 1.0,3188&exact_obj);3189{3190PreserveJVMState pjvms(this);3191set_control(slow_ctl);3192uncommon_trap_exact(class_reason, Deoptimization::Action_maybe_recompile);3193}3194replace_in_map(not_null_obj, exact_obj);3195obj = exact_obj;3196}3197} else {3198if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) {3199Node* exact_obj = null_assert(obj);3200replace_in_map(obj, exact_obj);3201obj = exact_obj;3202}3203}3204return obj;3205}32063207//-------------------------------gen_instanceof--------------------------------3208// Generate an instance-of idiom. Used by both the instance-of bytecode3209// and the reflective instance-of call.3210Node* GraphKit::gen_instanceof(Node* obj, Node* superklass, bool safe_for_replace) {3211kill_dead_locals(); // Benefit all the uncommon traps3212assert( !stopped(), "dead parse path should be checked in callers" );3213assert(!TypePtr::NULL_PTR->higher_equal(_gvn.type(superklass)->is_klassptr()),3214"must check for not-null not-dead klass in callers");32153216// Make the merge point3217enum { _obj_path = 1, _fail_path, _null_path, PATH_LIMIT };3218RegionNode* region = new RegionNode(PATH_LIMIT);3219Node* phi = new PhiNode(region, TypeInt::BOOL);3220C->set_has_split_ifs(true); // Has chance for split-if optimization32213222ciProfileData* data = NULL;3223if (java_bc() == Bytecodes::_instanceof) { // Only for the bytecode3224data = method()->method_data()->bci_to_data(bci());3225}3226bool speculative_not_null = false;3227bool never_see_null = (ProfileDynamicTypes // aggressive use of profile3228&& seems_never_null(obj, data, speculative_not_null));32293230// Null check; get casted pointer; set region slot 33231Node* null_ctl = top();3232Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);32333234// If not_null_obj is dead, only null-path is taken3235if (stopped()) { // Doing instance-of on a NULL?3236set_control(null_ctl);3237return intcon(0);3238}3239region->init_req(_null_path, null_ctl);3240phi ->init_req(_null_path, intcon(0)); // Set null path value3241if (null_ctl == top()) {3242// Do this eagerly, so that pattern matches like is_diamond_phi3243// will work even during parsing.3244assert(_null_path == PATH_LIMIT-1, "delete last");3245region->del_req(_null_path);3246phi ->del_req(_null_path);3247}32483249// Do we know the type check always succeed?3250bool known_statically = false;3251if (_gvn.type(superklass)->singleton()) {3252ciKlass* superk = _gvn.type(superklass)->is_klassptr()->klass();3253ciKlass* subk = _gvn.type(obj)->is_oopptr()->klass();3254if (subk != NULL && subk->is_loaded()) {3255int static_res = C->static_subtype_check(superk, subk);3256known_statically = (static_res == Compile::SSC_always_true || static_res == Compile::SSC_always_false);3257}3258}32593260if (!known_statically) {3261const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();3262// We may not have profiling here or it may not help us. If we3263// have a speculative type use it to perform an exact cast.3264ciKlass* spec_obj_type = obj_type->speculative_type();3265if (spec_obj_type != NULL || (ProfileDynamicTypes && data != NULL)) {3266Node* cast_obj = maybe_cast_profiled_receiver(not_null_obj, NULL, spec_obj_type, safe_for_replace);3267if (stopped()) { // Profile disagrees with this path.3268set_control(null_ctl); // Null is the only remaining possibility.3269return intcon(0);3270}3271if (cast_obj != NULL) {3272not_null_obj = cast_obj;3273}3274}3275}32763277// Generate the subtype check3278Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass);32793280// Plug in the success path to the general merge in slot 1.3281region->init_req(_obj_path, control());3282phi ->init_req(_obj_path, intcon(1));32833284// Plug in the failing path to the general merge in slot 2.3285region->init_req(_fail_path, not_subtype_ctrl);3286phi ->init_req(_fail_path, intcon(0));32873288// Return final merged results3289set_control( _gvn.transform(region) );3290record_for_igvn(region);32913292// If we know the type check always succeeds then we don't use the3293// profiling data at this bytecode. Don't lose it, feed it to the3294// type system as a speculative type.3295if (safe_for_replace) {3296Node* casted_obj = record_profiled_receiver_for_speculation(obj);3297replace_in_map(obj, casted_obj);3298}32993300return _gvn.transform(phi);3301}33023303//-------------------------------gen_checkcast---------------------------------3304// Generate a checkcast idiom. Used by both the checkcast bytecode and the3305// array store bytecode. Stack must be as-if BEFORE doing the bytecode so the3306// uncommon-trap paths work. Adjust stack after this call.3307// If failure_control is supplied and not null, it is filled in with3308// the control edge for the cast failure. Otherwise, an appropriate3309// uncommon trap or exception is thrown.3310Node* GraphKit::gen_checkcast(Node *obj, Node* superklass,3311Node* *failure_control) {3312kill_dead_locals(); // Benefit all the uncommon traps3313const TypeKlassPtr *tk = _gvn.type(superklass)->is_klassptr();3314const Type *toop = TypeOopPtr::make_from_klass(tk->klass());33153316// Fast cutout: Check the case that the cast is vacuously true.3317// This detects the common cases where the test will short-circuit3318// away completely. We do this before we perform the null check,3319// because if the test is going to turn into zero code, we don't3320// want a residual null check left around. (Causes a slowdown,3321// for example, in some objArray manipulations, such as a[i]=a[j].)3322if (tk->singleton()) {3323const TypeOopPtr* objtp = _gvn.type(obj)->isa_oopptr();3324if (objtp != NULL && objtp->klass() != NULL) {3325switch (C->static_subtype_check(tk->klass(), objtp->klass())) {3326case Compile::SSC_always_true:3327// If we know the type check always succeed then we don't use3328// the profiling data at this bytecode. Don't lose it, feed it3329// to the type system as a speculative type.3330return record_profiled_receiver_for_speculation(obj);3331case Compile::SSC_always_false:3332// It needs a null check because a null will *pass* the cast check.3333// A non-null value will always produce an exception.3334if (!objtp->maybe_null()) {3335builtin_throw(Deoptimization::Reason_class_check, makecon(TypeKlassPtr::make(objtp->klass())));3336return top();3337} else if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) {3338return null_assert(obj);3339}3340break; // Fall through to full check3341}3342}3343}33443345ciProfileData* data = NULL;3346bool safe_for_replace = false;3347if (failure_control == NULL) { // use MDO in regular case only3348assert(java_bc() == Bytecodes::_aastore ||3349java_bc() == Bytecodes::_checkcast,3350"interpreter profiles type checks only for these BCs");3351data = method()->method_data()->bci_to_data(bci());3352safe_for_replace = true;3353}33543355// Make the merge point3356enum { _obj_path = 1, _null_path, PATH_LIMIT };3357RegionNode* region = new RegionNode(PATH_LIMIT);3358Node* phi = new PhiNode(region, toop);3359C->set_has_split_ifs(true); // Has chance for split-if optimization33603361// Use null-cast information if it is available3362bool speculative_not_null = false;3363bool never_see_null = ((failure_control == NULL) // regular case only3364&& seems_never_null(obj, data, speculative_not_null));33653366// Null check; get casted pointer; set region slot 33367Node* null_ctl = top();3368Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);33693370// If not_null_obj is dead, only null-path is taken3371if (stopped()) { // Doing instance-of on a NULL?3372set_control(null_ctl);3373return null();3374}3375region->init_req(_null_path, null_ctl);3376phi ->init_req(_null_path, null()); // Set null path value3377if (null_ctl == top()) {3378// Do this eagerly, so that pattern matches like is_diamond_phi3379// will work even during parsing.3380assert(_null_path == PATH_LIMIT-1, "delete last");3381region->del_req(_null_path);3382phi ->del_req(_null_path);3383}33843385Node* cast_obj = NULL;3386if (tk->klass_is_exact()) {3387// The following optimization tries to statically cast the speculative type of the object3388// (for example obtained during profiling) to the type of the superklass and then do a3389// dynamic check that the type of the object is what we expect. To work correctly3390// for checkcast and aastore the type of superklass should be exact.3391const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();3392// We may not have profiling here or it may not help us. If we have3393// a speculative type use it to perform an exact cast.3394ciKlass* spec_obj_type = obj_type->speculative_type();3395if (spec_obj_type != NULL || data != NULL) {3396cast_obj = maybe_cast_profiled_receiver(not_null_obj, tk->klass(), spec_obj_type, safe_for_replace);3397if (cast_obj != NULL) {3398if (failure_control != NULL) // failure is now impossible3399(*failure_control) = top();3400// adjust the type of the phi to the exact klass:3401phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR));3402}3403}3404}34053406if (cast_obj == NULL) {3407// Generate the subtype check3408Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass );34093410// Plug in success path into the merge3411cast_obj = _gvn.transform(new CheckCastPPNode(control(), not_null_obj, toop));3412// Failure path ends in uncommon trap (or may be dead - failure impossible)3413if (failure_control == NULL) {3414if (not_subtype_ctrl != top()) { // If failure is possible3415PreserveJVMState pjvms(this);3416set_control(not_subtype_ctrl);3417builtin_throw(Deoptimization::Reason_class_check, load_object_klass(not_null_obj));3418}3419} else {3420(*failure_control) = not_subtype_ctrl;3421}3422}34233424region->init_req(_obj_path, control());3425phi ->init_req(_obj_path, cast_obj);34263427// A merge of NULL or Casted-NotNull obj3428Node* res = _gvn.transform(phi);34293430// Note I do NOT always 'replace_in_map(obj,result)' here.3431// if( tk->klass()->can_be_primary_super() )3432// This means that if I successfully store an Object into an array-of-String3433// I 'forget' that the Object is really now known to be a String. I have to3434// do this because we don't have true union types for interfaces - if I store3435// a Baz into an array-of-Interface and then tell the optimizer it's an3436// Interface, I forget that it's also a Baz and cannot do Baz-like field3437// references to it. FIX THIS WHEN UNION TYPES APPEAR!3438// replace_in_map( obj, res );34393440// Return final merged results3441set_control( _gvn.transform(region) );3442record_for_igvn(region);34433444return record_profiled_receiver_for_speculation(res);3445}34463447//------------------------------next_monitor-----------------------------------3448// What number should be given to the next monitor?3449int GraphKit::next_monitor() {3450int current = jvms()->monitor_depth()* C->sync_stack_slots();3451int next = current + C->sync_stack_slots();3452// Keep the toplevel high water mark current:3453if (C->fixed_slots() < next) C->set_fixed_slots(next);3454return current;3455}34563457//------------------------------insert_mem_bar---------------------------------3458// Memory barrier to avoid floating things around3459// The membar serves as a pinch point between both control and all memory slices.3460Node* GraphKit::insert_mem_bar(int opcode, Node* precedent) {3461MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);3462mb->init_req(TypeFunc::Control, control());3463mb->init_req(TypeFunc::Memory, reset_memory());3464Node* membar = _gvn.transform(mb);3465set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));3466set_all_memory_call(membar);3467return membar;3468}34693470//-------------------------insert_mem_bar_volatile----------------------------3471// Memory barrier to avoid floating things around3472// The membar serves as a pinch point between both control and memory(alias_idx).3473// If you want to make a pinch point on all memory slices, do not use this3474// function (even with AliasIdxBot); use insert_mem_bar() instead.3475Node* GraphKit::insert_mem_bar_volatile(int opcode, int alias_idx, Node* precedent) {3476// When Parse::do_put_xxx updates a volatile field, it appends a series3477// of MemBarVolatile nodes, one for *each* volatile field alias category.3478// The first membar is on the same memory slice as the field store opcode.3479// This forces the membar to follow the store. (Bug 6500685 broke this.)3480// All the other membars (for other volatile slices, including AliasIdxBot,3481// which stands for all unknown volatile slices) are control-dependent3482// on the first membar. This prevents later volatile loads or stores3483// from sliding up past the just-emitted store.34843485MemBarNode* mb = MemBarNode::make(C, opcode, alias_idx, precedent);3486mb->set_req(TypeFunc::Control,control());3487if (alias_idx == Compile::AliasIdxBot) {3488mb->set_req(TypeFunc::Memory, merged_memory()->base_memory());3489} else {3490assert(!(opcode == Op_Initialize && alias_idx != Compile::AliasIdxRaw), "fix caller");3491mb->set_req(TypeFunc::Memory, memory(alias_idx));3492}3493Node* membar = _gvn.transform(mb);3494set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));3495if (alias_idx == Compile::AliasIdxBot) {3496merged_memory()->set_base_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)));3497} else {3498set_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)),alias_idx);3499}3500return membar;3501}35023503//------------------------------shared_lock------------------------------------3504// Emit locking code.3505FastLockNode* GraphKit::shared_lock(Node* obj) {3506// bci is either a monitorenter bc or InvocationEntryBci3507// %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces3508assert(SynchronizationEntryBCI == InvocationEntryBci, "");35093510if( !GenerateSynchronizationCode )3511return NULL; // Not locking things?3512if (stopped()) // Dead monitor?3513return NULL;35143515assert(dead_locals_are_killed(), "should kill locals before sync. point");35163517// Box the stack location3518Node* box = _gvn.transform(new BoxLockNode(next_monitor()));3519Node* mem = reset_memory();35203521FastLockNode * flock = _gvn.transform(new FastLockNode(0, obj, box) )->as_FastLock();3522if (UseBiasedLocking && PrintPreciseBiasedLockingStatistics) {3523// Create the counters for this fast lock.3524flock->create_lock_counter(sync_jvms()); // sync_jvms used to get current bci3525}35263527// Create the rtm counters for this fast lock if needed.3528flock->create_rtm_lock_counter(sync_jvms()); // sync_jvms used to get current bci35293530// Add monitor to debug info for the slow path. If we block inside the3531// slow path and de-opt, we need the monitor hanging around3532map()->push_monitor( flock );35333534const TypeFunc *tf = LockNode::lock_type();3535LockNode *lock = new LockNode(C, tf);35363537lock->init_req( TypeFunc::Control, control() );3538lock->init_req( TypeFunc::Memory , mem );3539lock->init_req( TypeFunc::I_O , top() ) ; // does no i/o3540lock->init_req( TypeFunc::FramePtr, frameptr() );3541lock->init_req( TypeFunc::ReturnAdr, top() );35423543lock->init_req(TypeFunc::Parms + 0, obj);3544lock->init_req(TypeFunc::Parms + 1, box);3545lock->init_req(TypeFunc::Parms + 2, flock);3546add_safepoint_edges(lock);35473548lock = _gvn.transform( lock )->as_Lock();35493550// lock has no side-effects, sets few values3551set_predefined_output_for_runtime_call(lock, mem, TypeRawPtr::BOTTOM);35523553insert_mem_bar(Op_MemBarAcquireLock);35543555// Add this to the worklist so that the lock can be eliminated3556record_for_igvn(lock);35573558#ifndef PRODUCT3559if (PrintLockStatistics) {3560// Update the counter for this lock. Don't bother using an atomic3561// operation since we don't require absolute accuracy.3562lock->create_lock_counter(map()->jvms());3563increment_counter(lock->counter()->addr());3564}3565#endif35663567return flock;3568}356935703571//------------------------------shared_unlock----------------------------------3572// Emit unlocking code.3573void GraphKit::shared_unlock(Node* box, Node* obj) {3574// bci is either a monitorenter bc or InvocationEntryBci3575// %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces3576assert(SynchronizationEntryBCI == InvocationEntryBci, "");35773578if( !GenerateSynchronizationCode )3579return;3580if (stopped()) { // Dead monitor?3581map()->pop_monitor(); // Kill monitor from debug info3582return;3583}35843585// Memory barrier to avoid floating things down past the locked region3586insert_mem_bar(Op_MemBarReleaseLock);35873588const TypeFunc *tf = OptoRuntime::complete_monitor_exit_Type();3589UnlockNode *unlock = new UnlockNode(C, tf);3590#ifdef ASSERT3591unlock->set_dbg_jvms(sync_jvms());3592#endif3593uint raw_idx = Compile::AliasIdxRaw;3594unlock->init_req( TypeFunc::Control, control() );3595unlock->init_req( TypeFunc::Memory , memory(raw_idx) );3596unlock->init_req( TypeFunc::I_O , top() ) ; // does no i/o3597unlock->init_req( TypeFunc::FramePtr, frameptr() );3598unlock->init_req( TypeFunc::ReturnAdr, top() );35993600unlock->init_req(TypeFunc::Parms + 0, obj);3601unlock->init_req(TypeFunc::Parms + 1, box);3602unlock = _gvn.transform(unlock)->as_Unlock();36033604Node* mem = reset_memory();36053606// unlock has no side-effects, sets few values3607set_predefined_output_for_runtime_call(unlock, mem, TypeRawPtr::BOTTOM);36083609// Kill monitor from debug info3610map()->pop_monitor( );3611}36123613//-------------------------------get_layout_helper-----------------------------3614// If the given klass is a constant or known to be an array,3615// fetch the constant layout helper value into constant_value3616// and return (Node*)NULL. Otherwise, load the non-constant3617// layout helper value, and return the node which represents it.3618// This two-faced routine is useful because allocation sites3619// almost always feature constant types.3620Node* GraphKit::get_layout_helper(Node* klass_node, jint& constant_value) {3621const TypeKlassPtr* inst_klass = _gvn.type(klass_node)->isa_klassptr();3622if (!StressReflectiveCode && inst_klass != NULL) {3623ciKlass* klass = inst_klass->klass();3624bool xklass = inst_klass->klass_is_exact();3625if (xklass || klass->is_array_klass()) {3626jint lhelper = klass->layout_helper();3627if (lhelper != Klass::_lh_neutral_value) {3628constant_value = lhelper;3629return (Node*) NULL;3630}3631}3632}3633constant_value = Klass::_lh_neutral_value; // put in a known value3634Node* lhp = basic_plus_adr(klass_node, klass_node, in_bytes(Klass::layout_helper_offset()));3635return make_load(NULL, lhp, TypeInt::INT, T_INT, MemNode::unordered);3636}36373638// We just put in an allocate/initialize with a big raw-memory effect.3639// Hook selected additional alias categories on the initialization.3640static void hook_memory_on_init(GraphKit& kit, int alias_idx,3641MergeMemNode* init_in_merge,3642Node* init_out_raw) {3643DEBUG_ONLY(Node* init_in_raw = init_in_merge->base_memory());3644assert(init_in_merge->memory_at(alias_idx) == init_in_raw, "");36453646Node* prevmem = kit.memory(alias_idx);3647init_in_merge->set_memory_at(alias_idx, prevmem);3648kit.set_memory(init_out_raw, alias_idx);3649}36503651//---------------------------set_output_for_allocation-------------------------3652Node* GraphKit::set_output_for_allocation(AllocateNode* alloc,3653const TypeOopPtr* oop_type,3654bool deoptimize_on_exception) {3655int rawidx = Compile::AliasIdxRaw;3656alloc->set_req( TypeFunc::FramePtr, frameptr() );3657add_safepoint_edges(alloc);3658Node* allocx = _gvn.transform(alloc);3659set_control( _gvn.transform(new ProjNode(allocx, TypeFunc::Control) ) );3660// create memory projection for i_o3661set_memory ( _gvn.transform( new ProjNode(allocx, TypeFunc::Memory, true) ), rawidx );3662make_slow_call_ex(allocx, env()->Throwable_klass(), true, deoptimize_on_exception);36633664// create a memory projection as for the normal control path3665Node* malloc = _gvn.transform(new ProjNode(allocx, TypeFunc::Memory));3666set_memory(malloc, rawidx);36673668// a normal slow-call doesn't change i_o, but an allocation does3669// we create a separate i_o projection for the normal control path3670set_i_o(_gvn.transform( new ProjNode(allocx, TypeFunc::I_O, false) ) );3671Node* rawoop = _gvn.transform( new ProjNode(allocx, TypeFunc::Parms) );36723673// put in an initialization barrier3674InitializeNode* init = insert_mem_bar_volatile(Op_Initialize, rawidx,3675rawoop)->as_Initialize();3676assert(alloc->initialization() == init, "2-way macro link must work");3677assert(init ->allocation() == alloc, "2-way macro link must work");3678{3679// Extract memory strands which may participate in the new object's3680// initialization, and source them from the new InitializeNode.3681// This will allow us to observe initializations when they occur,3682// and link them properly (as a group) to the InitializeNode.3683assert(init->in(InitializeNode::Memory) == malloc, "");3684MergeMemNode* minit_in = MergeMemNode::make(malloc);3685init->set_req(InitializeNode::Memory, minit_in);3686record_for_igvn(minit_in); // fold it up later, if possible3687Node* minit_out = memory(rawidx);3688assert(minit_out->is_Proj() && minit_out->in(0) == init, "");3689// Add an edge in the MergeMem for the header fields so an access3690// to one of those has correct memory state3691set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::mark_offset_in_bytes())));3692set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::klass_offset_in_bytes())));3693if (oop_type->isa_aryptr()) {3694const TypePtr* telemref = oop_type->add_offset(Type::OffsetBot);3695int elemidx = C->get_alias_index(telemref);3696hook_memory_on_init(*this, elemidx, minit_in, minit_out);3697} else if (oop_type->isa_instptr()) {3698ciInstanceKlass* ik = oop_type->klass()->as_instance_klass();3699for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) {3700ciField* field = ik->nonstatic_field_at(i);3701if (field->offset() >= TrackedInitializationLimit * HeapWordSize)3702continue; // do not bother to track really large numbers of fields3703// Find (or create) the alias category for this field:3704int fieldidx = C->alias_type(field)->index();3705hook_memory_on_init(*this, fieldidx, minit_in, minit_out);3706}3707}3708}37093710// Cast raw oop to the real thing...3711Node* javaoop = new CheckCastPPNode(control(), rawoop, oop_type);3712javaoop = _gvn.transform(javaoop);3713C->set_recent_alloc(control(), javaoop);3714assert(just_allocated_object(control()) == javaoop, "just allocated");37153716#ifdef ASSERT3717{ // Verify that the AllocateNode::Ideal_allocation recognizers work:3718assert(AllocateNode::Ideal_allocation(rawoop, &_gvn) == alloc,3719"Ideal_allocation works");3720assert(AllocateNode::Ideal_allocation(javaoop, &_gvn) == alloc,3721"Ideal_allocation works");3722if (alloc->is_AllocateArray()) {3723assert(AllocateArrayNode::Ideal_array_allocation(rawoop, &_gvn) == alloc->as_AllocateArray(),3724"Ideal_allocation works");3725assert(AllocateArrayNode::Ideal_array_allocation(javaoop, &_gvn) == alloc->as_AllocateArray(),3726"Ideal_allocation works");3727} else {3728assert(alloc->in(AllocateNode::ALength)->is_top(), "no length, please");3729}3730}3731#endif //ASSERT37323733return javaoop;3734}37353736//---------------------------new_instance--------------------------------------3737// This routine takes a klass_node which may be constant (for a static type)3738// or may be non-constant (for reflective code). It will work equally well3739// for either, and the graph will fold nicely if the optimizer later reduces3740// the type to a constant.3741// The optional arguments are for specialized use by intrinsics:3742// - If 'extra_slow_test' if not null is an extra condition for the slow-path.3743// - If 'return_size_val', report the the total object size to the caller.3744// - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)3745Node* GraphKit::new_instance(Node* klass_node,3746Node* extra_slow_test,3747Node* *return_size_val,3748bool deoptimize_on_exception) {3749// Compute size in doublewords3750// The size is always an integral number of doublewords, represented3751// as a positive bytewise size stored in the klass's layout_helper.3752// The layout_helper also encodes (in a low bit) the need for a slow path.3753jint layout_con = Klass::_lh_neutral_value;3754Node* layout_val = get_layout_helper(klass_node, layout_con);3755int layout_is_con = (layout_val == NULL);37563757if (extra_slow_test == NULL) extra_slow_test = intcon(0);3758// Generate the initial go-slow test. It's either ALWAYS (return a3759// Node for 1) or NEVER (return a NULL) or perhaps (in the reflective3760// case) a computed value derived from the layout_helper.3761Node* initial_slow_test = NULL;3762if (layout_is_con) {3763assert(!StressReflectiveCode, "stress mode does not use these paths");3764bool must_go_slow = Klass::layout_helper_needs_slow_path(layout_con);3765initial_slow_test = must_go_slow ? intcon(1) : extra_slow_test;3766} else { // reflective case3767// This reflective path is used by Unsafe.allocateInstance.3768// (It may be stress-tested by specifying StressReflectiveCode.)3769// Basically, we want to get into the VM is there's an illegal argument.3770Node* bit = intcon(Klass::_lh_instance_slow_path_bit);3771initial_slow_test = _gvn.transform( new AndINode(layout_val, bit) );3772if (extra_slow_test != intcon(0)) {3773initial_slow_test = _gvn.transform( new OrINode(initial_slow_test, extra_slow_test) );3774}3775// (Macro-expander will further convert this to a Bool, if necessary.)3776}37773778// Find the size in bytes. This is easy; it's the layout_helper.3779// The size value must be valid even if the slow path is taken.3780Node* size = NULL;3781if (layout_is_con) {3782size = MakeConX(Klass::layout_helper_size_in_bytes(layout_con));3783} else { // reflective case3784// This reflective path is used by clone and Unsafe.allocateInstance.3785size = ConvI2X(layout_val);37863787// Clear the low bits to extract layout_helper_size_in_bytes:3788assert((int)Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");3789Node* mask = MakeConX(~ (intptr_t)right_n_bits(LogBytesPerLong));3790size = _gvn.transform( new AndXNode(size, mask) );3791}3792if (return_size_val != NULL) {3793(*return_size_val) = size;3794}37953796// This is a precise notnull oop of the klass.3797// (Actually, it need not be precise if this is a reflective allocation.)3798// It's what we cast the result to.3799const TypeKlassPtr* tklass = _gvn.type(klass_node)->isa_klassptr();3800if (!tklass) tklass = TypeKlassPtr::OBJECT;3801const TypeOopPtr* oop_type = tklass->as_instance_type();38023803// Now generate allocation code38043805// The entire memory state is needed for slow path of the allocation3806// since GC and deoptimization can happened.3807Node *mem = reset_memory();3808set_all_memory(mem); // Create new memory state38093810AllocateNode* alloc = new AllocateNode(C, AllocateNode::alloc_type(Type::TOP),3811control(), mem, i_o(),3812size, klass_node,3813initial_slow_test);38143815return set_output_for_allocation(alloc, oop_type, deoptimize_on_exception);3816}38173818//-------------------------------new_array-------------------------------------3819// helper for both newarray and anewarray3820// The 'length' parameter is (obviously) the length of the array.3821// See comments on new_instance for the meaning of the other arguments.3822Node* GraphKit::new_array(Node* klass_node, // array klass (maybe variable)3823Node* length, // number of array elements3824int nargs, // number of arguments to push back for uncommon trap3825Node* *return_size_val,3826bool deoptimize_on_exception) {3827jint layout_con = Klass::_lh_neutral_value;3828Node* layout_val = get_layout_helper(klass_node, layout_con);3829int layout_is_con = (layout_val == NULL);38303831if (!layout_is_con && !StressReflectiveCode &&3832!too_many_traps(Deoptimization::Reason_class_check)) {3833// This is a reflective array creation site.3834// Optimistically assume that it is a subtype of Object[],3835// so that we can fold up all the address arithmetic.3836layout_con = Klass::array_layout_helper(T_OBJECT);3837Node* cmp_lh = _gvn.transform( new CmpINode(layout_val, intcon(layout_con)) );3838Node* bol_lh = _gvn.transform( new BoolNode(cmp_lh, BoolTest::eq) );3839{ BuildCutout unless(this, bol_lh, PROB_MAX);3840inc_sp(nargs);3841uncommon_trap(Deoptimization::Reason_class_check,3842Deoptimization::Action_maybe_recompile);3843}3844layout_val = NULL;3845layout_is_con = true;3846}38473848// Generate the initial go-slow test. Make sure we do not overflow3849// if length is huge (near 2Gig) or negative! We do not need3850// exact double-words here, just a close approximation of needed3851// double-words. We can't add any offset or rounding bits, lest we3852// take a size -1 of bytes and make it positive. Use an unsigned3853// compare, so negative sizes look hugely positive.3854int fast_size_limit = FastAllocateSizeLimit;3855if (layout_is_con) {3856assert(!StressReflectiveCode, "stress mode does not use these paths");3857// Increase the size limit if we have exact knowledge of array type.3858int log2_esize = Klass::layout_helper_log2_element_size(layout_con);3859fast_size_limit <<= (LogBytesPerLong - log2_esize);3860}38613862Node* initial_slow_cmp = _gvn.transform( new CmpUNode( length, intcon( fast_size_limit ) ) );3863Node* initial_slow_test = _gvn.transform( new BoolNode( initial_slow_cmp, BoolTest::gt ) );38643865// --- Size Computation ---3866// array_size = round_to_heap(array_header + (length << elem_shift));3867// where round_to_heap(x) == align_to(x, MinObjAlignmentInBytes)3868// and align_to(x, y) == ((x + y-1) & ~(y-1))3869// The rounding mask is strength-reduced, if possible.3870int round_mask = MinObjAlignmentInBytes - 1;3871Node* header_size = NULL;3872int header_size_min = arrayOopDesc::base_offset_in_bytes(T_BYTE);3873// (T_BYTE has the weakest alignment and size restrictions...)3874if (layout_is_con) {3875int hsize = Klass::layout_helper_header_size(layout_con);3876int eshift = Klass::layout_helper_log2_element_size(layout_con);3877BasicType etype = Klass::layout_helper_element_type(layout_con);3878if ((round_mask & ~right_n_bits(eshift)) == 0)3879round_mask = 0; // strength-reduce it if it goes away completely3880assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");3881assert(header_size_min <= hsize, "generic minimum is smallest");3882header_size_min = hsize;3883header_size = intcon(hsize + round_mask);3884} else {3885Node* hss = intcon(Klass::_lh_header_size_shift);3886Node* hsm = intcon(Klass::_lh_header_size_mask);3887Node* hsize = _gvn.transform( new URShiftINode(layout_val, hss) );3888hsize = _gvn.transform( new AndINode(hsize, hsm) );3889Node* mask = intcon(round_mask);3890header_size = _gvn.transform( new AddINode(hsize, mask) );3891}38923893Node* elem_shift = NULL;3894if (layout_is_con) {3895int eshift = Klass::layout_helper_log2_element_size(layout_con);3896if (eshift != 0)3897elem_shift = intcon(eshift);3898} else {3899// There is no need to mask or shift this value.3900// The semantics of LShiftINode include an implicit mask to 0x1F.3901assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");3902elem_shift = layout_val;3903}39043905// Transition to native address size for all offset calculations:3906Node* lengthx = ConvI2X(length);3907Node* headerx = ConvI2X(header_size);3908#ifdef _LP643909{ const TypeInt* tilen = _gvn.find_int_type(length);3910if (tilen != NULL && tilen->_lo < 0) {3911// Add a manual constraint to a positive range. Cf. array_element_address.3912jint size_max = fast_size_limit;3913if (size_max > tilen->_hi) size_max = tilen->_hi;3914const TypeInt* tlcon = TypeInt::make(0, size_max, Type::WidenMin);39153916// Only do a narrow I2L conversion if the range check passed.3917IfNode* iff = new IfNode(control(), initial_slow_test, PROB_MIN, COUNT_UNKNOWN);3918_gvn.transform(iff);3919RegionNode* region = new RegionNode(3);3920_gvn.set_type(region, Type::CONTROL);3921lengthx = new PhiNode(region, TypeLong::LONG);3922_gvn.set_type(lengthx, TypeLong::LONG);39233924// Range check passed. Use ConvI2L node with narrow type.3925Node* passed = IfFalse(iff);3926region->init_req(1, passed);3927// Make I2L conversion control dependent to prevent it from3928// floating above the range check during loop optimizations.3929lengthx->init_req(1, C->constrained_convI2L(&_gvn, length, tlcon, passed));39303931// Range check failed. Use ConvI2L with wide type because length may be invalid.3932region->init_req(2, IfTrue(iff));3933lengthx->init_req(2, ConvI2X(length));39343935set_control(region);3936record_for_igvn(region);3937record_for_igvn(lengthx);3938}3939}3940#endif39413942// Combine header size (plus rounding) and body size. Then round down.3943// This computation cannot overflow, because it is used only in two3944// places, one where the length is sharply limited, and the other3945// after a successful allocation.3946Node* abody = lengthx;3947if (elem_shift != NULL)3948abody = _gvn.transform( new LShiftXNode(lengthx, elem_shift) );3949Node* size = _gvn.transform( new AddXNode(headerx, abody) );3950if (round_mask != 0) {3951Node* mask = MakeConX(~round_mask);3952size = _gvn.transform( new AndXNode(size, mask) );3953}3954// else if round_mask == 0, the size computation is self-rounding39553956if (return_size_val != NULL) {3957// This is the size3958(*return_size_val) = size;3959}39603961// Now generate allocation code39623963// The entire memory state is needed for slow path of the allocation3964// since GC and deoptimization can happened.3965Node *mem = reset_memory();3966set_all_memory(mem); // Create new memory state39673968if (initial_slow_test->is_Bool()) {3969// Hide it behind a CMoveI, or else PhaseIdealLoop::split_up will get sick.3970initial_slow_test = initial_slow_test->as_Bool()->as_int_value(&_gvn);3971}39723973const TypeOopPtr* ary_type = _gvn.type(klass_node)->is_klassptr()->as_instance_type();3974Node* valid_length_test = _gvn.intcon(1);3975if (ary_type->klass()->is_array_klass()) {3976BasicType bt = ary_type->klass()->as_array_klass()->element_type()->basic_type();3977jint max = TypeAryPtr::max_array_length(bt);3978Node* valid_length_cmp = _gvn.transform(new CmpUNode(length, intcon(max)));3979valid_length_test = _gvn.transform(new BoolNode(valid_length_cmp, BoolTest::le));3980}39813982// Create the AllocateArrayNode and its result projections3983AllocateArrayNode* alloc3984= new AllocateArrayNode(C, AllocateArrayNode::alloc_type(TypeInt::INT),3985control(), mem, i_o(),3986size, klass_node,3987initial_slow_test,3988length, valid_length_test);39893990// Cast to correct type. Note that the klass_node may be constant or not,3991// and in the latter case the actual array type will be inexact also.3992// (This happens via a non-constant argument to inline_native_newArray.)3993// In any case, the value of klass_node provides the desired array type.3994const TypeInt* length_type = _gvn.find_int_type(length);3995if (ary_type->isa_aryptr() && length_type != NULL) {3996// Try to get a better type than POS for the size3997ary_type = ary_type->is_aryptr()->cast_to_size(length_type);3998}39994000Node* javaoop = set_output_for_allocation(alloc, ary_type, deoptimize_on_exception);40014002array_ideal_length(alloc, ary_type, true);4003return javaoop;4004}40054006// The following "Ideal_foo" functions are placed here because they recognize4007// the graph shapes created by the functions immediately above.40084009//---------------------------Ideal_allocation----------------------------------4010// Given an oop pointer or raw pointer, see if it feeds from an AllocateNode.4011AllocateNode* AllocateNode::Ideal_allocation(Node* ptr, PhaseTransform* phase) {4012if (ptr == NULL) { // reduce dumb test in callers4013return NULL;4014}40154016BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();4017ptr = bs->step_over_gc_barrier(ptr);40184019if (ptr->is_CheckCastPP()) { // strip only one raw-to-oop cast4020ptr = ptr->in(1);4021if (ptr == NULL) return NULL;4022}4023// Return NULL for allocations with several casts:4024// j.l.reflect.Array.newInstance(jobject, jint)4025// Object.clone()4026// to keep more precise type from last cast.4027if (ptr->is_Proj()) {4028Node* allo = ptr->in(0);4029if (allo != NULL && allo->is_Allocate()) {4030return allo->as_Allocate();4031}4032}4033// Report failure to match.4034return NULL;4035}40364037// Fancy version which also strips off an offset (and reports it to caller).4038AllocateNode* AllocateNode::Ideal_allocation(Node* ptr, PhaseTransform* phase,4039intptr_t& offset) {4040Node* base = AddPNode::Ideal_base_and_offset(ptr, phase, offset);4041if (base == NULL) return NULL;4042return Ideal_allocation(base, phase);4043}40444045// Trace Initialize <- Proj[Parm] <- Allocate4046AllocateNode* InitializeNode::allocation() {4047Node* rawoop = in(InitializeNode::RawAddress);4048if (rawoop->is_Proj()) {4049Node* alloc = rawoop->in(0);4050if (alloc->is_Allocate()) {4051return alloc->as_Allocate();4052}4053}4054return NULL;4055}40564057// Trace Allocate -> Proj[Parm] -> Initialize4058InitializeNode* AllocateNode::initialization() {4059ProjNode* rawoop = proj_out_or_null(AllocateNode::RawAddress);4060if (rawoop == NULL) return NULL;4061for (DUIterator_Fast imax, i = rawoop->fast_outs(imax); i < imax; i++) {4062Node* init = rawoop->fast_out(i);4063if (init->is_Initialize()) {4064assert(init->as_Initialize()->allocation() == this, "2-way link");4065return init->as_Initialize();4066}4067}4068return NULL;4069}40704071//----------------------------- loop predicates ---------------------------40724073//------------------------------add_predicate_impl----------------------------4074void GraphKit::add_empty_predicate_impl(Deoptimization::DeoptReason reason, int nargs) {4075// Too many traps seen?4076if (too_many_traps(reason)) {4077#ifdef ASSERT4078if (TraceLoopPredicate) {4079int tc = C->trap_count(reason);4080tty->print("too many traps=%s tcount=%d in ",4081Deoptimization::trap_reason_name(reason), tc);4082method()->print(); // which method has too many predicate traps4083tty->cr();4084}4085#endif4086// We cannot afford to take more traps here,4087// do not generate predicate.4088return;4089}40904091Node *cont = _gvn.intcon(1);4092Node* opq = _gvn.transform(new Opaque1Node(C, cont));4093Node *bol = _gvn.transform(new Conv2BNode(opq));4094IfNode* iff = create_and_map_if(control(), bol, PROB_MAX, COUNT_UNKNOWN);4095Node* iffalse = _gvn.transform(new IfFalseNode(iff));4096C->add_predicate_opaq(opq);4097{4098PreserveJVMState pjvms(this);4099set_control(iffalse);4100inc_sp(nargs);4101uncommon_trap(reason, Deoptimization::Action_maybe_recompile);4102}4103Node* iftrue = _gvn.transform(new IfTrueNode(iff));4104set_control(iftrue);4105}41064107//------------------------------add_predicate---------------------------------4108void GraphKit::add_empty_predicates(int nargs) {4109// These loop predicates remain empty. All concrete loop predicates are inserted above the corresponding4110// empty loop predicate later by 'PhaseIdealLoop::create_new_if_for_predicate'. All concrete loop predicates of4111// a specific kind (normal, profile or limit check) share the same uncommon trap as the empty loop predicate.4112if (UseLoopPredicate) {4113add_empty_predicate_impl(Deoptimization::Reason_predicate, nargs);4114}4115if (UseProfiledLoopPredicate) {4116add_empty_predicate_impl(Deoptimization::Reason_profile_predicate, nargs);4117}4118// loop's limit check predicate should be near the loop.4119add_empty_predicate_impl(Deoptimization::Reason_loop_limit_check, nargs);4120}41214122void GraphKit::sync_kit(IdealKit& ideal) {4123set_all_memory(ideal.merged_memory());4124set_i_o(ideal.i_o());4125set_control(ideal.ctrl());4126}41274128void GraphKit::final_sync(IdealKit& ideal) {4129// Final sync IdealKit and graphKit.4130sync_kit(ideal);4131}41324133Node* GraphKit::load_String_length(Node* str, bool set_ctrl) {4134Node* len = load_array_length(load_String_value(str, set_ctrl));4135Node* coder = load_String_coder(str, set_ctrl);4136// Divide length by 2 if coder is UTF164137return _gvn.transform(new RShiftINode(len, coder));4138}41394140Node* GraphKit::load_String_value(Node* str, bool set_ctrl) {4141int value_offset = java_lang_String::value_offset();4142const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),4143false, NULL, 0);4144const TypePtr* value_field_type = string_type->add_offset(value_offset);4145const TypeAryPtr* value_type = TypeAryPtr::make(TypePtr::NotNull,4146TypeAry::make(TypeInt::BYTE, TypeInt::POS),4147ciTypeArrayKlass::make(T_BYTE), true, 0);4148Node* p = basic_plus_adr(str, str, value_offset);4149Node* load = access_load_at(str, p, value_field_type, value_type, T_OBJECT,4150IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);4151return load;4152}41534154Node* GraphKit::load_String_coder(Node* str, bool set_ctrl) {4155if (!CompactStrings) {4156return intcon(java_lang_String::CODER_UTF16);4157}4158int coder_offset = java_lang_String::coder_offset();4159const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),4160false, NULL, 0);4161const TypePtr* coder_field_type = string_type->add_offset(coder_offset);41624163Node* p = basic_plus_adr(str, str, coder_offset);4164Node* load = access_load_at(str, p, coder_field_type, TypeInt::BYTE, T_BYTE,4165IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);4166return load;4167}41684169void GraphKit::store_String_value(Node* str, Node* value) {4170int value_offset = java_lang_String::value_offset();4171const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),4172false, NULL, 0);4173const TypePtr* value_field_type = string_type->add_offset(value_offset);41744175access_store_at(str, basic_plus_adr(str, value_offset), value_field_type,4176value, TypeAryPtr::BYTES, T_OBJECT, IN_HEAP | MO_UNORDERED);4177}41784179void GraphKit::store_String_coder(Node* str, Node* value) {4180int coder_offset = java_lang_String::coder_offset();4181const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),4182false, NULL, 0);4183const TypePtr* coder_field_type = string_type->add_offset(coder_offset);41844185access_store_at(str, basic_plus_adr(str, coder_offset), coder_field_type,4186value, TypeInt::BYTE, T_BYTE, IN_HEAP | MO_UNORDERED);4187}41884189// Capture src and dst memory state with a MergeMemNode4190Node* GraphKit::capture_memory(const TypePtr* src_type, const TypePtr* dst_type) {4191if (src_type == dst_type) {4192// Types are equal, we don't need a MergeMemNode4193return memory(src_type);4194}4195MergeMemNode* merge = MergeMemNode::make(map()->memory());4196record_for_igvn(merge); // fold it up later, if possible4197int src_idx = C->get_alias_index(src_type);4198int dst_idx = C->get_alias_index(dst_type);4199merge->set_memory_at(src_idx, memory(src_idx));4200merge->set_memory_at(dst_idx, memory(dst_idx));4201return merge;4202}42034204Node* GraphKit::compress_string(Node* src, const TypeAryPtr* src_type, Node* dst, Node* count) {4205assert(Matcher::match_rule_supported(Op_StrCompressedCopy), "Intrinsic not supported");4206assert(src_type == TypeAryPtr::BYTES || src_type == TypeAryPtr::CHARS, "invalid source type");4207// If input and output memory types differ, capture both states to preserve4208// the dependency between preceding and subsequent loads/stores.4209// For example, the following program:4210// StoreB4211// compress_string4212// LoadB4213// has this memory graph (use->def):4214// LoadB -> compress_string -> CharMem4215// ... -> StoreB -> ByteMem4216// The intrinsic hides the dependency between LoadB and StoreB, causing4217// the load to read from memory not containing the result of the StoreB.4218// The correct memory graph should look like this:4219// LoadB -> compress_string -> MergeMem(CharMem, StoreB(ByteMem))4220Node* mem = capture_memory(src_type, TypeAryPtr::BYTES);4221StrCompressedCopyNode* str = new StrCompressedCopyNode(control(), mem, src, dst, count);4222Node* res_mem = _gvn.transform(new SCMemProjNode(_gvn.transform(str)));4223set_memory(res_mem, TypeAryPtr::BYTES);4224return str;4225}42264227void GraphKit::inflate_string(Node* src, Node* dst, const TypeAryPtr* dst_type, Node* count) {4228assert(Matcher::match_rule_supported(Op_StrInflatedCopy), "Intrinsic not supported");4229assert(dst_type == TypeAryPtr::BYTES || dst_type == TypeAryPtr::CHARS, "invalid dest type");4230// Capture src and dst memory (see comment in 'compress_string').4231Node* mem = capture_memory(TypeAryPtr::BYTES, dst_type);4232StrInflatedCopyNode* str = new StrInflatedCopyNode(control(), mem, src, dst, count);4233set_memory(_gvn.transform(str), dst_type);4234}42354236void GraphKit::inflate_string_slow(Node* src, Node* dst, Node* start, Node* count) {4237/**4238* int i_char = start;4239* for (int i_byte = 0; i_byte < count; i_byte++) {4240* dst[i_char++] = (char)(src[i_byte] & 0xff);4241* }4242*/4243add_empty_predicates();4244C->set_has_loops(true);42454246RegionNode* head = new RegionNode(3);4247head->init_req(1, control());4248gvn().set_type(head, Type::CONTROL);4249record_for_igvn(head);42504251Node* i_byte = new PhiNode(head, TypeInt::INT);4252i_byte->init_req(1, intcon(0));4253gvn().set_type(i_byte, TypeInt::INT);4254record_for_igvn(i_byte);42554256Node* i_char = new PhiNode(head, TypeInt::INT);4257i_char->init_req(1, start);4258gvn().set_type(i_char, TypeInt::INT);4259record_for_igvn(i_char);42604261Node* mem = PhiNode::make(head, memory(TypeAryPtr::BYTES), Type::MEMORY, TypeAryPtr::BYTES);4262gvn().set_type(mem, Type::MEMORY);4263record_for_igvn(mem);4264set_control(head);4265set_memory(mem, TypeAryPtr::BYTES);4266Node* ch = load_array_element(src, i_byte, TypeAryPtr::BYTES, /* set_ctrl */ true);4267Node* st = store_to_memory(control(), array_element_address(dst, i_char, T_BYTE),4268AndI(ch, intcon(0xff)), T_CHAR, TypeAryPtr::BYTES, MemNode::unordered,4269false, false, true /* mismatched */);42704271IfNode* iff = create_and_map_if(head, Bool(CmpI(i_byte, count), BoolTest::lt), PROB_FAIR, COUNT_UNKNOWN);4272head->init_req(2, IfTrue(iff));4273mem->init_req(2, st);4274i_byte->init_req(2, AddI(i_byte, intcon(1)));4275i_char->init_req(2, AddI(i_char, intcon(2)));42764277set_control(IfFalse(iff));4278set_memory(st, TypeAryPtr::BYTES);4279}42804281Node* GraphKit::make_constant_from_field(ciField* field, Node* obj) {4282if (!field->is_constant()) {4283return NULL; // Field not marked as constant.4284}4285ciInstance* holder = NULL;4286if (!field->is_static()) {4287ciObject* const_oop = obj->bottom_type()->is_oopptr()->const_oop();4288if (const_oop != NULL && const_oop->is_instance()) {4289holder = const_oop->as_instance();4290}4291}4292const Type* con_type = Type::make_constant_from_field(field, holder, field->layout_type(),4293/*is_unsigned_load=*/false);4294if (con_type != NULL) {4295return makecon(con_type);4296}4297return NULL;4298}429943004301